Example usage for java.util LinkedList isEmpty

List of usage examples for java.util LinkedList isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils.java

/**
 * Gets the list of matching templates for the given object class description.
 * <p>//from w w  w  .j  ava2s . c  om
 * To do this, we're using a "Breadth First Search" algorithm to go through all
 * the superiors (and the superiors of these superiors, etc.).
 *
 * @param objectClassDescription
 *      the object class description
 * @param schema
 *      the associated schema
 * @return
 *      the list of matching templates for the given object class description
 */
private static List<Template> getTemplatesFromHighestObjectClass(ObjectClass objectClassDescription,
        Schema schema) {
    // Creating a set to hold all the matching templates
    List<Template> matchingTemplates = new ArrayList<Template>();

    // Getting the templates manager
    TemplatesManager manager = EntryTemplatePlugin.getDefault().getTemplatesManager();

    // Getting the list of all the available templates
    Template[] templates = manager.getTemplates();

    // Creating a MultiValueMap that holds the templates ordered by ObjectClassDescription object
    MultiValueMap templatesByOcd = new MultiValueMap();

    // Populating this map
    for (Template template : templates) {
        templatesByOcd.put(getObjectClass(template.getStructuralObjectClass(), schema), template);
    }

    // Initializing the LIFO queue with the highest ObjectClassDescription object
    LinkedList<ObjectClass> ocdQueue = new LinkedList<ObjectClass>();
    ocdQueue.add(objectClassDescription);

    // Looking if we need to test a new ObjectClassDescription object
    while (!ocdQueue.isEmpty()) {
        // Dequeuing the last object for testing
        ObjectClass currentOcd = ocdQueue.removeLast();

        // Adds the templates for the current object class description to the list of matching templates
        addTemplatesForObjectClassDescription(currentOcd, matchingTemplates, manager);

        // Adding each superior object to the queue
        List<String> currentOcdSups = currentOcd.getSuperiorOids();
        if (currentOcdSups != null) {
            for (String currentOcdSup : currentOcdSups) {
                ocdQueue.addFirst(getObjectClass(currentOcdSup, schema));
            }
        }
    }

    return matchingTemplates;
}

From source file:eulermind.importer.LineNode.java

private static LineNode reduceToChapterTreeByBlankLine(List<LineNode> lineNodes) {
    LinkedList<LineNode> newlineNodes = new LinkedList<LineNode>();

    //??, //  ww  w  . j a  v a  2s  .c  o  m
    for (LineNode lineNode : lineNodes) {
        if (lineNode.m_blankLines > 200) {
            lineNode.m_blankLines = 200;
        }
    }
    Iterator<LineNode> iterator = lineNodes.iterator();
    newlineNodes.add(iterator.next());

    //lineNode ?????newLineNodes
    //

    //?????
    {
        int maxBlankLines = 0;
        while (iterator.hasNext()) {
            LineNode lineNode = iterator.next();
            maxBlankLines = Math.max(maxBlankLines, lineNode.m_blankLines);

            //
            for (int i = newlineNodes.peekLast().m_blankLines + 1; i < lineNode.m_blankLines; i++) {
                newlineNodes.add(new LineNode(i));
            }
            newlineNodes.add(lineNode);
        }

        //
        for (int i = newlineNodes.peekLast().m_blankLines + 1; i <= maxBlankLines + 1; i++) {
            newlineNodes.add(new LineNode(i));
        }
    }

    //?
    LinkedList<LineNode> stack = new LinkedList<LineNode>();

    for (LineNode newLineNode : newlineNodes) {
        if (!stack.isEmpty() && stack.peekLast().m_blankLines < newLineNode.m_blankLines) {
            List<LineNode> reducedLineNodes = popSameBlankLineNodes(stack);

            for (LineNode reducedLineNode : reducedLineNodes) {
                newLineNode.add(reducedLineNode);
            }
        }

        stack.add(newLineNode);
    }

    assert stack.size() == 1;

    return stack.peekFirst();
}

From source file:se.trillian.goodies.spring.DomainObjectFactoryFactoryBean.java

private static Constructor<?> findMatchingConstructor(Class<?> clazz, Method m) {
    LinkedList<Constructor<?>> constructors = new LinkedList<Constructor<?>>();
    Constructor<?> directMatch = null;
    for (Constructor<?> c : clazz.getDeclaredConstructors()) {
        if (isParameterTypesPrefix(m.getParameterTypes(), c.getParameterTypes())) {
            constructors.add(c);/*from  www .  j  a  v a2 s  .  c  om*/
            if (directMatch == null && isParameterTypesPrefix(c.getParameterTypes(), m.getParameterTypes())) {
                directMatch = c;
            }
        }
    }
    if (constructors.isEmpty()) {
        throw new IllegalArgumentException("No matching constructor found in " + "implementation class '"
                + clazz + "' for factory method '" + m + "'");
    }
    if (constructors.size() > 1) {
        if (directMatch != null) {
            return directMatch;
        }
        throw new IllegalArgumentException("More than 1 matching constructor "
                + "found in implementation class '" + clazz + "' for factory method '" + m + "'");
    }
    return constructors.getFirst();
}

From source file:eulermind.importer.LineNode.java

private static LinkedList<LineNode> popSameBlankLineNodes(LinkedList<LineNode> stack) {
    int lastBlankLines = stack.peekLast().m_blankLines;
    LinkedList<LineNode> lastSameLineNodes = new LinkedList<LineNode>();

    while (!stack.isEmpty() && stack.peekLast().m_blankLines == lastBlankLines) {
        //pollLast? addFirst??
        lastSameLineNodes.addFirst(stack.pollLast());
    }/*from   w  w w  . j  a v  a 2 s . co  m*/
    return lastSameLineNodes;
}

From source file:org.eclipse.wb.internal.core.xml.model.description.ComponentDescriptionHelper.java

private static ComponentDescription getDescriptionEx(EditorContext context, Class<?> componentClass)
        throws Exception {
    ComponentDescription componentDescription = new ComponentDescription(componentClass);
    // prepare description resources, from generic to specific
    LinkedList<ClassResourceInfo> descriptionInfos;
    {// w  ww  .  ja  v a2  s  .  c  o m
        descriptionInfos = Lists.newLinkedList();
        DescriptionHelper.addDescriptionResources(descriptionInfos, context.getLoadingContext(),
                componentClass);
        Assert.isTrueException(!descriptionInfos.isEmpty(), IExceptionConstants.DESCRIPTION_NO_DESCRIPTIONS,
                componentClass.getName());
    }
    // prepare Digester
    Digester digester;
    {
        digester = new Digester();
        digester.setLogger(new NoOpLog());
        addRules(digester, context, componentClass);
    }
    // read descriptions from generic to specific
    for (ClassResourceInfo descriptionInfo : descriptionInfos) {
        ResourceInfo resourceInfo = descriptionInfo.resource;
        // read next description
        {
            //componentDescription.setCurrentClass(descriptionInfo.clazz);
            digester.push(componentDescription);
            // do parse
            InputStream is = resourceInfo.getURL().openStream();
            try {
                digester.parse(is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
        // clear parts that can not be inherited
        if (descriptionInfo.clazz == componentClass) {
            setDescriptionWithInnerTags(componentDescription, resourceInfo);
        } else {
            componentDescription.clearCreations();
            componentDescription.setDescription(null);
        }
    }
    // set toolkit
    if (componentDescription.getToolkit() == null) {
        for (int i = descriptionInfos.size() - 1; i >= 0; i--) {
            ClassResourceInfo descriptionInfo = descriptionInfos.get(i);
            ToolkitDescription toolkit = descriptionInfo.resource.getToolkit();
            if (toolkit != null) {
                componentDescription.setToolkit(toolkit);
                break;
            }
        }
    }
    // mark for caching presentation
    if (shouldCachePresentation(descriptionInfos.getLast(), componentClass)) {
        componentDescription.setPresentationCached(true);
    }
    // final operations
    setIcon(context, componentDescription, componentClass);
    useDescriptionProcessors(context, componentDescription);
    componentDescription.postProcess();
    // done
    return componentDescription;
}

From source file:org.apache.cocoon.util.NetUtils.java

/**
 * Normalize a uri containing ../ and ./ paths.
 *
 * @param uri The uri path to normalize/*from  w ww . java  2s. c o  m*/
 * @return The normalized uri
 */
public static String normalize(String uri) {
    if ("".equals(uri)) {
        return uri;
    }
    int leadingSlashes = 0;
    for (leadingSlashes = 0; leadingSlashes < uri.length()
            && uri.charAt(leadingSlashes) == '/'; ++leadingSlashes) {
    }
    boolean isDir = (uri.charAt(uri.length() - 1) == '/');
    StringTokenizer st = new StringTokenizer(uri, "/");
    LinkedList clean = new LinkedList();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if ("..".equals(token)) {
            if (!clean.isEmpty() && !"..".equals(clean.getLast())) {
                clean.removeLast();
                if (!st.hasMoreTokens()) {
                    isDir = true;
                }
            } else {
                clean.add("..");
            }
        } else if (!".".equals(token) && !"".equals(token)) {
            clean.add(token);
        }
    }
    StringBuffer sb = new StringBuffer();
    while (leadingSlashes-- > 0) {
        sb.append('/');
    }
    for (Iterator it = clean.iterator(); it.hasNext();) {
        sb.append(it.next());
        if (it.hasNext()) {
            sb.append('/');
        }
    }
    if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
        sb.append('/');
    }
    return sb.toString();
}

From source file:com.salsaberries.narchiver.Writer.java

/**
 * Writes all the pages to file./*  www.  j  a v a 2 s . co m*/
 *
 * @param pages
 * @param location
 */
public static void storePages(LinkedList<Page> pages, String location) {

    logger.info("Dumping " + pages.size() + " pages to file at " + location + "/");

    File file = new File(location);
    // Make sure the directory exists
    if (!file.exists()) {
        try {
            file.mkdirs();
            logger.info("Directory " + file.getAbsolutePath() + " does not exist, creating.");
        } catch (SecurityException e) {
            logger.error(e.getMessage());
        }
    }
    // Write them to the file if they haven't been already written
    while (!pages.isEmpty()) {
        Page page = pages.removeFirst();

        String fileName = file.getAbsolutePath() + "/" + page.getDate() + "|"
                + URLEncoder.encode(page.getTagURL());

        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
            writer.write(page.toString());
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
        // Temporarily try to reduce memory
        page.setHtml("");
    }
}

From source file:org.dcm4che3.conf.core.misc.DeepEquals.java

/**
 * Get a deterministic hashCode (int) value for an Object, regardless of
 * when it was created or where it was loaded into memory.  The problem
 * with java.lang.Object.hashCode() is that it essentially relies on
 * memory location of an object (what identity it was assigned), whereas
 * this method will produce the same hashCode for any object graph, regardless
 * of how many times it is created.<br/><br/>
 *
 * This method will handle cycles correctly (A->B->C->A).  In this case,
 * Starting with object A, B, or C would yield the same hashCode.  If an
 * object encountered (root, suboject, etc.) has a hashCode() method on it
 * (that is not Object.hashCode()), that hashCode() method will be called
 * and it will stop traversal on that branch.
 * @param obj Object who hashCode is desired.
 * @return the 'deep' hashCode value for the passed in object.
 *//*from   w  ww. j  a v a 2 s . co  m*/
public static int deepHashCode(Object obj) {
    Set visited = new HashSet();
    LinkedList<Object> stack = new LinkedList<Object>();
    stack.addFirst(obj);
    int hash = 0;

    while (!stack.isEmpty()) {
        obj = stack.removeFirst();
        if (obj == null || visited.contains(obj)) {
            continue;
        }

        visited.add(obj);

        if (obj.getClass().isArray()) {
            int len = Array.getLength(obj);
            for (int i = 0; i < len; i++) {
                stack.addFirst(Array.get(obj, i));
            }
            continue;
        }

        if (obj instanceof Collection) {
            stack.addAll(0, (Collection) obj);
            continue;
        }

        if (obj instanceof Map) {
            stack.addAll(0, ((Map) obj).keySet());
            stack.addAll(0, ((Map) obj).values());
            continue;
        }

        if (hasCustomHashCode(obj.getClass())) { // A real hashCode() method exists, call it.
            hash += obj.hashCode();
            continue;
        }

        Collection<Field> fields = getDeepDeclaredFields(obj.getClass());
        for (Field field : fields) {
            try {
                stack.addFirst(field.get(obj));
            } catch (Exception ignored) {
            }
        }
    }
    return hash;
}

From source file:com.frochr123.helper.CachedFileDownloader.java

public synchronized static SimpleEntry<String, SimpleEntry<String, File>> downloadFile(String url,
        String commaSeperatedAllowedFileTypes) throws IOException {
    // On invalid URL return null
    if (url == null || url.isEmpty()) {
        return null;
    }/* www  .j  a v  a 2 s.  c o m*/

    // Prepare check file extensions
    String allowedFileTypesString = commaSeperatedAllowedFileTypes;

    // Fallback to default allowed file types
    if (allowedFileTypesString == null || allowedFileTypesString.isEmpty()) {
        allowedFileTypesString = CACHE_DOWNLOADER_DEFAULT_FILETYPES;
    }

    // Get seperate file types from string and normalize to lowercase
    String[] allowedFileTypesArray = allowedFileTypesString.split(",");

    if (allowedFileTypesArray.length > 0) {
        // Normalize file extensions to lower case
        for (int i = 0; i < allowedFileTypesArray.length; ++i) {
            if (allowedFileTypesArray[i] != null && !allowedFileTypesArray[i].isEmpty()) {
                allowedFileTypesArray[i] = allowedFileTypesArray[i].toLowerCase();
            }
        }
    }

    File file = null;
    String finalUrl = null;
    String fileExtension = null;
    String fileBaseName = null;
    SimpleEntry<String, File> innerResult = null;
    SimpleEntry<String, SimpleEntry<String, File>> finalResult = null;

    // Check if URL is already stored in cache map
    if (cacheMap.containsKey(url)) {
        if (cacheMap.get(url) != null) {
            innerResult = cacheMap.get(url);
            file = (File) (cacheMap.get(url).getValue());
        }
    }
    // URL is not stored in cache, download and store it in cache
    else {
        // Resize cache if needed, LinkedHashMap keeps insertion order, oldest entries are first entries
        // Temporary store keys in list and remove afterwards to avoid read / write issues
        // Get one free space for new download
        LinkedList<String> deleteKeys = new LinkedList<String>();
        for (Entry<String, SimpleEntry<String, File>> cacheEntry : cacheMap.entrySet()) {
            if ((cacheMap.size() - deleteKeys.size()) >= CACHE_DOWNLOADER_MAX_ENTRIES) {
                deleteKeys.add(cacheEntry.getKey());
            } else {
                break;
            }
        }

        // Remove keys
        if (!deleteKeys.isEmpty()) {
            for (String key : deleteKeys) {
                // Delete old files
                if (cacheMap.get(key) != null && cacheMap.get(key).getValue() != null) {
                    cacheMap.get(key).getValue().delete();
                }

                // Remove entry in cache map
                cacheMap.remove(key);
            }
        }

        // Download file
        SimpleEntry<String, ByteArrayOutputStream> download = getResultFromURL(url);

        if (download == null || download.getKey() == null || download.getKey().isEmpty()
                || download.getValue() == null) {
            return null;
        }

        // Check for file type
        if (allowedFileTypesArray.length > 0) {
            finalUrl = download.getKey();
            fileExtension = FilenameUtils.getExtension(finalUrl);

            // Check for valid fileExtension
            if (fileExtension == null || fileExtension.isEmpty()) {
                return null;
            }

            // Check if fileExtension is contained in allowed file extensions
            // Normalize file extensions to lower case
            boolean foundAllowedFileExtension = false;

            for (int i = 0; i < allowedFileTypesArray.length; ++i) {
                if (allowedFileTypesArray[i].equals(fileExtension)) {
                    foundAllowedFileExtension = true;
                    break;
                }
            }

            // File extension was not found, abort
            if (!foundAllowedFileExtension) {
                return null;
            }
        }

        // Write result to file, it is allowed file type
        fileBaseName = FilenameUtils.getBaseName(finalUrl);
        file = FileUtils.getNonexistingWritableFile(fileBaseName + "." + fileExtension);
        file.deleteOnExit();
        FileOutputStream filestream = new FileOutputStream(file);
        download.getValue().writeTo(filestream);

        // Insert into cache and result variable
        innerResult = new SimpleEntry<String, File>(finalUrl, file);
        cacheMap.put(url, innerResult);
    }

    if (innerResult != null) {
        finalResult = new SimpleEntry<String, SimpleEntry<String, File>>(url, innerResult);
    }

    return finalResult;
}

From source file:jp.co.ctc_g.jse.vid.ViewId.java

private static ViewId current(ViewIdStore store) {

    ViewId id = null;// w w w  . j ava2s .c om
    synchronized (store.semaphore()) {
        LinkedList<ViewId> ids = store.find(false);
        id = ids != null && !ids.isEmpty() ? ids.getLast() : null;
    }
    return id;
}