Example usage for java.util Queue peek

List of usage examples for java.util Queue peek

Introduction

In this page you can find the example usage for java.util Queue peek.

Prototype

E peek();

Source Link

Document

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Usage

From source file:drpc.BptiEnsembleQuery.java

public static void main(final String[] args) throws IOException, TException, DRPCExecutionException {
    if (args.length < 3) {
        System.err.println("Where are the arguments? args -- DrpcServer DrpcFunctionName folder");
        return;/*from   w  w w. ja va  2 s .  c  om*/
    }

    final DRPCClient client = new DRPCClient(args[0], 3772, 1000000 /*timeout*/);
    final Queue<String> featureFiles = new ArrayDeque<String>();
    SpoutUtils.listFilesForFolder(new File(args[2]), featureFiles);

    Scanner scanner = new Scanner(featureFiles.peek());
    int i = 0;
    while (scanner.hasNextLine() && i++ < 1) {
        List<Map<String, List<Double>>> dict = SpoutUtils.pythonDictToJava(scanner.nextLine());
        for (Map<String, List<Double>> map : dict) {
            final Double[] features = map.get("chi1").toArray(new Double[0]);
            final Double[] moreFeatures = map.get("chi2").toArray(new Double[0]);
            final Double[] both = (Double[]) ArrayUtils.addAll(features, moreFeatures);
            final String parameters = serializeFeatureVector(ArrayUtils.toPrimitive(both));
            Logger.getAnonymousLogger().log(Level.INFO, runQuery(args[1], parameters, client));
        }
    }
    client.close();
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<String>();
    queue.offer("First");
    queue.offer("Second");
    queue.offer("Third");
    queue.offer("Fourth");

    System.out.println("Size: " + queue.size());

    System.out.println("Queue head using peek   : " + queue.peek());
    System.out.println("Queue head using element: " + queue.element());

    Object data;/*from   w  w w  .ja v a 2  s.  c o m*/
    while ((data = queue.poll()) != null) {
        System.out.println(data);
    }
}

From source file:drpc.KMeansDrpcQuery.java

public static void main(final String[] args)
        throws IOException, TException, DRPCExecutionException, DecoderException, ClassNotFoundException {
    if (args.length < 3) {
        System.err.println("Where are the arguments? args -- DrpcServer DrpcFunctionName folder");
        return;/*ww  w .j a va  2s.c o m*/
    }

    final DRPCClient client = new DRPCClient(args[0], 3772, 1000000 /*timeout*/);
    final Queue<String> featureFiles = new ArrayDeque<String>();
    SpoutUtils.listFilesForFolder(new File(args[2]), featureFiles);

    Scanner scanner = new Scanner(featureFiles.peek());
    int i = 0;
    while (scanner.hasNextLine() && i++ < 10) {
        List<Map<String, List<Double>>> dict = SpoutUtils.pythonDictToJava(scanner.nextLine());
        for (Map<String, List<Double>> map : dict) {
            i++;

            Double[] features = map.get("chi2").toArray(new Double[0]);
            Double[] moreFeatures = map.get("chi1").toArray(new Double[0]);
            Double[] rmsd = map.get("rmsd").toArray(new Double[0]);
            Double[] both = (Double[]) ArrayUtils.addAll(features, moreFeatures);
            String parameters = serializeFeatureVector(ArrayUtils.toPrimitive(both));

            String centroidsSerialized = runQuery(args[1], parameters, client);

            Gson gson = new Gson();
            Object[] deserialized = gson.fromJson(centroidsSerialized, Object[].class);

            for (Object obj : deserialized) {
                // result we get is of the form List<result>
                List l = ((List) obj);
                centroidsSerialized = (String) l.get(0);

                String[] centroidSerializedArrays = centroidsSerialized
                        .split(MlStormClustererQuery.KmeansClustererQuery.CENTROID_DELIM);
                List<double[]> centroids = new ArrayList<double[]>();
                for (String centroid : centroidSerializedArrays) {
                    centroids.add(MlStormFeatureVectorUtils.deserializeToFeatureVector(centroid));
                }

                double[] rmsdPrimitive = ArrayUtils.toPrimitive(both);
                double[] rmsdKmeans = new double[centroids.size()];

                for (int k = 0; k < centroids.size(); k++) {
                    System.out.println("centroid        -- " + Arrays.toString(centroids.get(k)));
                    double[] centroid = centroids.get(k);
                    rmsdKmeans[k] = computeRootMeanSquare(centroid);
                }

                System.out.println("1 rmsd original -- " + Arrays.toString(rmsd));
                System.out.println("2 rmsd k- Means -- " + Arrays.toString(rmsdKmeans));
                System.out.println();
            }

        }
    }
    client.close();
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<>();
    queue.add("Java");
    // offer() will work the same as add()
    queue.offer("SQL");
    queue.offer("CSS");
    queue.offer("XML");

    System.out.println("Queue: " + queue);

    // Let's remove elements until the queue is empty
    while (queue.peek() != null) {
        System.out.println("Head  Element: " + queue.peek());
        queue.remove();//from   w  w  w.j  a  v  a 2s . c o m
        System.out.println("Removed one  element from  Queue");
        System.out.println("Queue: " + queue);
    }
    System.out.println("queue.isEmpty(): " + queue.isEmpty());
    System.out.println("queue.peek(): " + queue.peek());
    System.out.println("queue.poll(): " + queue.poll());
    try {
        String str = queue.element();
        System.out.println("queue.element(): " + str);
        str = queue.remove();
        System.out.println("queue.remove(): " + str);
    } catch (NoSuchElementException e) {
        System.out.println("queue.remove(): Queue is  empty.");
    }
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<String>();

    queue.add("A");
    queue.add("B");

    queue.offer("C");
    queue.offer("D");

    System.out.println("remove: " + queue.remove());

    System.out.println("element: " + queue.element());

    System.out.println("poll: " + queue.poll());

    System.out.println("peek: " + queue.peek());
}

From source file:ComparablePerson.java

public static void main(String[] args) {
    int initialCapacity = 5;
    Comparator<ComparablePerson> nameComparator = Comparator.comparing(ComparablePerson::getName);

    Queue<ComparablePerson> pq = new PriorityQueue<>(initialCapacity, nameComparator);
    pq.add(new ComparablePerson(1, "Oracle"));
    pq.add(new ComparablePerson(4, "XML"));
    pq.add(new ComparablePerson(2, "HTML"));
    pq.add(new ComparablePerson(3, "CSS"));
    pq.add(new ComparablePerson(4, "Java"));

    System.out.println("Priority  queue: " + pq);

    while (pq.peek() != null) {
        System.out.println("Head  Element: " + pq.peek());
        pq.remove();/*ww  w . j  av a2  s.  co m*/
        System.out.println("Removed one  element from  Queue");
        System.out.println("Priority  queue: " + pq);
    }
}

From source file:info.magnolia.vaadin.periscope.result.SupplierUtil.java

/**
 * Highlight (using HTML tags) all occurrences of a query string, ignoring case.
 *
 * @param text Text in which parts should be highlighted
 * @param query Parts to highlight/*from  w  ww  .ja v  a  2  s.  c o m*/
 * @return Highlighted string
 */
public static String highlight(final String text, final String query) {
    if (StringUtils.isBlank(query)) {
        return text;
    }

    final List<Integer> startIndices = allIndicesOf(text, query);
    final List<Integer> endIndices = startIndices.stream().map(i -> i + query.length()).collect(toList());

    // we run back to front to not mess up indices when inserting tags
    Collections.reverse(startIndices);
    Collections.reverse(endIndices);
    Queue<Integer> startQueue = new LinkedList<>(startIndices);
    Queue<Integer> endQueue = new LinkedList<>(endIndices);

    StringBuilder highlighted = new StringBuilder(text);
    while (!startQueue.isEmpty() || !endQueue.isEmpty()) {
        final Integer startCandidate = startQueue.peek();
        final Integer endCandidate = endQueue.peek();

        if (startCandidate != null && (endCandidate == null || startCandidate > endCandidate)) {
            highlighted.insert(startCandidate, "<strong>");
            startQueue.poll();
        } else {
            highlighted.insert(endCandidate, "</strong>");
            endQueue.poll();
        }
    }

    return highlighted.toString();
}

From source file:de.saxsys.synchronizefx.core.metamodel.executors.RepairingSingleValuePropertyCommandExecutor.java

@Override
public void execute(final SetPropertyValue command) {
    @SuppressWarnings("unchecked")
    final Property<Object> property = (Property<Object>) objectRegistry.getByIdOrFail(command.getPropertyId());
    final Queue<UUID> localCommands = propertyToChangeLog.get(property);

    if (!(localCommands == null || localCommands.isEmpty())) {
        if (localCommands.peek().equals(command.getCommandId())) {
            localCommands.poll();//from w  w  w . j  a  v  a  2s.  c om
        }
        return;
    }

    executor.execute(command);
}

From source file:com.clustercontrol.jobmanagement.util.JobMultiplicityCache.java

/**
 * ??//from w w w.  jav  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.ibm.amc.feedback.FeedbackHandler.java

public FeedbackHandler() {
    if (logger.isEntryEnabled())
        logger.entry("FeedbackHandler");

    mapper = new ObjectMapper();
    mapper.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    ShutdownListener.addShutdownListener(this);

    ActionFactory.getActionLog().addActionListener(this);

    // Check for action statuses that are too old and remove them
    executor.scheduleAtFixedRate(new Runnable() {

        @Override//from  w  w w .  j  av  a 2 s .c o m
        public void run() {
            final Date date = new Date(System.currentTimeMillis() - ACTION_STATUS_TIMEOUT);
            synchronized (statuses) {
                for (Queue<ActionStatusResponse> queue : statuses.values()) {
                    while (queue.peek().updated.before(date)) {
                        final ActionStatusResponse response = queue.poll();
                        if (logger.isDebugEnabled())
                            logger.debug("FeedbackHandler$Runnable.run",
                                    "Expiring action feedback response for action " + response.actionId);
                    }
                }
            }

        }
    }, ACTION_STATUS_TIMEOUT, ACTION_STATUS_TIMEOUT, TimeUnit.MILLISECONDS);

    if (logger.isEntryEnabled())
        logger.exit("FeedbackHandler");
}