List of usage examples for java.util Queue isEmpty
boolean isEmpty();
From source file:org.commonjava.maven.ext.manip.rest.DefaultVersionTranslator.java
/** * Translate the versions./*from w w w . ja v a 2 s. com*/ * There may be a lot of them, possibly causing timeouts or other issues. * This is mitigated by splitting them into smaller chunks when an error occurs and retrying. */ public Map<ProjectVersionRef, String> translateVersions(List<ProjectVersionRef> projects) { final Map<ProjectVersionRef, String> result = new HashMap<>(); final Queue<Task> queue = new ArrayDeque<>(); queue.add(new Task(pvrm, projects, endpointUrl)); while (!queue.isEmpty()) { Task task = queue.remove(); task.executeTranslate(); if (task.isSuccess()) { result.putAll(task.getResult()); } else { if (task.canSplit()) { if (task.getStatus() < 0) { logger.debug("Caught exception calling server with message {}", task.getErrorMessage()); } else { logger.debug("Did not get status {} but received {}", SC_OK, task.getStatus()); } List<Task> tasks = task.split(); logger.warn( "Failed to translate versions for task @{}, splitting and retrying. Chunk size was: {} and new chunk size {} in {} segments.", task.hashCode(), task.getChunkSize(), tasks.get(0).getChunkSize(), tasks.size()); queue.addAll(tasks); } else { logger.debug("Cannot split and retry anymore."); if (task.getStatus() > 0) { throw new RestException("Received response status " + task.getStatus() + " with message: " + task.getErrorMessage()); } else { throw new RestException("Received response status " + task.getStatus() + " with message " + task.getErrorMessage()); } } } } return result; }
From source file:org.rhq.plugins.cassandra.itest.DiscoveryAndConfigurationTest.java
private Set<Resource> findResourcesForTest(Resource parent, Set<String> ignoredResourceTypes, Set<String> ignoredResourceNames) { Set<Resource> foundResources = new HashSet<Resource>(); Queue<Resource> discoveryQueue = new LinkedList<Resource>(); discoveryQueue.add(parent);//from w w w.jav a 2 s . c o m while (!discoveryQueue.isEmpty()) { Resource currentResource = discoveryQueue.poll(); if (ignoredResourceTypes.contains(currentResource.getResourceType().getName()) || ignoredResourceNames.contains(currentResource.getName())) { continue; } log.info("Discovered resource of type: " + currentResource.getResourceType().getName()); if (currentResource.getResourceType().getPlugin().equals(PLUGIN_NAME)) { foundResources.add(currentResource); } if (currentResource.getChildResources() != null) { for (Resource child : currentResource.getChildResources()) { discoveryQueue.add(child); } } } return foundResources; }
From source file:org.jasig.portal.portlet.rendering.worker.HungWorkerAnalyzer.java
public void analyze(final Queue<IPortletExecutionWorker<?>> hungWorkers) { final long startTime = System.currentTimeMillis(); if (hungWorkers.isEmpty()) { hungWorkerAnalysis = Collections.emptyMap(); return;/*from w w w. j a v a 2 s . co m*/ } // Prepare the report final Map<String, PortletHungWorkerAnalysisEntry> report = new HashMap<String, PortletHungWorkerAnalysisEntry>(); for (final IPortletExecutionWorker<?> worker : hungWorkers) { // We won't analyze complete workers since they're not a problem if (!worker.isComplete()) { final String fname = worker.getPortletFname(); PortletHungWorkerAnalysisEntry entry = report.get(fname); if (entry == null) { entry = new PortletHungWorkerAnalysisEntry(fname, worker.getApplicableTimeout()); report.put(fname, entry); } entry.recordHungWorker(worker.getStartedTime()); } } // Log information from the report, if applicable if (!report.isEmpty()) { for (final PortletHungWorkerAnalysisEntry entry : report.values()) { switch (entry.getNumberInHungWorkersQueue()) { case THRESHOLD_LOG_WARN: if (log.isWarnEnabled()) { log.warn(entry.toString()); } break; case THRESHOLD_LOG_INFO: if (log.isInfoEnabled()) { log.info(entry.toString()); } break; default: if (log.isDebugEnabled()) { log.debug(entry.toString()); } break; } } } // Replace the existing hungWorkerAnalysis with the new report hungWorkerAnalysis = Collections.unmodifiableMap(report); if (log.isTraceEnabled()) { final long runTime = System.currentTimeMillis() - startTime; log.trace("Hung worker analysis performed; analysis completed in (milliseconds): " + runTime); } }
From source file:graph.inference.module.TransitiveWorker.java
protected void transitiveSearch(QueryObject queryObj) { // Find the index int atomicIndex = queryObj.getAtomicIndex(); int varIndex = (atomicIndex == 1) ? 2 : 1; DAGNode atomic = queryObj.getAtomic(); if (atomic == null) return;/* ww w. j a va 2s . c om*/ Queue<DAGNode> toCheck = new LinkedList<>(); toCheck.add(atomic); Collection<Edge> genlEdges = relatedModule_.findEdgeByNodes((DAGNode) queryObj.getNode(0)); while (!toCheck.isEmpty()) { DAGNode n = querier_.getExpanded(toCheck.poll()); if (queryObj.isCompleted(n)) continue; queryObj.addCompleted(n); // Function checking if (atomicIndex == 1 && n instanceof OntologyFunction) { Collection<DAGNode> functionEdges = querier_.functionResults((OntologyFunction) n, CommonConcepts.RESULT_GENL); for (DAGNode resultNode : functionEdges) { if (queryObj.isProof() && resultNode.equals(queryObj.getNode(2))) { queryObj.addResult(new Substitution(), CommonConcepts.GENLS.getNode(dag_), n, resultNode); return; } if (queryObj.addResult(CommonConcepts.GENLS.getNode(dag_), n, resultNode)) return; toCheck.add(resultNode); } } // Intersect the collections Collection<Edge> nodeEdges = relatedModule_.execute(n, atomicIndex + 1); nodeEdges = CollectionUtils.retainAll(nodeEdges, genlEdges); // Self genls check if (n == atomic) { Collection<Edge> selfEdges = nodeEdges; if (selfEdges.isEmpty()) { selfEdges = relatedModule_.execute(atomic, varIndex + 1); selfEdges = CollectionUtils.retainAll(selfEdges, genlEdges); } if (!selfEdges.isEmpty()) { if (queryObj.addResult(queryObj.getNode(0), atomic, n)) return; } } // Create the subs for (Edge e : nodeEdges) { if (!(e.getNodes()[varIndex] instanceof DAGNode)) continue; DAGNode edgeNode = (DAGNode) e.getNodes()[varIndex]; if (queryObj.isProof() && e.getNodes()[varIndex].equals(queryObj.getNode(2))) { queryObj.addResult(new Substitution(), e.getNodes()); return; } if (queryObj.addResult(e.getNodes())) return; toCheck.add(edgeNode); } } }
From source file:it.geosolutions.geobatch.destination.action.datamigration.MigrationAction.java
/** * *//*from w w w.j a v a 2 s .co m*/ public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.setTask("Check config"); checkInit(); final LinkedList<EventObject> ret = new LinkedList<EventObject>(); try { listenerForwarder.started(); while (!events.isEmpty()) { EventObject event = events.poll(); if (event instanceof FileSystemEvent) { FileSystemEvent fse = (FileSystemEvent) event; File file = fse.getSource(); doProcess(configuration, FilenameUtils.getBaseName(file.getName())); } // pass the feature config to the next action ret.add(new FileSystemEvent(((FileSystemEvent) event).getSource(), FileSystemEventType.FILE_ADDED)); } listenerForwarder.completed(); return ret; } catch (Exception t) { listenerForwarder.failed(t); throw new ActionException(this, t.getMessage(), t); } }
From source file:org.kuali.rice.krad.uif.util.ObjectPropertyUtils.java
/** * Locate the generic type declaration for a given target class in the generic type hierarchy of * the source class./* w w w . ja v a 2 s .c om*/ * * @param sourceClass The class representing the generic type hierarchy to scan. * @param targetClass The class representing the generic type declaration to locate within the * source class' hierarchy. * @return The generic type representing the target class within the source class' generic * hierarchy. */ public static Type findGenericType(Class<?> sourceClass, Class<?> targetClass) { if (!targetClass.isAssignableFrom(sourceClass)) { throw new IllegalArgumentException(targetClass + " is not assignable from " + sourceClass); } if (sourceClass.equals(targetClass)) { return sourceClass; } @SuppressWarnings("unchecked") Queue<Type> typeQueue = RecycleUtils.getInstance(LinkedList.class); typeQueue.offer(sourceClass); while (!typeQueue.isEmpty()) { Type type = typeQueue.poll(); Class<?> upperBound = getUpperBound(type); if (targetClass.equals(upperBound)) { return type; } Type genericSuper = upperBound.getGenericSuperclass(); if (genericSuper != null) { typeQueue.offer(genericSuper); } Type[] genericInterfaces = upperBound.getGenericInterfaces(); for (int i = 0; i < genericInterfaces.length; i++) { if (genericInterfaces[i] != null) { typeQueue.offer(genericInterfaces[i]); } } } throw new IllegalStateException(targetClass + " is assignable from " + sourceClass + " but could not be found in the generic type hierarchy"); }
From source file:edu.emory.cci.aiw.cvrg.eureka.etl.ksb.PropositionDefinitionFinder.java
private void readParentsForSearchResult(PropositionDefinition pf, LinkedHashSet<String> nodesToLoad) throws PropositionFinderException { try {//from www . ja v a 2 s .c o m Queue<PropositionDefinition> toProcessQueue = new LinkedList<>(); Stack<String> processedStack = new Stack<>(); toProcessQueue.add(pf); while (!toProcessQueue.isEmpty()) { PropositionDefinition currentPropDef = toProcessQueue.remove(); List<PropositionDefinition> parents; synchronized (parentsCache) { parents = parentsCache.get(currentPropDef.getId()); if (parents == null) { parents = knowledgeSource.readParents(currentPropDef); parentsCache.put(currentPropDef.getId(), parents); } } for (PropositionDefinition parent : parents) { toProcessQueue.add(parent); processedStack.add(parent.getId()); } } getNodesToLoad(processedStack, nodesToLoad); } catch (KnowledgeSourceReadException e) { throw new PropositionFinderException(e); } }
From source file:com.github.rvesse.airline.builder.CliBuilder.java
@Override public Cli<C> build() { CommandMetadata defaultCommandMetadata = null; List<CommandMetadata> allCommands = new ArrayList<CommandMetadata>(); if (defaultCommand != null) { defaultCommandMetadata = MetadataLoader.loadCommand(defaultCommand); }//from www .j a va 2 s . com List<CommandMetadata> defaultCommandGroup = defaultCommandGroupCommands != null ? MetadataLoader.loadCommands(defaultCommandGroupCommands) : new ArrayList<CommandMetadata>(); allCommands.addAll(defaultCommandGroup); if (defaultCommandMetadata != null) allCommands.add(defaultCommandMetadata); // Build groups List<CommandGroupMetadata> commandGroups; if (groups != null) { commandGroups = new ArrayList<CommandGroupMetadata>(); for (GroupBuilder<C> groupBuilder : groups.values()) { commandGroups.add(groupBuilder.build()); } } else { commandGroups = new ArrayList<>(); } // Find all commands registered in groups and sub-groups, we use this to // check this is a valid CLI with at least 1 command for (CommandGroupMetadata group : commandGroups) { allCommands.addAll(group.getCommands()); if (group.getDefaultCommand() != null) allCommands.add(group.getDefaultCommand()); // Make sure to scan sub-groups Queue<CommandGroupMetadata> subGroups = new LinkedList<CommandGroupMetadata>(); subGroups.addAll(group.getSubGroups()); while (!subGroups.isEmpty()) { CommandGroupMetadata subGroup = subGroups.poll(); allCommands.addAll(subGroup.getCommands()); if (subGroup.getDefaultCommand() != null) allCommands.add(subGroup.getDefaultCommand()); subGroups.addAll(subGroup.getSubGroups()); } } // add commands to groups based on the value of groups in the @Command // annotations // rather than change the entire way metadata is loaded, I figured just // post-processing was an easier, yet uglier, way to go MetadataLoader.loadCommandsIntoGroupsByAnnotation(allCommands, commandGroups, defaultCommandGroup); // Build restrictions // Use defaults if none specified if (restrictions.size() == 0) withDefaultRestrictions(); if (allCommands.size() == 0) throw new IllegalArgumentException("Must specify at least one command to create a CLI"); // Build metadata objects GlobalMetadata<C> metadata = MetadataLoader.<C>loadGlobal(name, description, defaultCommandMetadata, ListUtils.unmodifiableList(defaultCommandGroup), ListUtils.unmodifiableList(commandGroups), ListUtils.unmodifiableList(restrictions), this.parserBuilder.build()); return new Cli<C>(metadata); }
From source file:org.apache.http.HC4.impl.auth.HttpAuthenticator.java
public boolean handleAuthChallenge(final HttpHost host, final HttpResponse response, final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) { try {//from w ww. j av a2 s .co m if (this.log.isDebugEnabled()) { this.log.debug(host.toHostString() + " requested authentication"); } final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context); if (challenges.isEmpty()) { this.log.debug("Response contains no authentication challenges"); return false; } final AuthScheme authScheme = authState.getAuthScheme(); switch (authState.getState()) { case FAILURE: return false; case SUCCESS: authState.reset(); break; case CHALLENGED: case HANDSHAKE: if (authScheme == null) { this.log.debug("Auth scheme is null"); authStrategy.authFailed(host, null, context); authState.reset(); authState.setState(AuthProtocolState.FAILURE); return false; } case UNCHALLENGED: if (authScheme != null) { final String id = authScheme.getSchemeName(); final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT)); if (challenge != null) { this.log.debug("Authorization challenge processed"); authScheme.processChallenge(challenge); if (authScheme.isComplete()) { this.log.debug("Authentication failed"); authStrategy.authFailed(host, authState.getAuthScheme(), context); authState.reset(); authState.setState(AuthProtocolState.FAILURE); return false; } else { authState.setState(AuthProtocolState.HANDSHAKE); return true; } } else { authState.reset(); // Retry authentication with a different scheme } } } final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context); if (authOptions != null && !authOptions.isEmpty()) { if (this.log.isDebugEnabled()) { this.log.debug("Selected authentication options: " + authOptions); } authState.setState(AuthProtocolState.CHALLENGED); authState.update(authOptions); return true; } else { return false; } } catch (final MalformedChallengeException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Malformed challenge: " + ex.getMessage()); } authState.reset(); return false; } }
From source file:com.epam.reportportal.apache.http.impl.auth.HttpAuthenticator.java
public boolean handleAuthChallenge(final HttpHost host, final HttpResponse response, final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) { try {//from w w w . j a v a 2 s . com if (this.log.isDebugEnabled()) { this.log.debug(host.toHostString() + " requested authentication"); } final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context); if (challenges.isEmpty()) { this.log.debug("Response contains no authentication challenges"); return false; } final AuthScheme authScheme = authState.getAuthScheme(); switch (authState.getState()) { case FAILURE: return false; case SUCCESS: authState.reset(); break; case CHALLENGED: case HANDSHAKE: if (authScheme == null) { this.log.debug("Auth scheme is null"); authStrategy.authFailed(host, null, context); authState.reset(); authState.setState(AuthProtocolState.FAILURE); return false; } case UNCHALLENGED: if (authScheme != null) { final String id = authScheme.getSchemeName(); final Header challenge = challenges.get(id.toLowerCase(Locale.US)); if (challenge != null) { this.log.debug("Authorization challenge processed"); authScheme.processChallenge(challenge); if (authScheme.isComplete()) { this.log.debug("Authentication failed"); authStrategy.authFailed(host, authState.getAuthScheme(), context); authState.reset(); authState.setState(AuthProtocolState.FAILURE); return false; } else { authState.setState(AuthProtocolState.HANDSHAKE); return true; } } else { authState.reset(); // Retry authentication with a different scheme } } } final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context); if (authOptions != null && !authOptions.isEmpty()) { if (this.log.isDebugEnabled()) { this.log.debug("Selected authentication options: " + authOptions); } authState.setState(AuthProtocolState.CHALLENGED); authState.update(authOptions); return true; } else { return false; } } catch (final MalformedChallengeException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Malformed challenge: " + ex.getMessage()); } authState.reset(); return false; } }