Example usage for java.util Collection clear

List of usage examples for java.util Collection clear

Introduction

In this page you can find the example usage for java.util Collection clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this collection (optional operation).

Usage

From source file:com.haulmont.cuba.core.app.cache.CacheSet.java

/**
 * Sequential filtering by selectors/*from  ww w.j  a v  a 2s .c o  m*/
 *
 * @param selectors Selectors
 * @return CacheSet
 */
public CacheSet querySequential(Predicate... selectors) {
    checkNotNull(selectors);

    Collection<Object> resultCollection = new ArrayList<>(items);
    Collection<Object> filterCollection = new LinkedList<>();
    Collection<Object> tempCollection;

    int i = 0;
    while ((i < selectors.length) && (resultCollection.size() > 0)) {
        CollectionUtils.select(resultCollection, selectors[i], filterCollection);

        tempCollection = resultCollection;
        resultCollection = filterCollection;
        filterCollection = tempCollection;

        filterCollection.clear();
        i++;
    }

    return new CacheSet(resultCollection);
}

From source file:ubic.gemma.core.search.GeneSetSearchImpl.java

@Override
public Collection<GeneSet> findGeneSetsByName(String query, Long taxonId) {

    if (StringUtils.isBlank(query)) {
        return new HashSet<>();
    }//from   w  ww  .ja  v a2s  . c o  m
    Collection<GeneSet> foundGeneSets;
    Taxon tax;
    tax = taxonService.load(taxonId);

    if (tax == null) {
        // throw new IllegalArgumentException( "Can't locate taxon with id=" + taxonId );
        foundGeneSets = this.findByName(query);
    } else {
        foundGeneSets = this.findByName(query, tax);
    }

    foundGeneSets.clear(); // for testing general search

    /*
     * SEARCH GENE ONTOLOGY
     */

    if (query.toUpperCase().startsWith("GO")) {
        if (tax == null) {
            Collection<GeneSet> goSets = this.findByGoId(query);
            foundGeneSets.addAll(goSets);
        } else {
            GeneSet goSet = this.findByGoId(query, tax);
            if (goSet != null)
                foundGeneSets.add(goSet);
        }
    } else {
        foundGeneSets.addAll(this.findByGoTermName(query, tax));
    }

    return foundGeneSets;
}

From source file:org.nuxeo.ecm.platform.mimetype.service.MimetypeRegistryService.java

@Override
public String getMimetypeFromFile(File file) throws MimetypeNotFoundException, MimetypeDetectionException {
    if (file.length() > MAX_SIZE_FOR_SCAN) {
        String exceptionMessage = "Not able to determine mime type from filename and file is too big for binary scan.";
        if (file.getAbsolutePath() == null) {
            throw new MimetypeNotFoundException(exceptionMessage);
        }/*from   ww w .j  av  a  2  s .c o  m*/
        try {
            return getMimetypeFromFilename(file.getAbsolutePath());
        } catch (MimetypeNotFoundException e) {
            throw new MimetypeNotFoundException(exceptionMessage, e);
        }
    }
    try {
        MagicMatch match = Magic.getMagicMatch(file, true, false);
        String mimeType;

        if (match.getSubMatches().isEmpty()) {
            mimeType = match.getMimeType();
        } else {
            // Submatches found
            // TODO: we only take the first here
            // what to do with other possible responses ?
            // b.t.w., multiple responses denotes a non-accuracy problem in
            // magic.xml but be careful to nested possible
            // sub-sub-...-submatches make this as recursive ?
            Collection<MagicMatch> possibilities = match.getSubMatches();
            Iterator<MagicMatch> iter = possibilities.iterator();
            MagicMatch m = iter.next();
            mimeType = m.getMimeType();
            // need to clean for subsequent calls
            possibilities.clear();
            match.setSubMatches(possibilities);
        }
        if ("text/plain".equals(mimeType)) {
            // check we didn't mis-detect files with zeroes
            // check first 16 bytes
            byte[] bytes = new byte[16];
            FileInputStream is = new FileInputStream(file);
            int n = 0;
            try {
                n = is.read(bytes);
            } finally {
                is.close();
            }
            for (int i = 0; i < n; i++) {
                if (bytes[i] == 0) {
                    mimeType = "application/octet-stream";
                    break;
                }
            }
        }
        return mimeType;
    } catch (MagicMatchNotFoundException e) {
        if (file.getAbsolutePath() != null) {
            return getMimetypeFromFilename(file.getAbsolutePath());
        }
        throw new MimetypeNotFoundException(e.getMessage(), e);
    } catch (MagicException | MagicParseException | IOException e) {
        throw new MimetypeDetectionException(e.getMessage(), e);
    }
}

From source file:org.apache.openjpa.kernel.AttachStrategy.java

/**
 * Return a new collection with the attached contents of the given one.
 *//*w  w w .  java2s  . c  om*/
protected Collection attachCollection(AttachManager manager, Collection orig, OpenJPAStateManager sm,
        FieldMetaData fmd) {
    Collection coll = copyCollection(manager, orig, fmd, sm);
    ValueMetaData vmd = fmd.getElement();
    if (!vmd.isDeclaredTypePC())
        return coll;

    // unfortunately we have to clear the original and re-add
    coll.clear();
    Object elem;
    for (Iterator itr = orig.iterator(); itr.hasNext();) {
        if (vmd.getCascadeAttach() == ValueMetaData.CASCADE_NONE)
            elem = getReference(manager, itr.next(), sm, vmd);
        else
            elem = manager.attach(itr.next(), null, sm, vmd, false);
        coll.add(elem);
    }
    return coll;
}

From source file:uk.ac.ebi.intact.dbupdate.prot.actions.impl.DuplicatesFinderImpl.java

/**
 *
 * @param possibleDuplicates  : the list containing the possible duplicates of a same transcript
 * @param context : the datacontext/*from   www .j a  v  a2  s.co  m*/
 * @param processor : the proteinProcessor
 * @param isSpliceVariant : a boolean value to indicate if the transcript is a splice variant (true) or a feature chain (false)
 * @return  the collection of duplicetFoundEvent for each set of duplicated transcript in the list of possible duplicates
 * @throws ProcessorException
 */
private Collection<DuplicatesFoundEvent> findProteinTranscriptDuplicates(
        List<ProteinTranscript> possibleDuplicates, DataContext context, ProteinProcessor processor,
        boolean isSpliceVariant) throws ProcessorException {
    // the list containing the duplicateFoundEvents
    Collection<DuplicatesFoundEvent> duplicateEvents = new ArrayList<DuplicatesFoundEvent>();

    // if there are possible duplicates (more than 1 result), check and fix when necessary
    if (possibleDuplicates.size() > 1) {

        // the collection containing all the possible duplicates
        Collection<ProteinTranscript> totalProteins = new ArrayList(possibleDuplicates);

        // the collection which will contain the duplicates of a same protein transcript
        Collection<ProteinTranscript> duplicates = new ArrayList<ProteinTranscript>(possibleDuplicates.size());

        // while the list of possible duplicates has not been fully treated, we need to check the duplicates
        while (totalProteins.size() > 0) {
            // clear the list of duplicates of a same transcript
            duplicates.clear();

            // pick the first protein of the list and add it in the list of duplicates
            Iterator<ProteinTranscript> iterator = totalProteins.iterator();

            ProteinTranscript trans = iterator.next();
            Protein protToCompare = trans.getProtein();

            // get the uniprot identity of this protein
            InteractorXref firstIdentity = ProteinUtils.getUniprotXref(protToCompare);
            String firstUniprotAc = null;

            if (firstIdentity != null) {
                firstUniprotAc = firstIdentity.getPrimaryId();
            }

            // this first protein represents a uniprot transcript and is added to the list of duplicates of this transcript
            duplicates.add(trans);

            // extract the parents of this protein
            Collection<InteractorXref> transcriptParent;

            // if splice variant, the isoform-parents
            if (isSpliceVariant) {
                transcriptParent = ProteinUtils.extractIsoformParentCrossReferencesFrom(protToCompare);
            }
            // if feature chain, the chain-parents
            else {
                transcriptParent = ProteinUtils.extractChainParentCrossReferencesFrom(protToCompare);
            }

            // we compare the parents of this first protein against the parents of the other proteins
            while (iterator.hasNext()) {
                // we extract the parents of the next protein to compare
                ProteinTranscript trans2 = iterator.next();
                Protein proteinCompared = trans2.getProtein();

                // get the uniprot identity of this protein
                InteractorXref secondIdentity = ProteinUtils.getUniprotXref(proteinCompared);
                String secondUniprotAc = null;

                if (secondIdentity != null) {
                    secondUniprotAc = secondIdentity.getPrimaryId();
                }

                // if both uniprot identities are identical or null, we may have a duplicate. Need to check the parents
                if ((firstUniprotAc != null && secondUniprotAc != null
                        && firstUniprotAc.equalsIgnoreCase(secondUniprotAc))
                        || (firstUniprotAc == null && secondUniprotAc == null)) {
                    Collection<InteractorXref> transcriptParents2;

                    if (isSpliceVariant) {
                        transcriptParents2 = ProteinUtils
                                .extractIsoformParentCrossReferencesFrom(proteinCompared);
                    } else {
                        transcriptParents2 = ProteinUtils
                                .extractChainParentCrossReferencesFrom(proteinCompared);
                    }

                    // if the parents are identical, we add the protein to the list of duplicates
                    if (hasSameParents(transcriptParent, transcriptParents2)) {
                        duplicates.add(trans2);
                    }
                }
            }

            // if we have more than two proteins in the duplicate list, we merge them
            if (duplicates.size() > 1) {
                // get the uniprot transcript
                UniprotProteinTranscript transcript = trans.getUniprotVariant();

                // set the uniprot sequence and CRC64 of the event
                String uniprotSequence = null;
                String uniprotCrc64 = null;
                String primaryAc = null;
                String organism = null;

                if (transcript != null) {
                    uniprotSequence = transcript.getSequence();
                    uniprotCrc64 = Crc64.getCrc64(uniprotSequence);
                    primaryAc = transcript.getPrimaryAc();
                    organism = transcript.getOrganism() != null
                            ? String.valueOf(transcript.getOrganism().getTaxid())
                            : null;
                }

                // list of duplicates
                Collection<Protein> duplicateToFix = new ArrayList<Protein>(duplicates.size());

                for (ProteinTranscript t : duplicates) {
                    duplicateToFix.add(t.getProtein());
                }

                // create the DuplicateFoundEvent and add it to the list of duplicateFoundEvent
                DuplicatesFoundEvent duplEvt = new DuplicatesFoundEvent(processor, context, duplicateToFix,
                        uniprotSequence, uniprotCrc64, primaryAc, organism);
                duplicateEvents.add(duplEvt);
            }

            // we remove the processed proteins from the list of protein to process
            totalProteins.removeAll(duplicates);
        }
    }

    return duplicateEvents;
}

From source file:com.graphaware.module.es.ElasticSearchModule.java

private void reindexNodes(GraphDatabaseService database) {
    final Collection<WriteOperation<?>> operations = new HashSet<>();

    new IterableInputBatchTransactionExecutor<>(database, reindexBatchSize,
            new AllNodes(database, reindexBatchSize), (db, node, batchNumber, stepNumber) -> {

                if (shouldReindexNode(node)) {
                    operations.add(new NodeCreated<>(new NodeExpressions(node)));
                }/*from   ww w  . j  a  v  a2s.  c om*/

                if (operations.size() >= reindexBatchSize) {
                    writer.processOperations(Arrays.asList(operations));
                    operations.clear();
                    LOG.info("Done " + reindexBatchSize);
                }
            }).execute();

    if (operations.size() > 0) {
        writer.processOperations(Arrays.asList(operations));
        operations.clear();
    }
}

From source file:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java

private void populateEntity(Object entity, Object jsonObj, MetaData metaData, String path,
        BeanMapper beanMapper, DataSession dataSession) throws BusinessException {

    if (jsonObj == null) {
        return;// w w  w .j  a  v  a  2 s  .c o m
    }

    if (metaData == null) {
        throw new IllegalArgumentException("El argumento 'metaData' no puede ser null");
    }

    for (String propertyName : metaData.getPropertiesMetaData().keySet()) {
        MetaData propertyMetaData = metaData.getPropertiesMetaData().get(propertyName);

        String absolutePropertyName;
        if ((path == null) || (path.trim().length() == 0)) {
            absolutePropertyName = propertyName;
        } else {
            absolutePropertyName = path + "." + propertyName;
        }

        if (beanMapper.isDeleteInProperty(absolutePropertyName) == true) {
            //No se puede generar esa propiedad desde el "exterior"
            continue;
        }

        if (propertyMetaData.isCollection() == false) {
            switch (propertyMetaData.getMetaType()) {
            case Scalar: {
                Object rawValue = getValueFromBean(jsonObj, propertyName);
                setValueToBean(entity, rawValue, propertyName);
                break;
            }
            case Entity: {
                //Debemos leer la referencia de la base de datos
                Object rawValue = getValueFromBean(jsonObj, propertyName);

                Object value = readForeingEntity(rawValue, propertyMetaData, dataSession);
                setValueToBean(entity, value, propertyName);
                break;
            }
            case Component: {
                //Es un componente, as que hacemos la llamada recursiva
                Object rawValue = getValueFromBean(jsonObj, propertyName);
                Object component = getValueFromBean(entity, propertyName);
                if (component == null) {
                    try {
                        component = propertyMetaData.getType().newInstance();
                        setValueToBean(entity, component, propertyName);
                    } catch (InstantiationException ex) {
                        throw new RuntimeException(ex);
                    } catch (IllegalAccessException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                populateEntity(component, rawValue, propertyMetaData, absolutePropertyName, beanMapper,
                        dataSession);
                break;
            }
            default:
                throw new RuntimeException("El MetaTypo es desconocido:" + propertyMetaData.getMetaType());
            }
        } else {
            switch (propertyMetaData.getCollectionType()) {
            case List:
            case Set: {
                if (beanMapper.isExpandInProperty(absolutePropertyName)) {
                    Collection rawCollection = (Collection) getValueFromBean(jsonObj, propertyName);
                    Collection currentCollection = (Collection) getValueFromBean(entity, propertyName);

                    //Borramos todos los elementos para aadir despues los que vienen desde JSON
                    if (currentCollection != null) {
                        currentCollection.clear();
                    } else {
                        //Si no hay coleccion hay que crearla aqui
                        if (propertyMetaData.getCollectionType() == CollectionType.List) {
                            currentCollection = new ArrayList();
                        } else if (propertyMetaData.getCollectionType() == CollectionType.Set) {
                            currentCollection = new HashSet();
                        } else {
                            throw new RuntimeException(
                                    "El tipo coneccion no es vlida:" + propertyMetaData.getCollectionType());
                        }
                        setValueToBean(entity, currentCollection, propertyName);
                    }
                    //Aadimos los elementos que vienen desde JSON
                    if (rawCollection != null) {
                        for (Object rawValue : rawCollection) {
                            Object value = readForeingEntity(rawValue, propertyMetaData, dataSession);
                            currentCollection.add(value);
                        }
                    }
                } else {
                    //NO cargamos la coleccion desde el JSON
                }
                break;
            }
            case Map: {
                if (beanMapper.isExpandInProperty(absolutePropertyName)) { //TODO:No cargamos nunca las coleccione pq aun no sabemos si hay que hacerlo o no
                    Map rawMap = (Map) getValueFromBean(jsonObj, propertyName);
                    Map currentMap = (Map) getValueFromBean(entity, propertyName);

                    //Borramos todos los elementos para aadir despues los que vienen desde JSON
                    if (currentMap != null) {
                        currentMap.clear();
                    } else {
                        //Si no hay coleccion hay que crearla qui
                        currentMap = new HashMap();
                        setValueToBean(entity, currentMap, propertyName);
                    }

                    //Aadimos los elementos que vienen desde JSON
                    if (rawMap != null) {
                        for (Object key : rawMap.keySet()) {
                            Object rawValue = rawMap.get(key);
                            Object value = readEntity(rawValue, propertyMetaData, absolutePropertyName,
                                    beanMapper, dataSession);
                            currentMap.put(key, value);
                        }
                    }
                } else {
                    //NO cargamos la coleccion desde el JSON
                }
                break;
            }
            default:
                throw new RuntimeException(
                        "El CollectionType es desconocido:" + propertyMetaData.getCollectionType());
            }
        }

    }
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.impl.SearchBreadcrumbBuilder.java

protected void createBreadcrumbCategoryHierarchyPath(final String categoryCode, final boolean emptyBreadcrumbs,
        final List<Breadcrumb> breadcrumbs) {
    // Create category hierarchy path for breadcrumb
    final List<Breadcrumb> categoryBreadcrumbs = new ArrayList<>();
    final Collection<CategoryModel> categoryModels = new ArrayList<>();
    final CategoryModel lastCategoryModel = getCommerceCategoryService().getCategoryForCode(categoryCode);
    categoryModels.addAll(lastCategoryModel.getSupercategories());
    categoryBreadcrumbs.add(getCategoryBreadcrumb(lastCategoryModel, !emptyBreadcrumbs ? LAST_LINK_CLASS : ""));

    while (!categoryModels.isEmpty()) {
        final CategoryModel categoryModel = categoryModels.iterator().next();

        if (!(categoryModel instanceof ClassificationClassModel)) {
            if (categoryModel != null) {
                categoryBreadcrumbs.add(getCategoryBreadcrumb(categoryModel));
                categoryModels.clear();/*w  w  w .  java  2 s  .  c o  m*/
                categoryModels.addAll(categoryModel.getSupercategories());
            }
        } else {
            categoryModels.remove(categoryModel);
        }
    }
    Collections.reverse(categoryBreadcrumbs);
    breadcrumbs.addAll(categoryBreadcrumbs);
}

From source file:com.kalessil.phpStorm.yii2inspections.inspectors.MissingPropertyAnnotationsInspector.java

@Override
@NotNull/*from w  ww .j a  v a  2s  .com*/
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpClass(PhpClass clazz) {
            /* check only regular named classes */
            final PsiElement nameNode = NamedElementUtil.getNameIdentifier(clazz);
            if (null == nameNode) {
                return;
            }

            /* check if the class inherited from yii\base\Object */
            boolean supportsPropertyFeature = false;
            final Set<PhpClass> parents = InheritanceChainExtractUtil.collect(clazz);
            if (!parents.isEmpty()) {
                for (final PhpClass parent : parents) {
                    if (baseObjectClasses.contains(parent.getFQN())) {
                        supportsPropertyFeature = true;
                        break;
                    }
                }

                parents.clear();
            }
            if (!supportsPropertyFeature) {
                return;
            }

            /* iterate get methods, find matching set methods */
            final Map<String, String> props = this.findPropertyCandidates(clazz);
            if (props.size() > 0) {
                List<String> names = new ArrayList<>(props.keySet());
                Collections.sort(names);
                final String message = messagePattern.replace("%p%", String.join("', '", names));
                holder.registerProblem(nameNode, message, ProblemHighlightType.WEAK_WARNING,
                        new TheLocalFix(props));
            }
        }

        @NotNull
        private Map<String, String> findPropertyCandidates(@NotNull PhpClass clazz) {
            final Map<String, String> properties = new HashMap<>();

            /* extract methods and operate on name-methods relations */
            final Method[] methods = clazz.getOwnMethods();
            if (null == methods || 0 == methods.length) {
                return properties;
            }
            final Map<String, Method> mappedMethods = new HashMap<>();
            for (Method method : methods) {
                mappedMethods.put(method.getName(), method);
            }

            /* process extracted methods*/
            for (String candidate : mappedMethods.keySet()) {
                Method getterMethod = null;
                Method setterMethod = null;

                /* extract methods: get (looks up and extracts set), set (looks up get and skipped if found) */
                if (candidate.startsWith("get")) {
                    getterMethod = mappedMethods.get(candidate);
                    if (getterMethod.isStatic() || 0 != getterMethod.getParameters().length) {
                        getterMethod = null;
                    }

                    final String complimentarySetter = candidate.replaceAll("^get", "set");
                    if (mappedMethods.containsKey(complimentarySetter)) {
                        setterMethod = mappedMethods.get(complimentarySetter);
                        if (setterMethod.isStatic() || 0 == setterMethod.getParameters().length) {
                            setterMethod = null;
                        }

                    }
                }
                if (candidate.startsWith("set")) {
                    setterMethod = mappedMethods.get(candidate);
                    if (setterMethod.isStatic() || setterMethod.getParameters().length != 1) {
                        setterMethod = null;
                    }

                    final String complimentaryGetter = candidate.replaceAll("^set", "get");
                    if (mappedMethods.containsKey(complimentaryGetter)) {
                        continue;
                    }
                }

                /* ensure that strategies are reachable */
                if ((null == getterMethod && null == setterMethod)
                        || (REQUIRE_BOTH_GETTER_SETTER && (null == getterMethod || null == setterMethod))) {
                    continue;
                }

                /* store property and it's types */
                final Set<String> propertyTypesFqns = new HashSet<>();

                if (null != getterMethod) {
                    propertyTypesFqns.addAll(getterMethod.getType().filterUnknown().getTypes());
                }
                if (null != setterMethod) {
                    final Parameter[] setterParams = setterMethod.getParameters();
                    if (setterParams.length > 0) {
                        propertyTypesFqns.addAll(setterParams[0].getType().filterUnknown().getTypes());
                    }
                }

                /* drop preceding \ in core types */
                final Set<String> propertyTypes = new HashSet<>();
                for (String type : propertyTypesFqns) {
                    if (type.length() > 0) {
                        if ('\\' == type.charAt(0) && 1 == StringUtils.countMatches(type, "\\")) {
                            type = type.replace("\\", "");
                        }
                        propertyTypes.add(type);
                    }
                }
                propertyTypesFqns.clear();

                final String typesAsString = propertyTypes.isEmpty() ? "mixed"
                        : String.join("|", propertyTypes);
                properties.put(StringUtils.uncapitalize(candidate.replaceAll("^(get|set)", "")), typesAsString);
            }

            /* exclude annotated properties: lazy bulk operation */
            if (properties.size() > 0) {
                final Collection<Field> fields = clazz.getFields();
                for (Field candidate : fields) {
                    /* do not process constants and static fields */
                    if (candidate.isConstant() || candidate.getModifier().isStatic()) {
                        continue;
                    }

                    properties.remove(candidate.getName());
                }
                fields.clear();
            }

            return properties;
        }
    };
}

From source file:org.carewebframework.shell.CareWebShell.java

/**
 * Populates a list of all activated plugins.
 * //from   w  ww .j a  v a 2 s .c om
 * @param list The list to be populated. If null, a new list is created.
 * @return A list of active plugins.
 */
public Collection<PluginContainer> getActivatedPlugins(Collection<PluginContainer> list) {
    if (list == null) {
        list = new ArrayList<PluginContainer>();
    } else {
        list.clear();
    }

    for (PluginContainer plugin : plugins) {
        if (UIElementZKBase.getAssociatedUIElement(plugin).isActivated()) {
            list.add(plugin);
        }
    }

    return list;
}