Java Code Examples for java.util.LinkedList#forEach()

The following examples show how to use java.util.LinkedList#forEach() . 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: DistkvAsyncSlistProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> put(
    String key, LinkedList<SlistEntity> list) {

  LinkedList<SlistProtocol.SlistEntity> listEntities = new LinkedList<>();
  list.forEach((v) -> {
    SlistProtocol.SlistEntity.Builder sortedListEntity =
        SlistProtocol.SlistEntity.newBuilder();
    sortedListEntity.setMember(v.getMember());
    sortedListEntity.setScore(v.getScore());
    listEntities.add(sortedListEntity.build());
  });

  SlistProtocol.SlistPutRequest slistPutRequest =
      SlistProtocol.SlistPutRequest.newBuilder().addAllList(listEntities).build();

  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.SLIST_PUT)
      .setRequest(Any.pack(slistPutRequest))
      .build();
  return call(request);
}
 
Example 2
Source File: NeuralCoordinator.java    From LSH_DeepLearning with Apache License 2.0 6 votes vote down vote up
public NeuralCoordinator(String model_title, String title, String dataset, NN_parameters params, List<NeuronLayer> layers, LinkedList<HiddenLayer> hiddenLayers, double L2, ICostFunction cf) throws IOException
{
    m_modelTitle = model_title;
    m_model_path = Util.DATAPATH + dataset + "/" + Util.MODEL + title + "_" + model_title;
    m_train_path = Util.DATAPATH + dataset + "/" + Util.TRAIN + title;
    m_test_path = Util.DATAPATH + dataset + "/" + Util.TEST + title;

    for(NeuronLayer layer : layers)
    {
        m_total_nodes += layer.m_layer_size;
    }

    m_params = params;
    m_networks = new ArrayList<>(Util.LAYER_THREADS);
    m_networks.add(new NeuralNetwork(params, layers, hiddenLayers, L2, cf));
    for(int idx = 1; idx < Util.LAYER_THREADS; ++idx)
    {
        LinkedList<HiddenLayer> hiddenLayers1 = new LinkedList<>();
        hiddenLayers.forEach(e -> hiddenLayers1.add(e.clone()));

        List<NeuronLayer> layers1 = new LinkedList<>();
        layers1.addAll(hiddenLayers1);
        layers1.add(layers.get(layers.size()-1).clone());
        m_networks.add(new NeuralNetwork(params, layers1, hiddenLayers1, L2, cf));
    }
}
 
Example 3
Source File: StorageManager.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private static void handleErrors ( final String message, final LinkedList<Exception> allErrors )
{
    if ( allErrors == null )
    {
        return;
    }

    if ( !allErrors.isEmpty () )
    {
        final RuntimeException e = new RuntimeException ( message, allErrors.poll () );

        // add remaining
        allErrors.forEach ( e::addSuppressed );

        throw e;
    }
}
 
Example 4
Source File: JPAMFieldDefinition.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private JPAMFieldDefinition(LinkedList<Attribute> intrinsicAttribute, Attribute managedAttribute) {
        if (intrinsicAttribute != null) {
            intrinsicAttribute.forEach((attr) -> {
                if (attr != null && attr.getOrignalObject() != null) {
                    this.intrinsicAttribute.add((Attribute) attr.getOrignalObject());
                } else {
                    this.intrinsicAttribute.add(attr);
                }
            });
        }
//       if(managedAttribute!=null){
        this.managedAttribute = managedAttribute.getOrignalObject() != null ? (Attribute) managedAttribute.getOrignalObject() : managedAttribute;
//       } else {
//           this.managedAttribute = null;
//       }
        this.inherited = false;
        this.intrinsicClass = null;
    }
 
Example 5
Source File: RunningRule.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private LinkedList<TraceLogMetric> transformValues(final LinkedList<Metrics> values) {
    LinkedList<TraceLogMetric> r = new LinkedList<>();
    values.forEach(m -> {
        if (m == null) {
            r.add(null);
            return;
        }
        switch (valueType) {
            case LONG:
                r.add(new TraceLogMetric(m.getTimeBucket(), new Number[] {((LongValueHolder) m).getValue()}));
                break;
            case INT:
                r.add(new TraceLogMetric(m.getTimeBucket(), new Number[] {((IntValueHolder) m).getValue()}));
                break;
            case DOUBLE:
                r.add(new TraceLogMetric(m.getTimeBucket(), new Number[] {((DoubleValueHolder) m).getValue()}));
                break;
            case MULTI_INTS:
                int[] iArr = ((MultiIntValuesHolder) m).getValues();
                r.add(new TraceLogMetric(m.getTimeBucket(), Arrays.stream(iArr).boxed().toArray(Number[]::new)));
                break;
        }
    });
    return r;
}
 
Example 6
Source File: CleanerConfig.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public CleanerConfig verify() throws RuntimeException {

        final LinkedList<RuntimeException> result = new LinkedList<>();

        if (getTenantId() == null) {
            result.add(missingField("tenantId"));
        }
        if (this.infinispan.getHost().isBlank()) {
            result.add(missingField("infinispan.host"));
        }
        if (this.infinispan.getPort() <= 0) {
            result.add(missingField("infinispan.port"));
        }
        if (this.infinispan.getCacheNames().getDevices().isBlank()) {
            result.add(missingField("infinispan.devicesCacheName"));
        }
        if (this.infinispan.getCacheNames().getDeviceConnections().isBlank()) {
            result.add(missingField("infinispan.deviceStatesCacheName"));
        }

        // create result

        final RuntimeException e = result.pollFirst();
        if (e != null) {
            result.forEach(e::addSuppressed);
            throw e;
        }

        return this;
    }
 
Example 7
Source File: ProfileStackNode.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * build GraphQL result, calculate duration and count data using parallels
 */
public ProfileStackTree buildAnalyzeResult() {
    // all nodes add to single-level list (such as flat), work for parallel calculating
    LinkedList<Pair<ProfileStackElement, ProfileStackNode>> nodeMapping = new LinkedList<>();
    int idGenerator = 1;

    ProfileStackElement root = buildElement(idGenerator++);
    nodeMapping.add(new Pair<>(root, this));

    // same with combine logic
    LinkedList<Pair<ProfileStackElement, ProfileStackNode>> stack = new LinkedList<>();
    stack.add(new Pair<>(root, this));
    while (!stack.isEmpty()) {
        Pair<ProfileStackElement, ProfileStackNode> mergingPair = stack.pop();
        ProfileStackElement respElement = mergingPair.key;

        // generate children node and add to stack and all node mapping
        for (ProfileStackNode children : mergingPair.value.children) {
            ProfileStackElement element = children.buildElement(idGenerator++);
            element.setParentId(respElement.getId());

            Pair<ProfileStackElement, ProfileStackNode> pair = new Pair<>(element, children);
            stack.add(pair);
            nodeMapping.add(pair);
        }
    }

    // calculate durations
    nodeMapping.parallelStream().forEach(t -> t.value.calculateDuration(t.key));
    nodeMapping.parallelStream().forEach(t -> t.value.calculateDurationExcludeChild(t.key));

    ProfileStackTree tree = new ProfileStackTree();
    nodeMapping.forEach(n -> tree.getElements().add(n.key));

    return tree;
}
 
Example 8
Source File: KcSamlSignedBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Document removeSignatureTag(Document orig, final Set<QName> qNames) throws DOMException {
    NodeList sigElements = orig.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    LinkedList<Node> nodesToRemove = new LinkedList<>();
    for (int i = 0; i < sigElements.getLength(); i ++) {
        Node n = sigElements.item(i);
        final Node p = n.getParentNode();
        QName q = new QName(p.getNamespaceURI(), p.getLocalName());
        if (qNames.contains(q)) {
            nodesToRemove.add(n);
        }
    }
    nodesToRemove.forEach(n -> n.getParentNode().removeChild(n));
    return orig;
}
 
Example 9
Source File: JsonNodeInfo.java    From mica with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 获取 mongo db的 key 语法
 *
 * @return mongo db的 key 语法
 */
private static String getNodeKeys(LinkedList<String> elements) {
	StringJoiner nodeKeysJoiner = new StringJoiner(".");
	elements.forEach(nodeKeysJoiner::add);
	return nodeKeysJoiner.toString();
}
 
Example 10
Source File: JsonNodeInfo.java    From mica with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 获取 json path 语法路径
 *
 * @return jsonPath 路径
 */
private static String getNodePath(LinkedList<String> elements) {
	StringJoiner nodePathJoiner = new StringJoiner("/", "/", "");
	elements.forEach(nodePathJoiner::add);
	return nodePathJoiner.toString();
}
 
Example 11
Source File: OptionsParser.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
@Override
public Options parse(String[] args) {
	OptionParser parser = new OptionParser();
	parser.allowsUnrecognizedOptions();
	log.info("Got following args <{}>", args);
	try {
		ArgumentAcceptingOptionSpec<Boolean> metaReleaseOpt = parser
				.acceptsAll(Arrays.asList("x", "meta-release"),
						"Do you want to do the meta release?")
				.withRequiredArg().ofType(Boolean.class).defaultsTo(false);
		ArgumentAcceptingOptionSpec<Boolean> fullReleaseOpt = parser
				.acceptsAll(Arrays.asList("f", "full-release"),
						"Do you want to do the full release of a single project?")
				.withOptionalArg().ofType(Boolean.class).defaultsTo(false);
		ArgumentAcceptingOptionSpec<Boolean> interactiveOpt = parser.acceptsAll(
				Arrays.asList("i", "interactive"),
				"Do you want to set the properties from the command line of a single project?")
				.withRequiredArg().ofType(Boolean.class).defaultsTo(true);
		ArgumentAcceptingOptionSpec<Boolean> dryRunOpt = parser.acceptsAll(
				Arrays.asList("dr", "dry-run"),
				"Do you want to do the release / meta release with build and install projects locally only?")
				.withRequiredArg().ofType(Boolean.class).defaultsTo(false);
		LinkedList<ReleaserTask> singleProjectReleaseTasks = this.allTasks.stream()
				.filter(releaserTask -> releaserTask instanceof SingleProjectReleaserTask)
				.collect(Collectors.toCollection(LinkedList::new));
		singleProjectReleaseTasks.forEach(task -> parser
				.acceptsAll(Arrays.asList(task.shortName(), task.name()),
						task.description())
				.withOptionalArg());
		ArgumentAcceptingOptionSpec<String> startFromOpt = parser.acceptsAll(
				Arrays.asList("a", "start-from"),
				"Starts all release task starting "
						+ "from the given task. Requires passing the task name (either one letter or the full name)")
				.withRequiredArg().ofType(String.class);
		ArgumentAcceptingOptionSpec<String> taskNamesOpt = parser
				.acceptsAll(Arrays.asList("tn", "task-names"),
						"Starts all release task for the given task names")
				.withRequiredArg().ofType(String.class).defaultsTo("");
		ArgumentAcceptingOptionSpec<String> rangeOpt = parser.acceptsAll(
				Arrays.asList("r", "range"),
				"Runs release tasks from the given range. Requires passing "
						+ "the task names with a hyphen. The first task is inclusive, "
						+ "the second inclusive. E.g. 's-m' would mean running 'snapshot', "
						+ "'push' and 'milestone' tasks")
				.withRequiredArg().ofType(String.class);
		parser.acceptsAll(Arrays.asList("h", "help")).withOptionalArg();
		OptionSet options = parser.parse(args);
		if (options.has("h")) {
			printHelpMessage(parser);
			SpringApplication.exit(this.context, () -> 0);
			System.exit(0);
		}
		Boolean metaRelease = options.valueOf(metaReleaseOpt);
		Boolean interactive = options.valueOf(interactiveOpt);
		Boolean dryRun = options.valueOf(dryRunOpt);
		Boolean fullRelease = options.has(fullReleaseOpt);
		List<String> providedTaskNames = StringUtils.hasText(options
				.valueOf(taskNamesOpt)) ? Arrays.asList(
						removeQuotingChars(options.valueOf(taskNamesOpt)).split(","))
						: new ArrayList<>();
		providedTaskNames = providedTaskNames.stream().map(this::removeQuotingChars)
				.collect(Collectors.toList());
		log.info("Passed tasks {} from command line", providedTaskNames);
		List<String> allTaskNames = singleProjectReleaseTasks.stream()
				.map(ReleaserTask::name).collect(Collectors.toList());
		List<String> tasksFromOptions = singleProjectReleaseTasks.stream().filter(
				task -> options.has(task.name()) || options.has(task.shortName()))
				.map(ReleaserTask::name).collect(Collectors.toList());
		if (providedTaskNames.isEmpty()) {
			providedTaskNames.addAll(tasksFromOptions.isEmpty() && !metaRelease
					? allTaskNames : tasksFromOptions);
		}
		List<String> taskNames = filterProvidedTaskNames(providedTaskNames,
				allTaskNames, metaRelease);
		String startFrom = options.valueOf(startFromOpt);
		String range = options.valueOf(rangeOpt);
		Options buildOptions = new OptionsBuilder().metaRelease(metaRelease)
				.fullRelease(fullRelease).interactive(interactive).dryRun(dryRun)
				.taskNames(taskNames).startFrom(startFrom).range(range).options();
		log.info(
				"\n\nWill use the following options to process the project\n\n{}\n\n",
				buildOptions);
		return buildOptions;
	}
	catch (Exception e) {
		printErrorMessage(e, parser);
		throw e;
	}
}