List of usage examples for java.util Queue poll
E poll();
From source file:org.rhq.cassandra.ClusterInitService.java
/** * This method attempts to establish a Thrift RPC connection to each host for the * number specified. In other words, if there are four hosts and <code>numHosts</code> * is 2, this method will block only until it can connect to two of the hosts. If the * connection fails, the host is retried after going through the other, remaining * hosts./*from w w w . ja v a 2 s .co m*/ * <br/><br/> * After connecting to all cluster nodes, this method will sleep for 10 seconds * before returning. This is to give the cluster a chance to create the system auth * schema and to create the cassandra super user. Cassandra has a hard-coded delay of * 10 sceonds before it creates the super user, which means the rhq schema cannot be * created before that. * @param numHosts The number of hosts to which a successful connection has to be made * before returning. * @param delay The amount of time wait between attempts to make a connection * @param retries The number of times to retry connecting. A runtime exception will be * thrown when the number of failed connections exceeds this value. * @param initialWait The amount of seconds before first try. */ public void waitForClusterToStart(String[] storageNodes, int jmxPorts[], int numHosts, long delay, int retries, int initialWait) { if (initialWait > 0) { if (log.isDebugEnabled()) { log.debug("Waiting before JMX calls to the storage nodes for " + initialWait + " seconds..."); } sleep(initialWait * 1000); } int connections = 0; int failedConnections = 0; Queue<Integer> queue = new LinkedList<Integer>(); for (int index = 0; index < storageNodes.length; index++) { queue.add(index); } Integer storageNodeIndex = queue.poll(); while (storageNodeIndex != null) { if (failedConnections >= retries) { throw new RuntimeException("Unable to verify that cluster nodes have started after " + failedConnections + " failed attempts"); } try { boolean isNativeTransportRunning = isNativeTransportRunning(storageNodes[storageNodeIndex], jmxPorts[storageNodeIndex]); if (log.isDebugEnabled() && isNativeTransportRunning) { log.debug("Successfully connected to cassandra node [" + storageNodes[storageNodeIndex] + "]"); } if (isNativeTransportRunning) { ++connections; } else { queue.offer(storageNodeIndex); } if (connections == numHosts) { if (log.isDebugEnabled()) { log.debug("Successdully connected to all nodes. Sleeping for 10 seconds to allow for the " + "cassandra superuser set up to complete."); } sleep(10 * 1000); return; } } catch (Exception e) { ++failedConnections; queue.offer(storageNodeIndex); if (log.isDebugEnabled()) { log.debug("Unable to open JMX connection on port [" + jmxPorts[storageNodeIndex] + "] to cassandra node [" + storageNodes[storageNodeIndex] + "].", e); } else if (log.isInfoEnabled()) { log.debug("Unable to open connection to cassandra node."); } } sleep(delay); storageNodeIndex = queue.poll(); } }
From source file:se.sics.gvod.common.GraphUtil.java
private void bfs(int v, int d[]) { Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { d[i] = n; // also means that the node has not been visited }//from www . j a va 2 s . com d[v] = 0; q.offer(v); q.offer(0); // depth of v while (!q.isEmpty()) { int u = q.poll(); int du = q.poll(); // depth of u for (int t = 0; t < neighbors[u].length; t++) { if (d[neighbors[u][t]] == n) { // on the first encounter, add to the queue d[neighbors[u][t]] = du + 1; q.offer(neighbors[u][t]); q.offer(du + 1); } } } }
From source file:org.primeframework.mvc.util.ClassClasspathResolver.java
private Collection<Class<U>> loadFromDirectory(File dir, Test<Class<U>> test, boolean recursive) throws IOException { Set<Class<U>> matches = new HashSet<Class<U>>(); // Loop over the files Queue<File> files = new LinkedList<File>(safeListFiles(dir, null)); while (!files.isEmpty()) { File file = files.poll(); if (file.isDirectory() && recursive) { files.addAll(safeListFiles(file, null)); } else if (file.isFile()) { // This file matches, test it Testable<Class<U>> testable = test.prepare(file); if (testable != null && testable.passes()) { matches.add(testable.result()); }//from w w w . jav a 2s.co m } } return matches; }
From source file:net.cellcloud.talk.HttpHeartbeatHandler.java
@Override protected void doGet(HttpRequest request, HttpResponse response) throws IOException { HttpSession session = request.getSession(); if (null != session) { // /*w ww . j av a2 s . c o m*/ session.heartbeat(); // ?? Queue<Message> queue = session.getQueue(); if (!queue.isEmpty()) { ArrayList<String> identifiers = new ArrayList<String>(queue.size()); ArrayList<Primitive> primitives = new ArrayList<Primitive>(queue.size()); for (int i = 0, size = queue.size(); i < size; ++i) { // ? Message message = queue.poll(); // Packet packet = Packet.unpack(message.get()); if (null != packet) { // ????? byte[] primData = packet.getSubsegment(0); ByteArrayInputStream stream = new ByteArrayInputStream(primData); // ??? Primitive prim = new Primitive(Nucleus.getInstance().getTagAsString()); prim.read(stream); // identifiers.add(Utils.bytes2String(packet.getSubsegment(1))); primitives.add(prim); } } JSONArray jsonPrimitives = this.convert(identifiers, primitives); JSONObject json = new JSONObject(); try { json.put(Primitives, jsonPrimitives); } catch (JSONException e) { Logger.log(getClass(), e, LogLevel.ERROR); } // ? this.respondWithOk(response, json); } else { this.respondWithOk(response); } } else { this.respond(response, HttpResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:fr.landel.utils.commons.CastUtilsTest.java
/** * Check cast list/*from ww w . j a v a 2s . c o m*/ */ @Test public void testGetQueue() { Queue<String> queue = new LinkedList<>(); queue.add("value1"); queue.add(null); queue.add("value2"); assertTrue(CollectionUtils.isEmpty(CastUtils.getLinkedListAsQueue(null, String.class))); assertTrue(CollectionUtils.isEmpty(CastUtils.getLinkedTransferQueue(null, String.class))); assertTrue(CollectionUtils.isEmpty(CastUtils.getPriorityQueue(null, String.class))); assertTrue(CollectionUtils.isEmpty(CastUtils.getLinkedBlockingQueue(null, String.class))); assertTrue(CollectionUtils.isEmpty(CastUtils.getPriorityBlockingQueue(null, String.class))); assertTrue(CollectionUtils.isEmpty(CastUtils.getArrayBlockingQueue(null, String.class, queue.size()))); Queue<String> result = CastUtils.getLinkedListAsQueue(queue, String.class); assertEquals("value1", result.poll()); assertNull(result.poll()); assertEquals("value2", result.poll()); result = CastUtils.getLinkedTransferQueue(queue, String.class); assertEquals("value1", result.poll()); assertEquals("value2", result.poll()); result = CastUtils.getPriorityQueue(queue, String.class); assertEquals("value1", result.poll()); assertEquals("value2", result.poll()); result = CastUtils.getLinkedBlockingQueue(queue, String.class); assertEquals("value1", result.poll()); assertEquals("value2", result.poll()); result = CastUtils.getPriorityBlockingQueue(queue, String.class); assertEquals("value1", result.poll()); assertEquals("value2", result.poll()); result = CastUtils.getArrayBlockingQueue(queue, String.class, queue.size()); assertEquals("value1", result.poll()); assertEquals("value2", result.poll()); assertEquals(0, CastUtils.getLinkedListAsQueue(12, String.class).size()); Queue<Integer> queue2 = new LinkedList<>(); queue2.add(2); assertEquals(0, CastUtils.getLinkedListAsQueue(queue2, String.class).size()); }
From source file:de.mrapp.android.util.view.AbstractViewRecycler.java
/** * Retrieves an unused view, which corresponds to a specific view type, from the cache, if any * is available.//from w ww . jav a 2 s . co m * * @param viewType * The view type of the unused view, which should be retrieved, as an {@link Integer} * value * @return An unused view, which corresponds to the given view type, as an instance of the class * {@link View} or null, if no such view is available in the cache */ @Nullable protected final View pollUnusedView(final int viewType) { if (useCache && unusedViews != null) { Queue<View> queue = unusedViews.get(viewType); if (queue != null) { return queue.poll(); } } return null; }
From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java
/** * Close any cached connections./*w w w .jav a2 s . co m*/ */ public void shutdown() throws PluginException { super.shutdown(); poolsShrinkTimer.cancel(); synchronized (connectionPools) { Set<Entry<String, Queue>> pools = connectionPools.entrySet(); Iterator<Entry<String, Queue>> it = pools.iterator(); while (it.hasNext()) { Entry<String, Queue> entry = it.next(); Queue<Connection> pool = entry.getValue(); Connection conn; while ((conn = pool.poll()) != null) { DBUtil.closeJDBCObjects(log, conn, null, null); } } connectionPools.clear(); } }
From source file:org.primeframework.mvc.util.ClassClasspathResolver.java
private Set<File> findDirectories(File dir, String locator) { // Loop over the files using tail-recursion Set<File> directories = new HashSet<File>(); Queue<File> files = new LinkedList<File>(safeListFiles(dir, DirectoryFileFilter.INSTANCE)); while (!files.isEmpty()) { File file = files.poll(); if (file.isDirectory() && file.getName().equals(locator)) { directories.add(file);/*from w w w . j a v a 2s . c o m*/ } else if (file.isDirectory()) { files.addAll(safeListFiles(file, null)); } } return directories; }
From source file:org.structr.pdf.servlet.PdfServlet.java
@Override protected void renderAsyncOutput(HttpServletRequest request, HttpServletResponse response, App app, RenderContext renderContext, DOMNode rootElement) throws IOException { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=\"FileName.pdf\""); threadPool.submit(new Runnable() { @Override// w w w . j a v a 2 s . c o m public void run() { try (final Tx tx = app.tx()) { // render rootNode.render(renderContext, 0); finished.set(true); tx.success(); } catch (Throwable t) { t.printStackTrace(); logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage()); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); finished.set(true); } catch (IOException ex) { logger.warn("", ex); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); String pageContent = ""; while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { pageContent += buffer; } else { if (finished.get()) { // TODO: implement parameters for wkhtmltopdf in settings Pdf pdf = new Pdf(); pdf.addPageFromString(pageContent); out.write(pdf.getPDF()); async.complete(); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (EofException ee) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } catch (IOException | InterruptedException t) { logger.warn("Unexpected exception", t); } } @Override public void onError(Throwable t) { if (t instanceof EofException) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } else { logger.warn("Unexpected exception", t); } } }); }
From source file:org.apache.marmotta.ldclient.services.provider.AbstractHttpProvider.java
/** * Retrieve the data for a resource using the given http client and endpoint definition. The service is * supposed to manage the connection handling itself. See {@link AbstractHttpProvider} * for a generic implementation of this method. * * * * @param resource the resource to be retrieved * @param endpoint the endpoint definition * @return a completely specified client response, including expiry information and the set of triples *//* ww w .j a v a 2 s. c om*/ @Override public ClientResponse retrieveResource(String resource, LDClientService client, Endpoint endpoint) throws DataRetrievalException { try { String contentType; if (endpoint != null && endpoint.getContentTypes().size() > 0) { contentType = CollectionUtils.fold(endpoint.getContentTypes(), new CollectionUtils.StringSerializer<ContentType>() { @Override public String serialize(ContentType contentType) { return contentType.toString("q"); } }, ","); } else { contentType = CollectionUtils.fold(Arrays.asList(listMimeTypes()), ","); } long defaultExpires = client.getClientConfiguration().getDefaultExpiry(); if (endpoint != null && endpoint.getDefaultExpiry() != null) { defaultExpires = endpoint.getDefaultExpiry(); } final ResponseHandler handler = new ResponseHandler(resource, endpoint); // a queue for queuing the request URLs needed to build the query response Queue<String> requestUrls = new LinkedList<String>(); requestUrls.addAll(buildRequestUrl(resource, endpoint)); Set<String> visited = new HashSet<String>(); String requestUrl = requestUrls.poll(); while (requestUrl != null) { if (!visited.contains(requestUrl)) { HttpGet get = new HttpGet(requestUrl); try { get.setHeader("Accept", contentType); get.setHeader("Accept-Language", "*"); // PoolParty compatibility log.info("retrieving resource data for {} from '{}' endpoint, request URI is <{}>", new Object[] { resource, getName(), get.getURI().toASCIIString() }); handler.requestUrl = requestUrl; List<String> additionalRequestUrls = client.getClient().execute(get, handler); requestUrls.addAll(additionalRequestUrls); visited.add(requestUrl); } finally { get.releaseConnection(); } } requestUrl = requestUrls.poll(); } Date expiresDate = handler.expiresDate; if (expiresDate == null) { expiresDate = new Date(System.currentTimeMillis() + defaultExpires * 1000); } long min_expires = System.currentTimeMillis() + client.getClientConfiguration().getMinimumExpiry() * 1000; if (expiresDate.getTime() < min_expires) { log.info( "expiry time returned by request lower than minimum expiration time; using minimum time instead"); expiresDate = new Date(min_expires); } if (log.isInfoEnabled()) { log.info("retrieved {} triples for resource {}; expiry date: {}", new Object[] { handler.triples.size(), resource, expiresDate }); } ClientResponse result = new ClientResponse(handler.httpStatus, handler.triples); result.setExpires(expiresDate); return result; } catch (RepositoryException e) { log.error("error while initialising Sesame repository; classpath problem?", e); throw new DataRetrievalException("error while initialising Sesame repository; classpath problem?", e); } catch (ClientProtocolException e) { log.error("HTTP client error while trying to retrieve resource {}: {}", resource, e.getMessage()); throw new DataRetrievalException("I/O error while trying to retrieve resource " + resource, e); } catch (IOException e) { log.error("I/O error while trying to retrieve resource {}: {}", resource, e.getMessage()); throw new DataRetrievalException("I/O error while trying to retrieve resource " + resource, e); } catch (RuntimeException ex) { log.error("Unknown error while trying to retrieve resource {}: {}", resource, ex.getMessage()); throw new DataRetrievalException("Unknown error while trying to retrieve resource " + resource, ex); } }