Example usage for java.util Collection removeAll

List of usage examples for java.util Collection removeAll

Introduction

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

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes all of this collection's elements that are also contained in the specified collection (optional operation).

Usage

From source file:org.apache.stratos.manager.persistence.RegistryBasedPersistenceManager.java

private Collection<CartridgeSubscription> traverseAndGetCartridgeSubscriptions(String resourcePath)
        throws PersistenceManagerException {

    if (log.isDebugEnabled()) {
        log.debug("Root resource path: " + resourcePath);
    }//from  w  w  w  .j  a v  a2s.c  o m

    Object resourceObj;

    try {
        resourceObj = RegistryManager.getInstance().retrieve(resourcePath);

    } catch (RegistryException e) {
        throw new PersistenceManagerException(e);
    }

    Collection<CartridgeSubscription> cartridgeSubscriptions = new ArrayList<CartridgeSubscription>();

    if (resourceObj == null) {
        // there is no resource at the given path
        return null;

    } else if (resourceObj instanceof String[]) {

        // get the paths for all SubscriptionContext instances
        String[] subscriptionResourcePaths = (String[]) resourceObj;
        if (log.isDebugEnabled()) {
            for (String retrievedResourcePath : subscriptionResourcePaths) {
                log.debug("Retrieved resource sub-path " + retrievedResourcePath);
            }
        }

        // traverse the paths recursively
        for (String subscriptionResourcePath : subscriptionResourcePaths) {

            if (log.isDebugEnabled()) {
                log.debug("Traversing resource path " + subscriptionResourcePath);
            }

            Collection<CartridgeSubscription> cartridgeSubscriptionSet = traverseAndGetCartridgeSubscriptions(
                    subscriptionResourcePath);
            if (cartridgeSubscriptionSet != null) {
                cartridgeSubscriptions.addAll(cartridgeSubscriptionSet);
            }
        }

    } else {
        // De-serialize
        Object subscriptionObj;

        try {
            subscriptionObj = Deserializer.deserializeFromByteArray((byte[]) resourceObj);

        } catch (Exception e) {
            // issue might be de-serializing only this object, therefore log and continue without throwing
            log.error("Error while de-serializing the object retrieved from " + resourcePath, e);
            return null;
        }

        if (subscriptionObj != null && subscriptionObj instanceof CartridgeSubscription) {

            CartridgeSubscription deserilizedCartridgeSubscription = (CartridgeSubscription) subscriptionObj;
            if (log.isDebugEnabled()) {
                log.debug("Successfully de-serialized CartridgeSubscription: "
                        + deserilizedCartridgeSubscription.toString());
            }

            //return Collections.singletonList(deserilizedCartridgeSubscription);
            cartridgeSubscriptions.add(deserilizedCartridgeSubscription);

        }
    }

    // remove any nulls
    cartridgeSubscriptions.removeAll(Collections.singleton(null));
    return cartridgeSubscriptions;
}

From source file:at.ait.dme.yuma.server.annotation.ImageAnnotationManager.java

@Override
public Collection<ImageAnnotation> listAnnotations(String europeanaUri, String imageUrl)
        throws AnnotationServiceException {

    Collection<ImageAnnotation> annotations = new ArrayList<ImageAnnotation>();
    ClientResponse<String> resp = null;
    try {/* w  w  w .  j a  v a2 s. c  o  m*/
        // call the europeana annotation service          
        resp = getAnnotationService().listAnnotations(URLEncoder.encode(europeanaUri));

        // check the response status
        if (resp.getStatus() != HttpResponseCodes.SC_OK && resp.getStatus() != HttpResponseCodes.SC_NOT_FOUND)
            throw new AnnotationServiceException(resp.getStatus());

        // parse the ids and fetch each annotation, we then group them together 
        // as a single rdf:RDF to reuse our existing rdfxml handler
        // TODO we should add some paging here in the future, should be simple
        // the way we have designed the API in Europeana
        // TODO we should also consider to use an alternative to RDF/XML                  
        Document mainDoc = null;
        String ids = resp.getEntity();
        for (String id : ids.split("\\n")) {
            if (!id.isEmpty()) {
                String annId = annotationServiceBaseUrl + ANNOTATION_SERVICE_URL_PATH + id;
                resp = getAnnotationService(resp.getHeaders()).findAnnotationById(id);
                if (resp.getStatus() != HttpResponseCodes.SC_OK)
                    throw new AnnotationServiceException(resp.getStatus());

                Document doc = new SAXBuilder().build(new StringReader(resp.getEntity()));
                Element rdfDescription = doc.getRootElement().getChild("Description",
                        doc.getRootElement().getNamespace());
                rdfDescription.setAttribute("about", annId, doc.getRootElement().getNamespace());
                if (mainDoc == null) {
                    mainDoc = doc;
                } else {
                    mainDoc.getRootElement().addContent((Element) rdfDescription.clone());
                }
            }
        }
        // parse the response
        if (mainDoc != null)
            annotations = RdfXmlAnnotationBuilder.fromRdfXml(XMLUtil.xmlToString(mainDoc));

        // an annotation in europeana points to an europeanaUri, there could be 
        // more than one image for that URI.
        // so we remove the annotations that address a different image
        Collection<ImageAnnotation> notNeeded = new ArrayList<ImageAnnotation>();
        for (ImageAnnotation annotation : annotations) {
            if (!annotation.getImageUrl().equals(imageUrl))
                notNeeded.add(annotation);
        }
        annotations.removeAll(notNeeded);

    } catch (AnnotationServiceException ase) {
        logger.error(ase.getMessage(), ase);
        throw ase;
    } catch (Exception e) {
        logger.error(FAILED_TO_PARSE_ANNOTATION, e);
        throw new AnnotationServiceException(e.getMessage());
    } finally {
        if (resp != null)
            copyResponseHeaders(resp.getHeaders());
    }
    return annotations;
}

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

/**
 * For each protein to review, check if it has interactions attached to it. If not and no transcripts with interactions
 * are attached to the protein, add the protein to the list of proteins to delete
 * @param protToInspect : list of proteins to review
 * @param protToDelete : list of proteins to delete
 * @param evt//from  w w  w. j  a  v a2 s  .  com
 */
private void collectProteinsWithoutInteractionsFrom(Collection<Protein> protToInspect,
        Set<Protein> protToDelete, UpdateCaseEvent evt) {

    for (Protein p : protToInspect) {
        if (p.getAc() == null) {
            log.debug("Protein without AC, cannot be deleted");

            protToDelete.add(p);
        } else {

            ProteinDao proteinDao = evt.getDataContext().getDaoFactory().getProteinDao();

            final Integer interactionCount = p.getActiveInstances().size();

            // check the number of interactions in which this protein is involved. If none,
            // check if the protein has splice variants/chains as they cannot be removed

            // Checking is any splice variant or feature chain is involved in interactions
            boolean hasProteinTranscriptAttached = false;
            // splice variants
            List<ProteinImpl> transcripts = proteinDao.getSpliceVariants(p);
            // feature chains
            transcripts.addAll(proteinDao.getProteinChains(p));

            for (Protein transcript : transcripts) {

                if (transcript.getActiveInstances().size() > 0) {
                    hasProteinTranscriptAttached = true;
                } else if (isDeleteProteinTranscriptsWithoutInteractions()) {
                    if (log.isDebugEnabled())
                        log.debug("Protein transcripts for protein '" + p.getShortLabel()
                                + "' will be deleted: " + transcript.getAc());
                    protToDelete.add(transcript);
                    if (evt.getPrimaryIsoforms().contains(transcript)) {
                        evt.getPrimaryIsoforms().remove(transcript);
                    } else if (evt.getSecondaryIsoforms().contains(transcript)) {
                        evt.getSecondaryIsoforms().remove(transcript);
                    } else if (evt.getPrimaryFeatureChains().contains(transcript)) {
                        evt.getPrimaryFeatureChains().remove(transcript);
                    }
                } else {
                    hasProteinTranscriptAttached = true;
                }
            }

            // if no splice variant/chain attached to that master either and it is not involved in interactions, then delete it.
            if (interactionCount == 0 && !hasProteinTranscriptAttached) {
                if (log.isDebugEnabled())
                    log.debug("Protein '" + p.getAc()
                            + "' will be deleted as it doesn't have interaction and has no isoform/chain attached.");
                protToDelete.add(p);
            }
        }
    }

    protToInspect.removeAll(protToDelete);
}

From source file:ubic.gemma.core.loader.expression.arrayDesign.ArrayDesignSequenceAlignmentServiceImpl.java

@Override
public Collection<BlatResult> processArrayDesign(ArrayDesign ad, Taxon taxon,
        Collection<BlatResult> rawBlatResults) {

    ArrayDesignSequenceAlignmentServiceImpl.log.info("Looking for old results to remove...");

    ad = arrayDesignService.thaw(ad);/*from  ww w. j a  va2  s .  c  o m*/

    arrayDesignService.deleteAlignmentData(ad);
    // Blat file processing can only be run on one taxon at a time
    taxon = this.validateTaxaForBlatFile(ad, taxon);

    Collection<BioSequence> sequencesToBlat = ArrayDesignSequenceAlignmentServiceImpl.getSequences(ad);
    sequencesToBlat = bioSequenceService.thaw(sequencesToBlat);

    // if the blat results were loaded from a file, we have to replace the
    // query sequences with the actual ones
    // attached to the array design. We have to do this by name because the
    // sequence name is what the files contain.
    // Note that if there is ambiguity there will be problems!
    Map<String, BioSequence> seqMap = new HashMap<>();
    for (BioSequence bioSequence : sequencesToBlat) {
        seqMap.put(bioSequence.getName(), bioSequence);
    }

    ExternalDatabase searchedDatabase = ShellDelegatingBlat.getSearchedGenome(taxon);

    Collection<BlatResult> toSkip = new HashSet<>();
    for (BlatResult result : rawBlatResults) {

        /*
         * If the sequences don't have ids, replace them with the actual sequences associated with the array design.
         */
        if (result.getQuerySequence().getId() == null) {
            String querySeqName = result.getQuerySequence().getName();
            BioSequence actualSequence = seqMap.get(querySeqName);
            if (actualSequence == null) {
                ArrayDesignSequenceAlignmentServiceImpl.log
                        .debug("Array design does not contain a sequence with name " + querySeqName);
                toSkip.add(result);
                continue;
            }
            result.setQuerySequence(actualSequence);
        } else {
            result.getQuerySequence().setTaxon(taxon);
        }

        result.setSearchedDatabase(searchedDatabase);
        try {
            FieldUtils.writeField(result.getTargetChromosome(), "taxon", taxon, true);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        result.getTargetChromosome().getSequence().setTaxon(taxon);

    }

    if (toSkip.size() > 0) {
        ArrayDesignSequenceAlignmentServiceImpl.log.warn(
                toSkip.size() + " blat results were for sequences not on " + ad + "; they will be ignored.");
        rawBlatResults.removeAll(toSkip);
    }

    Map<BioSequence, Collection<BlatResult>> goldenPathAlignments = new HashMap<>();
    this.getGoldenPathAlignments(sequencesToBlat, taxon, goldenPathAlignments);
    for (BioSequence sequence : goldenPathAlignments.keySet()) {
        rawBlatResults.addAll(goldenPathAlignments.get(sequence));
    }

    Collection<BlatResult> results = this.persistBlatResults(rawBlatResults);

    arrayDesignReportService.generateArrayDesignReport(ad.getId());

    return results;
}

From source file:com.salesmanager.core.module.impl.application.shipping.CalculateBoxPackingModule.java

public Collection<PackageDetail> calculatePacking(Collection<OrderProduct> products,
        MerchantConfiguration config, int merchantId) throws Exception {

    if (products == null) {
        throw new Exception("Product list cannot be null !!");
    }//  w  w w.ja v a  2s  .co  m

    double width = 0;
    double length = 0;
    double height = 0;
    double weight = 0;
    double maxweight = 0;

    int treshold = 0;

    // get box details from merchantconfiguration
    String values = config.getConfigurationValue1();
    if (!StringUtils.isBlank(values)) {
        StringTokenizer st = new StringTokenizer(config.getConfigurationValue1(), "|");

        Map parseTokens = new HashMap();

        int i = 1;
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (i == 1) {

                width = new BigDecimal(token).doubleValue();

            } else if (i == 2) {
                height = new BigDecimal(token).doubleValue();

            } else if (i == 3) {
                length = new BigDecimal(token).doubleValue();

            } else if (i == 4) {
                weight = new BigDecimal(token).doubleValue();

            } else if (i == 5) {

                maxweight = new BigDecimal(token).doubleValue();

            } else if (i == 6) {

                treshold = Integer.parseInt(token);

            }
            i++;
        }

    } else {
        LogMerchantUtil.log(merchantId, "Shipping Box information is not configured adequatly");
        throw new Exception("Cannot determine box size");
    }

    List boxes = new ArrayList();

    // maximum number of boxes
    int maxBox = 100;
    int iterCount = 0;

    Collection leftProducts = new ArrayList();

    // need to put items individualy
    Iterator prodIter = products.iterator();
    while (prodIter.hasNext()) {
        OrderProduct op = (OrderProduct) prodIter.next();

        if (!op.isShipping()) {
            continue;
        }

        int qty = op.getProductQuantity();

        Set attrs = op.getOrderattributes();

        // set attributes values
        BigDecimal w = op.getProductWeight();
        if (attrs != null && attrs.size() > 0) {
            Iterator attributesIterator = attrs.iterator();
            OrderProductAttribute opa = (OrderProductAttribute) attributesIterator.next();
            w = w.add(opa.getProductAttributeWeight());
        }

        if (qty > 1) {

            for (int i = 1; i <= qty; i++) {
                OrderProduct tempop = new OrderProduct();
                tempop.setProductHeight(op.getProductHeight());
                tempop.setProductLength(op.getProductLength());
                tempop.setProductWidth(op.getProductWidth());
                tempop.setProductWeight(w);
                tempop.setProductQuantity(1);
                tempop.setOrderattributes(attrs);
                leftProducts.add(tempop);
            }
        } else {
            op.setProductWeight(w);
            leftProducts.add(op);
        }
        iterCount++;
    }

    if (iterCount == 0) {
        return null;
    }

    int productCount = leftProducts.size();

    if (productCount < treshold) {
        throw new Exception("Number of item smaller than treshold");
    }

    List usedBoxesList = new ArrayList();

    PackingBox b = new PackingBox();
    // set box max volume
    double maxVolume = width * length * height;

    if (maxVolume == 0 || maxweight == 0) {
        LogMerchantUtil.log(merchantId, "Check shipping box configuration, it has a volume of " + maxVolume
                + " and a maximum weight of " + maxweight + ". Those values must be greater than 0.");
    }
    b.setVolumeLeft(maxVolume);
    b.setWeightLeft(maxweight);

    usedBoxesList.add(b);

    int boxCount = 1;
    Collection assignedProducts = new ArrayList();

    // calculate the volume for the next object
    if (assignedProducts.size() > 0) {
        leftProducts.removeAll(assignedProducts);
        assignedProducts = new ArrayList();
    }
    Iterator prodIterator = leftProducts.iterator();

    boolean productAssigned = false;

    while (prodIterator.hasNext()) {
        OrderProduct op = (OrderProduct) prodIterator.next();
        Collection attributes = op.getOrderattributes();
        productAssigned = false;

        double productWeight = op.getProductWeight().doubleValue();

        // validate if product fits in the box
        if (op.getProductWidth().doubleValue() > width || op.getProductHeight().doubleValue() > height
                || op.getProductLength().doubleValue() > length) {
            // log message to customer
            LogMerchantUtil.log(merchantId, "Product " + op.getProductId()
                    + " has a demension larger than the box size specified. Will use per item calculation.");
            // exit this process and let shipping calculator calculate
            // individual items
            throw new Exception("Product configuration exceeds box configuraton");
        }

        if (productWeight > maxweight) {
            LogMerchantUtil.log(merchantId, "Product " + op.getProductId()
                    + " has a weight larger than the box maximum weight specified. Will use per item calculation.");
            throw new Exception("Product weight exceeds box maximum weight");
        }

        double productVolume = (op.getProductWidth().doubleValue() * op.getProductHeight().doubleValue()
                * op.getProductLength().doubleValue());

        if (productVolume == 0) {
            LogMerchantUtil.log(merchantId, "Product " + op.getProductId()
                    + " has one of the dimension set to 0 and therefore cannot calculate the volume");
            throw new Exception("Cannot calculate volume");
        }

        List boxesList = usedBoxesList;

        // try each box
        Iterator boxIter = boxesList.iterator();
        while (boxIter.hasNext()) {
            PackingBox pb = (PackingBox) boxIter.next();
            double volumeLeft = pb.getVolumeLeft();
            double weightLeft = pb.getWeightLeft();

            if (pb.getVolumeLeft() >= productVolume && pb.getWeightLeft() >= productWeight) {// fit the item
                // in this
                // box
                // fit in the current box
                volumeLeft = volumeLeft - productVolume;
                pb.setVolumeLeft(volumeLeft);
                weightLeft = weightLeft - productWeight;
                pb.setWeightLeft(weightLeft);

                assignedProducts.add(op);
                productCount--;

                double w = pb.getWeight();
                w = w + productWeight;
                pb.setWeight(w);
                productAssigned = true;
                maxBox--;
                break;

            }

        }

        if (!productAssigned) {// create a new box

            b = new PackingBox();
            // set box max volume
            b.setVolumeLeft(maxVolume);
            b.setWeightLeft(maxweight);

            usedBoxesList.add(b);

            double volumeLeft = b.getVolumeLeft() - productVolume;
            b.setVolumeLeft(volumeLeft);
            double weightLeft = b.getWeightLeft() - productWeight;
            b.setWeightLeft(weightLeft);
            assignedProducts.add(op);
            productCount--;
            double w = b.getWeight();
            w = w + productWeight;
            b.setWeight(w);
            maxBox--;
        }

    }

    // now prepare the shipping info

    // number of boxes

    Iterator ubIt = usedBoxesList.iterator();

    System.out.println("###################################");
    System.out.println("Number of boxex " + usedBoxesList.size());
    System.out.println("###################################");

    while (ubIt.hasNext()) {
        PackingBox box = (PackingBox) ubIt.next();
        PackageDetail details = new PackageDetail();
        details.setShippingHeight(height);
        details.setShippingLength(length);
        details.setShippingWeight(weight + box.getWeight());
        details.setShippingWidth(width);
        boxes.add(details);
    }

    return boxes;

}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

public static void checkIngression(Ingression ingression, Person person,
        DegreeCurricularPlan degreeCurricularPlan) {
    if (ingression == Ingression.RI) {
        if (person == null || person.getStudent() == null) {
            throw new DomainException("error.registration.preBolonhaSourceDegreeNotFound");
        }//from w w w. ja  v a2 s .c o  m
        if (degreeCurricularPlan.getEquivalencePlan() != null) {
            final Student student = person.getStudent();
            final Degree sourceDegree = degreeCurricularPlan.getEquivalencePlan()
                    .getSourceDegreeCurricularPlan().getDegree();

            Registration sourceRegistration = person.getStudent().readRegistrationByDegree(sourceDegree);
            if (sourceRegistration == null) {
                final Collection<Registration> registrations = student
                        .getRegistrationsByDegreeType(DegreeType.DEGREE);
                registrations.removeAll(student.getRegistrationsFor(degreeCurricularPlan));
                sourceRegistration = registrations.size() == 1 ? registrations.iterator().next() : null;
            }

            if (sourceRegistration == null) {
                throw new DomainException("error.registration.preBolonhaSourceDegreeNotFound");
            } else if (!sourceRegistration.getActiveStateType().canReingress()) {
                throw new DomainException("error.registration.preBolonhaSourceRegistrationCannotReingress");
            }
        }
    }
}

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

@SuppressWarnings("unchecked")
private void setProperty(Object proxy, IPropertyDescriptor propertyDescriptor, Object newProperty) {
    String propertyName = propertyDescriptor.getName();

    Object oldProperty;//from  w  w w .  j a  v a 2  s  . c o  m
    try {
        oldProperty = accessorFactory
                .createPropertyAccessor(propertyName, componentDescriptor.getComponentContract())
                .getValue(proxy);
    } catch (IllegalAccessException | NoSuchMethodException ex) {
        throw new ComponentException(ex);
    } catch (InvocationTargetException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ex.getCause();
        }
        throw new ComponentException(ex.getCause());
    }
    Object actualNewProperty;
    if (propertyProcessorsEnabled) {
        actualNewProperty = propertyDescriptor.interceptSetter(proxy, newProperty);
    } else {
        actualNewProperty = newProperty;
    }
    if (isInitialized(oldProperty) && isInitialized(actualNewProperty)
            && ObjectUtils.equals(oldProperty, actualNewProperty)) {
        return;
    }
    if (propertyProcessorsEnabled) {
        propertyDescriptor.preprocessSetter(proxy, actualNewProperty);
    }
    if (propertyDescriptor instanceof IRelationshipEndPropertyDescriptor) {
        // It's a relation end
        IRelationshipEndPropertyDescriptor reversePropertyDescriptor = ((IRelationshipEndPropertyDescriptor) propertyDescriptor)
                .getReverseRelationEnd();
        try {
            if (propertyDescriptor instanceof IReferencePropertyDescriptor) {
                // It's a 'one' relation end
                storeReferenceProperty(proxy, (IReferencePropertyDescriptor<?>) propertyDescriptor, oldProperty,
                        actualNewProperty);
                if (reversePropertyDescriptor != null) {
                    // It is bidirectional, so we are going to update the other end.
                    if (reversePropertyDescriptor instanceof IReferencePropertyDescriptor) {
                        // It's a one-to-one relationship
                        if (proxy instanceof IEntity && oldProperty instanceof IEntity) {
                            entityDetached((IEntity) proxy, (IEntity) oldProperty,
                                    ((IRelationshipEndPropertyDescriptor) propertyDescriptor));
                        }
                        IAccessor reversePropertyAccessor = accessorFactory.createPropertyAccessor(
                                reversePropertyDescriptor.getName(),
                                ((IReferencePropertyDescriptor<?>) propertyDescriptor).getReferencedDescriptor()
                                        .getComponentContract());
                        if (oldProperty != null) {
                            reversePropertyAccessor.setValue(oldProperty, null);
                        }
                        if (actualNewProperty != null) {
                            reversePropertyAccessor.setValue(actualNewProperty, proxy);
                        }
                    } else if (reversePropertyDescriptor instanceof ICollectionPropertyDescriptor) {
                        // It's a one-to-many relationship
                        ICollectionAccessor reversePropertyAccessor = accessorFactory
                                .createCollectionPropertyAccessor(reversePropertyDescriptor.getName(),
                                        ((IReferencePropertyDescriptor<?>) propertyDescriptor)
                                                .getReferencedDescriptor().getComponentContract(),
                                        ((ICollectionPropertyDescriptor<?>) reversePropertyDescriptor)
                                                .getCollectionDescriptor().getElementDescriptor()
                                                .getComponentContract());
                        if (reversePropertyAccessor instanceof IModelDescriptorAware) {
                            ((IModelDescriptorAware) reversePropertyAccessor)
                                    .setModelDescriptor(reversePropertyDescriptor);
                        }
                        if (oldProperty != null) {
                            reversePropertyAccessor.removeFromValue(oldProperty, proxy);
                        }
                        if (actualNewProperty != null) {
                            reversePropertyAccessor.addToValue(actualNewProperty, proxy);
                        }
                    }
                }
            } else if (propertyDescriptor instanceof ICollectionPropertyDescriptor) {
                Collection<?> oldCollectionSnapshot = CollectionHelper
                        .cloneCollection((Collection<?>) oldProperty);
                // It's a 'many' relation end
                Collection<Object> oldPropertyElementsToRemove = new THashSet<>(1);
                Collection<Object> newPropertyElementsToAdd = new TLinkedHashSet<>(1);
                Collection<Object> propertyElementsToKeep = new THashSet<>(1);

                if (oldProperty != null) {
                    oldPropertyElementsToRemove.addAll((Collection<?>) oldProperty);
                    propertyElementsToKeep.addAll((Collection<?>) oldProperty);
                }
                if (actualNewProperty != null) {
                    newPropertyElementsToAdd.addAll((Collection<?>) actualNewProperty);
                }
                propertyElementsToKeep.retainAll(newPropertyElementsToAdd);
                oldPropertyElementsToRemove.removeAll(propertyElementsToKeep);
                newPropertyElementsToAdd.removeAll(propertyElementsToKeep);
                ICollectionAccessor propertyAccessor = accessorFactory.createCollectionPropertyAccessor(
                        propertyName, componentDescriptor.getComponentContract(),
                        ((ICollectionPropertyDescriptor<?>) propertyDescriptor).getCollectionDescriptor()
                                .getElementDescriptor().getComponentContract());
                boolean oldCollectionSortEnabled = collectionSortEnabled;
                boolean oldPropertyChangeEnabled = propertyChangeEnabled;
                boolean oldPropertyProcessorsEnabled = propertyProcessorsEnabled;
                try {
                    // Delay sorting for performance reasons.
                    collectionSortEnabled = false;
                    // Block property changes for performance reasons;
                    propertyChangeEnabled = false;
                    // Block property processors
                    propertyProcessorsEnabled = false;
                    for (Object element : oldPropertyElementsToRemove) {
                        propertyAccessor.removeFromValue(proxy, element);
                    }
                    for (Object element : newPropertyElementsToAdd) {
                        propertyAccessor.addToValue(proxy, element);
                    }
                    inlineComponentFactory.sortCollectionProperty((IComponent) proxy, propertyName);
                } finally {
                    collectionSortEnabled = oldCollectionSortEnabled;
                    propertyChangeEnabled = oldPropertyChangeEnabled;
                    propertyProcessorsEnabled = oldPropertyProcessorsEnabled;
                }
                // if the property is a list we may restore the element order and be
                // careful not to miss one...
                if (actualNewProperty instanceof List) {
                    Collection<Object> currentProperty = (Collection<Object>) oldProperty;
                    if (currentProperty instanceof List) {
                        // Just check that only order differs
                        Set<Object> temp = new THashSet<>(currentProperty);
                        temp.removeAll((List<?>) actualNewProperty);
                        if (currentProperty instanceof ICollectionWrapper) {
                            currentProperty = ((ICollectionWrapper) currentProperty).getWrappedCollection();
                        }
                        currentProperty.clear();
                        currentProperty.addAll((List<?>) actualNewProperty);
                        currentProperty.addAll(temp);
                    }
                }
                oldProperty = oldCollectionSnapshot;
            }
        } catch (RuntimeException ex) {
            rollbackProperty(proxy, propertyDescriptor, oldProperty);
            throw ex;
        } catch (InvocationTargetException ex) {
            rollbackProperty(proxy, propertyDescriptor, oldProperty);
            if (ex.getCause() instanceof RuntimeException) {
                throw (RuntimeException) ex.getCause();
            }
            throw new ComponentException(ex.getCause());
        } catch (IllegalAccessException | NoSuchMethodException ex) {
            throw new ComponentException(ex);
        }
    } else {
        storeProperty(propertyName, actualNewProperty);
    }
    doFirePropertyChange(proxy, propertyName, oldProperty, actualNewProperty);
    if (propertyProcessorsEnabled) {
        propertyDescriptor.postprocessSetter(proxy, oldProperty, actualNewProperty);
    }
}

From source file:fr.paris.lutece.plugins.workflow.web.WorkflowJspBean.java

/**
 * Get the selected linked actions/* w  w  w.  ja v  a2  s  .  c o  m*/
 * 
 * @param action
 *            the action
 * @param request
 *            the HTTP request
 * @return a collection of IDs action
 */
private Collection<Integer> getSelectedLinkedActions(Action action, HttpServletRequest request) {
    Collection<Integer> listIdsLinkedAction = action.getListIdsLinkedAction();

    if (listIdsLinkedAction == null) {
        listIdsLinkedAction = new LinkedHashSet<Integer>();
    }

    // Remove unselected id linked action from the list
    String[] strUnselectedLinkedActions = request.getParameterValues(PARAMETER_UNSELECT_LINKED_ACTIONS);

    if ((strUnselectedLinkedActions != null) && (strUnselectedLinkedActions.length > 0)) {
        if (!listIdsLinkedAction.isEmpty()) {
            Integer[] listUnselectedLinkedActions = WorkflowUtils
                    .convertStringToInt(strUnselectedLinkedActions);
            listIdsLinkedAction.removeAll(Arrays.asList(listUnselectedLinkedActions));
        }
    }

    // Add selected linked actions
    String[] strSelectedLinkedActions = request.getParameterValues(PARAMETER_SELECT_LINKED_ACTIONS);

    if ((strSelectedLinkedActions != null) && (strSelectedLinkedActions.length > 0)) {
        Integer[] listSelectedLinkedActions = WorkflowUtils.convertStringToInt(strSelectedLinkedActions);
        listIdsLinkedAction.addAll(Arrays.asList(listSelectedLinkedActions));
    }

    return listIdsLinkedAction;
}

From source file:com.FFLive.MySQLConnection.java

public void fetchMissingGWs(boolean showMissingGW, boolean fullRebuild) {

    //Changing Logging Level to 4 if set as default to make console output clearer
    boolean logChanged = false;
    if (Main.log.logLevel == 5) {
        //Change Level if it is default
        Main.log.logLevel(4);/*from  w w  w.j av a 2  s .  c  o m*/
        logChanged = true;
    }

    Fixtures currentGW = new Fixtures();
    currentGW.loadFixtures();
    //Get all Team Data for all previous GW

    if (fullRebuild) {
        Main.log.log(4, "Rebuilding All GW Data.. This May Take Some Time...\n");
    } else {
        Main.log.log(4, "Loading All Missing Gameweeks.. This May Take Some Time...\n");
    }

    int gw = Integer.parseInt(currentGW.gameweek);
    if (!currentGW.gameweekStarted()) {
        gw--;
    }

    try {
        //Get all of the IDs for Teams Currently In For This Week
        PreparedStatement getTeams = conn.prepareStatement("SELECT managerID FROM teamsGW?");
        getTeams.setInt(1, gw);
        ResultSet currentTeams = getTeams.executeQuery();

        Collection<Integer> allTeams = new ArrayList<Integer>();
        while (currentTeams.next()) {
            allTeams.add(currentTeams.getInt("managerID"));
        }

        if (allTeams.isEmpty()) {
            Main.log.log(3, "Please run again without arguments to fetch this weeks teams...\n");
        } else {
            //Start from 1 to current GW
            int lastGW = gw - 1;
            for (int x = 1; x < gw; x++) {
                Main.log.log(4, "Processing Week " + x + "/" + lastGW
                        + "...                                        \r");
                Collection<Integer> copyAllTeams = new ArrayList<Integer>();
                copyAllTeams.addAll(allTeams);

                //Create Tables if not Exist
                createGWTables(x);

                //If you want a full rebuild, do not remove existing teams
                if (!fullRebuild) {
                    PreparedStatement thisWeek = conn.prepareStatement("SELECT managerID FROM teamsGW?");
                    thisWeek.setInt(1, x);
                    ResultSet teams = thisWeek.executeQuery();

                    //Add This Week of Teams into a Collection then remove the overlaps
                    Collection<Integer> currentGWTeams = new ArrayList<Integer>();
                    while (teams.next()) {
                        currentGWTeams.add(teams.getInt("managerID"));
                    }

                    //This leaves the left over of missing teams
                    copyAllTeams.removeAll(currentGWTeams);
                }

                //If you just want to see what gameweeks were missing you would launch this as true
                if (showMissingGW) {
                    Main.log.log(4, "Missing Teams:" + copyAllTeams + "\n");
                } else {
                    Main.log.log(6, "Missing Teams:" + copyAllTeams + "\n");
                    for (Integer missingTeam : copyAllTeams) {
                        Team team = new Team(Integer.toString(missingTeam), x);
                        team.getTeam();
                        if (team.managerName != null) {
                            storeTeamGW(team, x);
                            storeTeamData(team);
                        } else {
                            Main.log.log(6, "Missing Team ID:" + team.managerID + " for GW:" + x + "\n");
                        }
                    }
                    //Generate a Player List for the teams and update the players with names, no scores (will be out of date)
                    //TODO Read the JSON for Previous Gameweeks (Will be annoying)
                    Main.log.log(4, "Processing Week " + x + "/" + lastGW
                            + "... Generating Player List...            \r");
                    generatePlayerList(x);
                    Main.log.log(4, "Processing Week " + x + "/" + lastGW
                            + "... Updating Player Scores...            \r");
                    updatePlayers(x, true);
                    Main.log.log(4, "Processing Week " + x + "/" + lastGW
                            + "... Done!                                \n");
                }
            }
            makePlayerGraph(gw);
        }
    } catch (SQLException e) {
        Main.log.ln(2);
        Main.log.log(2, "Error Fetching Missing Teams.. " + e + "\n");
        Main.log.log(9, e);
    }

    if (logChanged) {
        //Change Level back to default
        Main.log.logLevel(5);
    }

}

From source file:org.alfresco.repo.content.transform.TransformerConfigDynamicTransformers.java

private void createDynamicTransformers(TransformerConfig transformerConfig,
        TransformerProperties transformerProperties, MimetypeService mimetypeService,
        ContentService contentService, ContentTransformerRegistry transformerRegistry,
        TransformerDebug transformerDebug, ModuleService moduleService, DescriptorService descriptorService,
        Properties globalProperties) {
    Collection<String> SUFFIXES = Arrays.asList(new String[] { FAILOVER, PIPELINE, AVAILABLE, EDITION, AMP });

    Map<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue> transformerSourceTargetSuffixValues = getTransformerSourceTargetValuesMap(
            SUFFIXES, true, true, false, transformerProperties, mimetypeService);
    Collection<TransformerSourceTargetSuffixValue> properties = transformerSourceTargetSuffixValues.values();

    // Repeat until we cannot create any more transformers or all have been created
    Collection<TransformerSourceTargetSuffixValue> processed = new ArrayList<TransformerSourceTargetSuffixValue>();
    do {//from  ww w . j  ava 2s .c  om
        processed.clear();
        for (TransformerSourceTargetSuffixValue property : properties) {
            if (property.suffix.equals(PIPELINE) || property.suffix.equals(FAILOVER)) {
                try {
                    String edition = getProperty(property.transformerName, null, null, EDITION, null,
                            transformerSourceTargetSuffixValues);
                    String moduleId = getProperty(property.transformerName, null, null, AMP, null,
                            transformerSourceTargetSuffixValues);
                    if (!supportedEdition(descriptorService, edition)) {
                        processed.add(property);
                        logger.debug(property.transformerName + " ignored. As it is an " + edition
                                + " only transformer.");
                    } else if (!supportedModule(moduleService, moduleId)) {
                        processed.add(property);
                        logger.debug(property.transformerName + " ignored. As the AMP " + moduleId
                                + " is not installed.");
                    } else {
                        String availableStr = getProperty(property.transformerName, null, null, AVAILABLE, null,
                                transformerSourceTargetSuffixValues);
                        boolean available = availableStr == null || "true".equalsIgnoreCase(availableStr);

                        AbstractContentTransformer2 transformer = property.suffix.equals(PIPELINE)
                                ? createComplexTransformer(property, transformerConfig, mimetypeService,
                                        contentService, transformerRegistry, transformerDebug, available,
                                        globalProperties)
                                : createFailoverTransformer(property, transformerConfig, mimetypeService,
                                        contentService, transformerRegistry, transformerDebug, available,
                                        globalProperties);
                        transformer.register();
                        processed.add(property);
                        dynamicTransformers.add(transformer);
                        logger.debug(property.transformerName + " added");
                    }
                } catch (IllegalArgumentException e) {
                    // Thrown if unknown sub transformer name - it might be dynamic
                } catch (AlfrescoRuntimeException e) {
                    // Thrown if the mimetype is invalid or the transformer already exists
                    processed.add(property);
                    error(e.getMessage());
                }
            }
        }
    } while (properties.removeAll(processed) && properties.size() > 0);

    for (TransformerSourceTargetSuffixValue property : properties) {
        if (property.suffix.equals(PIPELINE) || property.suffix.equals(FAILOVER)) {
            error("Cannot create dynamic transformer " + property.transformerName
                    + " as sub transformers could not be found or created (\"" + property.value + "\").");
        }
    }
}