Java Code Examples for java.util.stream.Collectors

The following examples show how to use java.util.stream.Collectors. These examples are extracted from open source projects. 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
@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
@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 3
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 4
Source Project: baleen   Source File: ProperNounInformationCollector.java    License: 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 5
@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 Project: pravega   Source File: ExtendedS3StorageTest.java    License: 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 Project: cloudbreak   Source File: HueConfigProviderTest.java    License: 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 Project: uyuni   Source File: ActionChainManager.java    License: 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 Project: analysis-model   Source File: FileNameResolverTest.java    License: 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
@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 Project: DataflowTemplates   Source File: KafkaUnboundedReader.java    License: 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 Project: modeldb   Source File: AutogenPathDatasetBlob.java    License: 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 13
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 14
Source Project: Kepler   Source File: GameBattleShip.java    License: 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 15
Source Project: ifsc-rest-api   Source File: BankService.java    License: 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 16
/**
 * 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 17
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 Project: tlaplus   Source File: Model.java    License: 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 19
Source Project: symbol-sdk-java   Source File: BinarySerializationImpl.java    License: 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 20
Source Project: terracotta-platform   Source File: ManagementRegistry.java    License: 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 21
/**
 * 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 22
Source Project: selenium   Source File: TestFileLocator.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<Path> getExcludedFiles(final Path testDirectory) {
  String excludedFiles = getProperty(TEST_EXCLUDES_PROPERTY);
  if (excludedFiles == null) {
    return emptySet();
  }

  Iterable<String> splitExcludes = Splitter.on(',').omitEmptyStrings().split(excludedFiles);

  return StreamSupport.stream(splitExcludes.spliterator(), false)
      .map(testDirectory::resolve).collect(Collectors.toSet());
}
 
Example 23
Source Project: cubedb   Source File: CubeUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Map<String, Map<String, Map<String, Long>>> searchResultsToMap(
    Map<GroupedSearchResultRow, Long> in) {
  return in.entrySet()
      .stream()
      .collect(
          Collectors.groupingBy(
              e -> e.getKey().getFieldName(),
              Collectors.groupingBy(
                  e -> e.getKey().getFieldValue(),
                  Collectors.groupingBy(
                      e -> e.getKey().getMetricName(),
                      Collectors.summingLong(e -> e.getValue().longValue())))));
}
 
Example 24
Source Project: epcis   Source File: CachedTraversalEngine.java    License: 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 Project: hesperides   Source File: PlatformHistory.java    License: 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 26
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 27
Source Project: oneops   Source File: FqdnExecutor.java    License: 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 28
@Override
public List<BuildConfigurationAudited> findAllByIdOrderByRevDesc(Integer buildConfigurationId) {

    List<Object[]> result = AuditReaderFactory.get(entityManager)
            .createQuery()
            .forRevisionsOfEntity(BuildConfiguration.class, false, false)
            .add(AuditEntity.id().eq(buildConfigurationId))
            .addOrder(AuditEntity.revisionNumber().desc())
            .getResultList();

    return result.stream().map(o -> createAudited(o[0], o[1])).collect(Collectors.toList());
}
 
Example 29
Source Project: immutables   Source File: ReactorReader.java    License: Apache License 2.0 5 votes vote down vote up
public ReactorMapperTuple.DistinctLimitOffset select(Iterable<Projection<?>> projections) {
  Objects.requireNonNull(projections, "projections");
  Preconditions.checkArgument(!Iterables.isEmpty(projections), "empty projections");
  List<Expression> expressions = StreamSupport.stream(projections.spliterator(), false).map(Matchers::toExpression).collect(Collectors.toList());
  Query newQuery = this.query.addProjections(expressions);
  return new ReactorMappers.MapperTuple(newQuery, session);
}
 
Example 30
Source Project: Java-Coding-Problems   Source File: Strings.java    License: MIT License 5 votes vote down vote up
public static String removeCharacterV3(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return str.chars()
                .filter(c -> c != ch)
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());
    }