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:bobs.is.compress.sevenzip.SevenZOutputFile.java

private static <T> Iterable<T> reverse(final Iterable<T> i) {
    final LinkedList<T> l = new LinkedList<T>();
    for (final T t : i) {
        l.addFirst(t);
    }//from w w w.  j a  v  a  2s  .c  o m
    return l;
}

From source file:srebrinb.compress.sevenzip.SevenZOutputFile.java

private static <T> Iterable<T> reverse(final Iterable<T> i) {
    final LinkedList<T> l = new LinkedList<>();
    for (final T t : i) {
        l.addFirst(t);
    }//from   ww w .  ja v a2s .co  m
    return l;
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.DescriptionHelper.java

/**
 * Adds {@link ClassResourceInfo}'s for given component class and all its super classes and
 * interfaces./*from w  w  w  .j a v  a 2 s .  com*/
 */
public static void addDescriptionResources(LinkedList<ClassResourceInfo> descriptions, ILoadingContext context,
        Class<?> currentClass) throws Exception {
    if (currentClass != null) {
        ResourceInfo resource = getComponentDescriptionResource(context, currentClass);
        if (resource != null) {
            validateComponentDescription(resource);
            descriptions.addFirst(new ClassResourceInfo(currentClass, resource));
        }
        // handle interfaces
        for (Class<?> interfaceClass : currentClass.getInterfaces()) {
            addDescriptionResources(descriptions, context, interfaceClass);
        }
        // handle super class
        addDescriptionResources(descriptions, context, currentClass.getSuperclass());
    }
}

From source file:spade.storage.CompressedTextFile.java

private static SortedSet<Integer> uncompressReference(Integer id, String ancestorOrSuccessorList,
        boolean ancestorOrSuccessor) throws UnsupportedEncodingException {
    //System.out.println("step m");
    SortedSet<Integer> list = new TreeSet<Integer>();
    StringTokenizer st = new StringTokenizer(ancestorOrSuccessorList);
    //System.out.println("ancestorOrSuccessorList :" + ancestorOrSuccessorList + " /id :" + id);
    //st.nextToken();
    String token = st.nextToken();
    //System.out.println("step n");
    Integer referenceID = id + Integer.parseInt(token);
    //System.out.println("referenceID1: " + referenceID);
    LinkedList<String> previousLayers = new LinkedList<String>();
    previousLayers.addFirst(id + " " + ancestorOrSuccessorList);
    String toUncompress;//www.j  a v a  2s.  com
    //System.out.println("step o");
    boolean hasReference = true;
    //System.out.println(toUncompress);
    //System.out.println(ancestorOrSuccessorList);
    while (hasReference) {
        //System.out.println("step p");
        String currentLine = get(scaffoldWriter, referenceID);
        if (currentLine.length() > 0) {

            if (ancestorOrSuccessor) { // we want to uncompress ancestors
                toUncompress = currentLine.substring(currentLine.indexOf(' ') + 1,
                        currentLine.indexOf("/") - 1);
            } else { // we want to uncompress successors
                toUncompress = currentLine.substring(currentLine.indexOf("/") + 2);
                toUncompress = toUncompress.substring(toUncompress.indexOf(' ') + 1);
            }
            //System.out.println("step q");
            //System.out.println("toUncompress:" + toUncompress);
            // System.out.println(toUncompress);
            toUncompress = referenceID + " " + toUncompress;
            previousLayers.addFirst(toUncompress);
            //System.out.println("step r");
            if (toUncompress.contains(" _ ")) { // this is the last layer
                hasReference = false;
            } else { // we need to go one layer further to uncompress the successors
                String aux = toUncompress.substring(toUncompress.indexOf(" ") + 1);
                //System.out.println("toUncompress:" + toUncompress);
                referenceID = referenceID + Integer.parseInt(aux.substring(0, aux.indexOf(" ")));
                // System.out.println("referenceID : " + referenceID);
                //System.out.println("step s");
            }
        } else {
            System.out.println("Data missing.");
            hasReference = false;
        } //System.out.println("step t");
    }

    // System.out.println("previousLayers: " + previousLayers.toString());
    String bitListLayer;
    String remainingNodesLayer;
    Integer layerID;
    for (String layer : previousLayers) { //find the successors of the first layer and then those of the second layer and so on...
        layerID = Integer.parseInt(layer.substring(0, layer.indexOf(" ")));
        //System.out.println("step u");
        if (layer.contains("_ ")) { //this is the case for the first layer only
            remainingNodesLayer = layer.substring(layer.indexOf("_ ") + 2);
            //System.out.println("step v");
        } else {
            // uncompress the bitlist
            remainingNodesLayer = layer.substring(layer.indexOf(" ") + 1);
            //System.out.println("remaining Nodes Layer 1: " + remainingNodesLayer);
            //// System.out.println("step 1 :" + remainingNodesLayer + "/");
            remainingNodesLayer = remainingNodesLayer.substring(remainingNodesLayer.indexOf(" ") + 1);
            //remainingNodesLayer = remainingNodesLayer.substring(remainingNodesLayer.indexOf(" ") + 1);
            //// System.out.println("step 2 :" + remainingNodesLayer + "/");
            //System.out.println("step w");
            //System.out.println("remaining Nodes Layer " + remainingNodesLayer);
            if (remainingNodesLayer.contains(" ")) {
                bitListLayer = remainingNodesLayer.substring(0, remainingNodesLayer.indexOf(" "));
                remainingNodesLayer = remainingNodesLayer.substring(remainingNodesLayer.indexOf(" ") + 1);
            } else {

                bitListLayer = remainingNodesLayer.substring(0);
                remainingNodesLayer = "";
            }
            //System.out.println("bitListLayer :" + bitListLayer + "/");
            int count = 0;
            SortedSet<Integer> list2 = new TreeSet<Integer>();
            list2.addAll(list);
            //   System.out.println("step x");
            //System.out.println(bitListLayer);
            for (Integer successor : list2) {
                //System.out.println(successor + " " + count);
                if (bitListLayer.charAt(count) == '0') {
                    list.remove(successor);
                    //System.out.println("step y");
                }
                count++;
            }
        }
        // uncompress remaining nodes
        list.addAll(uncompressRemainingNodes(layerID, remainingNodesLayer));
        //System.out.println("step z");
    }
    //System.out.println("uncompressReference : " + list.toString() + "id : " + id);
    return list;
}

From source file:org.orbeon.oxf.util.SystemUtils.java

/**
 * Walks class loader hierarchy of clazz looking for instances of URLClassLoader.
 * For each found gets file urls and adds, converted, elements to the path.
 * Note that the more junior a class loader is the later in the path it's
 * contribution is. <br/>//from www  .ja  v  a 2 s .c o m
 * Also, tries to deal with fact that urls may or may not be encoded.
 * Converts the urls to java.io.File and checks for existence.  If it
 * exists file name is used as is.  If not name is URLDecoded.  If the
 * decoded form exists that that is used.  If neither exists then the
 * undecoded for is used.
 *
 * @param clazz Class to try and build a classpath from.
 * @return   java.io.File.pathSeparator delimited path.
 */
public static String pathFromLoaders(final Class clazz) throws java.io.UnsupportedEncodingException {
    final TreeSet sysPths = new TreeSet();
    gatherSystemPaths(sysPths);
    final StringBuilder sbuf = new StringBuilder();
    final LinkedList urlLst = new LinkedList();
    for (ClassLoader cl = clazz.getClassLoader(); cl != null; cl = cl.getParent()) {
        if (!(cl instanceof java.net.URLClassLoader)) {
            continue;
        }
        final java.net.URLClassLoader ucl = (java.net.URLClassLoader) cl;
        final java.net.URL[] urls = ucl.getURLs();
        if (urls == null)
            continue;
        for (int i = urls.length - 1; i > -1; i--) {
            final java.net.URL url = urls[i];
            final String prot = url.getProtocol();
            if (!"file".equalsIgnoreCase(prot))
                continue;
            urlLst.addFirst(url);
        }
    }
    for (final Iterator itr = urlLst.iterator(); itr.hasNext();) {
        final java.net.URL url = (java.net.URL) itr.next();
        final String fnam = url.getFile();
        final File fil = new File(fnam);
        if (sysPths.contains(fil))
            continue;
        // 11/14/2004 d : Odd test attempts to deal with fact that
        // a.) The URLs passed to a URLClassLoader don't have to be encoded
        //     in general.
        // b.) The app class loader and the extensions class loader, the
        //     jdk class loaders responsible for loading classes from classpath
        //     and the extensions dir respectively, do encode their urls.
        // c.) java.io.File.toURL doesn't produce encoded urls. ( Perhaps
        //     a sun bug... )
        // As you can see given (a) and (c) odds are pretty good that
        // should anyone use something other than jdk class loaders we
        // will end up unencoded urls.
        if (!fil.exists()) {
            final String unEncNam = URLDecoder.decode(fnam, "utf-8");
            final File unEncFil = new File(unEncNam);
            if (unEncFil.exists())
                sbuf.append(unEncNam);
        } else {
            sbuf.append(fnam);
        }
        sbuf.append(File.pathSeparatorChar);
    }
    final String ret = sbuf.toString();
    return ret;
}

From source file:AndroidUninstallStock.java

public static void reboot(String adb, String... args) throws Exception {
    LinkedList<String> adb_and_args = new LinkedList<String>(Arrays.asList(args));
    adb_and_args.addFirst(adb);
    run(adb_and_args.toArray(new String[0]));
    String deverror, lastdeverror = "";
    while (!(deverror = getDeviceStatus(adb, null)).isEmpty()) {
        if (!lastdeverror.equals(deverror)) {
            System.out.println(deverror);
            lastdeverror = deverror;/*from  w w w.  j av a 2 s . co  m*/
            System.out.println("Retry... For Cancel press CTRL+C");
        }
        Thread.sleep(1000);
    }
}

From source file:minghai.nisesakura.SimpleTwitterHelper.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be
 * run from a UI thread./*from w  w w.  j  a  v a2s . c om*/
 * @param context 
 * 
 * @param title The exact title of the Wiktionary page requested.
 * @param expandTemplates If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException If any connection or server error occurs.
 * @throws ParseException If there are problems parsing the response.
 */
public static LinkedList<String> getPageContent(Context context) throws ApiException, ParseException {
    // Encode page title and expand templates if requested
    //String encodedTitle = Uri.encode(title);

    QUERY_OPTION = loadRefreshURL(context);
    Log.d(TAG, "QUERY_OPTION = " + QUERY_OPTION);

    // Query the API for content
    String content = getUrlContent(TWITTER_SEARCH + QUERY_OPTION);
    LinkedList<String> results = new LinkedList<String>();
    try {
        // Drill into the JSON response to find the content body
        JSONObject all = new JSONObject(content);
        JSONArray result = all.getJSONArray("results");
        int num = result.length();
        if (num == 0)
            return results;

        final String prefix = "@nisesakura \\t";
        for (int i = 0; i < num; i++) {
            JSONObject one = result.getJSONObject(i);
            String text = one.getString("text");

            if (text.startsWith(prefix)) {
                text = text.substring(prefix.length(), text.length());
                results.addFirst(text);
            }
        }
        QUERY_OPTION = all.getString("refresh_url");
        saveRefreshURL(context, QUERY_OPTION);
        return results;
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response", e);
    }
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

protected static void collectResources(String resourceName, ClassLoader classLoader,
        Map<URL, ClassLoaderResource> resources) {
    if (classLoader == null) {
        return;// w w w . ja v a  2s.  c o m
    }

    try {
        // creating a list of parent classloaders, with the highest in the
        // hierarchy first
        LinkedList<ClassLoader> classloaders = new LinkedList<ClassLoader>();
        ClassLoader ancestorLoader = classLoader;
        while (ancestorLoader != null) {
            classloaders.addFirst(ancestorLoader);

            try {
                ancestorLoader = ancestorLoader.getParent();
            } catch (SecurityException e) {
                // if we're not allowed to get the parent, stop here.
                // resources will be listed with the first classloader that
                // we're allowed to access.
                // one case when this happens is applets.
                // FIXME revisit logging on SecurityException for applet
                ancestorLoader = null;
            }
        }

        for (ClassLoader ancestor : classloaders) {
            Enumeration<URL> urls = ancestor.getResources(resourceName);
            if (urls != null) // class loaders should never return null on getResources, according to specs, but we've seen cases, so we protect our code here
            {
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    // if this is the first time we see this resource, add it
                    // with the current classloader.
                    // this way a resource will be added with the most first
                    // ancestor classloader that has it.
                    if (!resources.containsKey(url)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Found resource " + resourceName + " at " + url + " in classloader "
                                    + ancestor);
                        }

                        ClassLoaderResource resource = new ClassLoaderResource(url, ancestor);
                        resources.put(url, resource);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:org.rhq.enterprise.gui.legacy.util.SessionUtils.java

/**
 * Set the "returnPath," the possible point of origin for a worklow
 *
 * @param session The http session./*from  w ww . j  a  v a 2s  . com*/
 * @param path    The return path url represented as a String.
 * @param ignore
 */
public static void setReturnPath(HttpSession session, String path, Boolean ignore) {
    LinkedList stack = (LinkedList) session.getAttribute(AttrConstants.RETURN_LOC_SES_ATTR);

    ReturnPath returnPath = new ReturnPath();

    if (stack == null) {
        stack = new LinkedList();
    }

    returnPath.setPath(path);
    returnPath.setIgnore(ignore);

    stack.addFirst(returnPath);

    // don't let it grow too large.
    if (stack.size() > RETURN_STACK_MAX_SIZE) {
        stack.removeLast();
    }

    session.setAttribute(AttrConstants.RETURN_LOC_SES_ATTR, stack);
}

From source file:com.bittorrent.mpetazzoni.common.Torrent.java

/**
 * Helper method to create a {@link Torrent} object for a set of files.
 *
 * <p>//  www.j av a 2  s . co m
 * 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.
 */
private static Torrent create(File parent, List<File> files, URI announce, List<List<URI>> announceList,
        String createdBy) throws InterruptedException, IOException {
    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>();

    if (announce != null) {
        torrent.put("announce", new BEValue(announce.toString()));
    }
    if (announceList != null) {
        List<BEValue> tiers = new LinkedList<BEValue>();
        for (List<URI> trackers : announceList) {
            List<BEValue> tierInfo = new LinkedList<BEValue>();
            for (URI trackerURI : trackers) {
                tierInfo.add(new BEValue(trackerURI.toString()));
            }
            tiers.add(new BEValue(tierInfo));
        }
        torrent.put("announce-list", new BEValue(tiers));
    }

    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(Torrent.PIECE_LENGTH));

    if (files == null || files.isEmpty()) {
        info.put("length", new BEValue(parent.length()));
        info.put("pieces", new BEValue(Torrent.hashFile(parent), Torrent.BYTE_ENCODING));
    } else {
        List<BEValue> fileInfo = new LinkedList<BEValue>();
        for (File file : files) {
            Map<String, BEValue> fileMap = new HashMap<String, BEValue>();
            fileMap.put("length", new BEValue(file.length()));

            LinkedList<BEValue> filePath = new LinkedList<BEValue>();
            while (file != null) {
                if (file.equals(parent)) {
                    break;
                }

                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(Torrent.hashFiles(files), Torrent.BYTE_ENCODING));
    }
    torrent.put("info", new BEValue(info));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BEncoder.bencode(new BEValue(torrent), baos);
    return new Torrent(baos.toByteArray(), true);
}