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:edu.uci.ics.jung.graph.predicates.ConnectedGraphPredicate.java

/**
 * Returns <code>true</code> if there exists a path from each 
 * vertex to all other vertices (ignoring edge direction).
 * //  w  w  w .jav  a2 s  . c  om
 * <p>Returns <code>true</code> for an empty graph.</p>
 * 
 * @see org.apache.commons.collections.Predicate#evaluate(java.lang.Object)
 */
public boolean evaluateGraph(ArchetypeGraph graph) {
    Graph g = (Graph) graph;
    if (g.numVertices() == 0)
        return true;

    Vertex start = (Vertex) g.getVertices().iterator().next(); // pick any vertex
    Set visited = new HashSet();
    LinkedList stack = new LinkedList();
    stack.add(start);
    // traverse through graph in depth-first order
    while (!stack.isEmpty()) {
        Vertex v = (Vertex) stack.removeFirst();
        visited.add(v);
        Set neighbors = v.getNeighbors();
        for (Iterator n_it = neighbors.iterator(); n_it.hasNext();) {
            Vertex w = (Vertex) n_it.next();
            if (!visited.contains(w))
                stack.addFirst(w);
        }
    }
    return (visited.size() == g.numVertices());
}

From source file:org.apache.ode.bpel.compiler.WSDLRegistry.java

@SuppressWarnings("unchecked")
private void captureSchemas(Definition def, ResourceFinder rf, URI defuri) throws CompilationException {
    assert def != null;

    if (__log.isDebugEnabled())
        __log.debug("Processing XSD schemas in " + def.getDocumentBaseURI());

    Types types = def.getTypes();

    if (types != null) {
        int localSchemaId = 0;
        for (Iterator<ExtensibilityElement> iter = ((List<ExtensibilityElement>) def.getTypes()
                .getExtensibilityElements()).iterator(); iter.hasNext();) {
            ExtensibilityElement ee = iter.next();

            if (ee instanceof XMLSchemaType) {
                byte[] schema = ((XMLSchemaType) ee).getXMLSchema();
                WsdlFinderXMLEntityResolver resolver = new WsdlFinderXMLEntityResolver(rf, defuri,
                        _internalSchemas, false);
                try {
                    Map<URI, byte[]> capture = XSUtils.captureSchema(defuri, schema, resolver, localSchemaId);
                    for (URI uri : capture.keySet()) {
                        if (!_schemas.containsKey(uri)) {
                            _schemas.put(uri, capture.get(uri));
                        }// ww w  .j  ava 2s. com
                    }
                    //                        _schemas.putAll(capture);

                    try {
                        Document doc = DOMUtils.parse(new InputSource(new ByteArrayInputStream(schema)));
                        String schemaTargetNS = doc.getDocumentElement().getAttribute("targetNamespace");
                        if (schemaTargetNS != null && schemaTargetNS.length() > 0) {
                            URI schemaNamespace = new URI(schemaTargetNS);
                            if (!_internalSchemas.containsKey(schemaNamespace)) {
                                _internalSchemas.put(schemaNamespace, schema);
                            }
                            if (!_documentSchemas.containsKey(schemaNamespace)) {
                                _documentSchemas.put(schemaNamespace, doc);
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("Couldn't parse schema in " + def.getTargetNamespace(), e);
                    }
                } catch (XsdException xsde) {
                    __log.debug("captureSchemas: capture failed for " + defuri, xsde);

                    LinkedList<XsdException> exceptions = new LinkedList<XsdException>();
                    while (xsde != null) {
                        exceptions.addFirst(xsde);
                        xsde = xsde.getPrevious();
                    }

                    for (XsdException ex : exceptions) {
                        // TODO: the line number here is going to be wrong for the in-line schema.
                        // String location = ex.getSystemId() + ":"  + ex.getLineNumber();
                        CompilationException ce = new CompilationException(
                                __cmsgs.errSchemaError(ex.getDetailMessage())
                                        .setSource(new SourceLocationImpl(defuri)));
                        if (_ctx != null)
                            _ctx.recoveredFromError(new SourceLocationImpl(defuri), ce);
                        else
                            throw ce;
                    }
                }
                // invalidate model
                _model = null;

                localSchemaId++;
            }
        }
    }
}

From source file:com.turn.ttorrent.common.TorrentCreator.java

/**
 * Helper method to create a {@link Torrent} object for a set of files.
 *
 * <p>// ww  w .j a  v  a  2  s.  com
 * Hash the given files to create the multi-file {@link Torrent} object
 * representing the Torrent meta-info about them, needed for announcing
 * and/or sharing these files. Since we created the torrent, we're
 * considering we'll be a full initial seeder for it.
 * </p>
 *
 * @param parent The parent directory or location of the torrent files,
 * also used as the torrent's name.
 * @param files The files to add into this torrent.
 * @param announce The announce URI that will be used for this torrent.
 * @param announceList The announce URIs organized as tiers that will 
 * be used for this torrent
 * @param createdBy The creator's name, or any string identifying the
 * torrent's creator.
 */
@Nonnull
public Torrent create() throws InterruptedException, IOException, URISyntaxException {
    validate();

    if (files == null || files.isEmpty())
        logger.info("Creating single-file torrent for {}...", parent.getName());
    else
        logger.info("Creating {}-file torrent {}...", files.size(), parent.getName());

    Map<String, BEValue> torrent = new HashMap<String, BEValue>();

    ANNOUNCE: if (announce != null) {
        List<URI> announceFlat = new ArrayList<URI>();
        List<BEValue> announceTiers = new LinkedList<BEValue>();
        for (List<URI> trackers : announce) {
            List<BEValue> announceTier = new LinkedList<BEValue>();
            for (URI tracker : trackers) {
                announceFlat.add(tracker);
                announceTier.add(new BEValue(tracker.toString()));
            }
            if (!announceTier.isEmpty())
                announceTiers.add(new BEValue(announceTier));
        }
        if (announceFlat.size() == 1)
            torrent.put("announce", new BEValue(announceFlat.get(0).toString()));
        if (!announceTiers.isEmpty())
            torrent.put("announce-list", new BEValue(announceTiers));
    }

    torrent.put("creation date", new BEValue(new Date().getTime() / 1000));
    torrent.put("created by", new BEValue(createdBy));

    Map<String, BEValue> info = new TreeMap<String, BEValue>();
    info.put("name", new BEValue(parent.getName()));
    info.put("piece length", new BEValue(pieceLength));

    if (files == null || files.isEmpty()) {
        long nbytes = parent.length();
        info.put("length", new BEValue(nbytes));
        info.put("pieces", new BEValue(hashFiles(executor, Arrays.asList(parent), nbytes, pieceLength)));
    } else {
        List<BEValue> fileInfo = new LinkedList<BEValue>();
        long nbytes = 0L;
        for (File file : files) {
            Map<String, BEValue> fileMap = new HashMap<String, BEValue>();
            long length = file.length();
            fileMap.put("length", new BEValue(length));
            nbytes += length;

            LinkedList<BEValue> filePath = new LinkedList<BEValue>();
            while (file != null && !parent.equals(file)) {
                filePath.addFirst(new BEValue(file.getName()));
                file = file.getParentFile();
            }

            fileMap.put("path", new BEValue(filePath));
            fileInfo.add(new BEValue(fileMap));
        }
        info.put("files", new BEValue(fileInfo));
        info.put("pieces", new BEValue(hashFiles(executor, files, nbytes, pieceLength)));
    }
    torrent.put("info", new BEValue(info));

    return new Torrent(torrent);
}

From source file:fr.letroll.ttorrentandroid.common.TorrentCreator.java

/**
 * Helper method to create a {@link Torrent} object for a set of files.
 *
 * <p>//from w w w. j  ava 2s.c om
 * Hash the given files to create the {@link Torrent} object
 * representing the Torrent meta-info about them, needed for announcing
 * and/or sharing these files.
 * </p>
 */
@Nonnull
public Torrent create() throws InterruptedException, IOException, URISyntaxException {
    validate();

    if (files == null || files.isEmpty())
        logger.info("Creating single-file torrent for {}...", parent.getName());
    else
        logger.info("Creating {}-file torrent {}...", files.size(), parent.getName());

    Map<String, BEValue> torrent = new HashMap<String, BEValue>();

    ANNOUNCE: if (announce != null) {
        List<URI> announceFlat = new ArrayList<URI>();
        List<BEValue> announceTiers = new LinkedList<BEValue>();
        for (List<? extends URI> trackers : announce) {
            List<BEValue> announceTier = new LinkedList<BEValue>();
            for (URI tracker : trackers) {
                announceFlat.add(tracker);
                announceTier.add(new BEValue(tracker.toString()));
            }
            if (!announceTier.isEmpty())
                announceTiers.add(new BEValue(announceTier));
        }
        if (announceFlat.size() == 1)
            torrent.put("announce", new BEValue(announceFlat.get(0).toString()));
        if (!announceTiers.isEmpty())
            torrent.put("announce-list", new BEValue(announceTiers));
    }

    torrent.put("creation date", new BEValue(new Date().getTime() / 1000));
    torrent.put("created by", new BEValue(createdBy));

    Map<String, BEValue> info = new TreeMap<String, BEValue>();
    info.put("name", new BEValue(parent.getName()));
    info.put("piece length", new BEValue(pieceLength));

    if (files == null || files.isEmpty()) {
        long nbytes = parent.length();
        info.put("length", new BEValue(nbytes));
        info.put("pieces", new BEValue(hashFiles(executor, Arrays.asList(parent), nbytes, pieceLength)));
    } else {
        List<BEValue> fileInfo = new LinkedList<BEValue>();
        long nbytes = 0L;
        for (File file : files) {
            Map<String, BEValue> fileMap = new HashMap<String, BEValue>();
            long length = file.length();
            fileMap.put("length", new BEValue(length));
            nbytes += length;

            LinkedList<BEValue> filePath = new LinkedList<BEValue>();
            while (file != null && !parent.equals(file)) {
                filePath.addFirst(new BEValue(file.getName()));
                file = file.getParentFile();
            }

            fileMap.put("path", new BEValue(filePath));
            fileInfo.add(new BEValue(fileMap));
        }
        info.put("files", new BEValue(fileInfo));
        info.put("pieces", new BEValue(hashFiles(executor, files, nbytes, pieceLength)));
    }
    torrent.put("info", new BEValue(info));

    return new Torrent(torrent);
}

From source file:com.unboundid.scim2.common.utils.Parser.java

/**
 * Close a grouping of filters enclosed by parenthesis.
 *
 * @param operators The stack of operators tokens.
 * @param output The stack of output tokens.
 * @param isAtTheEnd Whether the end of the filter string was reached.
 * @return The last operator encountered that signaled the end of the group.
 * @throws BadRequestException If the filter string could not be parsed.
 *///from   w ww.  j  av  a2 s .  co m
private static String closeGrouping(final Stack<String> operators, final Stack<Filter> output,
        final boolean isAtTheEnd) throws BadRequestException {
    String operator = null;
    String repeatingOperator = null;
    LinkedList<Filter> components = new LinkedList<Filter>();

    // Iterate over the logical operators on the stack until either there are
    // no more operators or an opening parenthesis or not is found.
    while (!operators.isEmpty()) {
        operator = operators.pop();
        if (operator.equals("(") || operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) {
            if (isAtTheEnd) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            break;
        }
        if (repeatingOperator == null) {
            repeatingOperator = operator;
        }
        if (!operator.equals(repeatingOperator)) {
            if (output.isEmpty()) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            components.addFirst(output.pop());
            if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) {
                output.push(Filter.and(components));
            } else {
                output.push(Filter.or(components));
            }
            components.clear();
            repeatingOperator = operator;
        }
        if (output.isEmpty()) {
            throw BadRequestException.invalidFilter("Unexpected end of filter string");
        }
        components.addFirst(output.pop());
    }

    if (repeatingOperator != null && !components.isEmpty()) {
        if (output.isEmpty()) {
            throw BadRequestException.invalidFilter("Unexpected end of filter string");
        }
        components.addFirst(output.pop());
        if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) {
            output.push(Filter.and(components));
        } else {
            output.push(Filter.or(components));
        }
    }

    return operator;
}

From source file:org.apache.cassandra.db.HintedHandOffManager.java

public List<String> listEndpointsPendingHints() {
    List<Row> rows = getHintsSlice(1);

    // Extract the keys as strings to be reported.
    LinkedList<String> result = new LinkedList<String>();
    for (Row r : rows) {
        if (r.cf != null) //ignore removed rows
            result.addFirst(new String(r.key.key.array()));
    }// ww  w  .  j a v  a  2s  . co  m
    return result;
}

From source file:org.dspace.app.webui.cris.controller.admin.FormAdministrationProjectController.java

@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
    String mode = request.getParameter("mode");
    String paramSort = request.getParameter("sort");
    String paramPage = request.getParameter("page");
    String paramDir = request.getParameter("dir");
    String paramOldPage = request.getParameter("oldpage");

    if (paramOldPage != null
            && (paramOldPage.equals(paramPage) || (Integer.parseInt(paramOldPage) == 1 && paramPage == null))) {
        String message = request.getParameter("message");
        request.setAttribute("message", message);
    }// www . j  av a  2s.  c  o m

    String sort = paramSort != null ? paramSort : "id";
    String dir = paramDir != null ? paramDir : "asc";
    int page = paramPage != null ? Integer.parseInt(paramPage) : 1;
    long count = applicationService.count(Project.class);
    Integer pagesize = Integer.parseInt(ConfigurationManager.getProperty(CrisConstants.CFG_MODULE,
            "project.administration.table.pagesize"));

    //mode position only when administrator click on direct link on RP page  
    Integer id = null;
    if (mode != null && mode.equals("position") && paramPage == null && paramSort == null) {
        String id_s = request.getParameter("id");
        id = Integer.parseInt(id_s);
        page = id / pagesize + 1;
    }

    List<Project> researchers = applicationService.getPaginateList(Project.class, sort, "desc".equals(dir),
            page, pagesize);
    LinkedList<ProjectDTO> objectList = new LinkedList<ProjectDTO>();
    for (Project r : researchers) {
        ProjectDTO rpd = new ProjectDTO();
        rpd.setId(r.getId());
        rpd.setUuid(r.getUuid());
        rpd.setSourceID(r.getSourceID());
        rpd.setTitle(r.getName());
        rpd.setStatus(r.getStatus());
        rpd.setGrant(r);
        if ((r.getId()).equals(id)) {
            objectList.addFirst(rpd);
        } else {
            objectList.add(rpd);
        }
    }

    ProjectDisplayTagData displayList = new ProjectDisplayTagData(count, objectList, sort, dir, page, pagesize);

    return displayList;

}

From source file:org.dcm4chee.archive.conf.DeepEquals.java

/**
 * Deeply compare to Arrays []. Both arrays must be of the same type, same length, and all
 * elements within the arrays must be deeply equal in order to return true.
 * @param array1 [] type (Object[], String[], etc.)
 * @param array2 [] type (Object[], String[], etc.)
 * @param stack add items to compare to the Stack (Stack versus recursion)
 * @param visited Set of objects already compared (prevents cycles)
 * @return true if the two arrays are the same length and contain deeply equivalent items.
 *///from w  w w .  j a  v a2 s.c  o  m
private static boolean compareArrays(Object array1, Object array2, LinkedList stack, Set visited) {
    // Same instance check already performed...

    int len = Array.getLength(array1);
    if (len != Array.getLength(array2)) {
        return false;
    }

    // try sorting

    if (len > 0) {
        if (Array.get(array1, 0) instanceof Comparable) {

            Class<?> c = Array.get(array1, 0).getClass();

            if (ClassUtils.isPrimitiveOrWrapper(c)) {
                /*   Arrays.sort(array1);
                     Arrays.sort((Object[]) array2);*/

            } else {

                Arrays.sort((Object[]) array1);
                Arrays.sort((Object[]) array2);
            }

        }
    }

    for (int i = 0; i < len; i++) {
        DualKey dk = new DualKey(Array.get(array1, i), Array.get(array2, i));
        if (!visited.contains(dk)) { // push contents for further comparison
            stack.addFirst(dk);
        }
    }
    return true;
}

From source file:org.gephi.statistics.plugin.ConnectedComponents.java

private void tarjans(AttributeColumn col, LinkedList<Node> S, HierarchicalDirectedGraph hgraph, Node f,
        int[] index, int[] low_index, HashMap<Node, Integer> indicies) {
    int id = indicies.get(f);
    index[id] = count;//  w  w w . j  a  va 2  s .  com
    low_index[id] = count;
    count++;
    S.addFirst(f);
    EdgeIterable edgeIter = hgraph.getOutEdgesAndMetaOutEdges(f);
    for (Edge e : edgeIter) {
        Node u = hgraph.getOpposite(f, e);
        int x = indicies.get(u);
        if (index[x] == 0) {
            tarjans(col, S, hgraph, u, index, low_index, indicies);
            low_index[id] = Math.min(low_index[x], low_index[id]);
        } else if (S.contains(u)) {
            low_index[id] = Math.min(low_index[id], index[x]);
        }
    }
    if (low_index[id] == index[id]) {
        Node v = null;
        while (v != f) {
            v = S.removeFirst();
            AttributeRow row = (AttributeRow) v.getNodeData().getAttributes();
            row.setValue(col, stronglyCount);
        }
        stronglyCount++;
    }
}

From source file:org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry.java

private void registerMouseBinding(boolean first, MouseEventTypeEnum mouseEventType,
        IMouseEventMatcher mouseEventMatcher, IMouseAction action) {
    LinkedList<MouseBinding> mouseEventBindings = this.mouseBindingsMap.get(mouseEventType);
    if (mouseEventBindings == null) {
        mouseEventBindings = new LinkedList<MouseBinding>();
        this.mouseBindingsMap.put(mouseEventType, mouseEventBindings);
    }//from  ww w  .j  a va  2  s  .  com
    if (first) {
        mouseEventBindings.addFirst(new MouseBinding(mouseEventMatcher, action));
    } else {
        mouseEventBindings.addLast(new MouseBinding(mouseEventMatcher, action));
    }
}