List of usage examples for java.util Queue add
boolean add(E e);
From source file:com.datumbox.common.persistentstorage.factories.MongoDBStructureFactory.java
@Override public void postLoad(BigDataStructureContainer learnedParameters, MemoryConfiguration memoryConfiguration) { //InMemory DataStructureTypes can be used to speed up training. This point of load() //method is reached when the classifier calls a method that requires data and the //data are not already loaded. ////from ww w .j a v a 2s . c om //Loading the data from the DB to a map during methods like test() or predict() is //slow and a waste of resources. Usually LRU caching is more appropriate. //Thus using hashmaps during test() or predict() is disallowed if the //data are not already in there. // //Below if the MapType is set to HashMap we switch it to the default map. //We do the same with the other DataStructures if (memoryConfiguration.getMapType().isInMemory()) { memoryConfiguration.setMapType(getDefaultMapType()); memoryConfiguration.setLRUsize(getDefaultLRUsize()); } if (memoryConfiguration.getCollectionType().isInMemory()) { memoryConfiguration.setCollectionType(getDefaultCollectionType()); } if (memoryConfiguration.getSetType().isInMemory()) { memoryConfiguration.setSetType(getDefaultSetType()); } if (memoryConfiguration.getQueueType().isInMemory()) { memoryConfiguration.setQueueType(getDefaultQueueType()); } Queue<BigDataStructureContainer> learnableObjects = new LinkedList<>(); Set<BigDataStructureContainer> alreadyChecked = new HashSet<>(); //This set uses the default equals() which means that it compares memory addresses. This behavior is desired learnableObjects.add(learnedParameters); while (learnableObjects.size() > 0) { //get the next object from the queue BigDataStructureContainer obj = learnableObjects.poll(); //mark it as examined alreadyChecked.add(obj); //reinitialize the big data structures to load the data from the mongodb collections obj.bigDataStructureInitializer(this, memoryConfiguration); //get all the fields from all the inherited classes for (Field field : getAllFields(new LinkedList<>(), obj.getClass())) { Class<?> fieldClass = field.getType(); //if this object can be learned and is not already checked add it in the Queue if (BigDataStructureContainer.class.isAssignableFrom(fieldClass)) { field.setAccessible(true); BigDataStructureContainer fieldValue; try { fieldValue = (BigDataStructureContainer) field.get(obj); } catch (IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException(ex); } if (fieldValue != null && !alreadyChecked.contains(fieldValue)) { learnableObjects.add(fieldValue); } } } } }
From source file:org.exoplatform.services.cms.webdav.WebDavServiceImpl.java
@DELETE @Path("/{repoName}/{repoPath:.*}/") public Response delete(@PathParam("repoName") String repoName, @PathParam("repoPath") String repoPath, @HeaderParam(ExtHttpHeaders.LOCKTOKEN) String lockTokenHeader, @HeaderParam(ExtHttpHeaders.IF) String ifHeader) { Item item = null;// w ww . jav a 2 s. co m try { repoName = repositoryService.getCurrentRepository().getConfiguration().getName(); repoPath = convertRepoPath(repoPath, false); try { item = nodeFinder.getItem(workspaceName(repoPath), path(normalizePath(repoPath)), true); } catch (PathNotFoundException e) { item = nodeFinder.getItem(workspaceName(repoPath), path(Text.escapeIllegalJcrChars(repoPath)), true); } } catch (PathNotFoundException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (NoSuchWorkspaceException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot find the item at " + repoName + "/" + repoPath, e); } return Response.serverError().build(); } try { //Broadcast the event when user move node to Trash Node node = (Node) item; ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class); ActivityCommonService activityService = WCMCoreUtils.getService(ActivityCommonService.class); Node parent = node.getParent(); if (node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { if (activityService.isBroadcastNTFileEvents(node)) { listenerService.broadcast(ActivityCommonService.FILE_REMOVE_ACTIVITY, parent, node); } } else if (!WCMCoreUtils.isDocumentNodeType(node)) { Queue<Node> queue = new LinkedList<Node>(); queue.add(node); //Broadcast event to remove file activities Node tempNode = null; try { while (!queue.isEmpty()) { tempNode = queue.poll(); if (WCMCoreUtils.isDocumentNodeType(tempNode) || tempNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { listenerService.broadcast(ActivityCommonService.FILE_REMOVE_ACTIVITY, tempNode.getParent(), tempNode); } else { for (NodeIterator iter = tempNode.getNodes(); iter.hasNext();) { Node childNode = iter.nextNode(); if (WCMCoreUtils.isDocumentNodeType(childNode) || childNode.isNodeType(NodetypeConstant.NT_UNSTRUCTURED) || childNode.isNodeType(NodetypeConstant.NT_FOLDER)) queue.add(childNode); } } } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } } //Remove the symlinks of deleted node. Utils.removeSymlinks(node); } catch (Exception ex) { if (LOG.isWarnEnabled()) { LOG.warn(ex.getMessage()); } } return super.delete(repoName, repoPath, lockTokenHeader, ifHeader); }
From source file:org.kuali.rice.krms.service.impl.RuleEditorMaintainableImpl.java
public AgendaItemDefinition maintainAgendaItems(AgendaEditor agenda, String namePrefix, String nameSpace) { Queue<RuleDefinition.Builder> rules = new LinkedList<RuleDefinition.Builder>(); for (RuleEditor rule : agenda.getRuleEditors().values()) { if (!rule.isDummy()) { rules.add(this.finRule(rule, namePrefix, nameSpace)); }/* w w w . ja va 2 s. c o m*/ } AgendaItemDefinition.Builder rootItemBuilder = manageFirstItem(agenda); AgendaItemDefinition.Builder itemToDelete = null; AgendaItemDefinition.Builder itemBuilder = rootItemBuilder; while (rules.peek() != null) { itemBuilder.setRule(rules.poll()); itemBuilder.setRuleId(itemBuilder.getRule().getId()); if (rules.peek() != null) { if (itemBuilder.getWhenTrue() == null) { itemBuilder.setWhenTrue(AgendaItemDefinition.Builder.create(null, agenda.getId())); } itemBuilder = itemBuilder.getWhenTrue(); } else { itemToDelete = itemBuilder.getWhenTrue(); itemBuilder.setWhenTrue(null); } } return manageAgendaItems(agenda, rootItemBuilder, itemToDelete); }
From source file:com.naver.timetable.bo.TableParsingBO.java
/** * ? ?? url? Queue? ?./*from w ww . ja v a 2 s . c o m*/ * @param year * @param season * @return */ protected Queue<UrlEntity> makeUrlQueue(String year, String season) { Queue<UrlEntity> urlQueue = Lists.newLinkedList(); for (CampusMajorEnum campusMajor : CampusMajorEnum.values()) { List<String> categoryCodes = categoryDAO.getCatgCode(campusMajor.getCampus(), campusMajor.getMajorCode()); for (String categoryCode : categoryCodes) { UrlEntity urlEntity = new UrlEntity(year, season, categoryCode, campusMajor); urlQueue.add(urlEntity); //?? wait notify? // urlQueue.notify(); } } return urlQueue; }
From source file:com.thoughtworks.go.server.service.dd.reporting.ReportingDependencyFanInNode.java
private void addToRevisionQueue(PipelineTimelineEntry entry, Queue<PipelineTimelineEntry.Revision> revisionQueue, List<ReportingFaninScmMaterial> scmMaterials, ReportingFanInGraphContext context) { printPipelineTimelineEntry(entry, context); for (Map.Entry<String, List<PipelineTimelineEntry.Revision>> revisionList : entry.revisions().entrySet()) { String fingerprint = revisionList.getKey(); PipelineTimelineEntry.Revision revision = revisionList.getValue().get(0); if (isScmMaterial(fingerprint, context)) { scmMaterials.add(new ReportingFaninScmMaterial(fingerprint, revision)); continue; }//from ww w. j a va2s .c o m if (isDependencyMaterial(fingerprint, context)) { revisionQueue.add(revision); } } }
From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java
@Test public void testSparseUseNoReap() throws Exception { final int THRESHOLD = 3000; Timing timing = new Timing(); Reaper reaper = null;//from w w w . j a v a 2 s. c o m Future<Void> watcher = null; CuratorFramework client = makeClient(timing, null); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); final Queue<Reaper.PathHolder> holders = new ConcurrentLinkedQueue<Reaper.PathHolder>(); final ExecutorService pool = Executors.newCachedThreadPool(); ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1) { @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { final Reaper.PathHolder pathHolder = (Reaper.PathHolder) command; holders.add(pathHolder); final ScheduledFuture<?> f = super.schedule(command, delay, unit); pool.submit(new Callable<Void>() { @Override public Void call() throws Exception { f.get(); holders.remove(pathHolder); return null; } }); return f; } }; reaper = new Reaper(client, service, THRESHOLD); reaper.start(); reaper.addPath("/one/two/three"); long start = System.currentTimeMillis(); boolean emptyCountIsCorrect = false; while (((System.currentTimeMillis() - start) < timing.forWaiting().milliseconds()) && !emptyCountIsCorrect) // need to loop as the Holder can go in/out of the Reaper's DelayQueue { for (Reaper.PathHolder holder : holders) { if (holder.path.endsWith("/one/two/three")) { emptyCountIsCorrect = (holder.emptyCount > 0); break; } } Thread.sleep(1); } Assert.assertTrue(emptyCountIsCorrect); client.create().forPath("/one/two/three/foo"); Thread.sleep(2 * (THRESHOLD / Reaper.EMPTY_COUNT_THRESHOLD)); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client.delete().forPath("/one/two/three/foo"); Thread.sleep(THRESHOLD); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { if (watcher != null) { watcher.cancel(true); } IOUtils.closeQuietly(reaper); IOUtils.closeQuietly(client); } }
From source file:net.dv8tion.jda.audio.AudioConnection.java
private void setupReceiveThread() { if (receiveHandler != null && udpSocket != null) { if (receiveThread == null) { receiveThread = new Thread("AudioConnection ReceiveThread Guild: " + channel.getGuild().getId()) { @Override//from ww w. j av a 2s .c o m public void run() { try { udpSocket.setSoTimeout(100); } catch (SocketException e) { LOG.log(e); } while (!udpSocket.isClosed() && !this.isInterrupted()) { DatagramPacket receivedPacket = new DatagramPacket(new byte[1920], 1920); try { udpSocket.receive(receivedPacket); if (receiveHandler != null && (receiveHandler.canReceiveUser() || receiveHandler.canReceiveCombined()) && webSocket.getSecretKey() != null) { if (!couldReceive) { couldReceive = true; sendSilentPackets(); } AudioPacket decryptedPacket = AudioPacket.decryptAudioPacket(receivedPacket, webSocket.getSecretKey()); String userId = ssrcMap.get(decryptedPacket.getSSRC()); Decoder decoder = opusDecoders.get(decryptedPacket.getSSRC()); if (userId == null) { byte[] audio = decryptedPacket.getEncodedAudio(); if (!Arrays.equals(audio, silenceBytes)) LOG.debug("Received audio data with an unknown SSRC id."); } else if (decoder == null) LOG.warn( "Received audio data with known SSRC, but opus decoder for this SSRC was null. uh..HOW?!"); else if (!decoder.isInOrder(decryptedPacket.getSequence())) LOG.trace("Got out-of-order audio packet. Ignoring."); else { User user = getJDA().getUserById(userId); if (user == null) LOG.warn( "Received audio data with a known SSRC, but the userId associate with the SSRC is unknown to JDA!"); else { // if (decoder.wasPacketLost(decryptedPacket.getSequence())) // { // LOG.debug("Packet(s) missed. Using Opus packetloss-compensation."); // short[] decodedAudio = decoder.decodeFromOpus(null); // receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio)); // } short[] decodedAudio = decoder.decodeFromOpus(decryptedPacket); //If decodedAudio is null, then the Opus decode failed, so throw away the packet. if (decodedAudio == null) { LOG.trace( "Received audio data but Opus failed to properly decode, instead it returned an error"); } else { if (receiveHandler.canReceiveUser()) { receiveHandler .handleUserAudio(new UserAudio(user, decodedAudio)); } if (receiveHandler.canReceiveCombined()) { Queue<Pair<Long, short[]>> queue = combinedQueue.get(user); if (queue == null) { queue = new ConcurrentLinkedQueue<>(); combinedQueue.put(user, queue); } queue.add(Pair.<Long, short[]>of(System.currentTimeMillis(), decodedAudio)); } } } } } else if (couldReceive) { couldReceive = false; sendSilentPackets(); } } catch (SocketTimeoutException e) { //Ignore. We set a low timeout so that we wont block forever so we can properly shutdown the loop. } catch (SocketException e) { //The socket was closed while we were listening for the next packet. //This is expected. Ignore the exception. The thread will exit during the next while // iteration because the udpSocket.isClosed() will return true. } catch (Exception e) { LOG.log(e); } } } }; receiveThread.setDaemon(true); receiveThread.start(); } if (receiveHandler.canReceiveCombined()) { setupCombinedExecutor(); } } }
From source file:org.apache.camel.component.mail.MailConsumer.java
protected Queue<Exchange> createExchanges(Message[] messages) throws MessagingException { Queue<Exchange> answer = new LinkedList<Exchange>(); int fetchSize = getEndpoint().getConfiguration().getFetchSize(); int count = fetchSize == -1 ? messages.length : Math.min(fetchSize, messages.length); if (LOG.isDebugEnabled()) { LOG.debug("Fetching " + count + " messages. Total " + messages.length + " messages."); }//ww w . ja v a2 s . c om for (int i = 0; i < count; i++) { Message message = messages[i]; if (!message.getFlags().contains(Flags.Flag.DELETED)) { Exchange exchange = getEndpoint().createExchange(message); answer.add(exchange); } else { if (LOG.isDebugEnabled()) { LOG.debug("Skipping message as it was flagged as deleted: " + MailUtils.dumpMessage(message)); } } } return answer; }
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//from w ww . ja v a 2 s. 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); } }