Example usage for java.util LinkedList getLast

List of usage examples for java.util LinkedList getLast

Introduction

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

Prototype

public E getLast() 

Source Link

Document

Returns the last element in this list.

Usage

From source file:com.amalto.core.history.accessor.record.DataRecordAccessor.java

@SuppressWarnings("rawtypes")
private static LinkedList<PathElement> getPath(DataRecord dataRecord, String path) {
    LinkedList<PathElement> elements = new LinkedList<PathElement>();
    StringTokenizer tokenizer = new StringTokenizer(path, "/"); //$NON-NLS-1$
    DataRecord current = dataRecord;/*from  w  w w  .ja  v  a2 s.  c  om*/
    while (tokenizer.hasMoreElements()) {
        String element = tokenizer.nextToken();
        PathElement pathElement = new PathElement();
        if (element.indexOf('@') == 0) {
            pathElement.field = elements.getLast().field;
            pathElement.setter = TypeValue.SET;
            pathElement.getter = TypeValue.GET;
        } else {
            if (current == null) {
                throw new IllegalStateException("Cannot update '" + path + "'."); //$NON-NLS-1$ //$NON-NLS-2$
            }
            if (element.indexOf('[') > 0) {
                pathElement.field = current.getType().getField(StringUtils.substringBefore(element, "[")); //$NON-NLS-1$
                if (!pathElement.field.isMany()) {
                    throw new IllegalStateException(
                            "Expected a repeatable field for '" + element + "' in path '" + path //$NON-NLS-1$ //$NON-NLS-2$
                                    + "'."); //$NON-NLS-1$
                }
                int indexStart = element.indexOf('[');
                int indexEnd = element.indexOf(']');
                if (indexStart < 0 || indexEnd < 0) {
                    throw new RuntimeException(
                            "Field name '" + element + "' did not match many field pattern in path '" //$NON-NLS-1$ //$NON-NLS-2$
                                    + path + "'."); //$NON-NLS-1$
                }
                pathElement.index = Integer.parseInt(element.substring(indexStart + 1, indexEnd)) - 1;
                pathElement.setter = ManyValue.SET;
                pathElement.getter = ManyValue.GET;
                List list = (List) current.get(pathElement.field);
                if (list == null || pathElement.index > list.size() - 1) {
                    throw new IllegalStateException("Cannot update '" + path + "'."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                Object value = list.get(pathElement.index);
                if (value instanceof DataRecord) {
                    current = (DataRecord) value;
                } else if (value instanceof List) {
                    throw new IllegalStateException();
                }
            } else {
                pathElement.field = current.getType().getField(element);
                pathElement.setter = SimpleValue.SET;
                pathElement.getter = SimpleValue.GET;
                if (pathElement.field instanceof ContainedTypeFieldMetadata
                        || pathElement.field instanceof ReferenceFieldMetadata) {
                    Object value = current.get(pathElement.field);
                    if (value instanceof DataRecord) {
                        current = (DataRecord) value;
                    }
                }
            }
        }
        elements.add(pathElement);
    }
    return elements;
}

From source file:com.zimbra.cs.imap.ImapMessage.java

static void serializeStructure(PrintStream ps, MimeMessage root, boolean extensions)
        throws IOException, MessagingException {
    LinkedList<LinkedList<MPartInfo>> queue = new LinkedList<LinkedList<MPartInfo>>();
    LinkedList<MPartInfo> level = new LinkedList<MPartInfo>();
    level.add(Mime.getParts(root).get(0));
    queue.add(level);//from www  .  ja  v a2  s  . c  om

    boolean pop = false;
    while (!queue.isEmpty()) {
        level = queue.getLast();
        if (level.isEmpty()) {
            queue.removeLast();
            pop = true;
            continue;
        }

        MPartInfo mpi = level.getFirst();
        MimePart mp = mpi.getMimePart();
        boolean hasChildren = mpi.getChildren() != null && !mpi.getChildren().isEmpty();

        // we used to force unset charsets on text/plain parts to US-ASCII, but that always seemed unwise...
        ContentType ctype = new ContentType(mp.getHeader("Content-Type", null))
                .setContentType(mpi.getContentType());
        String primary = nATOM(ctype.getPrimaryType()), subtype = nATOM(ctype.getSubType());

        if (!pop)
            ps.write('(');
        if (primary.equals("\"MULTIPART\"")) {
            if (!pop) {
                // 7.4.2: "Multiple parts are indicated by parenthesis nesting.  Instead of a body type
                //         as the first element of the parenthesized list, there is a sequence of one
                //         or more nested body structures.  The second element of the parenthesized
                //         list is the multipart subtype (mixed, digest, parallel, alternative, etc.)."
                if (!hasChildren) {
                    ps.print("NIL");
                } else {
                    queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren()));
                    continue;
                }
            }
            ps.write(' ');
            ps.print(subtype);
            if (extensions) {
                // 7.4.2: "Extension data follows the multipart subtype.  Extension data is never
                //         returned with the BODY fetch, but can be returned with a BODYSTRUCTURE
                //         fetch.  Extension data, if present, MUST be in the defined order.  The
                //         extension data of a multipart body part are in the following order:
                //         body parameter parenthesized list, body disposition, body language,
                //         body location"
                ps.write(' ');
                nparams(ps, ctype);
                ps.write(' ');
                ndisposition(ps, mp.getHeader("Content-Disposition", null));
                ps.write(' ');
                nlist(ps, mp.getContentLanguage());
                ps.write(' ');
                nstring(ps, mp.getHeader("Content-Location", null));
            }
        } else {
            if (!pop) {
                // 7.4.2: "The basic fields of a non-multipart body part are in the following order:
                //         body type, body subtype, body parameter parenthesized list, body id, body
                //         description, body encoding, body size."
                String cte = mp.getEncoding();
                cte = (cte == null || cte.trim().equals("") ? "7bit" : cte);
                aSTRING(ps, ctype.getPrimaryType());
                ps.write(' ');
                aSTRING(ps, ctype.getSubType());
                ps.write(' ');
                nparams(ps, ctype);
                ps.write(' ');
                nstring(ps, mp.getContentID());
                ps.write(' ');
                nstring2047(ps, mp.getDescription());
                ps.write(' ');
                aSTRING(ps, cte);
                ps.write(' ');
                ps.print(Math.max(mp.getSize(), 0));
            }
            boolean rfc822 = primary.equals("\"MESSAGE\"") && subtype.equals("\"RFC822\"");
            if (rfc822) {
                // 7.4.2: "A body type of type MESSAGE and subtype RFC822 contains, immediately
                //         after the basic fields, the envelope structure, body structure, and
                //         size in text lines of the encapsulated message."
                if (!pop) {
                    if (!hasChildren) {
                        ps.print(" NIL NIL");
                    } else {
                        MimeMessage mm = (MimeMessage) mpi.getChildren().get(0).getMimePart();
                        ps.write(' ');
                        serializeEnvelope(ps, mm);
                        ps.write(' ');
                        queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren()));
                        continue;
                    }
                }
                ps.write(' ');
                ps.print(getLineCount(mp));
            } else if (primary.equals("\"TEXT\"")) {
                // 7.4.2: "A body type of type TEXT contains, immediately after the basic fields, the
                //         size of the body in text lines.  Note that this size is the size in its
                //         content transfer encoding and not the resulting size after any decoding."
                ps.write(' ');
                ps.print(getLineCount(mp));
            }
            if (extensions) {
                // 7.4.2: "Extension data follows the basic fields and the type-specific fields
                //         listed above.  Extension data is never returned with the BODY fetch,
                //         but can be returned with a BODYSTRUCTURE fetch.  Extension data, if
                //         present, MUST be in the defined order.  The extension data of a
                //         non-multipart body part are in the following order: body MD5, body
                //         disposition, body language, body location"
                ps.write(' ');
                nstring(ps, mp.getContentMD5());
                ps.write(' ');
                ndisposition(ps, mp.getHeader("Content-Disposition", null));
                ps.write(' ');
                nlist(ps, mp.getContentLanguage());
                ps.write(' ');
                nstring(ps, mp.getHeader("Content-Location", null));
            }
        }
        ps.write(')');

        level.removeFirst();
        pop = false;
    }
}

From source file:org.apache.ofbiz.solr.SolrProductSearch.java

/**
 * Return a map of the side deep categories.
 *///from   w  w  w.ja  v a2  s.  com
public static Map<String, Object> getSideDeepCategories(DispatchContext dctx, Map<String, Object> context) {
    Map<String, Object> result;
    String solrIndexName = (String) context.get("indexName");
    try {
        String catalogId = null;
        if (UtilValidate.isNotEmpty(context.get("catalogId")))
            catalogId = (String) context.get("catalogId");

        String productCategoryId = (String) context.get("productCategoryId") != null
                ? CategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), dctx)
                : null;
        result = ServiceUtil.returnSuccess();
        Map<String, List<Map<String, Object>>> catLevel = new HashMap<String, List<Map<String, Object>>>();
        Debug.logInfo("productCategoryId: " + productCategoryId, module);

        //Add toplevel categories
        String[] trailElements = productCategoryId.split("/");

        //iterate over actual results
        for (String elements : trailElements) {
            //catIds must be greater than 3 chars
            if (elements.length() > 3) {
                Debug.logInfo("elements: " + elements, module);
                String categoryPath = CategoryUtil.getCategoryNameWithTrail(elements, dctx);
                String[] categoryPathArray = categoryPath.split("/");
                int level = Integer.parseInt(categoryPathArray[0]);
                String facetQuery = CategoryUtil.getFacetFilterForCategory(categoryPath, dctx);
                //Debug.logInfo("categoryPath: "+categoryPath + " facetQuery: "+facetQuery,module);
                Map<String, Object> query = SolrUtil.categoriesAvailable(catalogId, categoryPath, null,
                        facetQuery, false, 0, 0, solrIndexName);
                QueryResponse cat = (QueryResponse) query.get("rows");
                List<Map<String, Object>> categories = new ArrayList<Map<String, Object>>();

                List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
                for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
                    FacetField field = (FacetField) catIterator.next();
                    List<Count> catL = (List<Count>) field.getValues();
                    if (catL != null) {
                        for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
                            FacetField.Count f = (FacetField.Count) catIter.next();
                            if (f.getCount() > 0) {
                                Map<String, Object> catMap = new HashMap<String, Object>();
                                LinkedList<String> iName = new LinkedList<String>();
                                iName.addAll(Arrays.asList(f.getName().split("/")));
                                //Debug.logInfo("topLevel "+topLevel,"");
                                // int l = Integer.parseInt((String) iName.getFirst());
                                catMap.put("catId", iName.getLast());
                                iName.removeFirst();
                                String path = f.getName();
                                catMap.put("path", path);
                                if (level > 0) {
                                    iName.removeLast();
                                    catMap.put("parentCategory", StringUtils.join(iName, "/"));
                                } else {
                                    catMap.put("parentCategory", null);
                                }
                                catMap.put("count", Long.toString(f.getCount()));
                                categories.add(catMap);
                            }
                        }
                    }
                }
                catLevel.put("menu-" + level, categories);
            }
        }
        result.put("categories", catLevel);
        result.put("numFound", (long) 0);

    } catch (Exception e) {
        result = ServiceUtil.returnError(e.toString());
        result.put("numFound", (long) 0);
    }
    return result;
}

From source file:org.piraso.headless.EntryCriteria.java

public Entry lastResult() {
    LinkedList<Entry> items = list();

    if (CollectionUtils.isEmpty(items)) {
        return null;
    }//w  w w. j  ava2 s .  co m

    return items.getLast();
}

From source file:com.kpb.other.AcmeCorpPhysicalNamingStrategy.java

public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
    final LinkedList<String> parts = splitAndReplace(name.getText());
    // Acme Corp says all sequences should end with _seq
    if (!"seq".equalsIgnoreCase(parts.getLast())) {
        parts.add("seq");
    }/*from  w  w w .  j av  a  2 s  .  c  om*/
    return jdbcEnvironment.getIdentifierHelper().toIdentifier(join(parts), name.isQuoted());
}

From source file:de.science.hack.meshbuilding.AbstractFaceBuilderTask.java

/**
 * creates two triangle based on the two projections
 *
 * @param projections/*from w w  w .  j av  a 2  s  .c  o m*/
 * @return
 */
protected List<Vec3D[]> createTriangles(LinkedList<Line> projections) {
    List<Vec3D[]> triangles = new ArrayList<>(2);
    if (!projections.isEmpty()) {
        Line first = projections.getFirst();
        Line last = projections.getLast();
        triangles.add(createTriangle(first.getPoint1(), first.getPoint2(), last.getPoint1()));
        triangles.add(createTriangle(first.getPoint2(), last.getPoint1(), last.getPoint2()));
    }
    return triangles;
}

From source file:cn.tata.t2s.ssm.util.AcmeCorpPhysicalNamingStrategy.java

@Override
public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
    final LinkedList<String> parts = splitAndReplace(name.getText());
    // Acme Corp says all sequences should end with _seq
    if (!"seq".equalsIgnoreCase(parts.getLast())) {
        parts.add("seq");
    }//from w w w  .java 2s  .c o m
    return jdbcEnvironment.getIdentifierHelper().toIdentifier(join(parts), name.isQuoted());
}

From source file:org.jboss.as.test.integration.logging.perdeploy.JBossLog4jXmlTestCase.java

@Test
public void testDeploymentConfigurationResource() throws Exception {
    final ModelNode loggingConfiguration = readDeploymentResource(DEPLOYMENT_NAME);
    // The address should have jboss-log4j.xml
    final LinkedList<Property> resultAddress = new LinkedList<>(
            Operations.getOperationAddress(loggingConfiguration).asPropertyList());
    final String name = resultAddress.getLast().getValue().asString();
    Assert.assertTrue("The configuration path did not include jboss-log4j.xml: " + name,
            name.endsWith("jboss-log4j.xml"));
    Assert.assertTrue(loggingConfiguration.has("handler"));
    // A log4j configuration cannot be defined in the model
    Assert.assertFalse("No handlers should be defined", loggingConfiguration.get("handler").isDefined());
}

From source file:io.github.jrobotframework.keyword.csv.criteria.CSVLineCriteria.java

public String[] lastResult() {
    LinkedList<String[]> items = list();

    if (CollectionUtils.isEmpty(items)) {
        throw new IllegalStateException("No items found.");
    }//from   w  w w  .java 2  s.com

    return items.getLast();
}

From source file:org.jboss.as.test.integration.logging.perdeploy.Log4jXmlTestCase.java

@Test
public void testDeploymentConfigurationResource() throws Exception {
    final ModelNode loggingConfiguration = readDeploymentResource(DEPLOYMENT_NAME);
    // The address should have jboss-log4j.xml
    final LinkedList<Property> resultAddress = new LinkedList<>(
            Operations.getOperationAddress(loggingConfiguration).asPropertyList());
    Assert.assertTrue("The configuration path did not include log4j.xml",
            resultAddress.getLast().getValue().asString().contains("log4j.xml"));
    Assert.assertTrue(loggingConfiguration.has("handler"));
    // A log4j configuration cannot be defined in the model
    Assert.assertFalse("No handlers should be defined", loggingConfiguration.get("handler").isDefined());
}