Java Code Examples for java.util.Queue.addAll()

The following are Jave code examples for showing how to use addAll() of the java.util.Queue class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hadoop   File: KMSClientProvider.java   Source Code and License Vote up 6 votes
@Override
public void fillQueueForKey(String keyName,
    Queue<EncryptedKeyVersion> keyQueue, int numEKVs) throws IOException {
  checkNotNull(keyName, "keyName");
  Map<String, String> params = new HashMap<String, String>();
  params.put(KMSRESTConstants.EEK_OP, KMSRESTConstants.EEK_GENERATE);
  params.put(KMSRESTConstants.EEK_NUM_KEYS, "" + numEKVs);
  URL url = createURL(KMSRESTConstants.KEY_RESOURCE, keyName,
      KMSRESTConstants.EEK_SUB_RESOURCE, params);
  HttpURLConnection conn = createConnection(url, HTTP_GET);
  conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
  List response = call(conn, null,
      HttpURLConnection.HTTP_OK, List.class);
  List<EncryptedKeyVersion> ekvs =
      parseJSONEncKeyVersion(keyName, response);
  keyQueue.addAll(ekvs);
}
 
Example 2
Project: NetCom2   File: QueuedReceivePipeline.java   Source Code and License Vote up 6 votes
@Override
public ReceivePipelineCondition<T> addFirst(final OnReceiveTriple<T> pipelineService) {
	final PipelineReceiver<T> pipelineReceiver = new PipelineReceiver<>(pipelineService);

	if (isClosed()) {
		falseAdd(pipelineService);
	} else {
		final Queue<PipelineReceiver<T>> newCore = new LinkedList<>();
		newCore.add(pipelineReceiver);
		synchronized (core) {
			newCore.addAll(core);
			core.clear();
			core.addAll(newCore);
		}
		pipelineService.onRegistration();
	}

	return new ReceivePipelineConditionImpl<>(pipelineReceiver);
}
 
Example 3
Project: Pogamut3   File: SimpleRoleCompetenceWidget.java   Source Code and License Vote up 6 votes
/**
 * Take a competence node that is connected to the triggered action
 * that is associated with this widget and create children so it looks
 * like this widget is root of competence.
 *
 * In most widgets, one widget is representing one node.
 * This one is representing competence and this function is regenerating competence structure to widgets.
 */
private void createCh() {
    Queue<PoshElement> fringe = new LinkedList<PoshElement>();
    fringe.add(this.compNode);

    while (!fringe.isEmpty()) {
        PoshElement head = fringe.poll();

        Set<PoshElementListener> listeners = head.getElementListeners();

        for (PoshElementListener listener : listeners) {
            if (listener instanceof PoshWidget) {
                PoshWidget widget = (PoshWidget) listener;
                if (widget.isAncestor(this)) {
                    for (PoshElement child : head.getChildDataNodes()) {
                        widget.nodeChanged(PoshTreeEvent.NEW_CHILD_NODE, child);
                    }
                }
            }
        }

        fringe.addAll(head.getChildDataNodes());
    }

}
 
Example 4
Project: hadoop-oss   File: KMSClientProvider.java   Source Code and License Vote up 6 votes
@Override
public void fillQueueForKey(String keyName,
    Queue<EncryptedKeyVersion> keyQueue, int numEKVs) throws IOException {
  checkNotNull(keyName, "keyName");
  Map<String, String> params = new HashMap<String, String>();
  params.put(KMSRESTConstants.EEK_OP, KMSRESTConstants.EEK_GENERATE);
  params.put(KMSRESTConstants.EEK_NUM_KEYS, "" + numEKVs);
  URL url = createURL(KMSRESTConstants.KEY_RESOURCE, keyName,
      KMSRESTConstants.EEK_SUB_RESOURCE, params);
  HttpURLConnection conn = createConnection(url, HTTP_GET);
  conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
  List response = call(conn, null,
      HttpURLConnection.HTTP_OK, List.class);
  List<EncryptedKeyVersion> ekvs =
      parseJSONEncKeyVersion(keyName, response);
  keyQueue.addAll(ekvs);
}
 
Example 5
Project: advent-of-code-2017   File: Day12.java   Source Code and License Vote up 6 votes
private static List<Integer> createConnectedComponent(HashMap<Integer, List<Integer>> graph, int root) {
	
	Queue<Integer> q = new ArrayDeque<>(); // next nodes to visit
	List<Integer> visited = new ArrayList<>(); // connected component so far
	q.add(root); // init queue

	while (!q.isEmpty()) {
		Integer poll = q.poll(); // get next node
		if (!visited.contains(poll)) { // if it's not already visited
			visited.add(poll); // visit it
			q.addAll(graph.get(poll)); // and put its neighbourhood in the queue
		}
	}
	visited.forEach(v -> graph.remove(v)); // removes the connected component from the graph
	return visited;
	
}
 
Example 6
Project: Java-9-Programming-Blueprints   File: DateCalcExpressionParser.java   Source Code and License Vote up 6 votes
public Queue<Token> parse(String text) {
    final Queue<Token> tokens = new ArrayDeque<>();

    if (text != null) {
        text = text.trim();
        if (!text.isEmpty()) {
            boolean matchFound = false;
            for (InfoWrapper iw : infos) {
                final Matcher matcher = iw.pattern.matcher(text);
                if (matcher.find()) {
                    matchFound = true;
                    String match = matcher.group().trim();
                    tokens.add(iw.info.getToken(match));
                    tokens.addAll(parse(text.substring(match.length())));
                    break;
                }
            }
            if (!matchFound) {
                throw new DateCalcException("Could not parse the expression: " + text);
            }
        }
    }

    return tokens;
}
 
Example 7
Project: Nird2   File: ValidationManagerImpl.java   Source Code and License Vote up 6 votes
@DatabaseExecutor
private void deliverOutstandingMessages(ClientId c) {
	try {
		Queue<MessageId> pending = new LinkedList<MessageId>();
		Transaction txn = db.startTransaction(true);
		try {
			pending.addAll(db.getPendingMessages(txn, c));
			db.commitTransaction(txn);
		} finally {
			db.endTransaction(txn);
		}
		deliverNextPendingMessageAsync(pending);
	} catch (DbException e) {
		if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
	}
}
 
Example 8
Project: openjdk-jdk10   File: ToolKit.java   Source Code and License Vote up 6 votes
@Override
public void gatherProcessInfo(HtmlSection section, long pid) {
    Queue<Long> pids = new LinkedList<>();
    pids.add(pid);
    for (Long p = pids.poll(); p != null; p = pids.poll()) {
        HtmlSection pidSection = section.createChildren("" + p);
        for (ActionSet set : actions) {
            set.gatherProcessInfo(pidSection, p);
        }
        List<Long> children = helper.getChildren(pidSection, p);
        if (!children.isEmpty()) {
            HtmlSection s = pidSection.createChildren("children");
            for (Long c : children) {
                s.link(section, c.toString(), c.toString());
            }
            pids.addAll(children);
        }
    }
}
 
Example 9
Project: L2J-Global   File: L2Character.java   Source Code and License Vote up 5 votes
@Override
public Queue<AbstractEventListener> getListeners(EventType type)
{
	final Queue<AbstractEventListener> objectListenres = super.getListeners(type);
	final Queue<AbstractEventListener> templateListeners = getTemplate().getListeners(type);
	final Queue<AbstractEventListener> globalListeners = isNpc() && !isMonster() ? Containers.Npcs().getListeners(type) : isMonster() ? Containers.Monsters().getListeners(type) : isPlayer() ? Containers.Players().getListeners(type) : EmptyQueue.emptyQueue();
	
	// Attempt to do not create collection
	if (objectListenres.isEmpty() && templateListeners.isEmpty() && globalListeners.isEmpty())
	{
		return EmptyQueue.emptyQueue();
	}
	else if (!objectListenres.isEmpty() && templateListeners.isEmpty() && globalListeners.isEmpty())
	{
		return objectListenres;
	}
	else if (!templateListeners.isEmpty() && objectListenres.isEmpty() && globalListeners.isEmpty())
	{
		return templateListeners;
	}
	else if (!globalListeners.isEmpty() && objectListenres.isEmpty() && templateListeners.isEmpty())
	{
		return globalListeners;
	}
	
	final Queue<AbstractEventListener> both = new LinkedBlockingDeque<>(objectListenres.size() + templateListeners.size() + globalListeners.size());
	both.addAll(objectListenres);
	both.addAll(templateListeners);
	both.addAll(globalListeners);
	return both;
}
 
Example 10
Project: Pogamut3   File: SimpleRoleActionPatternWidget.java   Source Code and License Vote up 5 votes
/**
 * Create children of AP. In most widgets, one widget is representing one
 * node. This one is representing AP and this function is regenerating AP
 * structure to widgets.
 */
private void createCh() {
    Queue<PoshWidget<? extends PoshElement>> fringe = new LinkedList<PoshWidget<? extends PoshElement>>(createWidgetChildren(this, apNode));

    while (!fringe.isEmpty()) {
        PoshWidget<? extends PoshElement> headWidget = fringe.poll();
        PoshElement headDataNode = headWidget.getDataNode();

        if (!(headDataNode instanceof TriggeredAction)) {
            fringe.addAll(createWidgetChildren(headWidget, headDataNode));
        }
    }
}
 
Example 11
Project: hadoop-oss   File: EagerKeyGeneratorKeyProviderCryptoExtension.java   Source Code and License Vote up 5 votes
@Override
public void fillQueueForKey(String keyName,
    Queue<EncryptedKeyVersion> keyQueue, int numKeys) throws IOException {
  List<EncryptedKeyVersion> retEdeks =
      new LinkedList<EncryptedKeyVersion>();
  for (int i = 0; i < numKeys; i++) {
    try {
      retEdeks.add(keyProviderCryptoExtension.generateEncryptedKey(
          keyName));
    } catch (GeneralSecurityException e) {
      throw new IOException(e);
    }
  }
  keyQueue.addAll(retEdeks);
}
 
Example 12
Project: AdvancedDataProfilingSeminar   File: IndGraph.java   Source Code and License Vote up 5 votes
private ImmutableSet<ColumnIdentifier> collectNodes(
        ColumnIdentifier node, int nodeIndex,Function<ColumnIdentifier, Set<ColumnIdentifier>> getSuccessor) {
    Set<ColumnIdentifier> results = new HashSet<>();
    Queue<ColumnIdentifier> queue = new LinkedList<>();
    queue.add(node);
    while (!queue.isEmpty()) {
        ColumnIdentifier nextNode = queue.remove();
        ImmutableSet<ColumnIdentifier> nodes = getSuccessor.apply(nextNode).stream()
                .filter(column -> getCandidateIndex(column) > nodeIndex)
                .collect(toImmutableSet());
        queue.addAll(Sets.difference(nodes, results));
        results.addAll(nodes);
    }
    return ImmutableSet.copyOf(results);
}
 
Example 13
Project: OpenJSharp   File: PolicyModelTranslator.java   Source Code and License Vote up 5 votes
/**
 * Expands content of 'EXACTLY_ONE' node. Direct 'EXACTLY_ONE' child nodes are dissolved in the process.
 */
private Collection<ModelNode> expandsExactlyOneContent(final Collection<ModelNode> content) throws PolicyException {
    final Collection<ModelNode> result = new LinkedList<ModelNode>();

    final Queue<ModelNode> eoContentQueue = new LinkedList<ModelNode>(content);
    ModelNode node;
    while ((node = eoContentQueue.poll()) != null) {
        // dissolving direct 'EXACTLY_ONE' child nodes
        switch (node.getType()) {
            case POLICY :
            case ALL :
            case ASSERTION :
                result.add(node);
                break;
            case POLICY_REFERENCE :
                result.add(getReferencedModelRootNode(node));
                break;
            case EXACTLY_ONE :
                eoContentQueue.addAll(node.getChildren());
                break;
            default :
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0001_UNSUPPORTED_MODEL_NODE_TYPE(node.getType())));
        }
    }

    return result;
}
 
Example 14
Project: openjdk-jdk10   File: PolicyModelTranslator.java   Source Code and License Vote up 5 votes
/**
 * Decomposes the unprocessed alternative content into two different collections:
 * <p/>
 * Content of 'EXACTLY_ONE' child nodes is expanded and placed in one list and
 * 'ASSERTION' nodes are placed into other list. Direct 'ALL' and 'POLICY' child nodes are 'dissolved' in the process.
 *
 * Method reuses precreated ContentDecomposition object, which is reset before reuse.
 */
private void decompose(final Collection<ModelNode> content, final ContentDecomposition decomposition) throws PolicyException {
    decomposition.reset();

    final Queue<ModelNode> allContentQueue = new LinkedList<ModelNode>(content);
    ModelNode node;
    while ((node = allContentQueue.poll()) != null) {
        // dissolving direct 'POLICY', 'POLICY_REFERENCE' and 'ALL' child nodes
        switch (node.getType()) {
            case POLICY :
            case ALL :
                allContentQueue.addAll(node.getChildren());
                break;
            case POLICY_REFERENCE :
                allContentQueue.addAll(getReferencedModelRootNode(node).getChildren());
                break;
            case EXACTLY_ONE :
                decomposition.exactlyOneContents.add(expandsExactlyOneContent(node.getChildren()));
                break;
            case ASSERTION :
                decomposition.assertions.add(node);
                break;
            default :
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0007_UNEXPECTED_MODEL_NODE_TYPE_FOUND(node.getType())));
        }
    }
}
 
Example 15
Project: Photato   File: PhotatoFilesManager.java   Source Code and License Vote up 5 votes
public List<PhotatoFolder> searchFoldersInFolder(String folder, String searchQuery) {
    // Search for a folder with the correct name. This is just a recursive exploration since we suppose the number of folders will be low enough and thus we would be able to "bruteforce" it
    List<String> searchQuerySplit = SearchQueryHelper.getSplittedTerms(searchQuery);
    List<PhotatoFolder> result = new ArrayList<>();

    if (!searchQuerySplit.isEmpty()) {
        PhotatoFolder currentFolder = isVirtualFolder(folder) ? this.albumsManager.getCurrentFolder(folder) : this.getCurrentFolder(this.rootFolder.fsPath.resolve(folder));

        Queue<PhotatoFolder> queue = new LinkedList<>();
        queue.add(currentFolder);

        while (!queue.isEmpty()) {
            currentFolder = queue.remove();
            queue.addAll(currentFolder.subFolders.values());

            if (!currentFolder.isEmpty()) {
                List<String> currentFolderCleanedFilename = SearchQueryHelper.getSplittedTerms(currentFolder.filename);
                boolean ok = searchQuerySplit.stream().allMatch((s) -> (currentFolderCleanedFilename.stream().anyMatch((String t) -> (prefixOnlyMode && t.startsWith(s)) || (!prefixOnlyMode && t.contains(s)))));

                if (ok) {
                    result.add(currentFolder);
                }
            }
        }
    }

    return result;
}
 
Example 16
Project: QDrill   File: WorkspaceSchemaFactory.java   Source Code and License Vote up 5 votes
/**
 * Check if the table contains homogenenous files that can be read by Drill. Eg: parquet, json csv etc.
 * However if it contains more than one of these formats or a totally different file format that Drill cannot
 * understand then we will raise an exception.
 * @param tableName - name of the table to be checked for homogeneous property
 * @return
 * @throws IOException
 */
private boolean isHomogeneous(String tableName) throws IOException {
  FileSelection fileSelection = FileSelection.create(fs, config.getLocation(), tableName);

  if (fileSelection == null) {
    throw UserException
        .validationError()
        .message(String.format("Table [%s] not found", tableName))
        .build(logger);
  }

  FormatMatcher matcher = null;
  Queue<FileStatus> listOfFiles = new LinkedList<>();
  listOfFiles.addAll(fileSelection.getFileStatusList(fs));

  while (!listOfFiles.isEmpty()) {
    FileStatus currentFile = listOfFiles.poll();
    if (currentFile.isDirectory()) {
      listOfFiles.addAll(fs.list(true, currentFile.getPath()));
    } else {
      if (matcher != null) {
        if (!matcher.isFileReadable(fs, currentFile)) {
          return false;
        }
      } else {
        matcher = findMatcher(currentFile);
        // Did not match any of the file patterns, exit
        if (matcher == null) {
          return false;
        }
      }
    }
  }
  return true;
}
 
Example 17
Project: openjdk-jdk10   File: PolicyModelTranslator.java   Source Code and License Vote up 5 votes
/**
 * Expands content of 'EXACTLY_ONE' node. Direct 'EXACTLY_ONE' child nodes are dissolved in the process.
 */
private Collection<ModelNode> expandsExactlyOneContent(final Collection<ModelNode> content) throws PolicyException {
    final Collection<ModelNode> result = new LinkedList<ModelNode>();

    final Queue<ModelNode> eoContentQueue = new LinkedList<ModelNode>(content);
    ModelNode node;
    while ((node = eoContentQueue.poll()) != null) {
        // dissolving direct 'EXACTLY_ONE' child nodes
        switch (node.getType()) {
            case POLICY :
            case ALL :
            case ASSERTION :
                result.add(node);
                break;
            case POLICY_REFERENCE :
                result.add(getReferencedModelRootNode(node));
                break;
            case EXACTLY_ONE :
                eoContentQueue.addAll(node.getChildren());
                break;
            default :
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0001_UNSUPPORTED_MODEL_NODE_TYPE(node.getType())));
        }
    }

    return result;
}
 
Example 18
Project: incubator-netbeans   File: ProjectConvertorFactory.java   Source Code and License Vote up 4 votes
@Override
@NonNull
public DynamicLookup getLookup() {
    DynamicLookup dynLkp = underConstruction.get();
    if (dynLkp != null) {
        return dynLkp;
    }
    synchronized (this) {
        dynLkp = projectLkp;
    }
    if (dynLkp != null) {
        return  dynLkp;
    }
    dynLkp = new DynamicLookup(Lookups.singleton(this));
    try {
        underConstruction.set(dynLkp);
        final Lookup preLkp = Lookups.fixed(new OpenHook(), this);
        final Lookup convertorLkp = this.result.getLookup();
        if (convertorLkp == null) {
            throw new IllegalStateException(String.format(
                "Convertor: %s returned null lookup.",  //NOI18N
                this.result));
        }
        final Queue<Object> postServices = new ArrayDeque<>();
        for (ProjectConvertorServiceFactory f : services.allInstances()) {
            postServices.addAll(f.createServices(this, result));
        }
        final Lookup postLkp = Lookups.fixed(postServices.toArray());
        dynLkp.setBaseLookups(preLkp, convertorLkp, postLkp);
        synchronized (this) {
            if (projectLkp == null) {
                projectLkp = dynLkp;
            } else {
                dynLkp = projectLkp;
            }
        }
        return dynLkp;
    } finally {
        underConstruction.remove();
    }
}
 
Example 19
Project: openjdk-jdk10   File: PolicyIntersector.java   Source Code and License Vote up 4 votes
/**
 * Performs intersection on the input collection of policies and returns the resulting (intersected) policy. If input policy
 * collection contains only a single policy instance, no intersection is performed and the instance is directly returned
 * as a method call result.
 *
 * @param policies collection of policies to be intersected. Must not be {@code null} nor empty, otherwise exception is thrown.
 * @return intersected policy as a result of perfromed policy intersection. A {@code null} value is never returned.
 *
 * @throws IllegalArgumentException in case {@code policies} argument is either {@code null} or empty collection.
 */
public Policy intersect(final Policy... policies) {
    if (policies == null || policies.length == 0) {
        throw LOGGER.logSevereException(new IllegalArgumentException(LocalizationMessages.WSP_0056_NEITHER_NULL_NOR_EMPTY_POLICY_COLLECTION_EXPECTED()));
    } else if (policies.length == 1) {
        return policies[0];
    }

    // check for "null" and "empty" policy: if such policy is found return "null" policy,
    // or if all policies are "empty", return "empty" policy
    boolean found = false;
    boolean allPoliciesEmpty = true;
    NamespaceVersion latestVersion = null;
    for (Policy tested : policies) {
        if (tested.isEmpty()) {
            found = true;
        } else {
            if (tested.isNull()) {
                found = true;
            }
            allPoliciesEmpty = false;
        }
        if (latestVersion == null) {
            latestVersion = tested.getNamespaceVersion();
        } else if (latestVersion.compareTo(tested.getNamespaceVersion()) < 0) {
            latestVersion = tested.getNamespaceVersion();
        }

        if (found && !allPoliciesEmpty) {
            return Policy.createNullPolicy(latestVersion, null, null);
        }
    }
    latestVersion = (latestVersion != null) ? latestVersion : NamespaceVersion.getLatestVersion();
    if (allPoliciesEmpty) {
        return Policy.createEmptyPolicy(latestVersion, null, null);
    }

    // simple tests didn't lead to final answer => let's performe some intersecting ;)
    final List<AssertionSet> finalAlternatives = new LinkedList<AssertionSet>(policies[0].getContent());
    final Queue<AssertionSet> testedAlternatives = new LinkedList<AssertionSet>();
    final List<AssertionSet> alternativesToMerge = new ArrayList<AssertionSet>(2);
    for (int i = 1; i < policies.length; i++) {
        final Collection<AssertionSet> currentAlternatives = policies[i].getContent();

        testedAlternatives.clear();
        testedAlternatives.addAll(finalAlternatives);
        finalAlternatives.clear();

        AssertionSet testedAlternative;
        while ((testedAlternative = testedAlternatives.poll()) != null) {
            for (AssertionSet currentAlternative : currentAlternatives) {
                if (testedAlternative.isCompatibleWith(currentAlternative, this.mode)) {
                    alternativesToMerge.add(testedAlternative);
                    alternativesToMerge.add(currentAlternative);
                    finalAlternatives.add(AssertionSet.createMergedAssertionSet(alternativesToMerge));
                    alternativesToMerge.clear();
                }
            }
        }
    }

    return Policy.createPolicy(latestVersion, null, null, finalAlternatives);
}
 
Example 20
Project: Learn4J   File: DBSCANClusterer.java   Source Code and License Vote up 4 votes
@Override
public Dataset[] cluster(Dataset set) {
	int c = 0;//cluster counter
	Map<double[],Integer> categories = new HashMap<>();
	
	for(double[] point : set.getContent()){
		if(categories.containsKey(point))continue;
		Set<double[]> neighbors = findNeighbors(set, point);
		if(neighbors.size() < config.getMinDensity()){
			categories.put(point, 0);//label 0 is noise
			continue;
		}
		c++;//next cluster
		categories.put(point, c);
		
		neighbors.remove(point);//remove the point

		//we are using a queue because we can't modify a list while looping through it
		Queue<double[]> queue = new LinkedBlockingQueue<>(neighbors);
		while(!queue.isEmpty()){
			double[] n = queue.poll();
			if(categories.containsKey(n) && categories.get(n) == 0)categories.put(n, c);
			if(categories.containsKey(n))continue;
			categories.put(n, c);
			
			Set<double[]> newNeighbors = findNeighbors(set, n);
			
			if(newNeighbors.size() >= config.getMinDensity())queue.addAll(newNeighbors);
		}
	}
	
	
	//create the dataset
	Dataset[] result = new Dataset[c+1];
	for (int i = 0; i < result.length; i++) {
		result[i] = new Dataset();
	}
	for(Entry<double[],Integer> entry : categories.entrySet()){
		result[entry.getValue()].addEntry(entry.getKey());
		
	}
	return result;
}