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:ubic.gemma.analysis.expression.coexpression.Gene2GenePopulationServiceImpl.java

/**
 * @param eeIdOrder map for creating bit vector data.
 * @param firstGene the query gene/*w  ww .j a va 2s.c om*/
 * @param toPersist results to persist
 * @param analysis Analysis object to associate with links
 * @param genesToAnalyze list of genes to limit analysis for (links to other genes are ignored)
 * @param alreadyPersisted to track genes we've already done, so we don't persist links in both directions
 * @param stringency minimum support to store a link.
 * @return
 */
private List<Gene2GeneCoexpression> persistCoexpressions(Map<Long, Integer> eeIdOrder, Gene firstGene,
        QueryGeneCoexpression toPersist, GeneCoexpressionAnalysis analysis,
        final Map<Long, Gene> genesToAnalyze, final Collection<Long> alreadyPersisted, int stringency) {

    assert analysis != null;

    Taxon taxon = firstGene.getTaxon();

    List<Gene2GeneCoexpression> all = new ArrayList<Gene2GeneCoexpression>();
    Collection<Gene2GeneCoexpression> batch = new ArrayList<Gene2GeneCoexpression>();

    for (CoexpressedGenePairValueObject co : toPersist.getAllGeneCoexpressionData(stringency)) {

        if (!genesToAnalyze.containsKey(co.getCoexpressedGeneId())) {
            if (log.isDebugEnabled())
                log.debug("coexpressed Gene " + co.getCoexpressedGeneId()
                        + " is not among the genes selected for analysis, so it will be skipped (while analyzing "
                        + firstGene.getOfficialSymbol() + ")");
            continue;
        }

        Gene secondGene = genesToAnalyze.get(co.getCoexpressedGeneId());

        // note we just check the id to avoid any problems with thaw etc.
        if (secondGene.getId().equals(firstGene.getId())) {
            /*
             * This check is 'just in case'; they should have been removed earlier. These can leak in because we 1)
             * there can be two probes for the same genes that are coexpressed and 2) we allow them in initial query
             * results
             */
            continue;
        }

        /*
         * If we store the links in both directions, only one query is needed for retrieval.
         */
        if (!SINGLE_QUERY_FOR_LINKS && alreadyPersisted.contains(secondGene.getId()))
            continue;

        if (log.isDebugEnabled())
            log.debug(firstGene.getName() + " link to " + secondGene.getName());

        byte[] testedInVector = co.getDatasetsTestedInBytes();
        assert testedInVector != null;
        byte[] specificityVector = computeSpecificityVector(co.getNonspecificEE(), eeIdOrder);
        assert specificityVector != null;

        /*
         * Note that we are storing the 'raw' link support, which includes 'non-specific' probes. These can be
         * filtered later.
         */
        if (co.getNegativeLinkSupport() >= stringency) {
            Gene2GeneCoexpression g2gCoexpression = getNewGGCOInstance(taxon);
            g2gCoexpression.setDatasetsTestedVector(testedInVector);
            g2gCoexpression.setSpecificityVector(specificityVector);
            g2gCoexpression.setSourceAnalysis(analysis);
            g2gCoexpression.setFirstGene(firstGene);
            g2gCoexpression.setSecondGene(secondGene);

            Collection<Long> contributing2NegativeLinks = co.getEEContributing2NegativeLinks();
            assert contributing2NegativeLinks.size() == co.getNegativeLinkSupport();
            byte[] supportVector = computeSupportingDatasetVector(contributing2NegativeLinks, eeIdOrder);
            g2gCoexpression.setNumDataSets(co.getNegativeLinkSupport());
            g2gCoexpression.setEffect(co.getNegativeScore());
            g2gCoexpression.setDatasetsSupportingVector(supportVector);

            batch.add(g2gCoexpression);
            if (batch.size() == BATCH_SIZE) {
                all.addAll(this.gene2GeneCoexpressionService.create(batch));
                batch.clear();
            }
        }

        if (co.getPositiveLinkSupport() >= stringency) {
            Gene2GeneCoexpression g2gCoexpression = getNewGGCOInstance(taxon);
            g2gCoexpression.setDatasetsTestedVector(testedInVector);
            g2gCoexpression.setSpecificityVector(specificityVector);
            g2gCoexpression.setSourceAnalysis(analysis);
            g2gCoexpression.setFirstGene(firstGene);
            g2gCoexpression.setSecondGene(secondGene);

            Collection<Long> contributing2PositiveLinks = co.getEEContributing2PositiveLinks();
            assert contributing2PositiveLinks.size() == co.getPositiveLinkSupport();
            byte[] supportVector = computeSupportingDatasetVector(contributing2PositiveLinks, eeIdOrder);
            g2gCoexpression.setNumDataSets(co.getPositiveLinkSupport());
            g2gCoexpression.setEffect(co.getPositiveScore());
            g2gCoexpression.setDatasetsSupportingVector(supportVector);
            batch.add(g2gCoexpression);
            if (batch.size() == BATCH_SIZE) {
                all.addAll(this.gene2GeneCoexpressionService.create(batch));
                batch.clear();
            }
        }

        if (log.isDebugEnabled())
            log.debug("Persisted: " + firstGene.getOfficialSymbol() + " --> " + secondGene.getOfficialSymbol()
                    + " ( " + co.getNegativeScore() + " , +" + co.getPositiveScore() + " )");
    }

    // bit at the end.
    if (batch.size() > 0) {
        all.addAll(this.gene2GeneCoexpressionService.create(batch));
        batch.clear();
    }

    if (log.isDebugEnabled() && all.size() > 0) {
        log.debug("Persisted " + all.size() + " links for " + firstGene.getOfficialSymbol() + " "
                + firstGene.getOfficialName());
    }
    return all;

}

From source file:org.openbel.framework.internal.KAMStoreDaoImpl.java

@SuppressWarnings("unchecked")
@Override/*from   w  ww  . ja v  a2 s  . co  m*/
public Integer getKamNodeId(String belTermString) throws SQLException {
    // See if the bel term is already mapped
    if (supportingTermLabelReverseCache.containsKey(belTermString)) {
        return supportingTermLabelReverseCache.get(belTermString);
    }

    // parse the BelTerm
    Term term;
    try {
        term = BELParser.parseTerm(belTermString);
    } catch (Exception e) {
        // invalid BEL
        return null;
    }

    Collection<Integer> possibleTermIds = null;
    int ordinal = 0;
    for (Parameter param : term.getAllParametersLeftToRight()) {
        Integer namespaceId = null;
        if (param.getNamespace() != null && StringUtils.isNotBlank(param.getNamespace().getPrefix())) {
            Namespace ns = getNamespaceByPrefix(param.getNamespace().getPrefix());
            if (ns != null) {
                namespaceId = ns.getId();
            }
        }
        String paramValue = param.getValue();
        if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) {
            paramValue = paramValue.substring(1, paramValue.length() - 1);
        }

        Integer valueOid = getObjectIdByValue(paramValue);
        if (valueOid == null) {
            // could not find label for param
            if (possibleTermIds != null) {
                possibleTermIds.clear();
            }
            break;
        }

        ResultSet rset = null;
        try {
            PreparedStatement ps = getPreparedStatement(SELECT_TERM_ID_BY_PARAMETERS_SQL);
            // set twice to handle is null, see http://stackoverflow.com/questions/4215135/
            if (namespaceId == null) {
                ps.setNull(1, Types.INTEGER);
                ps.setNull(2, Types.INTEGER);
            } else {
                ps.setInt(1, namespaceId);
                ps.setInt(2, namespaceId);
            }

            ps.setInt(3, valueOid);
            ps.setInt(4, ordinal);

            rset = ps.executeQuery();

            Set<Integer> termIdsWithParam = new HashSet<Integer>();
            while (rset.next()) {
                termIdsWithParam.add(rset.getInt(1));
            }

            if (possibleTermIds == null) {
                // first param
                possibleTermIds = termIdsWithParam;
            } else {
                possibleTermIds = CollectionUtils.intersection(possibleTermIds, termIdsWithParam);
            }
        } finally {
            close(rset);
        }

        // no need to continue to next param if possibleTermIds is empty
        if (possibleTermIds.isEmpty()) {
            break;
        }
        ordinal++;
    }

    Integer kamNodeId = null;
    // iterate over all possible terms and check for label matches
    if (possibleTermIds != null) {
        for (Integer termId : possibleTermIds) {
            BelTerm belTerm = getBelTermById(termId);
            if (belTerm.getLabel().equals(belTermString)) {
                kamNodeId = getKamNodeId(belTerm);
                break;
            }
        }
    }

    if (kamNodeId != null) {
        supportingTermLabelReverseCache.put(belTermString, kamNodeId);
    }
    return kamNodeId;
}

From source file:uk.nhs.cfh.dsp.snomed.normaliser.impl.NormalFormGeneratorImpl.java

/**
 * Gets the long normal form expression.
 *
 * @param focusConcepts the focus concepts
 * @param relationshipPropertyExpressions the relationship property expressions
 * @param roleGroupExpressions the role group expressions
 * @param addRefiningProperties the add refining properties
 * @return the long normal form expression
 *//*from ww w  .ja v a  2s .co m*/
private NormalFormExpression getLongNormalFormExpression(Collection<SnomedConcept> focusConcepts,
        Collection<SnomedRelationshipPropertyExpression> relationshipPropertyExpressions,
        Collection<SnomedRoleGroupExpression> roleGroupExpressions, boolean addRefiningProperties) {
    NormalFormExpression normalFormExpression = new NormalFormExpressionImpl();
    Collection<SnomedRoleGroupExpression> mergedRoleGroups = new ArrayList<SnomedRoleGroupExpression>();
    Collection<SnomedRelationshipPropertyExpression> mergedRelationships = new ArrayList<SnomedRelationshipPropertyExpression>();
    Map<SnomedConcept, Collection<SnomedRelationshipPropertyExpression>> conceptRelMap = new HashMap<SnomedConcept, Collection<SnomedRelationshipPropertyExpression>>();
    Map<SnomedConcept, Collection<SnomedRoleGroupExpression>> conceptRoleMap = new HashMap<SnomedConcept, Collection<SnomedRoleGroupExpression>>();

    // get and add proximalPrimitives
    Set<SnomedConcept> proximalPrimitives = new HashSet<SnomedConcept>();
    for (SnomedConcept focusConcept : focusConcepts) {
        proximalPrimitives.addAll(normalFormHierarchyProvider.getProximalPrimitivesParents(focusConcept));
    }
    normalFormExpression.setProximalPrimitives(proximalPrimitives);
    normalFormExpression.setFocusConcepts(proximalPrimitives);

    for (SnomedConcept conceptToProcess : focusConcepts) {
        Collection<SnomedRelationshipPropertyExpression> rels = new ArrayList<SnomedRelationshipPropertyExpression>();
        Collection<SnomedRoleGroupExpression> rols = new ArrayList<SnomedRoleGroupExpression>();
        for (SnomedRelationship relationship : conceptToProcess.getNonSubSumptionDefiningRelationships()) {
            // create new SnomedRelationshipPropertyExpression 
            rels.add(getExpressionWithLongNormalFormAsValue(relationship, addRefiningProperties));
        }

        if (addRefiningProperties) {
            for (SnomedRelationship refiningRelationship : conceptToProcess.getRefiningRelationships()) {
                // create new SnomedRelationshipPropertyExpression
                rels.add(getExpressionWithLongNormalFormAsValue(refiningRelationship, addRefiningProperties));
            }
        }

        conceptRelMap.put(conceptToProcess, rels);

        // add roleGroups
        for (SnomedRoleGroup roleGroup : conceptToProcess.getRoleGroups()) {
            // create and add roleGroupExpression  to rols
            rols.add(getExpressionWithLongNormalFormAsValue(roleGroup, addRefiningProperties));
        }
        conceptRoleMap.put(conceptToProcess, rols);
    }

    // merge role groups
    List<SnomedConcept> conceptList = new ArrayList<SnomedConcept>(focusConcepts);
    if (conceptList.size() > 1) {
        for (int i = 0; i < conceptList.size(); i++) {
            for (int j = i + 1; j < conceptList.size(); j++) {
                Collection<SnomedRoleGroupExpression> roleGroups1 = conceptRoleMap.get(conceptList.get(i));
                Collection<SnomedRoleGroupExpression> roleGroups2 = conceptRoleMap.get(conceptList.get(j));

                // merge role groups and add to merged role groups
                Collection<SnomedRoleGroupExpression> localMergedRoleGroups = getMergedRoleGroups(roleGroups1,
                        roleGroups2);
                mergedRoleGroups.addAll(localMergedRoleGroups);

                // merge relationships
                Collection<SnomedRelationshipPropertyExpression> relationshipSet1 = conceptRelMap
                        .get(conceptList.get(i));
                Collection<SnomedRelationshipPropertyExpression> relationshipSet2 = conceptRelMap
                        .get(conceptList.get(j));
                Collection<SnomedRelationshipPropertyExpression> localMergedRelationships = getMergedRelationships(
                        relationshipSet1, relationshipSet2, localMergedRoleGroups);
                // add to outer mergedRelationships
                mergedRelationships.addAll(localMergedRelationships);
            }
        }
    } else {
        mergedRoleGroups.addAll(conceptRoleMap.get(conceptList.get(0)));
        mergedRelationships.addAll(conceptRelMap.get(conceptList.get(0)));
    }

    Collection<SnomedRoleGroupExpression> nonRedundantRoleGroups = getNonRedundantMergedRoleGroups(
            mergedRoleGroups);
    Collection<SnomedRelationshipPropertyExpression> nonRedundantRelationships = getNonRedundantMergedRelationships(
            mergedRelationships);

    // loop through refinements supplied (relationshipPropertyExpressions  and roleGroupExpressions) and apply them
    for (SnomedConcept focusConcept : focusConcepts) {
        Collection<SnomedRelationshipPropertyExpression> localRefinements = new ArrayList<SnomedRelationshipPropertyExpression>();
        for (SnomedRelationshipPropertyExpression relationshipRefinement : relationshipPropertyExpressions) {
            String attributeType = relationshipRefinement.getRelationship().getRelationshipType();
            if (ConceptType.ATTRIBUTE_LATERALITY.getID().equalsIgnoreCase(attributeType)) {
                applyLateralityToAppropriateBodyPart(normalFormExpression, nonRedundantRelationships,
                        nonRedundantRoleGroups, relationshipRefinement);
            } else if (ConceptType.SITUATION_WEC == focusConcept.getType()) {
                /*
                 Check if attribute type is any of the situation model sanctioned types. If so,
                 we just add them to local refinements to be applied. If not, we check if the
                 attribute is not a laterality attribute and apply it on the associated focus finding or procedure
                 Note that we do not have to process a laterality attribute because it should have been processed
                 by the previous step.
                */

                if (ConceptType.ATTRIBUTE_SUBJECT_RELATIONSHIP_CONTEXT.getID().equalsIgnoreCase(attributeType)
                        || ConceptType.ATTRIBUTE_FINDING_CONTEXT.getID().equalsIgnoreCase(attributeType)
                        || ConceptType.ATTRIBUTE_TEMPORAL_CONTEXT.getID().equalsIgnoreCase(attributeType)
                        || ConceptType.ATTRIBUTE_ASSOCIATED_FINDING.getID().equalsIgnoreCase(attributeType)
                        || ConceptType.ATTRIBUTE_PROCEDURE_CONTEXT.getID().equalsIgnoreCase(attributeType)) {
                    // add to localRefinements and resolve as usual
                    localRefinements.add(relationshipRefinement);
                } else if (ConceptType.ATTRIBUTE_LATERALITY.getID().equalsIgnoreCase(attributeType)) {
                    checkAndApplyRefinementToFocusConcept(nonRedundantRoleGroups, relationshipRefinement);
                }
            } else {
                localRefinements.add(relationshipRefinement);
            }
        }

        if (localRefinements.size() > 0) {
            // merge localRefinements with nonRedundantRelationships
            Collection<SnomedRelationshipPropertyExpression> localMergedRelationships = getMergedRelationships(
                    localRefinements, nonRedundantRelationships, nonRedundantRoleGroups);

            // clear and reset nonRedundantRelationships
            nonRedundantRelationships.clear();
            nonRedundantRelationships.addAll(getNonRedundantMergedRelationships(localMergedRelationships));
        }
    }

    // create expressions for nonRedundantRelationships  and nonRedundantRoleGroups  and add to normalFormExpression
    for (SnomedRelationshipPropertyExpression relationshipExpression : nonRedundantRelationships) {
        //            relationshipExpression.addParentExpression(normalFormExpression);
        normalFormExpression.addRelationshipExpression(relationshipExpression);
    }

    for (SnomedRoleGroupExpression roleGroupExpression : nonRedundantRoleGroups) {
        //            roleGroupExpression.addParentExpression(normalFormExpression);
        normalFormExpression.addRelationshipExpression(roleGroupExpression);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("normalFormExpression.getCanonicalStringForm() = "
                + normalFormExpression.getCanonicalStringForm());
    }

    return normalFormExpression;
}

From source file:com.hs.mail.mailet.RemoteDelivery.java

/**
 * We arranged that the recipients are all going to the same mail server. We
 * will now rely on the DNS server to do DNS MX record lookup and try to
 * deliver to the multiple mail servers. If it fails, we should decide that
 * the failure is permanent or temporary.
 * /* ww  w. j a v  a  2s  . c  o  m*/
 * @param host
 *            the same host of recipients
 * @param recipients
 *            recipients who are all going to the same mail server
 * @param message
 *            Mail object to be delivered
 * @param mimemsg
 *            MIME message representation of the message
 * @return true if the delivery was successful or permanent failure so the
 *         message should be deleted, otherwise false and the message will
 *         be tried to send again later
 */
private boolean deliver(String host, Collection<Recipient> recipients, SmtpMessage message,
        MimeMessage mimemsg) {
    // Prepare javamail recipients
    InternetAddress[] addresses = new InternetAddress[recipients.size()];
    Iterator<Recipient> it = recipients.iterator();
    for (int i = 0; it.hasNext(); i++) {
        Recipient rcpt = it.next();
        addresses[i] = rcpt.toInternetAddress();
    }

    try {
        // Lookup the possible targets
        Iterator<HostAddress> targetServers = null;
        if (null == gateway) {
            targetServers = getSmtpHostAddresses(host);
        } else {
            targetServers = getGatewaySmtpHostAddresses(gateway);
        }
        if (!targetServers.hasNext()) {
            logger.info("No mail server found for: " + host);
            StringBuilder exceptionBuffer = new StringBuilder(128)
                    .append("There are no DNS entries for the hostname ").append(host)
                    .append(".  I cannot determine where to send this message.");
            return failMessage(message, addresses, new MessagingException(exceptionBuffer.toString()), false);
        }

        Properties props = session.getProperties();
        if (message.isNotificationMessage()) {
            props.put("mail.smtp.from", "<>");
        } else {
            props.put("mail.smtp.from", message.getFrom().getMailbox());
        }

        MessagingException lastError = null;
        StringBuilder logBuffer = null;
        HostAddress outgoingMailServer = null;
        while (targetServers.hasNext()) {
            try {
                outgoingMailServer = targetServers.next();
                logBuffer = new StringBuilder(256).append("Attempting to deliver message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                Transport transport = null;
                try {
                    transport = session.getTransport(outgoingMailServer);
                    try {
                        if (authUser != null) {
                            transport.connect(outgoingMailServer.getHostName(), authUser, authPass);
                        } else {
                            transport.connect();
                        }
                    } catch (MessagingException e) {
                        // Any error on connect should cause the mailet to
                        // attempt to connect to the next SMTP server
                        // associated with this MX record.
                        logger.error(e.getMessage());
                        continue;
                    }
                    transport.sendMessage(mimemsg, addresses);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (MessagingException e) {
                        }
                        transport = null;
                    }
                }
                logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                recipients.clear();
                return true;
            } catch (SendFailedException sfe) {
                if (sfe.getValidSentAddresses() != null) {
                    Address[] validSent = sfe.getValidSentAddresses();
                    if (validSent.length > 0) {
                        logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                                .append(outgoingMailServer.getHostName()).append(" at ")
                                .append(outgoingMailServer.getHost()).append(" for addresses ")
                                .append(Arrays.asList(validSent));
                        logger.info(logBuffer.toString());
                        // Remove the addresses to which this message was
                        // sent successfully
                        List<InternetAddress> temp = new ArrayList<InternetAddress>();
                        for (int i = 0; i < addresses.length; i++) {
                            if (!ArrayUtils.contains(validSent, addresses[i])) {
                                if (addresses[i] != null) {
                                    temp.add(addresses[i]);
                                }
                            }
                        }
                        addresses = temp.toArray(new InternetAddress[temp.size()]);
                        removeAll(recipients, validSent);
                    }
                }

                if (sfe instanceof SMTPSendFailedException) {
                    SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                    // If permanent error 5xx, terminate this delivery
                    // attempt by re-throwing the exception
                    if (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599)
                        throw sfe;
                }

                if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
                    // Valid addresses remained, so continue with any other server.
                    if (logger.isDebugEnabled())
                        logger.debug("Send failed, " + sfe.getValidUnsentAddresses().length
                                + " valid recipients(" + Arrays.asList(sfe.getValidUnsentAddresses())
                                + ") remain, continuing with any other servers");
                    lastError = sfe;
                    continue;
                } else {
                    // There are no valid addresses left to send, so re-throw
                    throw sfe;
                }
            } catch (MessagingException me) {
                Exception ne;
                if ((ne = me.getNextException()) != null && ne instanceof IOException) {
                    // It can be some socket or weird I/O related problem.
                    lastError = me;
                    continue;
                }
                throw me;
            }
        } // end while
        if (lastError != null) {
            throw lastError;
        }
    } catch (SendFailedException sfe) {
        boolean deleteMessage = false;

        if (sfe instanceof SMTPSendFailedException) {
            SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
            deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
        } else {
            // Sometimes we'll get a normal SendFailedException with nested
            // SMTPAddressFailedException, so use the latter RetCode
            MessagingException me = sfe;
            Exception ne;
            while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
                me = (MessagingException) ne;
                if (me instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) me;
                    deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
                }
            }
        }
        if (!ArrayUtils.isEmpty(sfe.getInvalidAddresses())) {
            // Invalid addresses should be considered permanent
            Address[] invalid = sfe.getInvalidAddresses();
            removeAll(recipients, invalid);
            deleteMessage = failMessage(message, invalid, sfe, true);
        }
        if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
            // Vaild-unsent addresses should be considered temporary
            deleteMessage = failMessage(message, sfe.getValidUnsentAddresses(), sfe, false);
        }
        return deleteMessage;
    } catch (MessagingException mex) {
        // Check whether this is a permanent error (like account doesn't
        // exist or mailbox is full or domain is setup wrong)
        // We fail permanently if this was 5xx error.
        return failMessage(message, addresses, mex, ('5' == mex.getMessage().charAt(0)));
    }
    // If we get here, we've exhausted the loop of servers without sending
    // the message or throwing an exception.
    // One case where this might happen is if there is no server we can
    // connect. So this should be considered temporary
    return failMessage(message, addresses, new MessagingException("No mail server(s) available at this time."),
            false);
}

From source file:org.zht.framework.web.bind.resolver.FormModelMethodArgumentResolver.java

/**
 * {@inheritDoc}/*from w  w w. j a  v a 2  s.co  m*/
 * <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
 *
 * @throws Exception
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
 */

protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
        WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception {

    Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();

    Class<?> targetType = binder.getTarget().getClass();
    ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
    WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);

    if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array

        Type type = parameter.getGenericParameterType();
        Class<?> componentType = Object.class;

        Collection target = (Collection) binder.getTarget();

        List targetList = new ArrayList(target);

        if (type instanceof ParameterizedType) {
            componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }

        if (parameter.getParameterType().isArray()) {
            componentType = parameter.getParameterType().getComponentType();
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) { //? array=1&array=2
                    for (Object value : paramValues.values()) {
                        targetList.add(simpleBinder.convertIfNecessary(value, componentType));
                    }
                } else { //? array[0]=1&array[1]=2
                    int index = Integer.valueOf(matcher.group(1));

                    if (targetList.size() <= index) {
                        growCollectionIfNecessary(targetList, index);
                    }
                    targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
                }
            } else { //? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
                Object component = null;
                //? ?????
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) {
                    throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
                }
                int index = Integer.valueOf(matcher.group(1));
                if (targetList.size() <= index) {
                    growCollectionIfNecessary(targetList, index);
                }
                Iterator iterator = targetList.iterator();
                for (int i = 0; i < index; i++) {
                    iterator.next();
                }
                component = iterator.next();

                if (component == null) {
                    component = BeanUtils.instantiate(componentType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);
                    validateIfApplicable(componentBinder, parameter);
                    if (componentBinder.getBindingResult().hasErrors()) {
                        if (isBindExceptionRequired(componentBinder, parameter)) {
                            throw new BindException(componentBinder.getBindingResult());
                        }
                    }
                    targetList.set(index, component);
                }
            }
            target.clear();
            target.addAll(targetList);
        }
    } else if (MapWapper.class.isAssignableFrom(targetType)) {

        Type type = parameter.getGenericParameterType();
        Class<?> keyType = Object.class;
        Class<?> valueType = Object.class;

        if (type instanceof ParameterizedType) {
            keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
        }

        MapWapper mapWapper = ((MapWapper) binder.getTarget());
        Map target = mapWapper.getInnerMap();
        if (target == null) {
            target = new HashMap();
            mapWapper.setInnerMap(target);
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);

                for (Object value : paramValues.values()) {
                    target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
                }
            } else {

                Object component = target.get(keyValue);
                if (component == null) {
                    component = BeanUtils.instantiate(valueType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);

                    validateComponent(componentBinder, parameter);

                    target.put(keyValue, component);
                }
            }
        }
    } else {//bind model
        ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
        servletBinder.bind(servletRequest);
    }
}

From source file:org.opentravel.schemacompiler.repository.ProjectManager.java

/**
 * Searches the model for dependencies of the given project item and adds them to the collection
 * of unmanaged references.// ww  w .  ja v  a2s . co  m
 * 
 * @param item
 *            the item to check for dependencies
 * @param pendingPublicationItems
 *            the list of all items to be published that are currently unmanaged
 * @param unmanagedReferences
 *            the collection of unmanaged references
 */
private void findUnmanagedReferences(Collection<ProjectItem> pendingPublicationItems,
        Collection<ProjectItem> unmanagedReferences) {
    for (ProjectItem item : pendingPublicationItems) {
        Collection<ProjectItem> itemList = new HashSet<ProjectItem>();
        int unmanagedReferenceCount = -1;

        itemList.add(item); // 1st loop - just analyze the new item

        while (unmanagedReferences.size() != unmanagedReferenceCount) { // continue until our
                                                                        // count does not change
            Collection<ProjectItem> newUnmanagedReferences = new HashSet<ProjectItem>();

            unmanagedReferenceCount = unmanagedReferences.size();

            for (ProjectItem currentItem : itemList) {
                if (currentItem.getContent() instanceof TLLibrary) {
                    List<AbstractLibrary> referencedLibraries = ImportManagementIntegrityChecker
                            .getReferencedLibraries((TLLibrary) currentItem.getContent());

                    for (AbstractLibrary referencedLib : referencedLibraries) {
                        if (referencedLib instanceof BuiltInLibrary)
                            continue;
                        ProjectItem referencedItem = getProjectItem(referencedLib);

                        if (referencedItem == null) {
                            throw new IllegalStateException(
                                    "A dependent library is referenced that is not under the control of the local Project Manager: "
                                            + referencedLib.getName());

                        } else if (!pendingPublicationItems.contains(referencedItem)
                                && (referencedItem.getState() == RepositoryItemState.UNMANAGED)
                                && !newUnmanagedReferences.contains(referencedItem)) {
                            newUnmanagedReferences.add(referencedItem);
                        }
                    }
                }
            }

            // Add the newly-found unmanaged dependencies to the list and continue looping until
            // we do not find any new dependencies.
            for (ProjectItem urItem : newUnmanagedReferences) {
                if (!unmanagedReferences.contains(urItem)) {
                    unmanagedReferences.add(urItem);
                }
            }
            itemList.clear();
            itemList.addAll(newUnmanagedReferences); // subsequent loops - look for dependencies
                                                     // of the items we just found
        }
    }
}

From source file:gedi.util.ArrayUtils.java

public static <T> void reverse(Collection<T> p) {
    Object[] a = p.toArray();//w  w w  . j  a  va 2s. co m
    reverse(a);
    p.clear();
    for (Object e : a)
        p.add((T) e);
}

From source file:net.droidsolutions.droidcharts.core.plot.CategoryPlot.java

/**
 * Clears all the range markers for the specified renderer.
 * /*from w ww  .  j a  v a  2 s .co  m*/
 * @param index
 *            the renderer index.
 * 
 * @see #clearDomainMarkers(int)
 */
public void clearRangeMarkers(int index) {
    Integer key = new Integer(index);
    if (this.backgroundRangeMarkers != null) {
        Collection markers = (Collection) this.backgroundRangeMarkers.get(key);
        if (markers != null) {
            Iterator iterator = markers.iterator();
            while (iterator.hasNext()) {
                Marker m = (Marker) iterator.next();
            }
            markers.clear();
        }
    }
    if (this.foregroundRangeMarkers != null) {
        Collection markers = (Collection) this.foregroundRangeMarkers.get(key);
        if (markers != null) {
            Iterator iterator = markers.iterator();
            while (iterator.hasNext()) {
                Marker m = (Marker) iterator.next();
            }
            markers.clear();
        }
    }
}

From source file:net.droidsolutions.droidcharts.core.plot.CategoryPlot.java

/**
 * Clears all the domain markers for the specified renderer.
 * /*  w ww.  ja v  a  2 s .  com*/
 * @param index
 *            the renderer index.
 * 
 * @see #clearRangeMarkers(int)
 */
public void clearDomainMarkers(int index) {
    Integer key = new Integer(index);
    if (this.backgroundDomainMarkers != null) {
        Collection markers = (Collection) this.backgroundDomainMarkers.get(key);
        if (markers != null) {
            Iterator iterator = markers.iterator();
            while (iterator.hasNext()) {
                Marker m = (Marker) iterator.next();
            }
            markers.clear();
        }
    }
    if (this.foregroundDomainMarkers != null) {
        Collection markers = (Collection) this.foregroundDomainMarkers.get(key);
        if (markers != null) {
            Iterator iterator = markers.iterator();
            while (iterator.hasNext()) {
                Marker m = (Marker) iterator.next();
            }
            markers.clear();
        }
    }
}

From source file:org.sakaiproject.unboundid.UnboundidDirectoryProvider.java

/**
 * Similar to iterating over <code>users</code> passing
 * each element to {@link #getUser(UserEdit)}, removing the
 * {@link org.sakaiproject.user.api.UserEdit} if that method 
 * returns <code>false</code>. 
 * /*from ww w. jav  a2  s . c  o m*/
 * <p>Adds search retry capability if any one lookup fails 
 * with a directory error. Empties <code>users</code> and 
 * returns if a retry exits exceptionally
 * <p>
 */
public void getUsers(Collection<UserEdit> users) {
    log.debug("getUsers(): [Collection size = {}]", users.size());

    boolean abortiveSearch = false;
    int maxQuerySize = getMaxObjectsToQueryFor();
    UserEdit userEdit = null;

    HashMap<String, UserEdit> usersToSearchInLDAP = new HashMap<String, UserEdit>();
    List<UserEdit> usersToRemove = new ArrayList<UserEdit>();
    try {
        int cnt = 0;
        for (Iterator<UserEdit> userEdits = users.iterator(); userEdits.hasNext();) {
            userEdit = (UserEdit) userEdits.next();
            String eid = userEdit.getEid();

            if (!(isSearchableEid(eid))) {
                userEdits.remove();
                //proceed ahead with this (perhaps the final) iteration
                //usersToSearchInLDAP needs to be processed unless empty
            } else {
                usersToSearchInLDAP.put(eid, userEdit);
                cnt++;
            }

            // We need to make sure this query isn't larger than maxQuerySize
            if ((!userEdits.hasNext() || cnt == maxQuerySize) && !usersToSearchInLDAP.isEmpty()) {
                String filter = ldapAttributeMapper.getManyUsersInOneSearch(usersToSearchInLDAP.keySet());
                List<LdapUserData> ldapUsers = searchDirectory(filter, null, null, null, maxQuerySize);

                for (LdapUserData ldapUserData : ldapUsers) {
                    String ldapEid = ldapUserData.getEid();

                    if (StringUtils.isEmpty(ldapEid)) {
                        continue;
                    }
                    ldapEid = ldapEid.toLowerCase();

                    UserEdit ue = usersToSearchInLDAP.get(ldapEid);
                    mapUserDataOntoUserEdit(ldapUserData, ue);
                    usersToSearchInLDAP.remove(ldapEid);
                }

                // see if there are any users that we could not find in the LDAP query
                for (Map.Entry<String, UserEdit> entry : usersToSearchInLDAP.entrySet()) {
                    usersToRemove.add(entry.getValue());
                }

                // clear the HashMap and reset the counter
                usersToSearchInLDAP.clear();
                cnt = 0;
            }
        }

        // Finally clean up the original collection and remove and users we could not find
        for (UserEdit userRemove : usersToRemove) {
            log.debug("Unboundid getUsers could not find user: {}", userRemove.getEid());
            users.remove(userRemove);
        }

    } catch (LDAPException e) {
        abortiveSearch = true;
        throw new RuntimeException("getUsers(): LDAPException during search [eid = "
                + (userEdit == null ? null : userEdit.getEid()) + "][result code = " + e.errorCodeToString()
                + "][error message = " + e.getLDAPErrorMessage() + "]", e);
    } catch (Exception e) {
        abortiveSearch = true;
        throw new RuntimeException("getUsers(): RuntimeException during search eid = "
                + (userEdit == null ? null : userEdit.getEid()) + "]", e);
    } finally {
        // no sense in returning a partially complete search result
        if (abortiveSearch) {
            log.debug("getUsers(): abortive search, clearing received users collection");
            users.clear();
        }
    }

}