Example usage for java.util LinkedList contains

List of usage examples for java.util LinkedList contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:de.uni_potsdam.hpi.bpt.bp2014.jcore.rest.RestInterface.java

/**
 * This method provides detailed information about an data Object.
 * The information contain the id, parent scenario instance, label
 * and the current state,//from  w w  w .j  ava 2 s. com
 * This information will be provided as a JSON-Object.
 * A Data object is specified by:
 *
 * @param scenarioID   The scenario Model ID.
 * @param instanceID   The scenario Instance ID.
 * @param dataObjectID The Data Object ID.
 * @return Returns a JSON-Object with information about the dataObject,
 * the response code will be a 200 (OK).
 * If the data object does not exist a 404 (NOT_FOUND) will not be
 * returned.
 * If the instance does exist but some params are wrong a 301
 * (REDIRECT) will be returned.
 */
@GET
@Path("scenario/{scenarioID}/instance/{instanceID}/dataobject/{dataObjectID}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDataObject(@PathParam("scenarioID") int scenarioID, @PathParam("instanceID") int instanceID,
        @PathParam("dataObjectID") int dataObjectID) {
    ExecutionService executionService = new ExecutionService();
    if (!executionService.existScenarioInstance(instanceID)) {
        return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON)
                .entity("{\"error\":\"There is no instance with the id " + instanceID + "\"}").build();
    } else if (!executionService.existScenario(scenarioID)) {
        try {
            return Response.seeOther(new URI(
                    "interface/v2/scenario/" + executionService.getScenarioIDForScenarioInstance(instanceID)
                            + "/instance/" + instanceID + "/dataobject/" + dataObjectID))
                    .build();
        } catch (URISyntaxException e) {
            return Response.serverError().build();
        }
    }
    executionService.openExistingScenarioInstance(scenarioID, instanceID);
    LinkedList<Integer> dataObjects = executionService.getAllDataObjectIDs(instanceID);
    HashMap<Integer, String> states = executionService.getAllDataObjectStates(instanceID);
    HashMap<Integer, String> labels = executionService.getAllDataObjectNames(instanceID);
    if (!dataObjects.contains(new Integer(dataObjectID))) {
        return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON)
                .entity("{\"error\":\"There is no dataobject with the id " + dataObjectID
                        + " for the scenario instance " + instanceID + "\"}")
                .build();
    }
    DataObjectJaxBean dataObject = new DataObjectJaxBean();
    dataObject.id = dataObjectID;
    dataObject.label = labels.get(new Integer(dataObjectID));
    dataObject.state = states.get(new Integer(dataObjectID));
    return Response.ok(dataObject, MediaType.APPLICATION_JSON).build();
}

From source file:org.bimserver.charting.Containers.TreeNode.java

public void padTreeSoThatLeafNodesAreAllTheSameDepth() {
    int maximumLeafDepth = maximumLeafDepth();
    ////from ww  w  . ja v  a  2s.  co m
    LinkedList<TreeNode> majorBranches = new LinkedList<>();
    Iterator<TreeNode> leaves = iterateLeafNodes();
    while (leaves.hasNext()) {
        TreeNode node = leaves.next();
        int depth = node.depth();
        boolean nodeMustBePadded = depth != maximumLeafDepth;
        if (nodeMustBePadded) {
            TreeNode branch = node.getMajorBranch();
            if (!majorBranches.contains(branch))
                majorBranches.add(branch);
        }
    }
    //
    while (majorBranches.size() > 0) {
        // Get branch.
        TreeNode branch = majorBranches.pop();
        LinkedList<TreeNode> nodesToConsider = new LinkedList<>(Arrays.asList(branch));
        TreeNode thisNode = null;
        do {
            thisNode = nodesToConsider.pop();
            if (thisNode.isLeaf()) {
                // This node is the only relevant one. Push it to the edge of the tree.
                int maximumDepthOfBranch = thisNode.depth();
                int delta = maximumLeafDepth - maximumDepthOfBranch;
                padParentWithXNodesThatCollapseIntoThisNode(thisNode, delta);
            } else if (thisNode.leavesAreAtSameDepth()) {
                // This node and all its children are only relevant. Push them all to the edge of the tree.
                int maximumDepthOfBranch = thisNode.maximumLeafDepth();
                int delta = maximumLeafDepth - maximumDepthOfBranch;
                padParentWithXNodesThatCollapseIntoThisNode(thisNode, delta);
            } else {
                // Prepare to move to next on next iteration of do-while loop. Only add children with an aggregate set of leaves less than the maximum leaf depth in the tree.
                for (TreeNode child : thisNode.Children) {
                    int minimumLeafDepth = child.minimumLeafDepth();
                    if (minimumLeafDepth < maximumLeafDepth)
                        nodesToConsider.add(child);
                }
            }
        } while (!branch.leavesAreAtSameDepth());
    }
}

From source file:org.dataconservancy.ui.services.MockDcsConnector.java

private void performParentSearch(LinkedList<DcsEntity> result, String archive_id) {
    //This mocks the parent search it ignores the parent id and just returns everything that parent isn't null
    for (Map.Entry<String, Set<DcsEntity>> entry : archiveUtil.getEntities().entrySet()) {
        for (DcsEntity entity : entry.getValue()) {
            if (!(entity instanceof DcsDeliverableUnit)) {
                continue;
            }//from w  ww  .  j a v  a 2  s  .c  om

            DcsDeliverableUnit du = (DcsDeliverableUnit) entity;
            for (DcsDeliverableUnitRef parentRef : du.getParents()) {
                if (parentRef.getRef().equalsIgnoreCase(archive_id)) {
                    if (!result.contains(du)) {
                        result.add(du);
                    }
                }
            }
        }
    }
}

From source file:com.tapcentive.sdk.icons.IconRetrievalService.java

protected void syncIcons(List<IconReference> icon_list) {
    Log.d(TAG, "Calling syncIcons with icon_list: " + icon_list.toString());
    // Get the current list of stored icons and delete ones that aren't in the icon_list
    File dir = new File(getApplicationContext().getFilesDir() + "/" + ICONDIR);
    dir.mkdirs(); // Just make sure it exists always
    LinkedList<Long> localFileIds = new LinkedList<Long>();
    if (dir.isDirectory()) {
        for (final File iconFile : dir.listFiles()) {
            //String iconFileId = iconFile.getName().substring(0, iconFile.getName().length()-4); // Remove .png, .gif, etc
            String iconFileId = iconFile.getName().substring(0, iconFile.getName().lastIndexOf(".")); // Remove extension
            localFileIds.add(Long.parseLong(iconFileId));
            boolean found = false;
            for (IconReference ref : icon_list) {
                if (Long.toString(ref.id).equals(iconFileId)) {
                    found = true;/*  www  .j  a v a  2s  . c  o  m*/
                    break;
                }
            }
            if (!found) {
                iconFile.delete();
            }
        }
        Log.d(TAG, "Would start to sync icons here: " + icon_list.toString());
        for (IconReference icon : icon_list) {
            if (!localFileIds.contains(icon.id)) {
                retrieveIcon(icon);
            }
        }
    }

}

From source file:org.cytoscape.app.internal.manager.App.java

/**
 * Moves an app file to the given directory, copying the app if it is outside one of the local app storage directories
 * and moving if it is not. Also assigns filename that does not colliide with any from the local app storage directories.
 * /*from  www  .j  ava2 s  .co  m*/
 * Will also add postfix to filename if desired filename already exists in target directory when
 * moving app to a directory other than the 3 local app storage directories.
 * 
 * @param appManager A reference to the app manager
 * @param targetDirectory The local storage directory to move to, such as the local sotrage directory
 * containing installed apps obtained via the app manager
 * @throws IOException If there was an error while moving/copying the file
 */
public void moveAppFile(AppManager appManager, File targetDirectory) throws IOException {
    File parentPath = this.getAppFile().getParentFile();
    File installDirectoryPath = new File(appManager.getInstalledAppsPath());
    File disabledDirectoryPath = new File(appManager.getDisabledAppsPath());
    File uninstallDirectoryPath = new File(appManager.getUninstalledAppsPath());

    // Want to make sure the app file's name does not collide with another name in these directories
    LinkedList<String> uniqueNameDirectories = new LinkedList<String>();

    if (!parentPath.equals(installDirectoryPath))
        uniqueNameDirectories.add(installDirectoryPath.getCanonicalPath());

    if (!parentPath.equals(disabledDirectoryPath))
        uniqueNameDirectories.add(disabledDirectoryPath.getCanonicalPath());

    if (!parentPath.equals(uninstallDirectoryPath))
        uniqueNameDirectories.add(uninstallDirectoryPath.getCanonicalPath());

    if (!parentPath.equals(targetDirectory) && !installDirectoryPath.equals(targetDirectory)
            && !disabledDirectoryPath.equals(targetDirectory)
            && !uninstallDirectoryPath.equals(targetDirectory))
        uniqueNameDirectories.add(targetDirectory.getCanonicalPath());

    // If the app file is in one of these directories, do a move instead of a copy
    LinkedList<File> moveDirectories = new LinkedList<File>();
    moveDirectories.add(installDirectoryPath);
    moveDirectories.add(disabledDirectoryPath);
    moveDirectories.add(uninstallDirectoryPath);

    File targetFile = new File(targetDirectory.getCanonicalPath() + File.separator
            + suggestFileName(uniqueNameDirectories, this.getAppFile().getName()));

    if (!targetDirectory.equals(parentPath)) {
        if (moveDirectories.contains(parentPath)) {
            FileUtils.moveFile(this.getAppFile(), targetFile);
            //System.out.println("Moving: " + this.getAppFile() + " -> " + targetFile);

            // ** Disabled to let directory observers assign file reference
            // this.setAppFile(targetFile);
        } else {
            FileUtils.copyFile(this.getAppFile(), targetFile);
            //System.out.println("Copying: " + this.getAppFile() + " -> " + targetFile);

            // ** Disabled to let directory observers assign file reference
            // this.setAppFile(targetFile);
        }
    }
}

From source file:org.alfresco.repo.management.SafeApplicationEventMulticaster.java

/**
 * Return a Collection of ApplicationListeners matching the given event
 * type. Non-matching listeners get excluded early.
 * /*ww w  . j  av  a 2  s. com*/
 * @param event
 *            the event to be propagated. Allows for excluding non-matching
 *            listeners early, based on cached matching information.
 * @return a Collection of ApplicationListeners
 * @see org.springframework.context.ApplicationListener
 */
protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) {
    Class<? extends ApplicationEvent> eventType = event.getClass();
    Class sourceType = event.getSource().getClass();
    ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);
    ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
    if (retriever != null) {
        return retriever.getApplicationListeners();
    } else {
        retriever = new ListenerRetriever(true);
        LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>();
        synchronized (this.defaultRetriever) {
            if (!this.defaultRetriever.applicationListenerBeans.isEmpty()) {
                BeanFactory beanFactory = getBeanFactory();
                for (String listenerBeanName : this.defaultRetriever.applicationListenerBeans) {
                    ApplicationListener listener = beanFactory.getBean(listenerBeanName,
                            ApplicationListener.class);
                    if (supportsEvent(listener, eventType, sourceType)) {
                        retriever.applicationListenerBeans.add(listenerBeanName);
                        allListeners.add(listener);
                    }
                }
            }
            for (ApplicationListener listener : this.defaultRetriever.applicationListeners) {
                if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
                    retriever.applicationListeners.add(listener);
                    allListeners.add(listener);
                }
            }
            OrderComparator.sort(allListeners);
            this.retrieverCache.put(cacheKey, retriever);
        }
        if (log.isDebugEnabled()) {
            log.debug(allListeners.toString());
        }
        return allListeners;
    }
}

From source file:com.jaspersoft.studio.property.section.style.inerithance.StylesListSection.java

/**
 * Build the hierarchy of styles of an element
 * /*from  w  w w  .  j a v a2s.  co  m*/
 * @param element
 *          Element from which the styles list will be generated
 * @return A list of MStyle, where the first is the style assigned to the element, the second is the style assigned to
 *         the first item of the list and so on
 */
private LinkedList<MStyle> buildStylesGerarchy(APropertyNode element) {
    LinkedList<MStyle> result = new LinkedList<MStyle>();
    Object style = getElementStyle(element);
    StyleContainer styleContainer = styleMaps.get(style);
    while (styleContainer != null) {
        MStyle styleModel = styleContainer.getStyle();
        if (!result.contains(styleModel))
            result.addLast(styleModel);
        else {
            //The style has itself set as parent style, break the cycle
            //this shouldn't happen, but maybe the jrxml was modifed manually on
            //it's better to put this check to avoid a java heap exception
            break;
        }
        style = getElementStyle(styleModel);
        styleContainer = styleMaps.get(style);
    }
    return result;
}

From source file:org.dataconservancy.ui.services.MockDcsConnector.java

/**
 * Performs an search.  The caller indicates the maximum number of results to return, and the offset within
 * the total number of results./*from ww w.  j  a v  a2s  .  c  o  m*/
 * <p/>
 * Because there is no concrete search implementation backing the mock connector, the query semantics are
 * determined by parsing the query string, and the query itself is emulated. Currently, the following kinds
 * of searches are supported:
 * <ul>
 * <li>ancestry search - find entities that share a common ancestor</li>
 * <li>identity search - find an entity with a specific id</li>
 * <li>parent search - find child Deliverable Units of a parent DU</li>
 * </ul>
 *
 * @param query the query string
 * @return an iterator over the search results
 * @throws DcsConnectorFault
 */
public CountableIterator<DcsEntity> search(String query, int maxResults, int offset) throws DcsConnectorFault {

    LinkedList<DcsEntity> result = new LinkedList<DcsEntity>();

    // Grab id
    String archive_id = null;
    if (query.contains("parent:")) {
        archive_id = query.substring(query.indexOf("parent:") + "parent:".length() + 1, query.length() - 2);
    } else {
        int i = query.indexOf('\"');
        archive_id = query.substring(i + 1, query.indexOf('\"', i + 1));
    }

    // TODO unescape solr syntax correctly
    archive_id = archive_id.replace("\\", "");

    if (query.contains(" OR ") && !query.contains("former:")) {
        // Assume sip recreation search

        // Find all the ancestors of archive_id
        performAncestrySearch(result, archive_id);

        // Add the common ancestor itself.
        DcsEntity e = archiveUtil.getEntity(archive_id);
        if (!result.contains(e)) {
            result.add(e);
        }

    } else if (query.startsWith("id:")) {
        // Assume id search
        if (archiveUtil.getEntity(archive_id) != null) {
            result.add(archiveUtil.getEntity(archive_id));
        }
    } else if (query.startsWith("ancestry:")) {
        // Assume ancestry search
        performAncestrySearch(result, archive_id);
    } else if (query.contains("parent")) {
        performParentSearch(result, archive_id);
    } else if (query.contains("former:")) {
        // example query we're handling:
        // ((entityType:"DeliverableUnit" AND former:"ed64f0fc\-8201\-47c0\-bdc9\-024078aaefbc" AND type:"root"))
        // OR ((entityType:"DeliverableUnit" AND former:"ed64f0fc\-8201\-47c0\-bdc9\-024078aaefbc" AND type:"state"))
        // another example query:
        // ((entityType:"DeliverableUnit" AND former:"id\://mooo" AND type:"root")) OR ((entityType:"DeliverableUnit" AND former:"id\://mooo" AND type:"state"))
        // another example:
        // (entityType:"DeliverableUnit" AND former:"http\://localhost\:8080/item/8" AND type:"org.dataconservancy\:types\:DataItem")

        Pattern p = Pattern.compile("^.*former:(\\S*)\\s.*$");
        Matcher m = p.matcher(query);
        if (m.find()) {
            String former_ref = m.group(1);
            former_ref = stripQuotes(former_ref);
            performFormerSearch(result, former_ref);
        } else {
            throw new RuntimeException(
                    "Unable to parse value for the 'former:' parameter from query string '" + query + "'");
        }

        LinkedList<DcsEntity> culledResults = new LinkedList<DcsEntity>();

        p = Pattern.compile("type:(\\S*)");
        m = p.matcher(query);
        if (!m.find()) {
            culledResults.addAll(result);
        }

        m = p.matcher(query);

        while (m.find()) {
            String type = stripQuotes(m.group(1));

            Iterator<DcsEntity> itr = result.iterator();
            while (itr.hasNext()) {
                DcsEntity entity = itr.next();
                if (!(entity instanceof DcsDeliverableUnit)) {
                    culledResults.add(entity);
                }

                if (type.equals(((DcsDeliverableUnit) entity).getType())) {
                    culledResults.add(entity);
                }
            }
        }

        result = culledResults;
    } else {
        throw new UnsupportedOperationException("Search not handled: " + query);
    }

    if (offset > 0 && result.size() > 0) {
        result.subList(0, offset).clear();
    }

    if (maxResults > 0 && result.size() > maxResults) {
        result.subList(maxResults, result.size()).clear();
    }

    return new MockSearchIterator(result);
}

From source file:fr.univlorraine.mondossierweb.views.RechercheMobileView.java

private List<ResultatDeRecherche> quickSearch(String valueString) {

    List<ResultatDeRecherche> listeReponses = new LinkedList<ResultatDeRecherche>();

    String value = valueString;/* w w w .  j a v  a  2  s .c o m*/
    if (StringUtils.hasText(value) && value.length() > 2) {

        ///////////////////////////////////////////////////////
        //appel elasticSearch
        ///////////////////////////////////////////////////////
        //transformation de la chaine recherche en fonction des besoins
        String valueselasticSearch = value;

        //valueselasticSearch = valueselasticSearch+"*";
        List<Map<String, Object>> lobjresult = ElasticSearchService.findObj(valueselasticSearch,
                Utils.NB_MAX_RESULT_QUICK_SEARCH * 5, true);

        //Liste des types autoriss
        LinkedList<String> listeTypeAutorise = new LinkedList();
        if (casesAcocherVet) {
            listeTypeAutorise.add(Utils.VET);
        }
        if (casesAcocherElp) {
            listeTypeAutorise.add(Utils.ELP);
        }
        if (casesAcocherEtudiant) {
            listeTypeAutorise.add(Utils.ETU);
        }

        ///////////////////////////////////////////////////////
        // recuperation des obj ElasticSearch
        ///////////////////////////////////////////////////////
        if (lobjresult != null && listeTypeAutorise.size() > 0) {
            for (Map<String, Object> obj : lobjresult) {
                if (listeReponses.size() < Utils.NB_MAX_RESULT_QUICK_SEARCH) {
                    if (obj != null) {
                        if (listeTypeAutorise.contains((String) obj.get(Utils.ES_TYPE))) {
                            if (listeReponses.size() > 0) {
                                boolean triOk = true;
                                int rang = 0;
                                //On evite des doublons
                                while (triOk && rang < listeReponses.size()) {
                                    //En quickSearch on prend la description et non pas le libelle
                                    if ((listeReponses.get(rang).lib.toUpperCase())
                                            .equals((new ResultatDeRecherche(obj)).lib.toUpperCase())) {
                                        triOk = false;
                                    }
                                    rang++;
                                }
                                if (triOk) {
                                    //En quickSearch on prend la description et non pas le libelle
                                    listeReponses.add(new ResultatDeRecherche(obj));
                                }
                            } else {
                                //En quickSearch on prend la description et non pas le libelle
                                listeReponses.add(new ResultatDeRecherche(obj));
                            }
                        }
                    }
                }
            }
        }

    }

    return listeReponses;

}

From source file:org.jahia.services.render.filter.cache.AggregateCacheFilter.java

/**
 * The prepare method is the first entry point in the cache. Its purpose is to check if a content is inside the
 * cache, and returns cached content for the fragment matching the requested resource if it is found. If other
 * fragment (module tags) are embedded inside this fragment, it will get them from the cache or by calling the
 * render service and aggregate them.//from www  .j ava 2 s. com
 *
 * @param renderContext The render context
 * @param resource      The resource to render
 * @param chain         The render chain
 * @return The content (with sub content aggregated) if found in the cache, null otherwise.
 * @throws Exception
 */
@Override
public String prepare(RenderContext renderContext, Resource resource, RenderChain chain) throws Exception {
    final boolean debugEnabled = logger.isDebugEnabled();
    // Generates the key of the requested fragment. The KeyGenerator will create a key based on the request
    // (resource and context) and the cache properties. The generated key will contains temporary placeholders
    // that will be replaced to have the final key.
    Properties properties = getAttributesForKey(renderContext, resource);
    final Map<String, Serializable> moduleParams = resource.getModuleParams();
    final Boolean forceGeneration = (Boolean) moduleParams.remove("cache.forceGeneration");

    String key = cacheProvider.getKeyGenerator().generate(resource, renderContext, properties);

    // Store the cache key in module params for usage in execute
    moduleParams.put("cacheKey", key);

    if (debugEnabled) {
        logger.debug("Cache filter for key with placeholders : {}", key);
    }

    // If we force the generation, return null
    if (Boolean.TRUE.equals(forceGeneration)) {
        return null;
    }

    // First check if the key is in the list of non-cacheable keys. The cache can also be skipped by specifying the
    // ec parameter with the uuid of the current node.
    if (!isCacheable(renderContext, resource, key, properties)) {
        return null;
    }

    // Replace the placeholders to have the final key that is used in the cache.
    String finalKey = replacePlaceholdersInCacheKey(renderContext, key);

    // Keeps a list of keys being generated to avoid infinite loops.
    LinkedList<String> userKeysLinkedList = userKeys.get();
    if (userKeysLinkedList == null) {
        userKeysLinkedList = new LinkedList<>();
        userKeys.set(userKeysLinkedList);
    }
    if (userKeysLinkedList.contains(finalKey)) {
        return null;
    }
    userKeysLinkedList.add(0, finalKey);

    Element element = null;
    final Cache cache = cacheProvider.getCache();

    try {
        if (debugEnabled) {
            logger.debug("Try to get content from cache for node with final key: {}", finalKey);
        }
        element = cache.get(finalKey);
    } catch (LockTimeoutException e) {
        logger.warn("Error while rendering " + renderContext.getMainResource() + e.getMessage(), e);
    }

    if (element != null && element.getObjectValue() != null) {
        // The element is found in the cache. Need to
        return returnFromCache(renderContext, resource, key, finalKey, element, cache);
    } else {
        // The element is not found in the cache with that key. Use CountLatch to avoid parallel processing of the
        // module - if somebody else is generating this fragment, wait for the entry to be generated and
        // return the content from the cache. Otherwise, return null to continue the render chain.
        // Note that the fragment MIGHT be in cache, but the key may not be correct - some parameters impacting the
        // key like dependencies can only be calculated when the fragment has been generated.
        CountDownLatch countDownLatch = avoidParallelProcessingOfSameModule(finalKey,
                renderContext.getRequest(), resource, properties);
        if (countDownLatch == null) {
            element = cache.get(finalKey);
            if (element != null && element.getObjectValue() != null) {
                return returnFromCache(renderContext, resource, key, finalKey, element, cache);
            }
        } else {
            Set<CountDownLatch> latches = processingLatches.get();
            if (latches == null) {
                latches = new HashSet<>();
                processingLatches.set(latches);
            }
            latches.add(countDownLatch);
        }
        return null;
    }
}