Example usage for java.util LinkedList addFirst

List of usage examples for java.util LinkedList addFirst

Introduction

In this page you can find the example usage for java.util LinkedList addFirst.

Prototype

public void addFirst(E e) 

Source Link

Document

Inserts the specified element at the beginning of this list.

Usage

From source file:org.apache.metron.common.stellar.StellarCompiler.java

@Override
public void exitList_entity(StellarParser.List_entityContext ctx) {
    expression.tokenDeque.push(new Token<>((tokenDeque, state) -> {
        LinkedList<Object> args = new LinkedList<>();
        while (true) {
            Token<?> token = popDeque(tokenDeque);
            if (token.getUnderlyingType().equals(FunctionMarker.class)) {
                break;
            } else {
                args.addFirst(token.getValue());
            }/*from w  ww. j a v  a  2  s .  c om*/
        }
        tokenDeque.push(new Token<>(args, List.class));
    }, DeferredFunction.class));
}

From source file:org.ejbca.ui.web.RequestHelper.java

/**
 * Handles PKCS10 certificate request, these are constructed as: <code> CertificationRequest
 * ::= SEQUENCE { certificationRequestInfo  CertificationRequestInfo, signatureAlgorithm
 * AlgorithmIdentifier{{ SignatureAlgorithms }}, signature                       BIT STRING }
 * CertificationRequestInfo ::= SEQUENCE { version             INTEGER { v1(0) } (v1,...),
 * subject             Name, subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
 * attributes          [0] Attributes{{ CRIAttributes }}} SubjectPublicKeyInfo { ALGORITHM :
 * IOSet} ::= SEQUENCE { algorithm           AlgorithmIdentifier {{IOSet}}, subjectPublicKey
 * BIT STRING }</code> PublicKey's encoded-format has to be RSA X.509.
 *
 * @param signsession signsession to get certificate from
 * @param caSession a reference to CaSessionBean
 * @param b64Encoded base64 encoded pkcs10 request message
 * @param username username of requesting user
 * @param password password of requesting user
 * @param resulttype should indicate if a PKCS7 or just the certificate is wanted.
 * @param doSplitLines/* w  ww. j ava  2s  .c  om*/
 * @return Base64 encoded byte[] 
 * @throws AuthorizationDeniedException 
 * @throws CesecoreException 
 * @throws EjbcaException 
 * @throws CertificateException 
 * @throws CertificateEncodingException 
 * @throws CertificateExtensionException if b64Encoded specified invalid extensions
 */
public CertificateRequestResponse pkcs10CertRequest(SignSessionLocal signsession, CaSessionLocal caSession,
        byte[] b64Encoded, String username, String password, CertificateResponseType resulttype,
        boolean doSplitLines) throws EjbcaException, CesecoreException, AuthorizationDeniedException,
        CertificateEncodingException, CertificateException, CertificateExtensionException {
    byte[] encoded = null;
    Certificate cert = null;
    PKCS10RequestMessage req = RequestMessageUtils.genPKCS10RequestMessage(b64Encoded);
    req.setUsername(username);
    req.setPassword(password);
    ResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
    cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    switch (resulttype) {
    case ENCODED_CERTIFICATE:
        encoded = Base64.encode(cert.getEncoded(), doSplitLines);
        break;
    case ENCODED_CERTIFICATE_CHAIN:
        CAInfo caInfo = signsession.getCAFromRequest(administrator, req, false).getCAInfo();
        LinkedList<Certificate> chain = new LinkedList<Certificate>(caInfo.getCertificateChain());
        chain.addFirst(cert);
        encoded = CertTools.getPemFromCertificateChain(chain);
        break;
    case ENCODED_PKCS7:
        encoded = Base64.encode(signsession.createPKCS7(administrator, cert, true), doSplitLines);
        break;
    default:
        break;
    }
    log.debug("Created certificate (PKCS7) for " + username);
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return new CertificateRequestResponse(cert, encoded);
}

From source file:com.trendrr.oss.networking.strest.StrestHeaders.java

List<String> getHeaders(final String name) {
    if (name == null) {
        throw new NullPointerException("name");
    }//from  w ww  . jav a2  s. c  om

    LinkedList<String> values = new LinkedList<String>();

    int h = hash(name);
    int i = index(h);
    Entry e = entries[i];
    while (e != null) {
        if (e.hash == h && eq(name, e.key)) {
            values.addFirst(e.value);
        }
        e = e.next;
    }
    return values;
}

From source file:org.mycard.net.network.RequestQueue.java

protected synchronized void queueRequest(Request request, boolean head) {
    HttpHost host = request.mProxyHost == null ? request.mHost : request.mProxyHost;
    LinkedList<Request> reqList;
    if (mPending.containsKey(host)) {
        reqList = mPending.get(host);//from w ww.  j  a v  a2  s  .c  om
    } else {
        reqList = new LinkedList<Request>();
        mPending.put(host, reqList);
    }
    if (head) {
        reqList.addFirst(request);
    } else {
        reqList.add(request);
    }
}

From source file:org.richfaces.model.StackingTreeModel.java

private void leaveModel(Iterator<StackEntry> iterator, StackEntry currentEntry, FacesContext context) {
    if (iterator == null) {
        return;/*from   w w w  .  j  ava2 s  . com*/
    }

    LinkedList<StackEntry> stack = new LinkedList<StackEntry>();

    StackingTreeModel lastModel = null;
    if (currentEntry != null) {
        iterator.remove();
        stack.addFirst(currentEntry);
        lastModel = currentEntry.model;
    }

    while (iterator.hasNext()) {
        StackEntry entry = (StackEntry) iterator.next();
        if (entry.model != lastModel) {
            //always true for non-recursive models
            lastModel = entry.model;
            stack.addFirst(entry);
        }

        iterator.remove();
    }

    for (Iterator<StackEntry> iterator2 = stack.iterator(); iterator2.hasNext();) {
        StackEntry stackEntry = (StackEntry) iterator2.next();
        stackEntry.model.setupVariable(stackEntry.varObject, context);
    }
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

/** Sends a certificate for download to a client */
private void sendEndEntityCert(final AuthenticationToken administrator, HttpServletRequest req,
        HttpServletResponse res, String format, Certificate certcert)
        throws CertificateEncodingException, NoSuchFieldException, IOException, CADoesntExistsException,
        SignRequestSignatureException, AuthorizationDeniedException {
    byte[] cert = certcert.getEncoded();
    String ending;/*from  w  w  w .j  av  a  2s .  com*/
    if (certcert instanceof CardVerifiableCertificate) {
        ending = ".cvcert";
    } else if (StringUtils.equals(format, "PEM") || StringUtils.equals(format, "chain")) {
        ending = ".pem";
    } else if (StringUtils.equals(format, "PKCS7")) {
        ending = ".p7b";
    } else {
        ending = ".crt";
    }
    String filename = RequestHelper.getFileNameFromCertNoEnding(certcert, "ca");
    filename = filename + ending;
    // We must remove cache headers for IE
    ServletUtils.removeCacheHeaders(res);
    if ("netscape".equals(req.getParameter(INSTALLTOBROWSER_PROPERTY))) {
        res.setContentType("application/x-x509-user-cert");
    } else {
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
    }
    if (StringUtils.equals(format, "PEM")) {
        RequestHelper.sendNewB64File(Base64.encode(cert, true), res, filename,
                RequestHelper.BEGIN_CERTIFICATE_WITH_NL, RequestHelper.END_CERTIFICATE_WITH_NL);
    } else if (StringUtils.equals(format, "PKCS7")) {
        byte[] pkcs7 = signSession.createPKCS7(administrator, certcert, true);
        RequestHelper.sendNewB64File(Base64.encode(pkcs7, true), res, filename,
                RequestHelper.BEGIN_PKCS7_WITH_NL, RequestHelper.END_PKCS7_WITH_NL);
    } else if (StringUtils.equals(format, "chain")) {
        int issuerCAId = CertTools.getIssuerDN(certcert).hashCode();
        LinkedList<Certificate> chain = new LinkedList<Certificate>(
                signSession.getCertificateChain(administrator, issuerCAId));
        chain.addFirst(certcert);
        byte[] chainbytes = CertTools.getPemFromCertificateChain(chain);
        RequestHelper.sendNewB64File(chainbytes, res, filename, "", ""); // chain includes begin/end already
    } else {
        res.setContentLength(cert.length);
        res.getOutputStream().write(cert);
    }
}

From source file:org.kuali.rice.krms.impl.provider.repository.SimplePropositionTypeService.java

/**
 * Translates the parameters on the given proposition definition to create an expression for evaluation.
 * The proposition parameters are defined in a reverse-polish notation so a stack is used for
 * evaluation purposes./*from w w w  .  ja  v a2  s.  c o  m*/
 * 
 * @param propositionDefinition the proposition definition to translate
 * 
 * @return the translated expression for the given proposition, this
 * expression, when evaluated, will return a Boolean.
 */
protected Expression<Boolean> translateToExpression(PropositionDefinition propositionDefinition) {
    LinkedList<Expression<? extends Object>> stack = new LinkedList<Expression<? extends Object>>();
    for (PropositionParameter parameter : propositionDefinition.getParameters()) {
        PropositionParameterType parameterType = PropositionParameterType
                .fromCode(parameter.getParameterType());
        if (parameterType == PropositionParameterType.CONSTANT) {
            // TODO - need some way to define data type on the prop parameter as well?  Not all constants will actually be String values!!!
            stack.addFirst(new ConstantExpression<String>(parameter.getValue()));
        } else if (parameterType == PropositionParameterType.FUNCTION) {
            String functionId = parameter.getValue();
            FunctionDefinition functionDefinition = functionRepositoryService.getFunction(functionId);
            if (functionDefinition == null) {
                throw new RepositoryDataException("Unable to locate function with the given id: " + functionId);
            }
            FunctionTypeService functionTypeService = typeResolver.getFunctionTypeService(functionDefinition);
            Function function = functionTypeService.loadFunction(functionDefinition);
            // TODO throw an exception if function is null?
            List<FunctionParameterDefinition> parameters = functionDefinition.getParameters();
            if (stack.size() < parameters.size()) {
                throw new RepositoryDataException(
                        "Failed to initialize custom function '" + functionDefinition.getNamespace() + " "
                                + functionDefinition.getName() + "'.  There were only " + stack.size()
                                + " values on the stack but function requires at least " + parameters.size());
            }
            List<Expression<? extends Object>> arguments = new ArrayList<Expression<? extends Object>>();
            // work backward through the list to match params to the stack
            for (int index = parameters.size() - 1; index >= 0; index--) {
                FunctionParameterDefinition parameterDefinition = parameters.get(index);
                // TODO need to check types here? expression object probably needs a getType on it so that we can confirm that the types will be compatible?
                parameterDefinition.getParameterType();
                Expression<? extends Object> argument = stack.removeFirst();
                arguments.add(argument);
            }

            String[] parameterTypes = getFunctionParameterTypes(functionDefinition);
            stack.addFirst(new FunctionExpression(function, parameterTypes, arguments,
                    getComparisonOperatorService()));

        } else if (parameterType == PropositionParameterType.OPERATOR) {
            ComparisonOperator operator = ComparisonOperator.fromCode(parameter.getValue());
            if (stack.size() < 2) {
                throw new RepositoryDataException(
                        "Failed to initialize expression for comparison operator " + operator
                                + " because a sufficient number of arguments was not available on the stack.  "
                                + "Current contents of stack: " + stack.toString());
            }
            Expression<? extends Object> rhs = stack.removeFirst();
            Expression<? extends Object> lhs = stack.removeFirst();
            stack.addFirst(new BinaryOperatorExpression(operator, lhs, rhs));
        } else if (parameterType == PropositionParameterType.TERM) {
            String termId = parameter.getValue();

            TermDefinition termDefinition = getTermRepositoryService().getTerm(termId);
            if (termDefinition == null) {
                throw new RepositoryDataException("unable to load term with id " + termId);
            }
            Term term = translateTermDefinition(termDefinition);

            stack.addFirst(new TermExpression(term));
        }
    }
    if (stack.size() != 1) {
        throw new RepositoryDataException(
                "Final contents of expression stack are incorrect, there should only be one entry but was "
                        + stack.size() + ".  Current contents of stack: " + stack.toString());
    }
    return new BooleanValidatingExpression(stack.removeFirst());
}

From source file:org.deegree.framework.xml.XMLFragment.java

/**
 * reads the encoding of a XML document from its header. If no header available
 * <code>CharsetUtils.getSystemCharset()</code> will be returned
 * //from   w ww.  j  av a 2s  .co  m
 * @param pbis
 * @return encoding of a XML document
 * @throws IOException
 */
private String readEncoding(PushbackInputStream pbis) throws IOException {
    byte[] b = new byte[80];
    String s = "";
    int rd = 0;

    LinkedList<byte[]> bs = new LinkedList<byte[]>();
    LinkedList<Integer> rds = new LinkedList<Integer>();
    while (rd < 80) {
        rds.addFirst(pbis.read(b));
        if (rds.peek() == -1) {
            rds.poll();
            break;
        }
        rd += rds.peek();
        s += new String(b, 0, rds.peek()).toLowerCase();
        bs.addFirst(b);
        b = new byte[80];
    }

    String encoding = CharsetUtils.getSystemCharset();
    if (s.indexOf("?>") > -1) {
        int p = s.indexOf("encoding=");
        if (p > -1) {
            StringBuffer sb = new StringBuffer();
            int k = p + 1 + "encoding=".length();
            while (s.charAt(k) != '"' && s.charAt(k) != '\'') {
                sb.append(s.charAt(k++));
            }
            encoding = sb.toString();
        }
    }
    while (!bs.isEmpty()) {
        pbis.unread(bs.poll(), 0, rds.poll());
    }

    return encoding;
}

From source file:org.apache.camel.component.pdf.text.DefaultLineBuilderStrategy.java

/**
 * Builds lines from words. Utilizes the same behaviour as office software:
 * <ul>//from w w  w. jav a 2  s .  c  o m
 *     <li>If word doesn't fit in current line, and current lines contains other words, then
 *     it will be moved to new line.</td>
 *     <li>Word doesn't fit in the line and line does not contain other words, then word will be
 *     slitted, and split index will be on max amount of characters that fits in the line </li>
 * </ul>
 */
@Override
public Collection<String> buildLines(Collection<String> splittedText) throws IOException {
    LinkedList<String> wordsList = new LinkedList<String>(splittedText);
    Collection<String> lines = new ArrayList<String>();
    LineBuilder currentLine = new LineBuilder();
    float allowedLineWidth = getAllowedLineWidth();
    while (!wordsList.isEmpty()) {
        String word = wordsList.removeFirst();
        if (isWordFitInCurrentLine(currentLine, word, allowedLineWidth)) {
            currentLine.appendWord(word);
            if (wordsList.isEmpty()) {
                lines.add(currentLine.buildLine());
            }
        } else if (currentLine.getWordsCount() != 0) {
            lines.add(currentLine.buildLine());
            wordsList.addFirst(word);
        } else {
            int splitIndex = findSplitIndex(word, allowedLineWidth);
            currentLine.appendWord(word.substring(0, splitIndex));
            lines.add(currentLine.buildLine());
            wordsList.addFirst(word.substring(splitIndex));
        }
    }
    return lines;
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * A <code>TargetConfiguration</code> can depend on another and so multiple
 * build processes might need to be run for a single
 * <code>TargetConfiguration</code>.
 * //from  w w  w  .j  av  a2  s  .  c o  m
 * <p>
 * The list of <code>TargetConfiguration</code> instance that need to be
 * built is called a build chain. A build chain with <code>n</code> entries
 * contains <code>n-1</code> instances that need to be built before. The
 * last element in the build chain is the one that was initially requested
 * and must be build last.
 * </p>
 * 
 * @param target
 * @param distro
 * @return
 * @throws MojoExecutionException
 */
public static List<TargetConfiguration> createBuildChain(String target, String distro,
        List<TargetConfiguration> targetConfigurations) throws MojoExecutionException {
    LinkedList<TargetConfiguration> tcs = new LinkedList<TargetConfiguration>();

    // Merges vertically, that means through the 'parent' property.
    TargetConfiguration tc = Utils.getTargetConfigurationFromString(target, targetConfigurations);
    // Utils.getMergedConfigurationImpl(target, distro,
    // targetConfigurations, true);

    // In getMergedConfiguraion we check if targets that are hierarchically
    // related
    // support the same distro. Here we will have to check again, as there
    // may not
    // be parent-child relationship between them.

    if (tc.getDistros().contains(distro)) {
        tcs.addFirst(tc);

        List<String> relations = tc.getRelations();
        for (String relation : relations) {
            tcs.addAll(0, createBuildChain(relation, distro, targetConfigurations));
        }
        return tcs;
    } else {
        throw new MojoExecutionException(
                "target configuration '" + tc.getTarget() + "' does not support distro: " + distro);
    }
}