List of usage examples for java.util Queue poll
E poll();
From source file:com.mgmtp.jfunk.common.util.Configuration.java
/** * If properties are present which start with {@link JFunkConstants#SYSTEM_PROPERTIES} the * corresponding values are taken as property files and loaded here. *//*from w w w .j a v a 2 s. c o m*/ private void loadExtraFiles(final String filterPrefix, final boolean preserveExisting) { Map<String, String> view = Maps.filterKeys(this, Predicates.startsWith(filterPrefix)); while (true) { if (view.isEmpty()) { break; } Queue<String> fileKeys = Queues.newArrayDeque(view.values()); // we need to keep them separately in order to be able to reload them (see put method) extraFileProperties.addAll(fileKeys); // Remove original keys in order to prevent a stack overflow view.clear(); for (String fileNameKey = null; (fileNameKey = fileKeys.poll()) != null;) { // Recursion String fileName = processPropertyValue(fileNameKey); if (PLACEHOLDER_PATTERN.matcher(fileName).find()) { // not all placeholders were resolved, so we enqueue it again to process another file first fileKeys.offer(fileName); } else { load(fileName, preserveExisting); } } } }
From source file:org.eclipse.skalli.core.search.LuceneIndex.java
private List<IndexEntry> indexEntity(T entity) { List<IndexEntry> fields = new LinkedList<IndexEntry>(); Queue<EntityBase> queue = new LinkedList<EntityBase>(); queue.add(entity);/*from www. java2s . com*/ while (!queue.isEmpty()) { EntityBase currentEntity = queue.poll(); for (ExtensionService<?> extensionService : ExtensionServices.getAll()) { if (currentEntity.getClass().equals(extensionService.getExtensionClass())) { Indexer<?> indexer = extensionService.getIndexer(); if (indexer != null) { indexer.indexEntity(fields, currentEntity); } } } if (currentEntity instanceof ExtensibleEntityBase) { queue.addAll(((ExtensibleEntityBase) currentEntity).getAllExtensions()); } } return fields; }
From source file:com.clustercontrol.jobmanagement.util.JobMultiplicityCache.java
/** * ??// ww w .j a v a 2 s . co m * ?????????????????? * * @param facilityId * @return */ public static void kick(String facilityId) { m_log.debug("kick " + facilityId); boolean kickFlag = false; try { _lock.writeLock(); HashMap<String, Queue<JobSessionNodeEntityPK>> waitingCache = getWaitingCache(); HashMap<String, Queue<JobSessionNodeEntityPK>> runningCache = getRunningCache(); Queue<JobSessionNodeEntityPK> waitingQueue = waitingCache.get(facilityId); Queue<JobSessionNodeEntityPK> runningQueue = runningCache.get(facilityId); if (waitingQueue == null || waitingQueue.size() == 0) { return; } if (runningQueue == null) { runningQueue = new LinkedList<JobSessionNodeEntityPK>(); runningCache.put(facilityId, runningQueue); } if (isRunNow(facilityId)) { JpaTransactionManager jtm = new JpaTransactionManager(); try { jtm.begin(); JobSessionNodeEntityPK pk = waitingQueue.peek(); //// waitQueue??(??????) m_log.debug("kick remove waitQueue : " + pk); int status = new JobSessionNodeImpl().wait2running(pk); // ? if (status == 0) { m_log.debug("kick add runningQueue : " + pk); waitingQueue.poll(); //// waitQueue? runningQueue.offer(pk); //// runningQueue? kickFlag = true; } // ?????????? else if (status == 1) { m_log.debug("kick not add runningQueue : " + pk); waitingQueue.poll(); //// waitQueue? kickFlag = true; } jtm.commit(); } catch (Exception e) { m_log.warn("kick : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); jtm.rollback(); } finally { jtm.close(); } } storeWaitingCache(waitingCache); storeRunningCache(runningCache); if (m_log.isDebugEnabled()) { for (JobSessionNodeEntityPK q : runningQueue) { m_log.debug("kick runningQueue : " + q); } for (JobSessionNodeEntityPK q : waitingQueue) { m_log.debug("kick waitQueue : " + q); } } if (kickFlag) { kick(facilityId); } } finally { _lock.writeUnlock(); } }
From source file:com.connection.factory.SftpConnectionApacheLib.java
@Override public void readAllFilesWalkingPathWithListener(FileListener listener, String remotePath) { // List<RemoteFileObject> willReturnObject = new ArrayList<>(); Queue<RemoteFileObject> directorylist = new LinkedBlockingQueue<>(); RemoteFileObject object = null;/*from w ww. j a va2 s. c o m*/ object = new FtpApacheFileObject(FileInfoEnum.DIRECTORY); object.setDirectPath(remotePath); directorylist.add(object); try { while (!directorylist.isEmpty()) { object = directorylist.poll(); List<ChannelSftp.LsEntry> list = command.ls(object.getPath()); for (ChannelSftp.LsEntry each : list) { if (each.getFilename().equals(".") || each.getFilename().equals("..")) { continue; } RemoteFileObject objectTemp = null; SftpATTRS attributes = each.getAttrs(); if (attributes.isDir()) { objectTemp = new SftpApacheFileObject(FileInfoEnum.DIRECTORY); objectTemp.setFileName(each.getFilename()); objectTemp.setAbsolutePath(object.getPath()); directorylist.add(objectTemp); } else if (attributes.isReg()) { objectTemp = new SftpApacheFileObject(FileInfoEnum.FILE); objectTemp.setFileName(each.getFilename()); objectTemp.setAbsolutePath(object.getPath()); objectTemp.setFileSize(attributes.getSize()); objectTemp.setDate(attributes.getMtimeString()); objectTemp.setFileType(); listener.handleRemoteFile(object); } } object = null; list = null; } } catch (ConnectionException | SftpException ex) { // ex.printStackTrace(); } //return willReturnObject; }
From source file:com.connection.factory.SftpConnectionApacheLib.java
@Override public List<RemoteFileObject> readAllFilesWalkinPath(String remotePath) { List<RemoteFileObject> willReturnObject = new ArrayList<>(); Queue<RemoteFileObject> directorylist = new LinkedBlockingQueue<>(); RemoteFileObject object = null;/*from w w w . ja va2s.co m*/ object = new FtpApacheFileObject(FileInfoEnum.DIRECTORY); object.setDirectPath(remotePath); directorylist.add(object); try { while (!directorylist.isEmpty()) { object = directorylist.poll(); List<ChannelSftp.LsEntry> list = command.ls(object.getPath()); for (ChannelSftp.LsEntry each : list) { if (each.getFilename().equals(".") || each.getFilename().equals("..")) { continue; } RemoteFileObject objectTemp = null; SftpATTRS attributes = each.getAttrs(); if (attributes.isDir()) { objectTemp = new SftpApacheFileObject(FileInfoEnum.DIRECTORY); objectTemp.setFileName(each.getFilename()); objectTemp.setAbsolutePath(object.getPath()); directorylist.add(objectTemp); } else if (attributes.isReg()) { objectTemp = new SftpApacheFileObject(FileInfoEnum.FILE); objectTemp.setFileName(each.getFilename()); objectTemp.setAbsolutePath(object.getPath()); objectTemp.setFileSize(attributes.getSize()); objectTemp.setDate(attributes.getMtimeString()); objectTemp.setFileType(); willReturnObject.add(objectTemp); } } object = null; list = null; } } catch (ConnectionException | SftpException ex) { ex.printStackTrace(); } return willReturnObject; }
From source file:net.dv8tion.jda.audio.AudioConnection.java
private void setupCombinedExecutor() { if (combinedAudioExecutor == null) { combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor( r -> new Thread(r, "AudioConnection CombinedAudio Guild: " + channel.getGuild().getId())); combinedAudioExecutor.scheduleAtFixedRate(() -> { try { List<User> users = new LinkedList<>(); List<short[]> audioParts = new LinkedList<>(); if (receiveHandler != null && receiveHandler.canReceiveCombined()) { long currentTime = System.currentTimeMillis(); for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet()) { User user = entry.getKey(); Queue<Pair<Long, short[]>> queue = entry.getValue(); if (queue.isEmpty()) continue; Pair<Long, short[]> audioData = queue.poll(); //Make sure the audio packet is younger than 100ms while (audioData != null && currentTime - audioData.getLeft() > queueTimeout) { audioData = queue.poll(); }/*from www . j av a2 s . c o m*/ //If none of the audio packets were younger than 100ms, then there is nothing to add. if (audioData == null) { continue; } users.add(user); audioParts.add(audioData.getRight()); } if (!audioParts.isEmpty()) { int audioLength = audioParts.get(0).length; short[] mix = new short[1920]; //960 PCM samples for each channel int sample; for (int i = 0; i < audioLength; i++) { sample = 0; for (short[] audio : audioParts) { sample += audio[i]; } if (sample > Short.MAX_VALUE) mix[i] = Short.MAX_VALUE; else if (sample < Short.MIN_VALUE) mix[i] = Short.MIN_VALUE; else mix[i] = (short) sample; } receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix)); } else { //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel) receiveHandler .handleCombinedAudio(new CombinedAudio(new LinkedList(), new short[1920])); } } } catch (Exception e) { LOG.log(e); } }, 0, 20, TimeUnit.MILLISECONDS); } }
From source file:ch.mlutz.plugins.t4e.index.TapestryIndexer.java
/** * Iterates all folders and looks for *.specification files in a folder * named WEB-INF./* www .j a v a 2s. c o m*/ * * @param project * @return */ public List<TapestryModule> createModulesForProject(IProject project) { // the queue storing the potential app specification files Queue<IFile> appSpecificationFiles = new LinkedList<IFile>(); /* // add all children folders of project for (IResource member: project.members()) { if (member.getType() == IResource.FOLDER) { folderQueue.add((IFolder) member); } } */ // the queue used for breadth first search Queue<IContainer> containerQueue = new LinkedList<IContainer>(); containerQueue.add(project); IContainer currentContainer; while ((currentContainer = containerQueue.poll()) != null) { try { if (!TapestryModule.WEB_INF_FOLDER_NAME.equals(currentContainer.getName())) { // add all children folders of project for (IResource member : currentContainer.members()) { if (member.getType() == IResource.FOLDER) { containerQueue.add((IContainer) member); } } } else { // add all children folders of project and check files for // specification for (IResource member : currentContainer.members()) { if (member.getType() == IResource.FOLDER) { containerQueue.add((IContainer) member); } else if (member.getType() == IResource.FILE && isAppSpecification((IFile) member)) { appSpecificationFiles.add((IFile) member); } } } } catch (CoreException e) { log.warn("Couldn't iterate container " + currentContainer.getName(), e); } } // while List<TapestryModule> result = new ArrayList<TapestryModule>(); IFile currentFile; while ((currentFile = appSpecificationFiles.poll()) != null) { try { TapestryModule tapestryModule = new TapestryModule(currentFile, this); result.add(tapestryModule); } catch (TapestryException e) { log.warn("Couldn't validate tapestryModule for app specification" + " file " + currentFile.getName() + " in project " + project.getName() + ": ", e); } } return result; }
From source file:org.unitime.timetable.solver.curricula.CurriculaCourseDemands.java
protected void computeTargetShare(int nrStudents, Collection<CurriculumCourse> courses, CurriculumCourseGroupsProvider course2groups, CurModel model) { for (CurriculumCourse c1 : courses) { float x1 = c1.getPercShare() * nrStudents; Set<CurriculumCourse>[] group = new HashSet[] { new HashSet<CurriculumCourse>(), new HashSet<CurriculumCourse>() }; Queue<CurriculumCourse> queue = new LinkedList<CurriculumCourse>(); queue.add(c1);//from ww w .j a v a 2 s. c om Set<CurriculumCourseGroup> done = new HashSet<CurriculumCourseGroup>(); while (!queue.isEmpty()) { CurriculumCourse c = queue.poll(); for (CurriculumCourseGroup g : course2groups.getGroups(c)) if (done.add(g)) for (CurriculumCourse x : courses) if (!x.equals(c) && !x.equals(c1) && course2groups.getGroups(x).contains(g) && group[group[0].contains(c) ? 0 : g.getType()].add(x)) queue.add(x); } for (CurriculumCourse c2 : courses) { float x2 = c2.getPercShare() * nrStudents; if (c1.getUniqueId() >= c2.getUniqueId()) continue; float share = c1.getPercShare() * c2.getPercShare() * nrStudents; boolean opt = group[0].contains(c2); boolean req = !opt && group[1].contains(c2); model.setTargetShare(c1.getUniqueId(), c2.getUniqueId(), opt ? 0.0 : req ? Math.min(x1, x2) : share, true); } } }
From source file:it.geosolutions.geobatch.destination.action.datamigration.RasterMigrationAction.java
@Override public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.setTask("Check configuration"); checkConfiguration();/*w ww . jav a 2s .c o m*/ // Creation of a List containing the event objects final LinkedList<EventObject> ret = new LinkedList<EventObject>(); try { // Start of the operations listenerForwarder.started(); // Until the events are present, the input files are elaborated while (!events.isEmpty()) { // Each event is polled from the list EventObject event = events.poll(); if (event instanceof FileSystemEvent) { FileSystemEvent fse = (FileSystemEvent) event; File file = fse.getSource(); // Copy doProcess(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.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 w w. j ava2s .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); } }