java.util.stream.Collectors Java Examples

The following examples show how to use java.util.stream.Collectors. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractTernaryRelationGenerator.java    From capsule with BSD 2-Clause "Simplified" License 7 votes vote down vote up
@Override
public List<T> doShrink(SourceOfRandomness random, T larger) {
  @SuppressWarnings("unchecked")
  List<Object> asList = new ArrayList<>(larger);

  List<T> shrinks = new ArrayList<>();
  shrinks.addAll(removals(asList));

  @SuppressWarnings("unchecked")
  Shrink<Object> generator = (Shrink<Object>) componentGenerators().get(0);

  List<List<Object>> oneItemShrinks = shrinksOfOneItem(random, asList, generator);
  shrinks.addAll(oneItemShrinks.stream().map(this::convert).filter(this::inSizeRange)
      .collect(Collectors.toList()));

  return shrinks;
}
 
Example #2
Source File: ConnectionModelConverter.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a ConnectionModel from a ConnectionInformation
 *
 * @param connection
 * 		the {@link ConnectionInformation} object
 * @param location
 * 		the {@link RepositoryLocation} of the connection
 * @param editable
 *        {@code true} if the connection is editable
 * @return a connection model containing the information of the connection
 */
public static ConnectionModel fromConnection(ConnectionInformation connection, RepositoryLocation location, boolean editable) {
	List<ValueProviderModel> valueProviderModels = connection.getConfiguration().getValueProviders().stream().map(ValueProviderModelConverter::toModel).collect(Collectors.toList());
	ConnectionModel conn = new ConnectionModel(connection, location, editable, valueProviderModels);
	conn.setDescription(connection.getConfiguration().getDescription());
	conn.setTags(new ArrayList<>(connection.getConfiguration().getTags()));
	// use new (empty) connection to capture all potential new parameters
	ConnectionInformation newConnection = null;
	try {
		ConnectionHandler handler = ConnectionHandlerRegistry.getInstance().getHandler(connection.getConfiguration().getType());
		newConnection = handler.createNewConnectionInformation("emptyCI");
	} catch (GenericHandlerRegistry.MissingHandlerException e) {
		LogService.getRoot().log(Level.WARNING, "com.rapidminer.connection.gui.model.ConnectionModelConverter.creating_empty_connection_failed", connection.getConfiguration().getType());
	}
	if (newConnection != null) {
		addParameters(newConnection, conn);
	}
	// now overwrite with values of existing connection
	addParameters(connection, conn);
	for (PlaceholderParameter p : connection.getConfiguration().getPlaceholders()) {
		conn.addOrSetPlaceholder(p.getGroup(), p.getName(), p.getValue(), p.isEncrypted(), p.getInjectorName(), p.isEnabled());
	}
	conn.setLibraryFiles(connection.getLibraryFiles());
	conn.setOtherFiles(connection.getOtherFiles());
	return conn;
}
 
Example #3
Source File: ProperNounInformationCollector.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Entity> Set<EntityInformation<T>> getEntityInformation(
    JCas jCas, Class<T> clazz) {
  Multimap<ReferenceTarget, T> map = ReferentUtils.createReferentMap(jCas, clazz);
  Map<T, List<Sentence>> index = JCasUtil.indexCovering(jCas, clazz, Sentence.class);
  Map<T, List<WordToken>> tokens = JCasUtil.indexCovered(jCas, clazz, WordToken.class);

  Set<EntityInformation<T>> infos = new HashSet<>();
  for (Map.Entry<ReferenceTarget, Collection<T>> entry : map.asMap().entrySet()) {
    Collection<Sentence> sentences =
        entry.getValue().stream().flatMap(m -> index.get(m).stream()).collect(Collectors.toSet());

    List<T> properNouns =
        entry.getValue().stream()
            .filter(
                e ->
                    tokens.get(e).stream()
                        .map(WordToken::getPartOfSpeech)
                        .anyMatch("NNP"::equals))
            .collect(toList());

    infos.add(new EntityInformation<T>(entry.getKey(), properNouns, sentences));
  }

  return infos;
}
 
Example #4
Source File: StoreCRUDServiceVertxEBProxy.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private <T> Map<String, T> convertMap(Map map) {
  if (map.isEmpty()) { 
    return (Map<String, T>) map; 
  } 
   
  Object elem = map.values().stream().findFirst().get(); 
  if (!(elem instanceof Map) && !(elem instanceof List)) { 
    return (Map<String, T>) map; 
  } else { 
    Function<Object, T> converter; 
    if (elem instanceof List) { 
      converter = object -> (T) new JsonArray((List) object); 
    } else { 
      converter = object -> (T) new JsonObject((Map) object); 
    } 
    return ((Map<String, T>) map).entrySet() 
     .stream() 
     .collect(Collectors.toMap(Map.Entry::getKey, converter::apply)); 
  } 
}
 
Example #5
Source File: MTLowHeteroplasmyFilterToolTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "lowhetData")
public void testLowHetVariantsFiltered(List<List<String>> expectedASFilters) {
    final Set<Integer> low_het_sites = new HashSet<>(Arrays.asList(301));
    final File outputFile = createTempFile("low-het-test", ".vcf");
    final ArgumentsBuilder argsBuilder = new ArgumentsBuilder()
            .addReference(MITO_REF.getAbsolutePath())
            .add(StandardArgumentDefinitions.VARIANT_SHORT_NAME, NA12878_MITO_FILTERED_VCF.getAbsolutePath())
            .add(MTLowHeteroplasmyFilterTool.MAX_ALLOWED_LOW_HETS_LONG_NAME, 0)
            .addOutput(outputFile);
    runCommandLine(argsBuilder);
    Set<VariantContext> variants = VariantContextTestUtils.streamVcf(outputFile)
            .filter(vcf -> vcf.getFilters().contains(GATKVCFConstants.LOW_HET_FILTER_NAME)).collect(Collectors.toSet());
    Set<Integer> actual_sites = variants.stream().map(var -> var.getStart()).collect(Collectors.toSet());
    Assert.assertEquals(actual_sites, low_het_sites, "did not find the correct " + GATKVCFConstants.LOW_HET_FILTER_NAME + " site filters.");

    final List<List<String>> actualASFilters = VariantContextTestUtils.streamVcf(outputFile)
            .map(vc -> AnnotationUtils.decodeAnyASListWithRawDelim(vc.getCommonInfo().getAttributeAsString(GATKVCFConstants.AS_FILTER_STATUS_KEY, ""))).collect(Collectors.toList());
    Assert.assertEquals(actualASFilters, expectedASFilters);

}
 
Example #6
Source File: ExtendedS3StorageTest.java    From pravega with Apache License 2.0 6 votes vote down vote up
TestContext() throws Exception {
    String bucketName = BUCKET_NAME_PREFIX + UUID.randomUUID().toString();
    this.adapterConfig = ExtendedS3StorageConfig.builder()
            .with(ExtendedS3StorageConfig.CONFIGURI, configUri)
            .with(ExtendedS3StorageConfig.BUCKET, bucketName)
            .with(ExtendedS3StorageConfig.PREFIX, "samplePrefix")
            .build();
    s3Config = new ConfigUri<>(S3Config.class).parseUri(configUri);
    s3Proxy = new S3ProxyImpl(configUri, s3Config);
    s3Proxy.start();
    client = new S3JerseyClientWrapper(s3Config, s3Proxy);
    client.createBucket(bucketName);
    List<ObjectKey> keys = client.listObjects(bucketName).getObjects().stream()
            .map(object -> new ObjectKey(object.getKey()))
            .collect(Collectors.toList());

    if (!keys.isEmpty()) {
        client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
    }
}
 
Example #7
Source File: HueConfigProviderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void getServiceConfigVariables() {
    BlueprintView blueprintView = getMockBlueprintView("7.2.0", "7.1.0");

    RDSConfig rdsConfig = new RDSConfig();
    rdsConfig.setType(HUE);
    rdsConfig.setConnectionURL(String.format("jdbc:%s://%s:%s/%s", DB_PROVIDER, HOST, PORT, DB_NAME));
    rdsConfig.setConnectionUserName(USER_NAME);
    rdsConfig.setConnectionPassword(PASSWORD);
    TemplatePreparationObject tpo = new Builder()
            .withRdsConfigs(Set.of(rdsConfig))
            .withBlueprintView(blueprintView)
            .build();

    List<ApiClusterTemplateVariable> result = underTest.getServiceConfigVariables(tpo);
    Map<String, String> paramToVariable =
            result.stream().collect(Collectors.toMap(ApiClusterTemplateVariable::getName, ApiClusterTemplateVariable::getValue));
    assertThat(paramToVariable).containsOnly(
            new SimpleEntry<>("hue-hue_database_host", HOST),
            new SimpleEntry<>("hue-hue_database_port", PORT),
            new SimpleEntry<>("hue-hue_database_name", DB_NAME),
            new SimpleEntry<>("hue-hue_database_type", DB_PROVIDER),
            new SimpleEntry<>("hue-hue_database_user", USER_NAME),
            new SimpleEntry<>("hue-hue_database_password", PASSWORD));
}
 
Example #8
Source File: ActionChainManager.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Schedules the application of states to minions
 * @param user the requesting user
 * @param sids list of system IDs
 * @param test for test mode
 * @param earliest earliest execution date
 * @param actionChain Action Chain instance
 * @return a set of Actions
 * @throws TaskomaticApiException if there was a Taskomatic error
 * (typically: Taskomatic is down)
 */
public static Set<Action> scheduleApplyStates(User user, List<Long> sids, Optional<Boolean> test,
                                               Date earliest, ActionChain actionChain)
        throws TaskomaticApiException {

    if (!sids.stream().map(sid -> ServerFactory.lookupById(sid))
            .filter(server -> !MinionServerUtils.isMinionServer(server))
            .collect(Collectors.toList()).isEmpty()) {
        throw new IllegalArgumentException("Server ids include non minion servers.");
    }

    Set<Long> sidSet = new HashSet<Long>();
    sidSet.addAll(sids);

    String summary = "Apply highstate" + (test.isPresent() && test.get() ? " in test-mode" : "");
    Set<Action> result = scheduleActions(user, ActionFactory.TYPE_APPLY_STATES, summary,
            earliest, actionChain, null, sidSet);
    for (Action action : result) {
        ApplyStatesActionDetails applyState = new ApplyStatesActionDetails();
        applyState.setActionId(action.getId());
        test.ifPresent(t -> applyState.setTest(t));
        ((ApplyStatesAction)action).setDetails(applyState);
        ActionFactory.save(action);
    }
    return result;
}
 
Example #9
Source File: FileNameResolverTest.java    From analysis-model with MIT License 6 votes vote down vote up
@Test
@DisplayName("Should set path if the relative file name exists")
void shouldSetPath() {
    Report report = new Report();

    IssueBuilder builder = new IssueBuilder();

    report.add(builder.setFileName(RELATIVE_FILE).build());

    resolvePaths(report, RESOURCE_FOLDER_PATH);

    assertThat(report).hasSize(1);
    assertThat(report.get(0)).hasFileName(RELATIVE_FILE).hasPath(RESOURCE_FOLDER_STRING);

    assertThat(report.getInfoMessages()).hasSize(1);
    assertThat(report.getInfoMessages().get(0)).as("Files: "
            + report.stream().map(Issue::getFileName).collect(Collectors.joining(", ")))
            .contains("1 found", "0 not found");
    assertThat(report.getErrorMessages()).isEmpty();
}
 
Example #10
Source File: DataSetController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value = "/{uid}/categoryCombos", method = RequestMethod.GET )
public @ResponseBody RootNode getCategoryCombinations( @PathVariable( "uid" ) String uid, HttpServletRequest request,
    TranslateParams translateParams, HttpServletResponse response )
    throws Exception
{
    setUserContext( translateParams );
    DataSet dataSet = manager.get( DataSet.class, uid );

    if ( dataSet == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Data set does not exist: " + uid ) );
    }

    List<CategoryCombo> categoryCombos = dataSet.getDataSetElements().stream().
        map( DataSetElement::getResolvedCategoryCombo ).distinct().collect( Collectors.toList() );

    Collections.sort( categoryCombos );

    List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) );

    RootNode rootNode = NodeUtils.createMetadata();
    rootNode.addChild( fieldFilterService.toCollectionNode( CategoryCombo.class,
        new FieldFilterParams( categoryCombos, fields ) ) );

    return rootNode;
}
 
Example #11
Source File: KafkaUnboundedReader.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
@Override
public CheckpointMark getCheckpointMark() {
  reportBacklog();
  return new KafkaCheckpointMark(
      partitionStates
          .stream()
          .map(
              p ->
                  new PartitionMark(
                      p.topicPartition.topic(),
                      p.topicPartition.partition(),
                      p.nextOffset,
                      p.lastWatermark.getMillis()))
          .collect(Collectors.toList()),
      source.getSpec().isCommitOffsetsInFinalizeEnabled() ? Optional.of(this) : Optional.empty());
}
 
Example #12
Source File: TimerApplicationStubs.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private ProcessStubs concreteProcessStubs(Business business, String applicationId) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Process.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Process> cq = cb.createQuery(Process.class);
	Root<Process> root = cq.from(Process.class);
	Predicate p = cb.equal(root.get(Process_.application), applicationId);
	cq.select(root).where(p);
	List<Process> os = em.createQuery(cq).getResultList();
	List<ProcessStub> list = new ArrayList<>();
	for (Process o : os) {
		ProcessStub stub = new ProcessStub();
		stub.setName(o.getName());
		stub.setValue(o.getId());
		stub.setActivityStubs(this.concreteActivityStubs(business, o.getId()));
		list.add(stub);
	}
	list = list.stream().sorted(Comparator.comparing(ProcessStub::getName, Comparator.nullsLast(String::compareTo)))
			.collect(Collectors.toList());
	ProcessStubs stubs = new ProcessStubs();
	stubs.addAll(list);
	return stubs;
}
 
Example #13
Source File: EnrichedThingDTOMapperTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldMapEnrichedThingDTO() {
    when(linkedItemsMap.get("1")).thenReturn(Stream.of("linkedItem1", "linkedItem2").collect(Collectors.toSet()));

    EnrichedThingDTO enrichedThingDTO = EnrichedThingDTOMapper.map(thing, thingStatusInfo, firmwareStatus,
            linkedItemsMap, true);

    assertThat(enrichedThingDTO.editable, is(true));
    assertThat(enrichedThingDTO.firmwareStatus, is(equalTo(firmwareStatus)));
    assertThat(enrichedThingDTO.statusInfo, is(equalTo(thingStatusInfo)));
    assertThat(enrichedThingDTO.thingTypeUID, is(equalTo(thing.getThingTypeUID().getAsString())));
    assertThat(enrichedThingDTO.label, is(equalTo(THING_LABEL)));
    assertThat(enrichedThingDTO.bridgeUID, is(CoreMatchers.nullValue()));

    assertChannels(enrichedThingDTO);

    assertThat(enrichedThingDTO.configuration.values(), is(empty()));
    assertThat(enrichedThingDTO.properties, is(equalTo(properties)));
    assertThat(enrichedThingDTO.location, is(equalTo(LOCATION)));
}
 
Example #14
Source File: ManagementRegistry.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> toMap(Capability capability) {
  Map<String, Object> map = new LinkedHashMap<>();
  map.put("name", capability.getName());
  map.put("context", capability.getCapabilityContext().getAttributes().stream().map(ManagementRegistry::toMap).collect(Collectors.toList()));

  List<Map<String, Object>> descriptorList = new ArrayList<>(capability.getDescriptors().size());
  map.put("descriptors", descriptorList);
  for (Descriptor o : capability.getDescriptors()) {
    if (o instanceof CallDescriptor) {
      descriptorList.add(toMap((CallDescriptor) o));
    } else if (o instanceof StatisticDescriptor) {
      descriptorList.add(toMap((StatisticDescriptor) o));
    } else if (o instanceof Settings) {
      descriptorList.add(toMap((Settings) o));
    } else {
      descriptorList.add(toMap(o));
    }
  }
  return map;
}
 
Example #15
Source File: BinarySerializationImpl.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public TransactionFactory fromBodyBuilder(NetworkType networkType, Serializer transactionBuilder) {

    AccountAddressRestrictionTransactionBodyBuilder builder = (AccountAddressRestrictionTransactionBodyBuilder) transactionBuilder;

    long restrictionFlagsValue = builder.getRestrictionFlags().stream()
        .mapToLong(AccountRestrictionFlagsDto::getValue).sum();

    AccountAddressRestrictionFlags restrictionFlags = AccountAddressRestrictionFlags
        .rawValueOf((int) restrictionFlagsValue);

    List<UnresolvedAddress> restrictionAdditions = builder.getRestrictionAdditions().stream()
        .map(SerializationUtils::toUnresolvedAddress).collect(Collectors.toList());

    List<UnresolvedAddress> restrictionDeletions = builder.getRestrictionDeletions().stream()
        .map(SerializationUtils::toUnresolvedAddress).collect(Collectors.toList());

    return AccountAddressRestrictionTransactionFactory
        .create(networkType, restrictionFlags, restrictionAdditions, restrictionDeletions);
}
 
Example #16
Source File: Model.java    From tlaplus with MIT License 6 votes vote down vote up
private void pruneOldestSnapshots() throws CoreException {
	// Sort model by snapshot timestamp and remove oldest ones.
	final int snapshotKeepCount = TLCActivator.getDefault().getPreferenceStore().getInt(TLCActivator.I_TLC_SNAPSHOT_KEEP_COUNT);
	// Filter out running snapshots such as remotely running ones (CloudTLC).
	final List<Model> snapshotModels = new ArrayList<>(getSnapshots().stream()
			.filter(m -> !m.isRunning() && !m.isRunningRemotely()).collect(Collectors.toList()));
	if (snapshotModels.size() > snapshotKeepCount) {
	    final int pruneCount = snapshotModels.size() - snapshotKeepCount;
	    Collections.sort(snapshotModels, new Comparator<Model>() {
	        public int compare (final Model model1, final Model model2) {
	        	final long ts1 = model1.getSnapshotTimeStamp();
	        	final long ts2 = model2.getSnapshotTimeStamp();
	        	return Long.compare(ts1, ts2);
	        }
	    });
	    for (int i = 0; i < pruneCount; i++) {
	        final Model model = snapshotModels.get(i);
	        model.delete(new NullProgressMonitor());
	    }
	}
}
 
Example #17
Source File: BungeecordModuleManager.java    From BungeeChat2 with GNU General Public License v3.0 6 votes vote down vote up
public static List<BungeeChatModule> getLocalModules() {
  if (localModules == null) {
    localModules =
        Arrays.stream(BungeecordModuleManager.class.getDeclaredFields())
            .filter(field -> BungeeChatModule.class.isAssignableFrom(field.getType()))
            .map(
                field -> {
                  try {
                    return (BungeeChatModule) field.get(null);
                  } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();

                    return null;
                  }
                })
            .collect(Collectors.toList());
  }

  return localModules;
}
 
Example #18
Source File: ExplainOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Render axiom tree in indented Markdown using the provided renderer.
 *
 * @param tree indented collection of axioms
 * @param renderer renderer for displaying axioms and entities
 * @return
 */
private static String renderTree(Tree<OWLAxiom> tree, OWLObjectRenderer renderer) {
  StringBuilder builder = new StringBuilder();
  if (tree.isRoot()) {
    builder.append("## ");
    builder.append(renderer.render(tree.getUserObject()));
    builder.append(" ##");
    builder.append("\n");
  } else {
    String padding =
        tree.getPathToRoot().stream().skip(1).map(x -> "  ").collect(Collectors.joining());
    builder.append(padding);
    builder.append("- ");
    builder.append(renderer.render(tree.getUserObject()));
  }
  if (!tree.isLeaf()) builder.append("\n");
  String children =
      tree.getChildren()
          .stream()
          .map(child -> renderTree(child, renderer))
          .collect(Collectors.joining("\n"));
  builder.append(children);
  return builder.toString();
}
 
Example #19
Source File: BankService.java    From ifsc-rest-api with MIT License 6 votes vote down vote up
public ResponseEntity<GenericResponse<List<String>>> fuzzySearchBank(LikeBranchSearch likeBranchSearch) {
    GenericResponse<List<String>> response = new GenericResponse<>();
    if (mBankList != null && mBankList.length > 0) {
        List<ExtractedResult> levenshteinList = FuzzySearch.extractSorted(likeBranchSearch.getBankName(), Arrays.asList(mBankList), LEVENSHTEIN_CUTOFF);
        List<String> bankList = levenshteinList.stream().map(ExtractedResult::getString).collect(Collectors.toList());
        if (bankList.size() > 0) {
            response.setData(bankList);
            response.setStatus(STATUS_SUCCESS);
        } else {
            response.setStatus(STATUS_FAILED);
            response.setMessage("No bank found with name " + likeBranchSearch.getBankName());
        }

    } else {
        response.setStatus(STATUS_FAILED);
        response.setMessage("Something went wrong. Please try again");
    }
    return new ResponseEntity<>(response, HttpStatus.OK);
}
 
Example #20
Source File: GameBattleShip.java    From Kepler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Count the ships placed on the map.
 *
 * @param shipType the ship type (optional)
 * @param player the player (optional)
 * @return the count of the ships
 */
private int countShips(GameShipType shipType, Player player) {
    List<GameShip> gameShipType = null;

    if (shipType != null) {
        if (player != null) {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getShipType() == shipType && ship.getPlayer() == player).collect(Collectors.toList());
        } else {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getShipType() == shipType).collect(Collectors.toList());
        }
    } else {
        if (player != null) {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getPlayer() == player).collect(Collectors.toList());
        } else {
            gameShipType = new ArrayList<>(this.shipsPlaced.keySet());
        }
    }

    return gameShipType.size();
}
 
Example #21
Source File: AutogenPathDatasetBlob.java    From modeldb with Apache License 2.0 6 votes vote down vote up
public ai.verta.modeldb.versioning.PathDatasetBlob.Builder toProto() {
  ai.verta.modeldb.versioning.PathDatasetBlob.Builder builder =
      ai.verta.modeldb.versioning.PathDatasetBlob.newBuilder();
  {
    if (this.Components != null && !this.Components.equals(null) && !this.Components.isEmpty()) {
      Function<ai.verta.modeldb.versioning.PathDatasetBlob.Builder, Void> f =
          x -> {
            builder.addAllComponents(
                this.Components.stream()
                    .map(y -> y.toProto().build())
                    .collect(Collectors.toList()));
            return null;
          };
      f.apply(builder);
    }
  }
  return builder;
}
 
Example #22
Source File: RemoteActorSystems.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
public ActorSystem get(String actorSystemName) {
    List<RemoteActorSystemInstance> instances = remoteActorSystems.values().stream()
            .filter(remoteActorSystemInstance -> remoteActorSystemInstance.getName().equals(actorSystemName))
            .collect(Collectors.toList());
    if(!instances.isEmpty()) {
        if(instances.size() > 1) {
            // cannot determine which one to use,
            throw new IllegalArgumentException("Found multiple matching Remote ActorSystems, please use ActorSystems.get(clusterName, actorSystemName");
        } else {
            return instances.get(0);
        }
    } else {
        return null;
    }
}
 
Example #23
Source File: P2BrowseNodeGeneratorTest.java    From nexus-repository-p2 with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCompositeRepository() {
  Component component = createComponent(String.join(".", COMPONENT_NAME), null, COMPONENT_VERSION);
  Asset asset = createAsset(REMOTE_PREFIX + DIVIDER + FEATURES + DIVIDER + ASSET_NAME);

  List<String> paths = generator.computeAssetPaths(asset, component).stream().map(BrowsePaths::getBrowsePath).collect(
      Collectors.toList());
  List<String> expectedResult = new ArrayList<>();
  expectedResult.add(BASE_URL);
  expectedResult.addAll(COMPONENT_NAME);
  expectedResult.addAll(Arrays.asList(COMPONENT_VERSION, FEATURES, ASSET_NAME));
  Assert.assertEquals(expectedResult, paths);
}
 
Example #24
Source File: CachedTraversalEngine.java    From epcis with Apache License 2.0 5 votes vote down vote up
/**
 * Add in step to the traversal engine
 *
 * Path Enabled -> Greedy,
 * 
 * Path Disabled -> Lazy
 *
 * Pipeline: Stream<CachedChronoVertex> -> Stream<CachedChronoVertex> (flatMap)
 *
 * Path: Map<CachedChronoVertex, Set<CachedChronoVertex>>
 *
 * @param branchFactor
 *            the number of max adjacent vertices for each incoming vertex
 * @param labels
 *            the edge labels to traverse
 * @return the extended Stream
 */
public CachedTraversalEngine in(final BsonArray labels, final int branchFactor) {
	// Check Input element class
	checkInputElementClass(CachedChronoVertex.class);

	// Stream Update
	if (isPathEnabled) {
		// Get Sub-Path
		Map intermediate = (Map) stream.distinct().map(v -> {
			CachedChronoVertex cv = (CachedChronoVertex) v;
			return new AbstractMap.SimpleImmutableEntry(cv,
					cv.getChronoVertexSet(Direction.IN, labels, branchFactor));
		}).collect(Collectors.toMap(e -> ((Entry) e).getKey(), e -> ((Entry) e).getValue()));

		// Update Path
		updateTransformationPath(intermediate);

		// Make stream again
		stream = getStream(intermediate, isParallel);
	} else {
		stream = stream.flatMap(v -> {
			return ((CachedChronoVertex) v).getChronoVertexStream(Direction.IN, labels, branchFactor, isParallel);
		});
	}
	// Step Update
	final Class[] args = new Class[2];
	args[0] = BsonArray.class;
	args[1] = Integer.TYPE;
	final Step step = new Step(this.getClass().getName(), "in", args, labels, branchFactor);
	stepList.add(step);

	// Set Class
	elementClass = CachedChronoVertex.class;
	return this;
}
 
Example #25
Source File: FqdnExecutor.java    From oneops with Apache License 2.0 5 votes vote down vote up
private ProvisionedGslb provisionedGslb(CmsWorkOrderSimple wo, TorbitConfig torbitConfig, InfobloxConfig infobloxConfig, String logKey) {
  Context context = context(wo, infobloxConfig);
  List<String> aliases = getAliasesWithDefault(context, wo.getRfcCi().getCiAttributes()).stream()
      .collect(Collectors.toList());
  List<CloudARecord> cloudEntries = getCloudDnsEntry(context, wo.getCloud());
  return ProvisionedGslb.builder()
      .torbitConfig(torbitConfig)
      .infobloxConfig(infobloxConfig)
      .app(context.platform)
      .subdomain(context.subdomain)
      .cnames(aliases)
      .cloudARecords(cloudEntries)
      .logContextId(logKey)
      .build();
}
 
Example #26
Source File: UserDTOService.java    From celerio-angular-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the passed user to a DTO. The depth is used to control the
 * amount of association you want. It also prevents potential infinite serialization cycles.
 *
 * @param user
 * @param depth the depth of the serialization. A depth equals to 0, means no x-to-one association will be serialized.
 *              A depth equals to 1 means that xToOne associations will be serialized. 2 means, xToOne associations of
 *              xToOne associations will be serialized, etc.
 */
public UserDTO toDTO(User user, int depth) {
    if (user == null) {
        return null;
    }

    UserDTO dto = new UserDTO();

    dto.id = user.getId();
    dto.login = user.getLogin();
    dto.password = user.getPassword();
    dto.email = user.getEmail();
    dto.isEnabled = user.getIsEnabled();
    dto.civility = user.getCivility();
    dto.countryCode = user.getCountryCode();
    dto.firstName = user.getFirstName();
    dto.lastName = user.getLastName();
    dto.creationDate = user.getCreationDate();
    dto.creationAuthor = user.getCreationAuthor();
    dto.lastModificationDate = user.getLastModificationDate();
    dto.lastModificationAuthor = user.getLastModificationAuthor();
    dto.version = user.getVersion();
    if (depth-- > 0) {
        dto.passport = passportDTOService.toDTO(user.getPassport(), depth);
        final int fdepth = depth;
        dto.roles = user.getRoles().stream().map(role -> roleDTOService.toDTO(role, fdepth)).collect(Collectors.toList());
    }

    return dto;
}
 
Example #27
Source File: PlatformHistory.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public List<ApplicationOutput> buildApplicationOutputs() {
    Map<String, List<PlatformBuilder>> applicationPlatformsMap = platforms.stream()
            .filter(platform -> !platform.isDeleted)
            .map(PlatformTimestampedBuilders::getTimestampedBuilders)
            .map(PlatformHistory::getLastPlatformBuilder)
            .collect(Collectors.groupingBy(PlatformBuilder::getApplicationName));

    return applicationPlatformsMap.entrySet().stream()
            .map(entry -> buildApplicationOutput(entry.getKey(), entry.getValue(), false))
            .collect(Collectors.toList());
}
 
Example #28
Source File: MediationDisputeList.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static MediationDisputeList fromProto(protobuf.MediationDisputeList proto,
                                             CoreProtoResolver coreProtoResolver,
                                             Storage<MediationDisputeList> storage) {
    List<Dispute> list = proto.getDisputeList().stream()
            .map(disputeProto -> Dispute.fromProto(disputeProto, coreProtoResolver))
            .collect(Collectors.toList());
    list.forEach(e -> e.setStorage(storage));
    return new MediationDisputeList(storage, list);
}
 
Example #29
Source File: FindElements.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Map<String, String>> call() {
  List<WebElement> elements = getDriver().findElements(by);
  return elements.stream()
      .map(element -> ImmutableMap.of("ELEMENT", getKnownElements().add(element)))
      .collect(Collectors.toCollection(LinkedHashSet::new));
}
 
Example #30
Source File: IteratorErrorCodeTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void mappingIsUnique() {
    Set<Integer> uniqueEncoded = Arrays.stream(IteratorErrorCode.values())
            .map(IteratorErrorCode::getEncoded)
            .collect(Collectors.toSet());

    assertEquals("no duplicate encoded entries allowed", IteratorErrorCode.values().length, uniqueEncoded.size());
}