Example usage for java.util Queue size

List of usage examples for java.util Queue size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

From source file:org.opentestsystem.airose.docprocessors.ConventionsQualityDocProcessor.java

private ConventionsDocumentQualityHolder evaluateSyntax(Parse parse) {

    double overallPunctScore = 0.0;
    double minSyntaxScore = 1.0;
    double overallSyntaxScore = 0.0;

    double numOfNoms = 0;
    double numLongNominals = 0;
    double syntaxCount = 0;

    int countPunct = 0;

    Queue<Parse> parseTree = new LinkedList<Parse>();
    parseTree.add(parse);//from w  w w.j a v  a 2  s  .c o m
    double rootProb = parse.getProb();

    while (parseTree.size() > 0) {
        Parse p = parseTree.remove();
        if ((p.getChildCount() == 1) && (p.getProb() < 1)) {
            double prob = p.getProb();
            String pType = p.getType();
            if (StringUtils.equals(pType, ",") || StringUtils.equals(pType, ".")
                    || StringUtils.equals(pType, "!") || StringUtils.equals(pType, "?")
                    || StringUtils.equals(pType, ";") || StringUtils.equals(pType, ":")) {
                overallPunctScore += prob;
                countPunct++;
            } else {
                if (!StringUtils.equals(pType, "TOP") && !StringUtils.equals(pType, "S")) {
                    // string s = sentText_;
                    if ((pType.startsWith("NN")))// || p.Type.StartsWith("JJ"))
                    {
                        numOfNoms++;
                    } else {
                        if ((numOfNoms > 2) && (rootProb > -25.5))
                            numLongNominals++;
                        // _numOfNoms = 0;
                    }

                    if (prob < minSyntaxScore)
                        minSyntaxScore = prob;

                    overallSyntaxScore += prob;
                    syntaxCount++;
                }
            }
        }

        Parse[] children = p.getChildren();
        for (Parse pc : children)
            parseTree.add(pc);
    }
    overallPunctScore = (countPunct == 0) ? 0.0 : overallPunctScore / countPunct;

    ConventionsDocumentQualityHolder values = new ConventionsDocumentQualityHolder();
    values.setOverallPunctScore(overallPunctScore);
    values.setMinSyntaxScore(minSyntaxScore);
    values.setOverallSyntaxScore(overallSyntaxScore);
    values.setNumOfNoms(numOfNoms);
    values.setNumLongNominals(numLongNominals);
    values.setSyntaxCount(syntaxCount);

    return values;
}

From source file:com.sishuok.chapter3.web.controller.chat.MsgPublisher.java

public void logout(String username) {
    if (username == null) {
        return;/*from   w ww . ja v  a 2 s  . c  o  m*/
    }
    Queue<DeferredResult<String>> queue = usernameToDeferredResultMap.get(username);
    boolean isLogout = false;
    if (queue != null) {
        if (queue.size() == 0) {
            isLogout = true;
        } else {
            isLogout = true;
            Iterator<DeferredResult<String>> iter = queue.iterator();
            while (iter.hasNext()) {
                DeferredResult<String> result = iter.next();
                if (!result.isSetOrExpired()) {
                    isLogout = false;
                    break;
                }
            }
        }
    }

    if (isLogout) {
        StringBuilder data = new StringBuilder();
        data.append("{");
        data.append("\"type\" : \"logout\"");
        data.append(",\"username\" : \"" + username + "\"");
        data.append("}");
        publish(null, username, data.toString());
        usernameToDeferredResultMap.remove(username);
    }
}

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) {
        // //from   w w  w  .j  a  v a 2  s  .  co 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:org.bigwiv.blastgraph.SubSetCluster.java

@Override
public Set<Set<V>> transform(UndirectedGraph<V, E> theGraph) {
    Set<Set<V>> subSets = new LinkedHashSet<Set<V>>();

    if (theGraph.getVertices().isEmpty())
        return subSets;

    isVisited = new HashMap<V, Number>();
    for (V v : theGraph.getVertices()) {
        isVisited.put(v, 0);//  www.  j  a va  2 s .c om
    }

    for (V v : theGraph.getVertices()) {
        if (isVisited.get(v).intValue() == 0) {
            Set<V> subSet = new HashSet<V>();
            subSet.add(v);

            //            Stack<V> toVisitStack = new Stack<V>();//stack for DFS
            //            toVisitStack.push(v);
            //
            //            while (toVisitStack.size() != 0) {
            //               V curV = toVisitStack.pop();
            //               isVisited.put(curV, 1);
            //               for (V w : theGraph.getNeighbors(curV)) {
            //                  if (isVisited.get(w).intValue() == 0) // w hasn't yet
            //                                                // been visited
            //                  {
            //                     subSet.add(w);
            //                     toVisitStack.push(w);
            //                  }
            //               }
            //
            //            }

            Queue<V> toVisitQueue = new LinkedList<V>();//Queue for BFS
            toVisitQueue.add(v);

            while (toVisitQueue.size() != 0) {
                V curV = toVisitQueue.remove();
                isVisited.put(curV, 1);
                for (V w : theGraph.getNeighbors(curV)) {
                    if (isVisited.get(w).intValue() == 0) // w hasn't yet
                    // been visited
                    {
                        subSet.add(w);
                        toVisitQueue.add(w);
                    }
                }

            }

            subSets.add(subSet);
        }
    }
    return subSets;
}

From source file:org.polymap.rhei.batik.layout.cp.BestFirstOptimizerTest.java

@Test
public void boundSolutionQueue() {
    Queue<TestScoredSolution> queue = SolutionQueueBuilder.create(3);
    queue.add(new TestScoredSolution(PercentScore.NULL));
    queue.add(new TestScoredSolution(new PercentScore(10)));

    assertEquals(2, queue.size());
    //        assertEquals( PercentScore.NULL, queue.getFirst().score );
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(5)));
    assertEquals(3, queue.size());/*ww w.  java  2 s .com*/
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(5)));
    assertEquals(3, queue.size());
    //        assertEquals( new PercentScore( 5 ), queue.getFirst().score );
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(20)));
    assertEquals(3, queue.size());
    //        assertEquals( new PercentScore( 5 ), queue.getFirst().score );
    assertEquals(new PercentScore(20), queue.peek().score);
}

From source file:org.polymap.rhei.batik.layout.cp.BestFirstOptimizerTest.java

@Test
public void unboundSolutionQueue() {
    Queue<TestScoredSolution> queue = SolutionQueueBuilder.create(-1);
    queue.add(new TestScoredSolution(PercentScore.NULL));
    queue.add(new TestScoredSolution(new PercentScore(10)));

    assertEquals(2, queue.size());
    //        assertEquals( PercentScore.NULL, queue.getFirst().score );
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(5)));
    assertEquals(3, queue.size());/*ww w  . jav  a 2  s.  c o m*/
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(5)));
    //        assertEquals( 3, queue.size() );
    //        assertEquals( new PercentScore( 5 ), queue.getFirst().score );
    assertEquals(new PercentScore(10), queue.peek().score);

    queue.add(new TestScoredSolution(new PercentScore(20)));
    //        assertEquals( 3, queue.size() );
    //        assertEquals( new PercentScore( 5 ), queue.getFirst().score );
    assertEquals(new PercentScore(20), queue.peek().score);
}

From source file:org.auraframework.test.util.PooledRemoteWebDriverFactory.java

@Override
public synchronized WebDriver get(final DesiredCapabilities capabilities) {
    // default to use a pooled instance unless the test explicitly requests a brand new instance
    Object reuseBrowser = capabilities.getCapability(WebDriverProvider.REUSE_BROWSER_PROPERTY);
    if ((reuseBrowser != null) && (reuseBrowser.equals(false))) {
        return super.get(capabilities);
    }// w  w  w  .j a  v a  2s . c  o m

    Queue<PooledRemoteWebDriver> pool = pools.get(capabilities);

    if (pool == null) {
        pool = new LinkedList<>();
        pools.put(capabilities, pool);
    }

    if (pool.size() > 0) {
        return pool.poll();
    } else {
        final Queue<PooledRemoteWebDriver> thisPool = pool;
        return retry(new Callable<WebDriver>() {
            @Override
            public WebDriver call() throws Exception {
                return new PooledRemoteWebDriver(thisPool, serverUrl, capabilities);
            }
        }, MAX_GET_RETRIES, getGetDriverTimeout(capabilities), "Failed to get a new PooledRemoteWebDriver");
    }
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

@Override
protected void doPost(HttpRequest request, HttpResponse response) throws IOException {
    HttpSession session = request.getSession();
    if (null != session) {
        try {/* ww w  .j  a  v a  2  s.com*/
            // ??
            JSONObject json = new JSONObject(new String(request.readRequestData(), Charset.forName("UTF-8")));
            // ? JSON ?
            String speakerTag = json.getString(Tag);
            String celletIdentifier = json.getString(Identifier);
            JSONObject primitiveJSON = json.getJSONObject(Primitive);
            // ?
            Primitive primitive = new Primitive(speakerTag);
            PrimitiveSerializer.read(primitive, primitiveJSON);
            // ?
            this.talkService.processDialogue(session, speakerTag, celletIdentifier, primitive);

            // ?
            // FIXME 2014/10/03 ??
            JSONObject responseData = new JSONObject();

            // ??
            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) {
                        // ? cellet identifier
                        byte[] identifier = packet.getSubsegment(1);

                        // ?????
                        byte[] primData = packet.getSubsegment(0);
                        ByteArrayInputStream stream = new ByteArrayInputStream(primData);

                        // ???
                        Primitive prim = new Primitive(Nucleus.getInstance().getTagAsString());
                        prim.read(stream);

                        // 
                        identifiers.add(Utils.bytes2String(identifier));
                        primitives.add(prim);
                    }
                }

                // ?
                JSONArray jsonPrimitives = this.convert(identifiers, primitives);
                responseData.put(Primitives, jsonPrimitives);
            }

            // ?
            responseData.put(Queue, queue.size());

            // ?
            this.respondWithOk(response, responseData);
        } catch (JSONException e) {
            Logger.log(HttpDialogueHandler.class, e, LogLevel.ERROR);
            this.respond(response, HttpResponse.SC_BAD_REQUEST);
        }
    } else {
        this.respond(response, HttpResponse.SC_UNAUTHORIZED);
    }
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {//from  w ww  .java  2s  .c om
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

                // Get system properties
                Properties properties = new Properties();

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

                try {
                    // Create a default MimeMessage object.
                    MimeMessage message = new MimeMessage(session);

                    // Set From: header field of the header.
                    message.setFrom(new InternetAddress(mailFrom));

                    // Set To: header field of the header.
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

                    // Set Subject: header field
                    message.setSubject(conf.getMailSubject());

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

From source file:au.org.ala.delta.intkey.directives.StandardIntkeyDirective.java

@Override
public IntkeyDirectiveInvocation doProcess(IntkeyContext context, String data) throws Exception {
    StringBuilder stringRepresentationBuilder = new StringBuilder();
    stringRepresentationBuilder.append(StringUtils.join(getControlWords(), " ").toUpperCase());

    List<String> tokens = ParsingUtils.tokenizeDirectiveCall(data);
    Queue<String> tokenQueue = new ArrayDeque<String>(tokens);

    IntkeyDirectiveInvocation invoc = buildCommandObject();

    if (_intkeyFlagsList != null && tokenQueue.size() > 0) {
        boolean matchingFlags = true;
        while (matchingFlags) {
            boolean tokenMatched = false;
            String token = tokenQueue.peek();

            if (token != null) {
                for (IntkeyDirectiveFlag flag : _intkeyFlagsList) {
                    if (flag.takesStringValue()) {
                        // Flag can have a string value supplied with it in
                        // format "/X=string", where X is the character
                        // symbol. Note that
                        // it is acceptable to supply such a flag without a
                        // following equals sign and string value.
                        if (token.matches("^/[" + Character.toLowerCase(flag.getSymbol())
                                + Character.toUpperCase(flag.getSymbol()) + "](=.+)?")) {

                            // If string value is not supplied, it defaults
                            // to empty string
                            String flagStringValue = "";

                            String[] tokenPieces = token.split("=");

                            // There should only be 0 or 1 equals sign. If
                            // more than none is supplied, no match.
                            if (tokenPieces.length < 3) {
                                if (tokenPieces.length == 2) {
                                    flagStringValue = tokenPieces[1];
                                }/*from   w  w  w . j  a v a2s . com*/

                                BeanUtils.setProperty(invoc, flag.getName(), flagStringValue);
                                tokenQueue.remove();
                                tokenMatched = true;
                                stringRepresentationBuilder.append(" ");
                                stringRepresentationBuilder.append(token);
                                break;
                            }
                        }
                    } else {
                        if (token.equalsIgnoreCase("/" + flag.getSymbol())) {

                            BeanUtils.setProperty(invoc, flag.getName(), true);
                            tokenQueue.remove();
                            tokenMatched = true;
                            stringRepresentationBuilder.append(" ");
                            stringRepresentationBuilder.append(token);
                            break;
                        }
                    }
                }

                matchingFlags = tokenMatched;
            } else {
                matchingFlags = false;
            }
        }
    }

    // The arguments list needs to be generated each time a call to the
    // directive is processed. This is
    // because most arguments need to have provided with an initial value
    // which is used when prompting the user.
    // This initial value needs to be read out of the IntkeyContext at the
    // time of parsing.
    // E.g. the integer argument for the SET TOLERANCE directive will have
    // an initial value equal to the
    // the value of the tolerance setting before the call to the directive.
    List<IntkeyDirectiveArgument<?>> intkeyArgsList = generateArgumentsList(context);

    if (intkeyArgsList != null) {
        for (IntkeyDirectiveArgument<?> arg : intkeyArgsList) {
            Object parsedArgumentValue = arg.parseInput(tokenQueue, context,
                    StringUtils.join(_controlWords, " "), stringRepresentationBuilder);
            if (parsedArgumentValue != null) {
                BeanUtils.setProperty(invoc, arg.getName(), parsedArgumentValue);
            } else {
                // No argument value supplied, user cancelled out of the
                // prompt dialog.
                return null;
            }
        }
    }

    invoc.setStringRepresentation(stringRepresentationBuilder.toString());

    return invoc;
}