Example usage for java.util Deque isEmpty

List of usage examples for java.util Deque isEmpty

Introduction

In this page you can find the example usage for java.util Deque isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:nl.knaw.huc.di.tag.tagml.importer.TAGMLListener.java

private TAGMarkup removeFromMarkupStack(String extendedTag, Deque<TAGMarkup> markupStack) {
    if (markupStack == null || markupStack.isEmpty()) {
        return null;
    }/*from   ww w . j av a2s . c o m*/
    final TAGMarkup expected = markupStack.peek();
    if (extendedTag.equals(expected.getExtendedTag())) {
        markupStack.pop();
        currentTextVariationState().removeOpenMarkup(expected);
        return expected;
    }
    return null;
}

From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java

@Override
public String getContentStripped() {
    if (strippedContent != null)
        return strippedContent;
    synchronized (mutex) {
        if (strippedContent != null)
            return strippedContent;
        String tmp = getContentDisplay();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>(Comparator.comparingInt(t -> t.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find())
                tokens.add(new FormatToken(key, matcher.start()));
        }/*from   w w  w  . j  a  va2  s  .  co  m*/

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Deque<FormatToken> stack = new ArrayDeque<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.isEmpty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start)

            {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.isEmpty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.isEmpty())
                    //close tag closed the block
                    inBlock = false;
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        toRemove.sort(Comparator.comparingInt(t -> t.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start)
                out.append(tmp.substring(currIndex, formatToken.start));
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length())
            out.append(tmp.substring(currIndex));
        //return the stripped text, escape all remaining formatting characters (did not have matching
        // open/close before or were left/right of block
        return strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
}

From source file:RandomChooser.java

private RandomChooser(List<Double> weights, List<T> events, Random random) {
    double sum = 0.0;
    for (double prob : weights)
        sum += prob;//  ww  w  .  j ava2s.c o  m

    this.probs = new double[weights.size()];
    for (int i = 0; i < weights.size(); i++) {
        probs[i] = weights.get(i) * weights.size() / sum; //average = 1.0
    }

    Deque<Integer> smaller = new ArrayDeque<Integer>(weights.size() / 2 + 2);
    Deque<Integer> greater = new ArrayDeque<Integer>(weights.size() / 2 + 2);
    for (int i = 0; i < probs.length; i++) {
        if (probs[i] < 1.0) {
            smaller.push(i);
        } else {
            greater.push(i);
        }
    }
    indexes = new int[weights.size()];
    while (!smaller.isEmpty()) {
        Integer i = smaller.pop();
        Integer k = greater.peek();
        indexes[i] = k;
        probs[k] -= (1 - probs[i]);
        if (probs[k] < 1.0) {
            greater.pop();
            if (greater.isEmpty())
                break;
            smaller.push(k);
        }
    }
    this.events = events;
    this.random = random;
}

From source file:org.finra.herd.service.impl.JobServiceImpl.java

@Override
public Job deleteJob(String jobId, JobDeleteRequest jobDeleteRequest) throws Exception {
    Assert.hasText(jobId, "jobId must be specified");
    Assert.notNull(jobDeleteRequest, "jobDeleteRequest must be specified");
    Assert.hasText(jobDeleteRequest.getDeleteReason(), "deleteReason must be specified");

    // Trim input parameters.
    String localJobId = jobId.trim();

    ProcessInstance mainProcessInstance = activitiService.getProcessInstanceById(localJobId);

    if (mainProcessInstance != null) {
        checkPermissions(mainProcessInstance.getProcessDefinitionKey(),
                new NamespacePermissionEnum[] { NamespacePermissionEnum.EXECUTE });

        // Load all processes (main process and sub-processes) into a deque to be later deleted.
        Deque<String> processInstanceIds = new ArrayDeque<>();
        processInstanceIds.push(mainProcessInstance.getProcessInstanceId());
        Deque<String> superProcessInstanceIds = new ArrayDeque<>();
        superProcessInstanceIds.push(mainProcessInstance.getProcessInstanceId());
        while (!superProcessInstanceIds.isEmpty()) {
            String superProcessInstanceId = superProcessInstanceIds.pop();

            // Get all executions with the parent id equal to the super process instance id.
            for (Execution execution : activitiRuntimeService.createExecutionQuery()
                    .parentId(superProcessInstanceId).list()) {
                processInstanceIds.push(execution.getId());
            }// w  ww . j  ava2s  .  c  o  m

            // Get all active sub-processes for the super process instance id.
            for (ProcessInstance subProcessInstance : activitiRuntimeService.createProcessInstanceQuery()
                    .superProcessInstanceId(superProcessInstanceId).active().list()) {
                processInstanceIds.push(subProcessInstance.getId());
                superProcessInstanceIds.push(subProcessInstance.getId());
            }
        }

        // Delete all processes individually in LIFO order.
        while (!processInstanceIds.isEmpty()) {
            activitiService.deleteProcessInstance(processInstanceIds.pop(), jobDeleteRequest.getDeleteReason());
        }
    } else {
        throw new ObjectNotFoundException(
                String.format("Job with ID \"%s\" does not exist or is already completed.", localJobId));
    }

    return getJob(localJobId, false, false);
}

From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java

/**
 * Creates a zip file./*from   ww w  .  ja  v a 2s  .  co m*/
 * @param dir                   The Directory of the files to be zipped.
 * @param zip                   An output stream to write the file
 * @throws IOException
 */
private void createZip(File dir, ZipArchiveOutputStream zip) throws IOException {
    Deque<File> dir_stack = new LinkedList<File>();
    dir_stack.push(dir);

    // base path is the parent of the "Application.app" folder
    // it will be used to make "Application.app" the top-level folder in the zip
    String base_path = getParentDirAbsolutePath(dir);

    // verify that "dir" actually id the ".app" folder
    if (!dir.getName().endsWith(".app"))
        throw new IOException("Please verify the configuration. Directory does not end with '.app': " + dir);

    while (!dir_stack.isEmpty()) {

        File file = dir_stack.pop();
        File[] files = file.listFiles();

        for (File f : files) {
            String name = f.getAbsolutePath().substring(base_path.length());
            getLog().debug("Found: " + name);

            if (f.isFile() && isInContentsFolder(name)) {
                getLog().debug("Adding to zip file for signing: " + f);

                ZipArchiveEntry entry = new ZipArchiveEntry(name);
                zip.putArchiveEntry(entry);

                if (f.canExecute()) {
                    //work around to track the relative file names
                    // of those that need to be set as executable on unZip
                    executableFiles.add(name);
                }
                InputStream is = new FileInputStream(f);
                copyInputStreamToOutputStream(is, zip);

                is.close();
                zip.closeArchiveEntry();
            } else if (f.isDirectory() && isInContentsFolder(name)) { //add directory entry
                dir_stack.push(f);
            } else {
                getLog().debug(f + " was not included in the zip file to be signed.");
            }
        }
    }
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

/**
 * Parse XML into a simple Map structure.
 * /*  ww  w .  jav a2s .  c  o m*/
 * @param in
 *        the input stream to parse
 * @return a Map of the XML
 */
public Map<String, Object> parseXml(InputStream in) {
    Deque<Map<String, Object>> stack = new LinkedList<Map<String, Object>>();
    Map<String, Object> result = null;
    XMLStreamReader reader = startParse(in);
    try {
        int eventType;
        boolean parsing = true;
        while (parsing) {
            eventType = reader.next();
            switch (eventType) {
            case XMLStreamConstants.END_DOCUMENT:
                parsing = false;
                break;

            case XMLStreamConstants.START_ELEMENT:
                String name = reader.getLocalName();
                if (stack.isEmpty()) {
                    result = new LinkedHashMap<String, Object>();
                    stack.push(result);
                } else {
                    Map<String, Object> el = new LinkedHashMap<String, Object>();
                    putMapValue(stack.peek(), name, el);
                    stack.push(el);
                }
                parseElement(stack.peek(), reader);
                break;

            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        endParse(reader);
    }
    return result;
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

@Override
public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    try {//from   www.j  a  v a  2 s  .  c  om
        Collection<Link> simpleLinks = new ArrayList<Link>();
        Collection<Affordance> affordances = new ArrayList<Affordance>();
        Collection<Link> templatedLinks = new ArrayList<Link>();
        Collection<Affordance> collectionAffordances = new ArrayList<Affordance>();
        Link selfRel = null;
        for (Link link : links) {
            if (link instanceof Affordance) {
                final Affordance affordance = (Affordance) link;
                final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    // TODO: consider to use Link href for template even if it is not compatible
                    if (affordance.getUriTemplateComponents().hasVariables()) {
                        // TODO resolve rel against context
                        if ("hydra:search".equals(affordance.getRel())
                                || Cardinality.SINGLE == affordance.getCardinality()) {
                            templatedLinks.add(affordance);
                        } else {
                            collectionAffordances.add(affordance);
                        }
                    } else {
                        // if all required variables are satisfied, the url can be used as identifier
                        // by stripping optional variables
                        if (!affordance.isSelfRel() && Cardinality.COLLECTION == affordance.getCardinality()) {
                            collectionAffordances.add(affordance);
                        } else {
                            affordances.add(affordance);
                        }
                    }
                } else {
                    if (affordance.isTemplated()) {
                        templatedLinks.add(affordance);
                    } else {
                        simpleLinks.add(affordance);
                    }
                }
            } else if (link.isTemplated()) {
                templatedLinks.add(link);
            } else {
                simpleLinks.add(link);
            }
            if ("self".equals(link.getRel())) {
                selfRel = link;
            }
        }

        for (Link templatedLink : templatedLinks) {
            // templated affordance might turn out to have all variables satisfied or
            // only optional unsatisfied variables
            ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(templatedLink);
            // TODO handle rev here
            String rel = templatedLink.getRel();
            writeIriTemplate(rel, templatedLink.getHref(), templatedLink.getVariableNames(),
                    actionDescriptorForHttpGet, jgen);
        }
        @SuppressWarnings("unchecked")
        Deque<LdContext> contextStack = (Deque<LdContext>) serializerProvider
                .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
        String currentVocab = (contextStack != null && !contextStack.isEmpty()) ? contextStack.peek().vocab
                : null;

        // related collections
        if (!collectionAffordances.isEmpty()) {

            jgen.writeArrayFieldStart("hydra:collection");

            for (Affordance collectionAffordance : collectionAffordances) {
                jgen.writeStartObject();
                jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection");
                PartialUriTemplateComponents templateComponents = collectionAffordance
                        .getUriTemplateComponents();
                if (!collectionAffordance.isBaseUriTemplated()
                        && !collectionAffordance.hasUnsatisfiedRequiredVariables()) {
                    String collectionUri = templateComponents.getBaseUri() + templateComponents.getQueryHead();
                    jgen.writeStringField(JsonLdKeywords.AT_ID, collectionUri);
                }
                if (templateComponents.hasVariables()) {
                    ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(
                            collectionAffordance);
                    writeIriTemplate("hydra:search", templateComponents.toString(),
                            templateComponents.getVariableNames(), actionDescriptorForHttpGet, jgen);
                }
                jgen.writeObjectFieldStart("hydra:manages");
                // do we have a collection holder which is not owner of the affordance?
                TypedResource collectionHolder = collectionAffordance.getCollectionHolder();
                if (collectionAffordance.getRev() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRev());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:object", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:object", selfRel.getHref());
                    }
                } else if (collectionAffordance.getRel() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRel());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:subject", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:subject", selfRel.getHref());
                    }
                }
                jgen.writeEndObject(); // end manages

                List<ActionDescriptor> actionDescriptors = collectionAffordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeArrayFieldStart("hydra:operation");
                }
                writeActionDescriptors(jgen, currentVocab, actionDescriptors);
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeEndArray(); // end hydra:operation
                }

                jgen.writeEndObject(); // end collection
            }
            jgen.writeEndArray();
        }

        for (Affordance affordance : affordances) {
            final String rel = affordance.getRel();
            List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();

            if (!actionDescriptors.isEmpty()) {
                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeObjectFieldStart(rel); // begin rel
                }
                jgen.writeStringField(JsonLdKeywords.AT_ID, affordance.getHref());
                jgen.writeArrayFieldStart("hydra:operation");
            }

            writeActionDescriptors(jgen, currentVocab, actionDescriptors);

            if (!actionDescriptors.isEmpty()) {
                jgen.writeEndArray(); // end hydra:operation

                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeEndObject(); // end rel
                }
            }
        }

        for (Link simpleLink : simpleLinks) {
            final String rel = simpleLink.getRel();
            if (Link.REL_SELF.equals(rel)) {
                jgen.writeStringField("@id", simpleLink.getHref());
            } else {
                String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
                jgen.writeObjectFieldStart(linkAttributeName);
                jgen.writeStringField("@id", simpleLink.getHref());
                jgen.writeEndObject();
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.pig.builtin.Utf8StorageConverter.java

private Map<String, Object> consumeMap(PushbackInputStream in, ResourceFieldSchema fieldSchema)
        throws IOException {
    int buf;/*from  w ww . j  a  va  2s  . c om*/
    boolean emptyMap = true;

    while ((buf = in.read()) != '[') {
        if (buf == -1) {
            throw new IOException("Unexpect end of map");
        }
    }
    HashMap<String, Object> m = new HashMap<String, Object>();
    ByteArrayOutputStream mOut = new ByteArrayOutputStream(BUFFER_SIZE);
    while (true) {
        // Read key (assume key can not contains special character such as #, (, [, {, }, ], )
        while ((buf = in.read()) != '#') {
            // end of map
            if (emptyMap && buf == ']') {
                return m;
            }
            if (buf == -1) {
                throw new IOException("Unexpect end of map");
            }
            emptyMap = false;
            mOut.write(buf);
        }
        String key = bytesToCharArray(mOut.toByteArray());
        if (key.length() == 0)
            throw new IOException("Map key can not be null");

        // Read value
        mOut.reset();
        Deque<Character> level = new LinkedList<Character>(); // keep track of nested tuple/bag/map. We do not interpret, save them as bytearray
        while (true) {
            buf = in.read();
            if (buf == -1) {
                throw new IOException("Unexpect end of map");
            }
            if (buf == '[' || buf == '{' || buf == '(') {
                level.push((char) buf);
            } else if (buf == ']' && level.isEmpty()) // End of map
                break;
            else if (buf == ']' || buf == '}' || buf == ')') {
                if (level.isEmpty())
                    throw new IOException("Malformed map");

                if (level.peek() == findStartChar((char) buf))
                    level.pop();
            } else if (buf == ',' && level.isEmpty()) { // Current map item complete
                break;
            }
            mOut.write(buf);
        }
        Object value = null;
        if (fieldSchema != null && fieldSchema.getSchema() != null && mOut.size() > 0) {
            value = bytesToObject(mOut.toByteArray(), fieldSchema.getSchema().getFields()[0]);
        } else if (mOut.size() > 0) { // untyped map
            value = new DataByteArray(mOut.toByteArray());
        }
        m.put(key, value);
        mOut.reset();
        if (buf == ']')
            break;
    }
    return m;
}

From source file:org.roche.antibody.services.graphsynchronizer.GraphSynchronizer.java

private HELMCode buildHelm(Domain activeDomain) {
    HELMCode code = new HELMCode();
    Deque<Sequence> sequencesToHandle = new ArrayDeque<Sequence>();
    handledConnections.clear();//from w  w w . j a v a2s . co  m
    handledInterDomainConnections.clear();
    handledSequences.clear();
    sequencesToHandle.offer(activeDomain);
    Map<Sequence, HELMElement> helmElemMap = new HashMap<Sequence, HELMElement>();
    while (sequencesToHandle.isEmpty() == false) {
        Sequence seqToHandle = sequencesToHandle.poll();
        Sequence seqForConnectionCheck = seqToHandle;

        if (handledSequences.contains(seqToHandle)) {
            continue;
        } else {
            handledSequences.add(seqToHandle);
        }

        if (seqToHandle instanceof Domain) {
            activeDomain = (Domain) seqToHandle;
            HELMElement pep = seqService.toHELM(activeDomain);
            code.addHELMElement(pep);
            helmElemMap.put(activeDomain.getPeptide(), pep);
            seqForConnectionCheck = activeDomain.getPeptide();
        }

        for (Connection con : seqToHandle.getConnections()) {
            if (handledConnections.contains(con)) {
                continue;
            }
            if (con instanceof GeneralConnection) {
                HELMConnection helmCon = null;
                if (con.getSource() == seqForConnectionCheck && con.getTarget() == seqForConnectionCheck) {
                    HELMElement element = seqService.toHELM(seqToHandle);
                    code.addHELMElement(element);
                    helmCon = connectionService.createConnection(con, element, element);
                } else {
                    HELMElement source = helmElemMap.get(con.getSource());
                    if (source == null) {
                        source = seqService.toHELM(con.getSource());
                        helmElemMap.put(con.getSource(), source);
                        code.addHELMElement(source);
                        sequencesToHandle.push(con.getSource());
                    }

                    HELMElement target = helmElemMap.get(con.getTarget());
                    if (target == null) {
                        target = seqService.toHELM(con.getTarget());
                        helmElemMap.put(con.getTarget(), target);
                        code.addHELMElement(target);
                        sequencesToHandle.push(con.getTarget());
                    }
                    helmCon = connectionService.createConnection(con, source, target);
                }
                code.addHELMConnection(helmCon);
                handledConnections.add(con);
            }
            if (con instanceof CysteinConnection && connectionService.isIntraDomainConnection(con)) {
                HELMConnection helmCon = connectionService.createConnection(con,
                        helmElemMap.get(activeDomain.getPeptide()), helmElemMap.get(activeDomain.getPeptide()));
                handledConnections.add(con);
                code.addHELMConnection(helmCon);
            }
            if (con instanceof CysteinConnection && !connectionService.isIntraDomainConnection(con)) {
                handledInterDomainConnections.add(con);
            }
        }
    }
    return code;
}