List of usage examples for java.util Queue remove
E remove();
From source file:org.polymap.core.runtime.event.AnnotatedEventListener.java
/** * /*from w w w . j ava2 s . co m*/ */ public AnnotatedEventListener(Object handler, Integer mapKey, EventFilter... filters) { assert handler != null; assert filters != null; this.handlerRef = new WeakReference(handler); this.handlerClass = handler.getClass(); this.mapKey = mapKey; // find annotated methods Queue<Class> types = new ArrayDeque(16); types.add(handler.getClass()); while (!types.isEmpty()) { Class type = types.remove(); if (type.getSuperclass() != null) { types.add(type.getSuperclass()); } types.addAll(Arrays.asList(type.getInterfaces())); for (Method m : type.getDeclaredMethods()) { EventHandler annotation = m.getAnnotation(EventHandler.class); if (annotation != null) { m.setAccessible(true); // annotated method AnnotatedMethod am = annotation.delay() > 0 ? new DeferredAnnotatedMethod(m, annotation) : new AnnotatedMethod(m, annotation); EventListener listener = am; // display thread; if (annotation.display()) { // if this is NOT the delegate of the DeferringListener then // check DeferringListener#SessionUICallbackCounter listener = new DisplayingListener(listener); } // deferred // XXX There is a race cond. between the UIThread and the event thread; if the UIThread // completes the current request before all display events are handled then the UI // is not updated until next user request; DeferringListener handles this by activating // UICallBack, improving behaviour - but not really solving in all cases; after 500ms we // are quite sure that no more events are pending and UI callback can turned off // currenty COMMENTED OUT! see EventManger#SessionEventDispatcher if (annotation.delay() > 0 /*|| annotation.display()*/) { int delay = annotation.delay() > 0 ? annotation.delay() : 500; listener = new TimerDeferringListener(listener, delay, 10000); } // filters listener = new FilteringListener(listener, ObjectArrays.concat(am.filters, filters, EventFilter.class)); // session context; first in chain so that all listener/filters // get the proper context SessionContext session = SessionContext.current(); if (session != null) { listener = new SessioningListener(listener, mapKey, session, handlerClass); } methods.add(listener); } } } if (methods.isEmpty()) { throw new IllegalArgumentException("No EventHandler annotation found in: " + handler.getClass()); } }
From source file:DecorateMutationsSNP.java
/** * This function returns the set of leaves in the ARG that are reachable from a node give in input * @param root integer value representing the ID of the node in the arg * @param arg object of the class PopulationARG * @see PopulationARG//from w w w. j a va2 s . c o m * @see Node * @return the set of integer values representing the leaves in the ARG that are reachable from a node give in input (root) */ public static TreeSet<Integer> computeLeaves(int root, PopulationARG arg) { TreeSet<Integer> leaves = new TreeSet<Integer>(); Queue<Integer> q = new LinkedList<Integer>(); boolean visited[] = new boolean[arg.getNodeSet().size()]; /*System.out.println("ID Population = "+arg.getId_pop()); System.out.println("Population Kind = "+arg.getKind()); System.out.println("Extant units = "+arg.getExtantUnits()); System.out.println("Node set size = "+arg.getNodeSet().size());*/ for (int i = 0; i < visited.length; i++) { visited[i] = false; } //System.out.println("Root = "+root); //If root is a leaf I have to add just that leaf in leaves, no reason to do the visit if (root >= 0 && root < arg.getExtantUnits()) { leaves.add(new Integer(root)); } //Else bfv to search for all the leaves of the subtree with root root else { visited[root] = true; q.add(new Integer(root)); while (!q.isEmpty()) { // remove a labeled vertex from the queue int w = ((Integer) q.remove()).intValue(); // mark unreached vertices adjacent from w Iterator<Integer> it_edges = arg.getGraphEdges().keySet().iterator(); while (it_edges.hasNext()) { Integer keyE = it_edges.next(); Edge e = arg.getGraphEdges().get(keyE); //if I have found an edge with w has father if (e.getId_fath() == w) { int u = e.getId_son(); //System.out.println("Visiting edge "+w+"-"+u); if (!visited[u]) { q.add(new Integer(u)); visited[u] = true; //System.out.println("Visiting node :"+u); if (u >= 0 && u < arg.getExtantUnits()) { //System.out.println("u is a leaf :"+u); //u is a leaf node leaves.add(u); } } } //end if w is a father of the edge } //for all edge..select the one that has w has father and take u as son } //end while } // end else root is not a leaf return leaves; }
From source file:org.commonjava.maven.ext.manip.rest.DefaultVersionTranslator.java
/** * Translate the versions.// www . j av a2 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.opendatakit.aggregate.format.structure.KmlGeoTraceNGeoShapeGenerator.java
@Override String generatePlacemarkSubmission(Submission sub, List<FormElementModel> propertyNames, CallingContext cc) throws ODKDatastoreException { StringBuilder placemarks = new StringBuilder(); // check if gps coordinate is in top element, else it's in a repeat if (geoParentRootSubmissionElement()) { placemarks.append(generatePlacemark(sub)); } else {//from w w w . j ava 2 s . co m Queue<SubmissionSet> submissionSetLevelsToExamine = new LinkedList<SubmissionSet>(); submissionSetLevelsToExamine.add(sub); while (!submissionSetLevelsToExamine.isEmpty()) { SubmissionSet submissionSet = submissionSetLevelsToExamine.remove(); recursiveElementSearchToFindRepeats(submissionSet, submissionSetLevelsToExamine, placemarks); } } return placemarks.toString(); }
From source file:io.syndesis.project.converter.DefaultProjectGenerator.java
@SuppressWarnings("PMD.UnusedPrivateMethod") // PMD false positive private byte[] generateFlowYaml(TarArchiveOutputStream tos, GenerateProjectRequest request) throws JsonProcessingException { final Map<Step, String> connectorIdMap = new HashMap<>(); final List<? extends Step> steps = request.getIntegration().getSteps(); final Flow flow = new Flow(); if (!steps.isEmpty()) { // Determine connector prefix request.getIntegration().getSteps().stream().filter(s -> s.getStepKind().equals(Endpoint.KIND)) .filter(s -> s.getAction().isPresent()).filter(s -> s.getConnection().isPresent()) .collect(Collectors.groupingBy(s -> s.getAction().get().getCamelConnectorPrefix())) .forEach((prefix, stepList) -> { if (stepList.size() > 1) { for (int i = 0; i < stepList.size(); i++) { connectorIdMap.put(stepList.get(i), Integer.toString(i + 1)); }//from w w w.j a va 2 s .c om } }); Queue<Step> remaining = new LinkedList<>(steps); Step first = remaining.remove(); if (first != null) { GeneratorContext generatorContext = new GeneratorContext.Builder() .connectorCatalog(connectorCatalog).generatorProperties(generatorProperties) .request(request).tarArchiveOutputStream(tos).flow(flow).visitorFactoryRegistry(registry) .build(); StepVisitorContext stepContext = new StepVisitorContext.Builder().index(1).step(first) .remaining(remaining) .connectorIdSupplier(step -> Optional.ofNullable(connectorIdMap.get(step))).build(); visitStep(generatorContext, stepContext); } } SyndesisModel syndesisModel = new SyndesisModel(); syndesisModel.addFlow(flow); return YAML_OBJECT_MAPPER.writeValueAsBytes(syndesisModel); }
From source file:org.apache.http.HC4.impl.auth.HttpAuthenticator.java
public void generateAuthResponse(final HttpRequest request, final AuthState authState, final HttpContext context) throws HttpException, IOException { AuthScheme authScheme = authState.getAuthScheme(); Credentials creds = authState.getCredentials(); switch (authState.getState()) { // TODO add UNCHALLENGED and HANDSHAKE cases case FAILURE: return;//from w w w . j a v a 2 s .c om case SUCCESS: ensureAuthScheme(authScheme); if (authScheme.isConnectionBased()) { return; } break; case CHALLENGED: final Queue<AuthOption> authOptions = authState.getAuthOptions(); if (authOptions != null) { while (!authOptions.isEmpty()) { final AuthOption authOption = authOptions.remove(); authScheme = authOption.getAuthScheme(); creds = authOption.getCredentials(); authState.update(authScheme, creds); if (this.log.isDebugEnabled()) { this.log.debug("Generating response to an authentication challenge using " + authScheme.getSchemeName() + " scheme"); } try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); break; } catch (final AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn(authScheme + " authentication error: " + ex.getMessage()); } } } return; } else { ensureAuthScheme(authScheme); } } if (authScheme != null) { try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); } catch (final AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error(authScheme + " authentication error: " + ex.getMessage()); } } } }
From source file:com.epam.reportportal.apache.http.impl.auth.HttpAuthenticator.java
public void generateAuthResponse(final HttpRequest request, final AuthState authState, final HttpContext context) throws HttpException, IOException { AuthScheme authScheme = authState.getAuthScheme(); Credentials creds = authState.getCredentials(); switch (authState.getState()) { case FAILURE: return;//from www. j ava 2 s . c om case SUCCESS: ensureAuthScheme(authScheme); if (authScheme.isConnectionBased()) { return; } break; case CHALLENGED: final Queue<AuthOption> authOptions = authState.getAuthOptions(); if (authOptions != null) { while (!authOptions.isEmpty()) { final AuthOption authOption = authOptions.remove(); authScheme = authOption.getAuthScheme(); creds = authOption.getCredentials(); authState.update(authScheme, creds); if (this.log.isDebugEnabled()) { this.log.debug("Generating response to an authentication challenge using " + authScheme.getSchemeName() + " scheme"); } try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); break; } catch (final AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn(authScheme + " authentication error: " + ex.getMessage()); } } } return; } else { ensureAuthScheme(authScheme); } } if (authScheme != null) { try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); } catch (final AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error(authScheme + " authentication error: " + ex.getMessage()); } } } }
From source file:it.geosolutions.geobatch.mail.SendMailAction.java
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { final Queue<EventObject> ret = new LinkedList<EventObject>(); while (events.size() > 0) { final EventObject ev; try {//from w ww . ja va2s . co m if ((ev = events.remove()) != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource()); } File mail = (File) ev.getSource(); FileInputStream fis = new FileInputStream(mail); String kmlURL = IOUtils.toString(fis); // ///////////////////////////////////////////// // Send the mail with the given KML URL // ///////////////////////////////////////////// // Recipient's email ID needs to be mentioned. String mailTo = conf.getMailToAddress(); // Sender's email ID needs to be mentioned String mailFrom = conf.getMailFromAddress(); // Get system properties Properties properties = new Properties(); // Setup mail server String mailSmtpAuth = conf.getMailSmtpAuth(); properties.put("mail.smtp.auth", mailSmtpAuth); properties.put("mail.smtp.host", conf.getMailSmtpHost()); properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable()); properties.put("mail.smtp.port", conf.getMailSmtpPort()); // Get the default Session object. final String mailAuthUsername = conf.getMailAuthUsername(); final String mailAuthPassword = conf.getMailAuthPassword(); Session session = Session.getDefaultInstance(properties, (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailAuthUsername, mailAuthPassword); } } : null)); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(mailFrom)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); // Set Subject: header field message.setSubject(conf.getMailSubject()); String mailHeaderName = conf.getMailHeaderName(); String mailHeaderValule = conf.getMailHeaderValue(); if (mailHeaderName != null && mailHeaderValule != null) { message.addHeader(mailHeaderName, mailHeaderValule); } String mailMessageText = conf.getMailContentHeader(); message.setText(mailMessageText + "\n\n" + kmlURL); // Send message Transport.send(message); if (LOGGER.isInfoEnabled()) LOGGER.info("Sent message successfully...."); } catch (MessagingException exc) { ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ..."); continue; } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING..."); } continue; } } catch (Exception ioe) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Unable to produce the output: ", ioe.getLocalizedMessage(), ioe); } throw new ActionException(this, ioe.getLocalizedMessage(), ioe); } } return ret; }
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 w w w. j a va 2 s.com*/ 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:org.apache.hadoop.hbase.master.balancer.TestStochasticLoadBalancer.java
@Test public void testKeepRegionLoad() throws Exception { ServerName sn = ServerName.valueOf("test:8080", 100); int numClusterStatusToAdd = 20000; for (int i = 0; i < numClusterStatusToAdd; i++) { ServerLoad sl = mock(ServerLoad.class); RegionLoad rl = mock(RegionLoad.class); when(rl.getStores()).thenReturn(i); Map<byte[], RegionLoad> regionLoadMap = new TreeMap<byte[], RegionLoad>(Bytes.BYTES_COMPARATOR); regionLoadMap.put(Bytes.toBytes(REGION_KEY), rl); when(sl.getRegionsLoad()).thenReturn(regionLoadMap); ClusterStatus clusterStatus = mock(ClusterStatus.class); when(clusterStatus.getServers()).thenReturn(Arrays.asList(sn)); when(clusterStatus.getLoad(sn)).thenReturn(sl); loadBalancer.setClusterStatus(clusterStatus); }//ww w .ja v a2s . com assertTrue(loadBalancer.loads.get(REGION_KEY) != null); assertTrue(loadBalancer.loads.get(REGION_KEY).size() == 15); Queue<RegionLoad> loads = loadBalancer.loads.get(REGION_KEY); int i = 0; while (loads.size() > 0) { RegionLoad rl = loads.remove(); assertEquals(i + (numClusterStatusToAdd - 15), rl.getStores()); i++; } }