List of usage examples for java.util Queue size
int size();
From source file:nuclei.task.TaskPool.java
public int getPendingCount() { int count = 0; synchronized (runningIds) { for (int i = 0; i < pendingTasks.size(); i++) { Queue<TaskRunnable> pending = pendingTasks.valueAt(i); if (pending != null) count += pending.size(); }// ww w . j a v a 2 s . c o m } return count; }
From source file:com.jaspersoft.jasperserver.war.cascade.token.FilterCore.java
@Override public LinkedHashSet<String> resolveCascadingOrder(Map<String, Set<String>> masterDependencies) { Deque<String> orderedNames = new LinkedList<String>(); Queue<String> workingQueue = new LinkedList<String>(masterDependencies.keySet()); int maxIterations = (masterDependencies.size() * (masterDependencies.size() + 1)) / 2 + 1; while (workingQueue.size() > 0 && maxIterations-- > 0) { String currentName = workingQueue.remove(); Set<String> masterDependency = masterDependencies.get(currentName); if (masterDependency == null || masterDependency.isEmpty()) { orderedNames.addFirst(currentName); } else {/* www . ja v a2 s . co m*/ if (orderedNames.containsAll(masterDependency)) { orderedNames.addLast(currentName); } else { workingQueue.add(currentName); } } } if (maxIterations > 0) { return new LinkedHashSet<String>(orderedNames); } else { throw new JSException("Order cannot be resolved because of circular or non-existing dependencies."); } }
From source file:org.siddhiesb.transport.passthru.DeliveryAgent.java
/** * This method queues the message for delivery. If a connection is already existing for * the destination epr, the message will be delivered immediately. Otherwise message has * to wait until a connection is established. In this case this method will inform the * system about the need for a connection. * * @param commonContext the message context to be sent *//*w ww . j a va 2 s . c o m*/ public void submit(CommonContext commonContext) { try { String toAddress = (String) commonContext.getProperty(CommonAPIConstants.ENDPOINT); URL url = new URL(toAddress); String scheme = url.getProtocol() != null ? url.getProtocol() : "http"; String hostname = url.getHost(); int port = url.getPort(); if (port == -1) { // use default if ("http".equals(scheme)) { port = 80; } else if ("https".equals(scheme)) { port = 443; } } HttpHost target = new HttpHost(hostname, port, scheme); boolean secure = "https".equalsIgnoreCase(target.getSchemeName()); HttpHost proxy = null; //proxyConfig.selectProxy(target); HttpRoute route; if (proxy != null) { route = new HttpRoute(target, null, proxy, secure); } else { route = new HttpRoute(target, null, secure); } // first we queue the message Queue<CommonContext> queue = null; lock.lock(); try { queue = waitingMessages.get(route); if (queue == null) { queue = new ConcurrentLinkedQueue<CommonContext>(); waitingMessages.put(route, queue); } if (queue.size() == maxWaitingMessages) { CommonContext msgCtx = queue.poll(); } queue.add(commonContext); } finally { lock.unlock(); } NHttpClientConnection conn = targetConnections.getConnection(route); if (conn != null) { conn.resetInput(); conn.resetOutput(); CommonContext commonContext1 = queue.poll(); if (commonContext1 != null) { tryNextMessage(commonContext1, route, conn); } } } catch (MalformedURLException e) { handleException("Malformed URL in the target EPR", e); } }
From source file:it.geosolutions.geobatch.actions.commons.MoveAction.java
/** * Removes TemplateModelEvents from the queue and put */// w w w . ja v a 2 s .co m public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.started(); listenerForwarder.setTask("build the output absolute file name"); // return final Queue<EventObject> ret = new LinkedList<EventObject>(); listenerForwarder.setTask("Building/getting the root data structure"); boolean moveMultipleFile; final int size = events.size(); if (size == 0) { throw new ActionException(this, "Empty file list"); } else if (size > 1) { moveMultipleFile = true; } else { moveMultipleFile = false; } if (conf.getDestination() == null) { throw new IllegalArgumentException("Unable to work with a null dest dir"); } if (!conf.getDestination().isAbsolute()) { conf.setDestination(new File(this.getConfigDir(), conf.getDestination().getPath())); if (LOGGER.isWarnEnabled()) { LOGGER.warn("Destination is not an absolute path. Absolutizing destination using temp dir: " + conf.getDestination()); } } boolean moveToDir; if (!conf.getDestination().isDirectory()) { // TODO LOG moveToDir = false; if (moveMultipleFile) { throw new ActionException(this, "Unable to run on multiple file with an output file, use directory instead"); } } else { moveToDir = true; } while (!events.isEmpty()) { listenerForwarder.setTask("Generating the output"); final EventObject event = events.remove(); if (event == null) { // TODO LOG continue; } if (event instanceof FileSystemEvent) { File source = ((FileSystemEvent) event).getSource(); File dest; listenerForwarder.setTask("moving to destination"); if (moveToDir) { dest = conf.getDestination(); try { FileUtils.moveFileToDirectory(source, dest, true); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage()); } } else if (moveMultipleFile) { dest = new File(conf.getDestination(), source.getPath()); try { FileUtils.moveFile(source, dest); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage()); } } else { // LOG continue continue; } // add the file to the return ret.add(new FileSystemEvent(dest, FileSystemEventType.FILE_ADDED)); } } listenerForwarder.completed(); return ret; }
From source file:it.geosolutions.geobatch.actions.xstream.XstreamAction.java
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { // the output final Queue<EventObject> ret = new LinkedList<EventObject>(); listenerForwarder.started();// w w w . j a v a 2 s. co m while (events.size() > 0) { final EventObject event = events.remove(); if (event == null) { final String message = "The passed event object is null"; if (LOGGER.isWarnEnabled()) LOGGER.warn(message); if (conf.isFailIgnored()) { continue; } else { final ActionException e = new ActionException(this, message); listenerForwarder.failed(e); throw e; } } if (event instanceof FileSystemEvent) { // generate an object final File sourceFile = File.class.cast(event.getSource()); if (!sourceFile.exists() || !sourceFile.canRead()) { final String message = "XstreamAction.adapter(): The passed FileSystemEvent " + "reference to a not readable or not existent file: " + sourceFile.getAbsolutePath(); if (LOGGER.isWarnEnabled()) LOGGER.warn(message); if (conf.isFailIgnored()) { continue; } else { final ActionException e = new ActionException(this, message); listenerForwarder.failed(e); throw e; } } FileInputStream inputStream = null; try { inputStream = new FileInputStream(sourceFile); final Map<String, String> aliases = conf.getAlias(); if (aliases != null && aliases.size() > 0) { for (String alias : aliases.keySet()) { final Class<?> clazz = Class.forName(aliases.get(alias)); xstream.alias(alias, clazz); } } listenerForwarder.setTask("Converting file to a java object"); // deserialize final Object res = xstream.fromXML(inputStream); // generate event final EventObject eo = new EventObject(res); // append to the output ret.add(eo); } catch (XStreamException e) { // the object cannot be deserialized if (LOGGER.isErrorEnabled()) LOGGER.error("The passed FileSystemEvent reference to a not deserializable file: " + sourceFile.getAbsolutePath(), e); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(e); throw new ActionException(this, e.getLocalizedMessage()); } } catch (Throwable e) { // the object cannot be deserialized if (LOGGER.isErrorEnabled()) LOGGER.error("XstreamAction.adapter(): " + e.getLocalizedMessage(), e); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(e); throw new ActionException(this, e.getLocalizedMessage()); } } finally { IOUtils.closeQuietly(inputStream); } } else { // try to serialize // build the output absolute file name File outputDir; try { outputDir = new File(conf.getOutput()); // the output if (!outputDir.isAbsolute()) outputDir = it.geosolutions.tools.commons.file.Path.findLocation(outputDir, getTempDir()); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { final String message = "Unable to create the ouptut dir named: " + outputDir.toString(); if (LOGGER.isInfoEnabled()) LOGGER.info(message); if (conf.isFailIgnored()) { continue; } else { final ActionException e = new ActionException(this, message); listenerForwarder.failed(e); throw e; } } } if (LOGGER.isInfoEnabled()) { LOGGER.info("Output dir name: " + outputDir.toString()); } } catch (NullPointerException npe) { final String message = "Unable to get the output file path from :" + conf.getOutput(); if (LOGGER.isErrorEnabled()) LOGGER.error(message, npe); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(npe); throw new ActionException(this, npe.getLocalizedMessage()); } } final File outputFile; try { outputFile = File.createTempFile(conf.getOutput(), null, outputDir); } catch (IOException ioe) { final String message = "Unable to build the output file writer: " + ioe.getLocalizedMessage(); if (LOGGER.isErrorEnabled()) LOGGER.error(message, ioe); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(ioe); throw new ActionException(this, ioe.getLocalizedMessage()); } } // try to open the file to write into FileWriter fw = null; try { listenerForwarder.setTask("Serializing java object to " + outputFile); fw = new FileWriter(outputFile); final Map<String, String> aliases = conf.getAlias(); if (aliases != null && aliases.size() > 0) { for (String alias : aliases.keySet()) { final Class<?> clazz = Class.forName(aliases.get(alias)); xstream.alias(alias, clazz); } } xstream.toXML(event.getSource(), fw); } catch (XStreamException e) { if (LOGGER.isErrorEnabled()) LOGGER.error( "The passed event object cannot be serialized to: " + outputFile.getAbsolutePath(), e); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(e); throw new ActionException(this, e.getLocalizedMessage()); } } catch (Throwable e) { // the object cannot be deserialized if (LOGGER.isErrorEnabled()) LOGGER.error(e.getLocalizedMessage(), e); if (conf.isFailIgnored()) { continue; } else { listenerForwarder.failed(e); throw new ActionException(this, e.getLocalizedMessage()); } } finally { IOUtils.closeQuietly(fw); } // add the file to the queue ret.add(new FileSystemEvent(outputFile.getAbsoluteFile(), FileSystemEventType.FILE_ADDED)); } } listenerForwarder.completed(); return ret; }
From source file:it.geosolutions.geobatch.actions.commons.ExtractAction.java
/** * Removes TemplateModelEvents from the queue and put *//* ww w. java2 s. co m*/ public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.started(); listenerForwarder.setTask("build the output absolute file name"); // return final Queue<EventObject> ret = new LinkedList<EventObject>(); listenerForwarder.setTask("Building/getting the root data structure"); boolean extractMultipleFile; final int size = events.size(); if (size == 0) { throw new ActionException(this, "Empty file list"); } else if (size > 1) { extractMultipleFile = true; } else { extractMultipleFile = false; } final File dest = conf.getDestination(); if (dest != null && !dest.isDirectory()) { if (!dest.mkdirs()) { throw new ActionException(this, "bad destination (not writeable): " + dest); } } while (!events.isEmpty()) { listenerForwarder.setTask("Generating the output"); final EventObject event = events.remove(); if (event == null) { // TODO LOG continue; } if (event instanceof FileSystemEvent) { File source = ((FileSystemEvent) event).getSource(); try { listenerForwarder.setTask("Extracting file: " + source); final File extracted = Extract.extract(source, getTempDir(), false); if (extracted != null) { if (dest != null) { File newDest = new File(dest, extracted.getName()); listenerForwarder.setTask("moving \'" + extracted + "\' to \'" + newDest + "\'"); FileUtils.moveDirectoryToDirectory(extracted, newDest, true); listenerForwarder.terminated(); ret.add(new FileSystemEvent(newDest, FileSystemEventType.DIR_CREATED)); } else { throw new ActionException(this, "Unable to extracto file: " + source); } } else { final String message = "Unable to extract " + source; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } } catch (Exception e) { final String message = "Unable to copy extracted archive"; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(e.getLocalizedMessage()); } } } else { final String message = "Incoming instance is not a FileSystemEvent: " + event; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } // TODO setup task progress } // endwile listenerForwarder.completed(); return ret; }
From source file:org.apache.synapse.transport.passthru.DeliveryAgent.java
/** * This method queues the message for delivery. If a connection is already existing for * the destination epr, the message will be delivered immediately. Otherwise message has * to wait until a connection is established. In this case this method will inform the * system about the need for a connection. * * @param msgContext the message context to be sent * @param epr the endpoint to which the message should be sent * @throws AxisFault if an error occurs/* www . j a va 2s. co m*/ */ public void submit(MessageContext msgContext, EndpointReference epr) throws AxisFault { try { URL url = new URL(epr.getAddress()); String scheme = url.getProtocol() != null ? url.getProtocol() : "http"; String hostname = url.getHost(); int port = url.getPort(); if (port == -1) { // use default if ("http".equals(scheme)) { port = 80; } else if ("https".equals(scheme)) { port = 443; } } HttpHost target = new HttpHost(hostname, port, scheme); boolean secure = "https".equalsIgnoreCase(target.getSchemeName()); HttpHost proxy = proxyConfig.selectProxy(target); HttpRoute route; if (proxy != null) { route = new HttpRoute(target, null, proxy, secure); } else { route = new HttpRoute(target, null, secure); } // first we queue the message Queue<MessageContext> queue = null; lock.lock(); try { queue = waitingMessages.get(route); if (queue == null) { queue = new ConcurrentLinkedQueue<MessageContext>(); waitingMessages.put(route, queue); } if (queue.size() == maxWaitingMessages) { MessageContext msgCtx = queue.poll(); targetErrorHandler.handleError(msgCtx, ErrorCodes.CONNECTION_TIMEOUT, "Error connecting to the back end", null, ProtocolState.REQUEST_READY); } queue.add(msgContext); } finally { lock.unlock(); } NHttpClientConnection conn = targetConnections.getConnection(route); if (conn != null) { conn.resetInput(); conn.resetOutput(); MessageContext messageContext = queue.poll(); if (messageContext != null) { tryNextMessage(messageContext, route, conn); } } } catch (MalformedURLException e) { handleException("Malformed URL in the target EPR", e); } }
From source file:dendroscope.autumn.hybridnetwork.ComputeHybridizationNetwork.java
/** * get all alive leaves below the given root * * @param root/*www . j a v a 2 s .c om*/ * @return leaves */ private List<Root> getAllAliveLeaves(Root root) { List<Root> leaves = new LinkedList<Root>(); if (root.getTaxa().cardinality() > 0) { if (root.getOutDegree() == 0) leaves.add(root); else { Queue<Root> queue = new LinkedList<Root>(); queue.add(root); while (queue.size() > 0) { root = queue.poll(); for (Edge e = root.getFirstOutEdge(); e != null; e = root.getNextOutEdge(e)) { Root w = (Root) e.getTarget(); if (w.getTaxa().cardinality() > 0) { if (w.getOutDegree() == 0) leaves.add(w); else queue.add(w); } } } } } return leaves; }
From source file:hudson.plugins.emailext.plugins.content.BuildLogRegexContent.java
String getContent(BufferedReader reader) throws IOException { final boolean asHtml = matchedLineHtmlStyle != null; escapeHtml = asHtml || escapeHtml;/*www. ja va 2 s .c o m*/ final Pattern pattern = Pattern.compile(regex); final StringBuffer buffer = new StringBuffer(); int numLinesTruncated = 0; int numMatches = 0; int numLinesStillNeeded = 0; boolean insidePre = false; Queue<String> linesBeforeList = new LinkedList<String>(); String line = null; while ((line = reader.readLine()) != null) { // Remove console notes (JENKINS-7402) line = ConsoleNote.removeNotes(line); // Remove any lines before that are no longer needed. while (linesBeforeList.size() > linesBefore) { linesBeforeList.remove(); ++numLinesTruncated; } final Matcher matcher = pattern.matcher(line); final StringBuffer sb = new StringBuffer(); boolean matched = false; while (matcher.find()) { matched = true; if (substText != null) { matcher.appendReplacement(sb, substText); } else { break; } } if (matched) { // The current line matches. if (showTruncatedLines == true && numLinesTruncated > 0) { // Append information about truncated lines. insidePre = stopPre(buffer, insidePre); appendLinesTruncated(buffer, numLinesTruncated, asHtml); numLinesTruncated = 0; } if (asHtml) { insidePre = startPre(buffer, insidePre); } while (!linesBeforeList.isEmpty()) { appendContextLine(buffer, linesBeforeList.remove(), escapeHtml); } // Append the (possibly transformed) current line. if (substText != null) { matcher.appendTail(sb); line = sb.toString(); } appendMatchedLine(buffer, line, escapeHtml, matchedLineHtmlStyle, addNewline); ++numMatches; // Set up to add numLinesStillNeeded numLinesStillNeeded = linesAfter; } else { // The current line did not match. if (numLinesStillNeeded > 0) { // Append this line as a line after. appendContextLine(buffer, line, escapeHtml); --numLinesStillNeeded; } else { // Store this line as a possible line before. linesBeforeList.offer(line); } } if (maxMatches != 0 && numMatches >= maxMatches && numLinesStillNeeded == 0) { break; } } if (showTruncatedLines == true) { // Count the rest of the lines. // Include any lines in linesBefore. while (linesBeforeList.size() > 0) { linesBeforeList.remove(); ++numLinesTruncated; } if (line != null) { // Include the rest of the lines that haven't been read in. while ((line = reader.readLine()) != null) { ++numLinesTruncated; } } if (numLinesTruncated > 0) { insidePre = stopPre(buffer, insidePre); appendLinesTruncated(buffer, numLinesTruncated, asHtml); } } insidePre = stopPre(buffer, insidePre); if (buffer.length() == 0) { return defaultValue; } return buffer.toString(); }
From source file:org.glassfish.jersey.examples.sseitemstore.jaxrs.JaxrsItemStoreResourceTest.java
/** * Test the {@link SseEventSource} reconnect feature. * * @throws Exception in case of a test failure. *//*from ww w .j a v a2s . c o m*/ @Test public void testEventSourceReconnect() throws Exception { final WebTarget itemsTarget = target("items"); final CountDownLatch latch = new CountDownLatch(MAX_ITEMS * MAX_LISTENERS * 2); // countdown only on new item events final List<Queue<String>> receivedQueues = new ArrayList<>(MAX_LISTENERS); final SseEventSource[] sources = new SseEventSource[MAX_LISTENERS]; for (int i = 0; i < MAX_LISTENERS; i++) { final int id = i; final SseEventSource es = SseEventSource.target(itemsTarget.path("events")) .reconnectingEvery(1, TimeUnit.MILLISECONDS).build(); sources[id] = es; final Queue<String> received = new ConcurrentLinkedQueue<>(); receivedQueues.add(received); es.register(inboundEvent -> { try { if (null == inboundEvent.getName()) { final String data = inboundEvent.readData(); LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data); received.add(data); latch.countDown(); } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex); received.add("[data processing error]"); } }); } final String[] postedItems = new String[MAX_ITEMS * 2]; try { open(sources); for (int i = 0; i < MAX_ITEMS; i++) { final String item = String.format("round-1-%02d", i); postItem(itemsTarget, item); postedItems[i] = item; sendCommand(itemsTarget, "disconnect"); Thread.sleep(200); } final int reconnectDelay = 1; sendCommand(itemsTarget, "reconnect " + reconnectDelay); sendCommand(itemsTarget, "disconnect"); Thread.sleep(reconnectDelay * 1000); for (int i = 0; i < MAX_ITEMS; i++) { final String item = String.format("round-2-%02d", i); postedItems[i + MAX_ITEMS] = item; postItem(itemsTarget, item); } sendCommand(itemsTarget, "reconnect now"); assertTrue("Waiting to receive all events has timed out.", latch.await( (1 + MAX_LISTENERS * (MAX_ITEMS + 1) * reconnectDelay) * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS)); // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection sendCommand(itemsTarget, "disconnect"); } finally { close(sources); } final String storedItems = itemsTarget.request().get(String.class); for (String item : postedItems) { assertThat("Posted item '" + item + "' stored on server", storedItems, containsString(item)); } int sourceId = 0; for (Queue<String> queue : receivedQueues) { assertThat("Received events in source " + sourceId, queue, describedAs("Collection containing %0", hasItems(postedItems), Arrays.asList(postedItems).toString())); assertThat("Size of received queue for source " + sourceId, queue.size(), equalTo(postedItems.length)); sourceId++; } }