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:org.openmrs.web.dwr.DWRPatientService.java

/**
 * Returns a map of results with the values as count of matches and a partial list of the
 * matching patients (depending on values of start and length parameters) while the keys are are
 * 'count' and 'objectList' respectively, if the length parameter is not specified, then all
 * matches will be returned from the start index if specified.
 *
 * @param searchValue patient name or identifier
 * @param includeVoided true/false whether or not to included voided patients
 * @param start the beginning index//from   www  . j  a va  2s .c  om
 * @param length the number of matching patients to return
 * @param getMatchCount Specifies if the count of matches should be included in the returned map
 * @return a map of results
 * @throws APIException
 */
public Map<String, Object> findCountAndPatientsWithVoided(String searchValue, Integer start, Integer length,
        boolean getMatchCount, Boolean includeVoided) throws APIException {

    //Map to return
    Map<String, Object> resultsMap = new HashMap<String, Object>();
    Collection<Object> objectList = new Vector<Object>();

    if (includeVoided == null) {
        includeVoided = false;
    }

    try {
        PatientService ps = Context.getPatientService();
        int patientCount = 0;
        //if this is the first call
        if (getMatchCount) {
            patientCount += ps.getCountOfPatients(searchValue, includeVoided);

            // if there are no results found and a number was not in the
            // search and this is the first call, then do a decapitated search: 
            //trim each word down to the first three characters and search again            
            if (patientCount == 0 && start == 0 && !searchValue.matches(".*\\d+.*")) {
                String[] names = searchValue.split(" ");
                StringBuilder newSearch = new StringBuilder("");
                for (String name : names) {
                    if (name.length() > 3) {
                        name = name.substring(0, 3);
                    }
                    newSearch.append(" ").append(name);
                }

                String newSearchStr = newSearch.toString().trim();
                if (!newSearchStr.equals(searchValue)) {
                    int newPatientCount = ps.getCountOfPatients(newSearchStr);
                    if (newPatientCount > 0) {
                        // Send a signal to the core search widget to search again against newSearch
                        resultsMap.put("searchAgain", newSearchStr);
                        resultsMap.put("notification",
                                Context.getMessageSourceService().getMessage("searchWidget.noResultsFoundFor",
                                        new Object[] { searchValue, newSearchStr }, Context.getLocale()));
                    }
                }
            }

            //no results found and a number was in the search --
            //should check whether the check digit is correct.
            else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) {

                //Looks through all the patient identifier validators to see if this type of identifier
                //is supported for any of them.  If it isn't, then no need to warn about a bad check
                //digit.  If it does match, then if any of the validators validates the check digit
                //successfully, then the user is notified that the identifier has been entered correctly.
                //Otherwise, the user is notified that the identifier was entered incorrectly.

                Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
                boolean shouldWarnUser = true;
                boolean validCheckDigit = false;
                boolean identifierMatchesValidationScheme = false;

                for (IdentifierValidator piv : pivs) {
                    try {
                        if (piv.isValid(searchValue)) {
                            shouldWarnUser = false;
                            validCheckDigit = true;
                        }
                        identifierMatchesValidationScheme = true;
                    } catch (UnallowedIdentifierException e) {
                    }
                }

                if (identifierMatchesValidationScheme) {
                    if (shouldWarnUser) {
                        resultsMap.put("notification", "<b>" + Context.getMessageSourceService()
                                .getMessage("Patient.warning.inValidIdentifier") + "<b/>");
                    } else if (validCheckDigit) {
                        resultsMap.put("notification",
                                "<b style=\"color:green;\">" + Context.getMessageSourceService()
                                        .getMessage("Patient.message.validIdentifier") + "<b/>");
                    }
                }
            } else {
                //ensure that count never exceeds this value because the API's service layer would never
                //return more than it since it is limited in the DAO layer
                if (maximumResults == null) {
                    setMaximumResults(getMaximumSearchResults());
                }
                if (length != null && length > maximumResults) {
                    length = maximumResults;
                }

                if (patientCount > maximumResults) {
                    patientCount = maximumResults;
                    if (log.isDebugEnabled()) {
                        log.debug("Limitng the size of matching patients to " + maximumResults);
                    }
                }
            }

        }

        //if we have any matches or this isn't the first ajax call when the caller
        //requests for the count
        if (patientCount > 0 || !getMatchCount) {
            objectList = findBatchOfPatients(searchValue, includeVoided, start, length);
        }

        resultsMap.put("count", patientCount);
        resultsMap.put("objectList", objectList);
    } catch (Exception e) {
        log.error("Error while searching for patients", e);
        objectList.clear();
        objectList.add(
                Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
        resultsMap.put("count", 0);
        resultsMap.put("objectList", objectList);
    }
    return resultsMap;
}

From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java

public synchronized void start(final Class<?> marker, final Properties config, final String... args)
        throws Exception {
    if (started) {
        return;/*  w w  w .  ja  v a2 s.c o m*/
    }

    ensureAppInit(marker);
    started = true;

    final Class<?> appClass = app.getClass();
    final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(ancestors(appClass)));

    // setup the container config reading class annotation, using a randome http port and deploying the classpath
    final Configuration configuration = new Configuration();
    final ContainerProperties props = appClass.getAnnotation(ContainerProperties.class);
    if (props != null) {
        final Properties runnerProperties = new Properties();
        for (final ContainerProperties.Property p : props.value()) {
            final String name = p.name();
            if (name.startsWith("tomee.embedded.application.runner.")) { // allow to tune the Configuration
                // no need to filter there since it is done in loadFromProperties()
                runnerProperties.setProperty(name.substring("tomee.embedded.application.runner.".length()),
                        p.value());
            } else {
                configuration.property(name, StrSubstitutor.replaceSystemProperties(p.value()));
            }
        }
        if (!runnerProperties.isEmpty()) {
            configuration.loadFromProperties(runnerProperties);
        }
    }
    configuration.loadFromProperties(System.getProperties()); // overrides, note that some config are additive by design

    final List<Method> annotatedMethods = finder
            .findAnnotatedMethods(org.apache.openejb.testing.Configuration.class);
    if (annotatedMethods.size() > 1) {
        throw new IllegalArgumentException("Only one @Configuration is supported: " + annotatedMethods);
    }
    for (final Method m : annotatedMethods) {
        final Object o = m.invoke(app);
        if (Properties.class.isInstance(o)) {
            final Properties properties = Properties.class.cast(o);
            if (configuration.getProperties() == null) {
                configuration.setProperties(new Properties());
            }
            configuration.getProperties().putAll(properties);
        } else {
            throw new IllegalArgumentException("Unsupported " + o + " for @Configuration");
        }
    }

    final Collection<org.apache.tomee.embedded.LifecycleTask> lifecycleTasks = new ArrayList<>();
    final Collection<Closeable> postTasks = new ArrayList<>();
    final LifecycleTasks tasks = appClass.getAnnotation(LifecycleTasks.class);
    if (tasks != null) {
        for (final Class<? extends org.apache.tomee.embedded.LifecycleTask> type : tasks.value()) {
            final org.apache.tomee.embedded.LifecycleTask lifecycleTask = type.newInstance();
            lifecycleTasks.add(lifecycleTask);
            postTasks.add(lifecycleTask.beforeContainerStartup());
        }
    }

    final Map<String, Field> ports = new HashMap<>();
    {
        Class<?> type = appClass;
        while (type != null && type != Object.class) {
            for (final Field f : type.getDeclaredFields()) {
                final RandomPort annotation = f.getAnnotation(RandomPort.class);
                final String value = annotation == null ? null : annotation.value();
                if (value != null && value.startsWith("http")) {
                    f.setAccessible(true);
                    ports.put(value, f);
                }
            }
            type = type.getSuperclass();
        }
    }

    if (ports.containsKey("http")) {
        configuration.randomHttpPort();
    }

    // at least after LifecycleTasks to inherit from potential states (system properties to get a port etc...)
    final Configurers configurers = appClass.getAnnotation(Configurers.class);
    if (configurers != null) {
        for (final Class<? extends Configurer> type : configurers.value()) {
            type.newInstance().configure(configuration);
        }
    }

    final Classes classes = appClass.getAnnotation(Classes.class);
    String context = classes != null ? classes.context() : "";
    context = !context.isEmpty() && context.startsWith("/") ? context.substring(1) : context;

    Archive archive = null;
    if (classes != null && classes.value().length > 0) {
        archive = new ClassesArchive(classes.value());
    }

    final Jars jars = appClass.getAnnotation(Jars.class);
    final List<URL> urls;
    if (jars != null) {
        final Collection<File> files = ApplicationComposers.findFiles(jars);
        urls = new ArrayList<>(files.size());
        for (final File f : files) {
            urls.add(f.toURI().toURL());
        }
    } else {
        urls = null;
    }

    final WebResource resources = appClass.getAnnotation(WebResource.class);
    if (resources != null && resources.value().length > 1) {
        throw new IllegalArgumentException("Only one docBase is supported for now using @WebResource");
    }

    String webResource = null;
    if (resources != null && resources.value().length > 0) {
        webResource = resources.value()[0];
    } else {
        final File webapp = new File("src/main/webapp");
        if (webapp.isDirectory()) {
            webResource = "src/main/webapp";
        }
    }

    if (config != null) { // override other config from annotations
        configuration.loadFromProperties(config);
    }

    final Container container = new Container(configuration);
    SystemInstance.get().setComponent(TomEEEmbeddedArgs.class, new TomEEEmbeddedArgs(args, null));
    SystemInstance.get().setComponent(LifecycleTaskAccessor.class, new LifecycleTaskAccessor(lifecycleTasks));
    container.deploy(new Container.DeploymentRequest(context,
            // call ClasspathSearcher that lazily since container needs to be started to not preload logging
            urls == null
                    ? new DeploymentsResolver.ClasspathSearcher()
                            .loadUrls(Thread.currentThread().getContextClassLoader()).getUrls()
                    : urls,
            webResource != null ? new File(webResource) : null, true, null, archive));

    for (final Map.Entry<String, Field> f : ports.entrySet()) {
        switch (f.getKey()) {
        case "http":
            setPortField(f.getKey(), f.getValue(), configuration, context, app);
            break;
        case "https":
            break;
        default:
            throw new IllegalArgumentException("port " + f.getKey() + " not yet supported");
        }
    }

    SystemInstance.get().addObserver(app);
    composerInject(app);

    final AnnotationFinder appFinder = new AnnotationFinder(new ClassesArchive(appClass));
    for (final Method mtd : appFinder.findAnnotatedMethods(PostConstruct.class)) {
        if (mtd.getParameterTypes().length == 0) {
            if (!mtd.isAccessible()) {
                mtd.setAccessible(true);
            }
            mtd.invoke(app);
        }
    }

    hook = new Thread() {
        @Override
        public void run() { // ensure to log errors but not fail there
            for (final Method mtd : appFinder.findAnnotatedMethods(PreDestroy.class)) {
                if (mtd.getParameterTypes().length == 0) {
                    if (!mtd.isAccessible()) {
                        mtd.setAccessible(true);
                    }
                    try {
                        mtd.invoke(app);
                    } catch (final IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    } catch (final InvocationTargetException e) {
                        throw new IllegalStateException(e.getCause());
                    }
                }
            }

            try {
                container.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
            for (final Closeable c : postTasks) {
                try {
                    c.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
            postTasks.clear();
            app = null;
            try {
                SHUTDOWN_TASKS.remove(this);
            } catch (final Exception e) {
                // no-op: that's ok at that moment if not called manually
            }
        }
    };
    SHUTDOWN_TASKS.put(hook, hook);
}

From source file:com.gst.portfolio.loanaccount.domain.Loan.java

private Collection<LoanDisbursementDetails> fetchUndisbursedDetail() {
    Collection<LoanDisbursementDetails> disbursementDetails = new ArrayList<>();
    Date date = null;//from www  . j  a  v a 2  s . c om
    for (LoanDisbursementDetails disbursementDetail : this.disbursementDetails) {
        if (disbursementDetail.actualDisbursementDate() == null) {
            if (date == null || disbursementDetail.expectedDisbursementDate().equals(date)) {
                disbursementDetails.add(disbursementDetail);
                date = disbursementDetail.expectedDisbursementDate();
            } else if (disbursementDetail.expectedDisbursementDate().before(date)) {
                disbursementDetails.clear();
                disbursementDetails.add(disbursementDetail);
                date = disbursementDetail.expectedDisbursementDate();
            }
        }
    }
    return disbursementDetails;
}

From source file:org.alfresco.module.org_alfresco_module_rm.capability.RMAfterInvocationProvider.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Collection decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
        Collection returnedObject) {
    if (returnedObject == null) {
        return null;
    }//w w w  .  java2  s  .c  om

    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);
    if (logger.isDebugEnabled()) {
        logger.debug("Entries are " + supportedDefinitions);
    }

    if (supportedDefinitions.size() == 0) {
        return returnedObject;
    }

    // Default to the system-wide values and we'll see if they need to be reduced
    long targetResultCount = returnedObject.size();
    int maxPermissionChecks = Integer.MAX_VALUE;
    long maxPermissionCheckTimeMillis = this.maxPermissionCheckTimeMillis;
    if (returnedObject instanceof PermissionCheckCollection<?>) {
        PermissionCheckCollection permissionCheckCollection = (PermissionCheckCollection) returnedObject;
        // Get values
        targetResultCount = permissionCheckCollection.getTargetResultCount();
        if (permissionCheckCollection.getCutOffAfterCount() > 0) {
            maxPermissionChecks = permissionCheckCollection.getCutOffAfterCount();
        }
        if (permissionCheckCollection.getCutOffAfterTimeMs() > 0) {
            maxPermissionCheckTimeMillis = permissionCheckCollection.getCutOffAfterTimeMs();
        }
    }

    // Start timer and counter for cut-off
    boolean cutoff = false;
    long startTimeMillis = System.currentTimeMillis();
    int count = 0;

    // Keep values explicitly
    List<Object> keepValues = new ArrayList<Object>(returnedObject.size());

    for (Object nextObject : returnedObject) {
        // if the maximum result size or time has been exceeded, then we have to remove only
        long currentTimeMillis = System.currentTimeMillis();

        // NOTE: for reference - the "maxPermissionChecks" has never been honoured by this loop (since previously the count was not being incremented)
        if (count >= targetResultCount) {
            // We have enough results.  We stop without cutoff.
            break;
        } else if (count >= maxPermissionChecks) {
            // We have been cut off by count
            cutoff = true;
            if (logger.isDebugEnabled()) {
                logger.debug("decide (collection) cut-off: " + count + " checks exceeded " + maxPermissionChecks
                        + " checks");
            }
            break;
        } else if ((currentTimeMillis - startTimeMillis) > maxPermissionCheckTimeMillis) {
            // We have been cut off by time
            cutoff = true;
            if (logger.isDebugEnabled()) {
                logger.debug("decide (collection) cut-off: " + (currentTimeMillis - startTimeMillis)
                        + "ms exceeded " + maxPermissionCheckTimeMillis + "ms");
            }
            break;
        }

        boolean allowed = true;
        for (ConfigAttributeDefintion cad : supportedDefinitions) {
            if (cad.mode.equalsIgnoreCase("FilterNode")) {
                NodeRef testNodeRef = null;
                if (cad.parent) {
                    if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                        // Will be allowed
                        testNodeRef = null;
                    } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = nodeService.getPrimaryParent((NodeRef) nextObject).getParentRef();
                    } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((ChildAssociationRef) nextObject).getParentRef();
                    } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((AssociationRef) nextObject).getSourceRef();
                    } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                        NodeRef nodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                        testNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
                    } else {
                        throw new ACLEntryVoterException(
                                "The specified parameter is recognized: " + nextObject.getClass());
                    }
                } else {
                    if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = nodeService.getRootNode((StoreRef) nextObject);
                    } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = (NodeRef) nextObject;
                    } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((ChildAssociationRef) nextObject).getChildRef();
                    } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((AssociationRef) nextObject).getTargetRef();
                    } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                    } else {
                        throw new ACLEntryVoterException(
                                "The specified parameter is recognized: " + nextObject.getClass());
                    }
                }

                if (logger.isDebugEnabled()) {
                    logger.debug("\t" + cad.typeString + " test on " + testNodeRef + " from "
                            + nextObject.getClass().getName());
                }

                // Null allows
                if (isUnfiltered(testNodeRef)) {
                    // Continue to next ConfigAttributeDefintion
                    continue;
                }

                if (allowed && testNodeRef != null
                        && checkRead(testNodeRef) != AccessDecisionVoter.ACCESS_GRANTED) {
                    allowed = false;
                    // No point evaluating more ConfigAttributeDefintions
                    break;
                }
            }
        }

        // Failure or success, increase the count
        count++;

        if (allowed) {
            keepValues.add(nextObject);
        }
    }
    // Work out how many were left unchecked (for whatever reason)
    int sizeOriginal = returnedObject.size();
    int checksRemaining = sizeOriginal - count;
    // Note: There are use-cases where unmodifiable collections are passing through.
    //       So make sure that the collection needs modification at all
    if (keepValues.size() < sizeOriginal) {
        // There are values that need to be removed.  We have to modify the collection.
        try {
            returnedObject.clear();
            returnedObject.addAll(keepValues);
        } catch (UnsupportedOperationException e) {
            throw new AccessDeniedException("Permission-checked list must be modifiable", e);
        }
    }

    // Attach the extra permission-check data to the collection
    return PermissionCheckedCollectionMixin.create(returnedObject, cutoff, checksRemaining, sizeOriginal);
}

From source file:org.alfresco.repo.security.permissions.impl.acegi.ACLEntryAfterInvocationProvider.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Collection decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
        Collection returnedObject) throws AccessDeniedException {
    if (returnedObject == null) {
        return null;
    }//from  ww w.j  av a 2  s.c o  m

    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);
    if (log.isDebugEnabled()) {
        log.debug("Entries are " + supportedDefinitions);
    }

    if (supportedDefinitions.size() == 0) {
        return returnedObject;
    }

    // Default to the system-wide values and we'll see if they need to be reduced
    long targetResultCount = returnedObject.size();
    int maxPermissionChecks = Integer.MAX_VALUE;
    long maxPermissionCheckTimeMillis = this.maxPermissionCheckTimeMillis;
    if (returnedObject instanceof PermissionCheckCollection<?>) {
        PermissionCheckCollection permissionCheckCollection = (PermissionCheckCollection) returnedObject;
        // Get values
        targetResultCount = permissionCheckCollection.getTargetResultCount();
        if (permissionCheckCollection.getCutOffAfterCount() > 0) {
            maxPermissionChecks = permissionCheckCollection.getCutOffAfterCount();
        }
        if (permissionCheckCollection.getCutOffAfterTimeMs() > 0) {
            maxPermissionCheckTimeMillis = permissionCheckCollection.getCutOffAfterTimeMs();
        }
    }

    // Start timer and counter for cut-off
    boolean cutoff = false;
    long startTimeMillis = System.currentTimeMillis();
    int count = 0;

    // Keep values explicitly
    List<Object> keepValues = new ArrayList<Object>(returnedObject.size());

    for (Object nextObject : returnedObject) {
        // if the maximum result size or time has been exceeded, then we have to remove only
        long currentTimeMillis = System.currentTimeMillis();

        if (keepValues.size() >= targetResultCount) {
            // We have enough results.  We stop without cutoff.
            break;
        } else if (count >= maxPermissionChecks) {
            // We have been cut off by count
            cutoff = true;
            if (log.isDebugEnabled()) {
                log.debug("decide (collection) cut-off: " + count + " checks exceeded " + maxPermissionChecks
                        + " checks");
            }
            break;
        } else if ((currentTimeMillis - startTimeMillis) > maxPermissionCheckTimeMillis) {
            // We have been cut off by time
            cutoff = true;
            if (log.isDebugEnabled()) {
                log.debug("decide (collection) cut-off: " + (currentTimeMillis - startTimeMillis)
                        + "ms exceeded " + maxPermissionCheckTimeMillis + "ms");
            }
            break;
        }

        boolean allowed = true;
        for (ConfigAttributeDefintion cad : supportedDefinitions) {
            NodeRef testNodeRef = null;
            if (cad.typeString.equals(AFTER_ACL_NODE)) {
                if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = nodeService.getRootNode((StoreRef) nextObject);
                } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = (NodeRef) nextObject;
                } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = ((ChildAssociationRef) nextObject).getChildRef();
                } else if (Pair.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = (NodeRef) ((Pair) nextObject).getSecond();
                } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = ((AssociationRef) nextObject).getTargetRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is not recognized: " + nextObject.getClass());
                }
            } else if (cad.typeString.equals(AFTER_ACL_PARENT)) {
                if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                    // Will be allowed
                    testNodeRef = null;
                } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = nodeService.getPrimaryParent((NodeRef) nextObject).getParentRef();
                } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = ((ChildAssociationRef) nextObject).getParentRef();
                } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = ((AssociationRef) nextObject).getSourceRef();
                } else if (Pair.class.isAssignableFrom(nextObject.getClass())) {
                    testNodeRef = (NodeRef) ((Pair) nextObject).getSecond();
                } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                    NodeRef nodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                    testNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is recognized: " + nextObject.getClass());
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("\t" + cad.typeString + " test on " + testNodeRef + " from "
                        + nextObject.getClass().getName());
            }

            if (isUnfiltered(testNodeRef)) // Null allows
            {
                continue; // Continue to next ConfigAttributeDefintion
            }

            if (allowed && (testNodeRef != null) && (permissionService.hasPermission(testNodeRef,
                    cad.required.toString()) == AccessStatus.DENIED)) {
                allowed = false;
                break; // No point evaluating more ConfigAttributeDefintions
            }
        }

        // Failure or success, increase the count
        count++;

        if (allowed) {
            keepValues.add(nextObject);
        }
    }
    // Work out how many were left unchecked (for whatever reason)
    int sizeOriginal = returnedObject.size();
    int checksRemaining = sizeOriginal - count;
    // Note: There are use-cases where unmodifiable collections are passing through.
    //       So make sure that the collection needs modification at all
    if (keepValues.size() < sizeOriginal) {
        // There are values that need to be removed.  We have to modify the collection.
        try {
            returnedObject.clear();
            returnedObject.addAll(keepValues);
        } catch (UnsupportedOperationException e) {
            throw new AccessDeniedException("Permission-checked list must be modifiable", e);
        }
    }

    // Attach the extra permission-check data to the collection
    return PermissionCheckedCollectionMixin.create(returnedObject, cutoff, checksRemaining, sizeOriginal);
}

From source file:org.hyperledger.fabric.sdkintegration.End2endIT.java

void runChannel(HFClient client, Channel channel, boolean installChaincode, SampleOrg sampleOrg, int delta) {

    class ChaincodeEventCapture { //A test class to capture chaincode events
        final String handle;
        final BlockEvent blockEvent;
        final ChaincodeEvent chaincodeEvent;

        ChaincodeEventCapture(String handle, BlockEvent blockEvent, ChaincodeEvent chaincodeEvent) {
            this.handle = handle;
            this.blockEvent = blockEvent;
            this.chaincodeEvent = chaincodeEvent;
        }//from  w w  w  .  j av a2 s . c o  m
    }

    // The following is just a test to see if peers and orderers can be added and removed.
    // not pertinent to the code flow.
    testRemovingAddingPeersOrderers(client, channel);

    Vector<ChaincodeEventCapture> chaincodeEvents = new Vector<>(); // Test list to capture chaincode events.

    try {

        final String channelName = channel.getName();
        boolean isFooChain = FOO_CHANNEL_NAME.equals(channelName);
        out("Running channel %s", channelName);

        Collection<Orderer> orderers = channel.getOrderers();
        final ChaincodeID chaincodeID;
        Collection<ProposalResponse> responses;
        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();

        // Register a chaincode event listener that will trigger for any chaincode id and only for EXPECTED_EVENT_NAME event.

        String chaincodeEventListenerHandle = channel.registerChaincodeEventListener(Pattern.compile(".*"),
                Pattern.compile(Pattern.quote(EXPECTED_EVENT_NAME)), (handle, blockEvent, chaincodeEvent) -> {

                    chaincodeEvents.add(new ChaincodeEventCapture(handle, blockEvent, chaincodeEvent));

                    String es = blockEvent.getPeer() != null ? blockEvent.getPeer().getName()
                            : blockEvent.getEventHub().getName();
                    out("RECEIVED Chaincode event with handle: %s, chaincode Id: %s, chaincode event name: %s, "
                            + "transaction id: %s, event payload: \"%s\", from eventhub: %s", handle,
                            chaincodeEvent.getChaincodeId(), chaincodeEvent.getEventName(),
                            chaincodeEvent.getTxId(), new String(chaincodeEvent.getPayload()), es);

                });

        //For non foo channel unregister event listener to test events are not called.
        if (!isFooChain) {
            channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
            chaincodeEventListenerHandle = null;

        }

        ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
                .setVersion(CHAIN_CODE_VERSION);
        if (null != CHAIN_CODE_PATH) {
            chaincodeIDBuilder.setPath(CHAIN_CODE_PATH);

        }
        chaincodeID = chaincodeIDBuilder.build();

        if (installChaincode) {
            ////////////////////////////
            // Install Proposal Request
            //

            client.setUserContext(sampleOrg.getPeerAdmin());

            out("Creating install proposal");

            InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
            installProposalRequest.setChaincodeID(chaincodeID);

            if (isFooChain) {
                // on foo chain install from directory.

                ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.setChaincodeSourceLocation(
                        Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile());

                if (testConfig.isFabricVersionAtOrAfter("1.1")) { // Fabric 1.1 added support for  META-INF in the chaincode image.

                    //This sets an index on the variable a in the chaincode // see http://hyperledger-fabric.readthedocs.io/en/master/couchdb_as_state_database.html#using-couchdb-from-chaincode
                    // The file IndexA.json as part of the META-INF will be packaged with the source to create the index.
                    installProposalRequest
                            .setChaincodeMetaInfLocation(new File("src/test/fixture/meta-infs/end2endit"));
                }
            } else {
                // On bar chain install from an input stream.

                // For inputstream if indicies are desired the application needs to make sure the META-INF is provided in the stream.
                // The SDK does not change anything in the stream.

                if (CHAIN_CODE_LANG.equals(Type.GO_LANG)) {

                    installProposalRequest
                            .setChaincodeInputStream(
                                    Util.generateTarGzInputStream(
                                            (Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH, "src",
                                                    CHAIN_CODE_PATH).toFile()),
                                            Paths.get("src", CHAIN_CODE_PATH).toString()));
                } else {
                    installProposalRequest.setChaincodeInputStream(Util.generateTarGzInputStream(
                            (Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile()), "src"));
                }
            }

            installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION);
            installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);

            out("Sending install proposal");

            ////////////////////////////
            // only a client from the same org as the peer can issue an install request
            int numInstallProposal = 0;
            //    Set<String> orgs = orgPeers.keySet();
            //   for (SampleOrg org : testSampleOrgs) {

            Collection<Peer> peers = channel.getPeers();
            numInstallProposal = numInstallProposal + peers.size();
            responses = client.sendInstallProposal(installProposalRequest, peers);

            for (ProposalResponse response : responses) {
                if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                    out("Successful install proposal response Txid: %s from peer %s",
                            response.getTransactionID(), response.getPeer().getName());
                    successful.add(response);
                } else {
                    failed.add(response);
                }
            }

            //   }
            out("Received %d install proposal responses. Successful+verified: %d . Failed: %d",
                    numInstallProposal, successful.size(), failed.size());

            if (failed.size() > 0) {
                ProposalResponse first = failed.iterator().next();
                fail("Not enough endorsers for install :" + successful.size() + ".  " + first.getMessage());
            }
        }

        //   client.setUserContext(sampleOrg.getUser(TEST_ADMIN_NAME));
        //  final ChaincodeID chaincodeID = firstInstallProposalResponse.getChaincodeID();
        // Note installing chaincode does not require transaction no need to
        // send to Orderers

        ///////////////
        //// Instantiate chaincode.
        InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
        instantiateProposalRequest.setProposalWaitTime(DEPLOYWAITTIME);
        instantiateProposalRequest.setChaincodeID(chaincodeID);
        instantiateProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
        instantiateProposalRequest.setFcn("init");
        instantiateProposalRequest.setArgs(new String[] { "a", "500", "b", "" + (200 + delta) });
        Map<String, byte[]> tm = new HashMap<>();
        tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
        tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
        instantiateProposalRequest.setTransientMap(tm);

        /*
          policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2
          See README.md Chaincode endorsement policies section for more details.
        */
        ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
        chaincodeEndorsementPolicy
                .fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
        instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);

        out("Sending instantiateProposalRequest to all peers with arguments: a and b set to 100 and %s respectively",
                "" + (200 + delta));
        successful.clear();
        failed.clear();

        if (isFooChain) { //Send responses both ways with specifying peers and by using those on the channel.
            responses = channel.sendInstantiationProposal(instantiateProposalRequest, channel.getPeers());
        } else {
            responses = channel.sendInstantiationProposal(instantiateProposalRequest);
        }
        for (ProposalResponse response : responses) {
            if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
                successful.add(response);
                out("Succesful instantiate proposal response Txid: %s from peer %s",
                        response.getTransactionID(), response.getPeer().getName());
            } else {
                failed.add(response);
            }
        }
        out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d",
                responses.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            for (ProposalResponse fail : failed) {

                out("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with "
                        + fail.getMessage() + ", on peer" + fail.getPeer());

            }
            ProposalResponse first = failed.iterator().next();
            fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with "
                    + first.getMessage() + ". Was verified:" + first.isVerified());
        }
        ///////////////
        /// Send instantiate transaction to orderer
        out("Sending instantiateTransaction to orderer with a and b set to 100 and %s respectively",
                "" + (200 + delta));

        //Specify what events should complete the interest in this transaction. This is the default
        // for all to complete. It's possible to specify many different combinations like
        //any from a group, all from one group and just one from another or even None(NOfEvents.createNoEvents).
        // See. Channel.NOfEvents
        Channel.NOfEvents nOfEvents = createNofEvents();
        if (!channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).isEmpty()) {
            nOfEvents.addPeers(channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)));
        }
        if (!channel.getEventHubs().isEmpty()) {
            nOfEvents.addEventHubs(channel.getEventHubs());
        }

        channel.sendTransaction(successful, createTransactionOptions() //Basically the default options but shows it's usage.
                .userContext(client.getUserContext()) //could be a different user context. this is the default.
                .shuffleOrders(false) // don't shuffle any orderers the default is true.
                .orderers(channel.getOrderers()) // specify the orderers we want to try this transaction. Fails once all Orderers are tried.
                .nOfEvents(nOfEvents) // The events to signal the completion of the interest in the transaction
        ).thenApply(transactionEvent -> {

            waitOnFabric(0);

            assertTrue(transactionEvent.isValid()); // must be valid to be here.

            assertNotNull(transactionEvent.getSignature()); //musth have a signature.
            BlockEvent blockEvent = transactionEvent.getBlockEvent(); // This is the blockevent that has this transaction.
            assertNotNull(blockEvent.getBlock()); // Make sure the RAW Fabric block is returned.

            out("Finished instantiate transaction with transaction id %s", transactionEvent.getTransactionID());

            try {
                assertEquals(blockEvent.getChannelId(), channel.getName());
                successful.clear();
                failed.clear();

                client.setUserContext(sampleOrg.getUser(testUser1));

                ///////////////
                /// Send transaction proposal to all peers
                TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
                transactionProposalRequest.setChaincodeID(chaincodeID);
                transactionProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
                //transactionProposalRequest.setFcn("invoke");
                transactionProposalRequest.setFcn("move");
                transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
                transactionProposalRequest.setArgs("a", "b", "100");

                Map<String, byte[]> tm2 = new HashMap<>();
                tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); //Just some extra junk in transient map
                tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); // ditto
                tm2.put("result", ":)".getBytes(UTF_8)); // This should be returned in the payload see chaincode why.
                if (Type.GO_LANG.equals(CHAIN_CODE_LANG) && testConfig.isFabricVersionAtOrAfter("1.2")) {

                    expectedMoveRCMap.put(channelName, random.nextInt(300) + 100L); // the chaincode will return this as status see chaincode why.
                    tm2.put("rc", (expectedMoveRCMap.get(channelName) + "").getBytes(UTF_8)); // This should be returned see chaincode why.
                    // 400 and above results in the peer not endorsing!
                } else {
                    expectedMoveRCMap.put(channelName, 200L); // not really supported for Java or Node.
                }

                tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); //This should trigger an event see chaincode why.

                transactionProposalRequest.setTransientMap(tm2);

                out("sending transactionProposal to all peers with arguments: move(a,b,100)");

                //  Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposalToEndorsers(transactionProposalRequest);
                Collection<ProposalResponse> transactionPropResp = channel
                        .sendTransactionProposal(transactionProposalRequest, channel.getPeers());
                for (ProposalResponse response : transactionPropResp) {
                    if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                        out("Successful transaction proposal response Txid: %s from peer %s",
                                response.getTransactionID(), response.getPeer().getName());
                        successful.add(response);
                    } else {
                        failed.add(response);
                    }
                }

                out("Received %d transaction proposal responses. Successful+verified: %d . Failed: %d",
                        transactionPropResp.size(), successful.size(), failed.size());
                if (failed.size() > 0) {
                    ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
                    fail("Not enough endorsers for invoke(move a,b,100):" + failed.size() + " endorser error: "
                            + firstTransactionProposalResponse.getMessage() + ". Was verified: "
                            + firstTransactionProposalResponse.isVerified());
                }

                // Check that all the proposals are consistent with each other. We should have only one set
                // where all the proposals above are consistent. Note the when sending to Orderer this is done automatically.
                //  Shown here as an example that applications can invoke and select.
                // See org.hyperledger.fabric.sdk.proposal.consistency_validation config property.
                Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils
                        .getProposalConsistencySets(transactionPropResp);
                if (proposalConsistencySets.size() != 1) {
                    fail(format("Expected only one set of consistent proposal responses but got %d",
                            proposalConsistencySets.size()));
                }
                out("Successfully received transaction proposal responses.");

                //  System.exit(10);

                ProposalResponse resp = successful.iterator().next();
                byte[] x = resp.getChaincodeActionResponsePayload(); // This is the data returned by the chaincode.
                String resultAsString = null;
                if (x != null) {
                    resultAsString = new String(x, UTF_8);
                }
                assertEquals(":)", resultAsString);

                assertEquals(expectedMoveRCMap.get(channelName).longValue(),
                        resp.getChaincodeActionResponseStatus()); //Chaincode's status.

                TxReadWriteSetInfo readWriteSetInfo = resp.getChaincodeActionResponseReadWriteSetInfo();
                //See blockwalker below how to transverse this
                assertNotNull(readWriteSetInfo);
                assertTrue(readWriteSetInfo.getNsRwsetCount() > 0);

                ChaincodeID cid = resp.getChaincodeID();
                assertNotNull(cid);
                final String path = cid.getPath();
                if (null == CHAIN_CODE_PATH) {
                    assertTrue(path == null || "".equals(path));

                } else {

                    assertEquals(CHAIN_CODE_PATH, path);

                }

                assertEquals(CHAIN_CODE_NAME, cid.getName());
                assertEquals(CHAIN_CODE_VERSION, cid.getVersion());

                ////////////////////////////
                // Send Transaction Transaction to orderer
                out("Sending chaincode transaction(move a,b,100) to orderer.");
                return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(),
                        TimeUnit.SECONDS);

            } catch (Exception e) {
                out("Caught an exception while invoking chaincode");
                e.printStackTrace();
                fail("Failed invoking chaincode with error : " + e.getMessage());
            }

            return null;

        }).thenApply(transactionEvent -> {
            try {

                waitOnFabric(0);

                assertTrue(transactionEvent.isValid()); // must be valid to be here.
                out("Finished transaction with transaction id %s", transactionEvent.getTransactionID());
                testTxID = transactionEvent.getTransactionID(); // used in the channel queries later

                ////////////////////////////
                // Send Query Proposal to all peers
                //
                String expect = "" + (300 + delta);
                out("Now query chaincode for the value of b.");
                QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
                queryByChaincodeRequest.setArgs(new String[] { "b" });
                queryByChaincodeRequest.setFcn("query");
                queryByChaincodeRequest.setChaincodeID(chaincodeID);

                Map<String, byte[]> tm2 = new HashMap<>();
                tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
                tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
                queryByChaincodeRequest.setTransientMap(tm2);

                Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest,
                        channel.getPeers());
                for (ProposalResponse proposalResponse : queryProposals) {
                    if (!proposalResponse.isVerified()
                            || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
                        fail("Failed query proposal from peer " + proposalResponse.getPeer().getName()
                                + " status: " + proposalResponse.getStatus() + ". Messages: "
                                + proposalResponse.getMessage() + ". Was verified : "
                                + proposalResponse.isVerified());
                    } else {
                        String payload = proposalResponse.getProposalResponse().getResponse().getPayload()
                                .toStringUtf8();
                        out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(),
                                payload);
                        assertEquals(payload, expect);
                    }
                }

                return null;
            } catch (Exception e) {
                out("Caught exception while running query");
                e.printStackTrace();
                fail("Failed during chaincode query with error : " + e.getMessage());
            }

            return null;
        }).exceptionally(e -> {
            if (e instanceof TransactionEventException) {
                BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
                if (te != null) {
                    throw new AssertionError(format("Transaction with txid %s failed. %s",
                            te.getTransactionID(), e.getMessage()), e);
                }
            }

            throw new AssertionError(
                    format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()), e);

        }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);

        // Channel queries

        // We can only send channel queries to peers that are in the same org as the SDK user context
        // Get the peers from the current org being used and pick one randomly to send the queries to.
        //  Set<Peer> peerSet = sampleOrg.getPeers();
        //  Peer queryPeer = peerSet.iterator().next();
        //   out("Using peer %s for channel queries", queryPeer.getName());

        BlockchainInfo channelInfo = channel.queryBlockchainInfo();
        out("Channel info for : " + channelName);
        out("Channel height: " + channelInfo.getHeight());
        String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash());
        String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash());
        out("Chain current block hash: " + chainCurrentHash);
        out("Chainl previous block hash: " + chainPreviousHash);

        // Query by block number. Should return latest block, i.e. block number 2
        BlockInfo returnedBlock = channel.queryBlockByNumber(channelInfo.getHeight() - 1);
        String previousHash = Hex.encodeHexString(returnedBlock.getPreviousHash());
        out("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber()
                + " \n previous_hash " + previousHash);
        assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber());
        assertEquals(chainPreviousHash, previousHash);

        // Query by block hash. Using latest block's previous hash so should return block number 1
        byte[] hashQuery = returnedBlock.getPreviousHash();
        returnedBlock = channel.queryBlockByHash(hashQuery);
        out("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber());
        assertEquals(channelInfo.getHeight() - 2, returnedBlock.getBlockNumber());

        // Query block by TxID. Since it's the last TxID, should be block 2
        returnedBlock = channel.queryBlockByTransactionID(testTxID);
        out("queryBlockByTxID returned block with blockNumber " + returnedBlock.getBlockNumber());
        assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber());

        // query transaction by ID
        TransactionInfo txInfo = channel.queryTransactionByID(testTxID);
        out("QueryTransactionByID returned TransactionInfo: txID " + txInfo.getTransactionID()
                + "\n     validation code " + txInfo.getValidationCode().getNumber());

        if (chaincodeEventListenerHandle != null) {

            channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
            //Should be two. One event in chaincode and two notification for each of the two event hubs

            final int numberEventsExpected = channel.getEventHubs().size()
                    + channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).size();
            //just make sure we get the notifications.
            for (int i = 15; i > 0; --i) {
                if (chaincodeEvents.size() == numberEventsExpected) {
                    break;
                } else {
                    Thread.sleep(90); // wait for the events.
                }

            }
            assertEquals(numberEventsExpected, chaincodeEvents.size());

            for (ChaincodeEventCapture chaincodeEventCapture : chaincodeEvents) {
                assertEquals(chaincodeEventListenerHandle, chaincodeEventCapture.handle);
                assertEquals(testTxID, chaincodeEventCapture.chaincodeEvent.getTxId());
                assertEquals(EXPECTED_EVENT_NAME, chaincodeEventCapture.chaincodeEvent.getEventName());
                assertTrue(
                        Arrays.equals(EXPECTED_EVENT_DATA, chaincodeEventCapture.chaincodeEvent.getPayload()));
                assertEquals(CHAIN_CODE_NAME, chaincodeEventCapture.chaincodeEvent.getChaincodeId());

                BlockEvent blockEvent = chaincodeEventCapture.blockEvent;
                assertEquals(channelName, blockEvent.getChannelId());
                //   assertTrue(channel.getEventHubs().contains(blockEvent.getEventHub()));

            }

        } else {
            assertTrue(chaincodeEvents.isEmpty());
        }

        out("Running for Channel %s done", channelName);

    } catch (Exception e) {
        out("Caught an exception running channel %s", channel.getName());
        e.printStackTrace();
        fail("Test failed with error : " + e.getMessage());
    }
}

From source file:org.sakaiproject.tool.messageforums.DiscussionForumTool.java

/**
 * Takes groups defined and sorts them alphabetically by title
 * so will be in some order when displayed on permission widget.
 * //from  ww w.  ja v a 2 s. c o m
 * @param groups
 *          Collection of groups to be sorted
 * 
 * @return
 *       Collection of groups in sorted order
 */
private Collection sortGroups(Collection groups) {
    List sortGroupsList = new ArrayList();

    sortGroupsList.addAll(groups);

    final GroupComparator groupComparator = new GroupComparator("title", true);

    Collections.sort(sortGroupsList, groupComparator);

    groups.clear();

    groups.addAll(sortGroupsList);

    return groups;
}

From source file:dendroscope.autumn.hybridnetwork.ComputeHybridizationNetwork.java

/**
 * recursively compute the hybrid number
 *
 * @param root1//w  w w . j ava 2s  .  c  o m
 * @param root2
 * @param isReduced    @return hybrid number
 * @param k
 * @param totalResults
 */
private int computeRec(Root root1, Root root2, boolean isReduced, BitSet candidateHybridsOriginal, int k,
        Collection<Root> totalResults, String depth) throws IOException, CanceledException {
    if (verbose) {
        System.err.println(depth + "---------- ComputeRec:");
        System.err.println(depth + "Tree1: " + root1.toStringFullTreeX());
        System.err.println(depth + "Tree2: " + root2.toStringFullTreeX());
    }

    if (System.currentTimeMillis() > nextTime) {
        progressListener.incrementProgress();
        nextTime += waitTime;
        waitTime *= 1.5;
    } else
        progressListener.checkForCancel();

    // root1.reorderSubTree();
    //  root2.reorderSubTree();
    if (checking) {
        root1.checkTree();
        root2.checkTree();
        if (!root2.getTaxa().equals(root1.getTaxa()))
            throw new RuntimeException("Unequal taxon sets: X=" + Basic.toString(root1.getTaxa()) + " vs "
                    + Basic.toString(root2.getTaxa()));
    }

    if (!isReduced) {
        // 1. try to perform a subtree reduction:
        {
            final Single<Integer> placeHolderTaxon = new Single<Integer>();
            List<Pair<Root, Root>> reducedSubtreePairs = new LinkedList<Pair<Root, Root>>();

            switch (SubtreeReduction.apply(root1, root2, reducedSubtreePairs, placeHolderTaxon)) {
            case ISOMORPHIC:
                Root isomorphicTree = MergeIsomorphicInducedTrees.apply(root1, root2);
                if (verbose) {
                    System.err.println(depth + "Trees are isomorphic");
                    System.err.println(depth + "Isomorphic tree: " + isomorphicTree.toStringFullTreeX());
                }
                totalResults.add(isomorphicTree);
                return 0; // two trees are isomorphic, no hybrid node needed
            case REDUCED: // a reduction was performed, cannot maintain lexicographical ordering in removal loop below
                List<Root> subTrees = new LinkedList<Root>();
                for (Pair<Root, Root> pair : reducedSubtreePairs) {
                    subTrees.add(MergeIsomorphicInducedTrees.apply(pair.getFirst(), pair.getSecond()));
                }
                if (verbose) {
                    System.err.println(depth + "Trees are reducible:");
                    System.err.println(depth + "Tree1-reduced: " + root1.toStringFullTreeX());
                    System.err.println(depth + "Tree2-reduced: " + root2.toStringFullTreeX());
                    for (Root root : subTrees) {
                        System.err.println(depth + "Merged reduced subtree: " + root.toStringFullTreeX());
                    }
                }

                BitSet candidateHybrids;
                if (false)
                    candidateHybrids = getAllAliveTaxa(root1, root2); // need to reconsider all possible hybrids
                else {
                    candidateHybrids = (BitSet) candidateHybridsOriginal.clone();
                    candidateHybrids.set(placeHolderTaxon.get(), true);
                }

                Collection<Root> currentResults = new TreeSet<Root>(new NetworkComparator());

                int h = cacheComputeRec(root1, root2, false, candidateHybrids, k, currentResults, depth + " >");
                List<Root> merged = MergeNetworks.apply(currentResults, subTrees);
                if (verbose) {
                    for (Root r : merged) {
                        System.err.println(depth + "Result-merged: " + r.toStringNetworkFull());
                    }
                }
                totalResults.addAll(fixOrdering(merged));
                return h;
            case IRREDUCIBLE:
                if (verbose)
                    System.err.println(depth + "Trees are subtree-irreducible");
                break;
            }
        }

        // 2. try to perform a cluster reduction:
        {
            final Single<Integer> placeHolderTaxon = new Single<Integer>();
            Pair<Root, Root> clusterTrees = ClusterReduction.apply(root1, root2, placeHolderTaxon);

            if (clusterTrees != null) {
                Set<Root> resultBottomPair = new TreeSet<Root>(new NetworkComparator());
                int h = cacheComputeRec(clusterTrees.getFirst(), clusterTrees.getSecond(), true,
                        candidateHybridsOriginal, k, resultBottomPair, depth + " >");

                // for the top pair, we should reconsider the place holder in the top pair as a possible place holder
                BitSet candidateHybrids = (BitSet) candidateHybridsOriginal.clone();

                candidateHybrids.set(placeHolderTaxon.get(), true);

                Set<Root> resultTopPair = new TreeSet<Root>(new NetworkComparator());
                h += cacheComputeRec(root1, root2, false, candidateHybrids, k - h, resultTopPair, depth + " >");

                Set<Root> currentResults = new TreeSet<Root>(new NetworkComparator());

                for (Root r : resultBottomPair) {
                    currentResults.addAll(MergeNetworks.apply(resultTopPair, Arrays.asList(r)));
                }
                if (verbose) {
                    System.err.println(depth + "Cluster reduction applied::");
                    System.err.println(depth + "Tree1-reduced: " + root1.toStringFullTreeX());
                    System.err.println(depth + "Tree2-reduced: " + root2.toStringFullTreeX());
                    System.err.println(depth + "Subtree-1:     " + clusterTrees.getFirst().toStringFullTreeX());
                    System.err
                            .println(depth + "Subtree-2:     " + clusterTrees.getSecond().toStringFullTreeX());

                    for (Root r : resultBottomPair) {
                        System.err.println(depth + "Results for reduced-trees: " + r.toStringNetworkFull());
                    }

                    for (Root r : resultTopPair) {
                        System.err.println(depth + "Results for sub-trees: " + r.toStringNetworkFull());
                    }

                    for (Root r : currentResults) {
                        System.err
                                .println(depth + "Merged cluster-reduced networks: " + r.toStringNetworkFull());
                    }
                }
                totalResults.addAll(currentResults);
                clusterTrees.getFirst().deleteSubTree();
                clusterTrees.getSecond().deleteSubTree();

                return h;
            }
        }
    } else {
        if (verbose)
            System.err.println(depth + "Trees are already reduced");
    }

    if (k <= 0) // 1, if only interested in number or in finding only one network, 0 else
        return LARGE;

    int hBest = LARGE;
    List<Root> leaves1 = getAllAliveLeaves(root1);

    /*
    if (leaves1.size() <= 2) // try 2 rather than one...
    {
    totalResults.add(MergeNetworks.apply(root1,root2)); // todo: this needs to be fixed
    return 0;
    }
    */

    for (Root leaf2remove : leaves1) {
        BitSet taxa2remove = leaf2remove.getTaxa();
        if (taxa2remove.cardinality() != 1)
            throw new IOException(depth + "Leaf taxa cardinality: " + taxa2remove.cardinality());

        int hybridTaxon = taxa2remove.nextSetBit(0);

        if (candidateHybridsOriginal.get(hybridTaxon)) {
            if (verbose) {
                System.err.println(depth + "Removing: " + hybridTaxon);
                System.err.println(depth + "candidateHybrids: " + Basic.toString(candidateHybridsOriginal));
                System.err.println(depth + "Tree1: " + root1.toStringFullTreeX());
                System.err.println(depth + "Tree2: " + root2.toStringFullTreeX());
            }

            Root root1x = root1.copySubNetwork();
            Root root2x = root2.copySubNetwork();
            RemoveTaxon.apply(root1x, 1, hybridTaxon);
            RemoveTaxon.apply(root2x, 2, hybridTaxon); // now we keep removed taxa as separate sets

            if (verbose) {
                System.err.println(depth + "Tree1-x: " + root1x.toStringFullTreeX());
                System.err.println(depth + "Tree2-x: " + root2x.toStringFullTreeX());
            }

            Refine.apply(root1x, root2x);

            if (verbose) {
                System.err.println(depth + "Tree1-x-refined: " + root1x.toStringFullTreeX());
                System.err.println(depth + "Tree2-x-refined: " + root2x.toStringFullTreeX());
            }

            Collection<Root> currentResults = new TreeSet<Root>(new NetworkComparator());
            candidateHybridsOriginal.set(hybridTaxon, false);

            int h = cacheComputeRec(root1x, root2x, false, candidateHybridsOriginal, k - 1, currentResults,
                    depth + " >") + 1;
            candidateHybridsOriginal.set(hybridTaxon, true);

            if (h < k)
                k = h;

            // System.err.println("Subproblem with " + Basic.toString(taxa2remove) + " removed, h=" + h);

            if (h < hBest && h <= k) {
                hBest = h;
                totalResults.clear();
            }
            if (h == hBest && h <= k) {
                if (verbose) {
                    for (Root r : currentResults) {
                        System.err.println(depth + "Result: " + r.toStringNetworkFull());
                    }
                }

                // add the hybrid node:
                currentResults = copyAll(currentResults);
                AddHybridNode.apply(currentResults, hybridTaxon);
                totalResults.addAll(fixOrdering(currentResults));
            }
            root1x.deleteSubTree();
            root2x.deleteSubTree();
        }
    }
    return hBest;
}

From source file:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * We can assume that the recipients of this message are all going to the
 * same mail server. We will now rely on the JNDI to do DNS MX record lookup
 * and try to deliver to the multiple mail servers. If it fails, it should
 * throw an exception.//from  w w w . j  a  v a 2  s. co m
 * 
 * Creation date: (2/24/00 11:25:00 PM)
 * 
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param session
 *            javax.mail.Session
 * @return boolean Whether the delivery was successful and the message can
 *         be deleted
 */
private boolean deliver(QuedItem qi, Session session) {
    MailAddress rcpt = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)");
        }
        MailImpl mail = (MailImpl) qi.getMail();
        MimeMessage message = mail.getMessage();
        // Create an array of the recipients as InternetAddress objects
        Collection recipients = mail.getRecipients();
        InternetAddress addr[] = new InternetAddress[recipients.size()];
        int j = 0;
        // funky ass look because you can't getElementAt() in a Collection

        for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
            MailAddress currentRcpt = (MailAddress) i.next();
            addr[j] = currentRcpt.toInternetAddress();
        }
        if (addr.length <= 0) {
            if (log.isDebugEnabled()) {
                log.debug("No recipients specified... returning");
            }
            return true;
        }
        // Figure out which servers to try to send to. This collection
        // will hold all the possible target servers
        Collection targetServers = null;
        Iterator it = recipients.iterator();
        while (it.hasNext()) {
            rcpt = (MailAddress) recipients.iterator().next();
            if (!qi.recepientHasBeenHandled(rcpt)) {
                break;
            }
        }
        // theoretically it is possible to not hav eone that hasn't been
        // handled
        // however that's only if something has gone really wrong.
        if (rcpt != null) {
            String host = rcpt.getHost();
            // Lookup the possible targets
            try {
                // targetServers = MXLookup.urlsForHost(host); // farking
                // unreliable jndi bs
                targetServers = getMXRecordsForHost(host);
            } catch (Exception e) {
                log.error(e);
            }
            if (targetServers == null || targetServers.size() == 0) {
                log.warn("No mail server found for: " + host);
                StringBuffer exceptionBuffer = new StringBuffer(128)
                        .append("I found no MX record entries for the hostname ").append(host)
                        .append(".  I cannot determine where to send this message.");
                return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true);
            } else if (log.isTraceEnabled()) {
                log.trace(targetServers.size() + " servers found for " + host);
            }
            MessagingException lastError = null;
            Iterator i = targetServers.iterator();
            while (i.hasNext()) {
                try {
                    URLName outgoingMailServer = (URLName) i.next();
                    StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ")
                            .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString())
                            .append(" to addresses ").append(Arrays.asList(addr));
                    if (log.isDebugEnabled()) {
                        log.debug(logMessageBuffer.toString());
                    }
                    ;
                    // URLName urlname = new URLName("smtp://"
                    // + outgoingMailServer);
                    Properties props = session.getProperties();
                    if (mail.getSender() == null) {
                        props.put("mail.smtp.from", "<>");
                    } else {
                        String sender = mail.getSender().toString();
                        props.put("mail.smtp.from", sender);
                    }
                    // Many of these properties are only in later JavaMail
                    // versions
                    // "mail.smtp.ehlo" //default true
                    // "mail.smtp.auth" //default false
                    // "mail.smtp.dsn.ret" //default to nothing... appended
                    // as
                    // RET= after MAIL FROM line.
                    // "mail.smtp.dsn.notify" //default to
                    // nothing...appended as
                    // NOTIFY= after RCPT TO line.
                    Transport transport = null;
                    try {
                        transport = session.getTransport(outgoingMailServer);
                        try {
                            transport.connect();
                        } catch (MessagingException me) {
                            log.error(me);
                            // Any error on connect should cause the mailet
                            // to
                            // attempt
                            // to connect to the next SMTP server associated
                            // with this MX record,
                            // assuming the number of retries hasn't been
                            // exceeded.
                            if (failMessage(qi, rcpt, me, false)) {
                                return true;
                            } else {
                                continue;
                            }
                        }
                        transport.sendMessage(message, addr);
                        // log.debug("message sent to " +addr);
                        /*TODO: catch failures that should result 
                         * in failure with no retries
                         } catch (SendFailedException sfe){
                           qi.failForRecipient(que, );
                           */
                    } finally {
                        if (transport != null) {
                            transport.close();
                            transport = null;
                        }
                    }
                    logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName())
                            .append(") sent successfully to ").append(outgoingMailServer);
                    log.debug(logMessageBuffer.toString());
                    qi.succeededForRecipient(que, rcpt);
                    return true;
                } catch (MessagingException me) {
                    log.error(me);
                    // MessagingException are horribly difficult to figure
                    // out
                    // what actually happened.
                    StringBuffer exceptionBuffer = new StringBuffer(256)
                            .append("Exception delivering message (").append(mail.getName()).append(") - ")
                            .append(me.getMessage());
                    log.warn(exceptionBuffer.toString());
                    if ((me.getNextException() != null)
                            && (me.getNextException() instanceof java.io.IOException)) {
                        // This is more than likely a temporary failure
                        // If it's an IO exception with no nested exception,
                        // it's probably
                        // some socket or weird I/O related problem.
                        lastError = me;
                        continue;
                    }
                    // This was not a connection or I/O error particular to
                    // one
                    // SMTP server of an MX set. Instead, it is almost
                    // certainly
                    // a protocol level error. In this case we assume that
                    // this
                    // is an error we'd encounter with any of the SMTP
                    // servers
                    // associated with this MX record, and we pass the
                    // exception
                    // to the code in the outer block that determines its
                    // severity.
                    throw me;
                } // end catch
            } // end while
              // If we encountered an exception while looping through,
              // throw the last MessagingException we caught. We only
              // do this if we were unable to send the message to any
              // server. If sending eventually succeeded, we exit
              // deliver() though the return at the end of the try
              // block.
            if (lastError != null) {
                throw lastError;
            }
        } // END if (rcpt != null)
        else {
            log.error("unable to find recipient that handn't already been handled");
        }
    } catch (SendFailedException sfe) {
        log.error(sfe);
        boolean deleteMessage = false;
        Collection recipients = qi.getMail().getRecipients();
        // Would like to log all the types of email addresses
        if (log.isDebugEnabled()) {
            log.debug("Recipients: " + recipients);
        }
        /*
         * The rest of the recipients failed for one reason or another.
         * 
         * SendFailedException actually handles this for us. For example, if
         * you send a message that has multiple invalid addresses, you'll
         * get a top-level SendFailedException that that has the valid,
         * valid-unsent, and invalid address lists, with all of the server
         * response messages will be contained within the nested exceptions.
         * [Note: the content of the nested exceptions is implementation
         * dependent.]
         * 
         * sfe.getInvalidAddresses() should be considered permanent.
         * sfe.getValidUnsentAddresses() should be considered temporary.
         * 
         * JavaMail v1.3 properly populates those collections based upon the
         * 4xx and 5xx response codes.
         * 
         */
        if (sfe.getInvalidAddresses() != null) {
            Address[] address = sfe.getInvalidAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse invalid address: " + pe.getMessage());
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Invalid recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, true);
            }
        }
        if (sfe.getValidUnsentAddresses() != null) {
            Address[] address = sfe.getValidUnsentAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse unsent address: " + pe.getMessage());
                        }
                        pe.printStackTrace();
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unsent recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, false);
            }
        }
        return deleteMessage;
    } catch (MessagingException ex) {
        log.error(ex);
        // We should do a better job checking this... if the failure is a
        // general
        // connect exception, this is less descriptive than more specific
        // SMTP command
        // failure... have to lookup and see what are the various Exception
        // possibilities
        // Unable to deliver message after numerous tries... fail
        // accordingly
        // We check whether this is a 5xx error message, which
        // indicates a permanent failure (like account doesn't exist
        // or mailbox is full or domain is setup wrong).
        // We fail permanently if this was a 5xx error
        return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0)));
    } catch (Throwable t) {
        log.error(t);
    }
    /*
     * 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 we get a MessagingException on each transport.connect(),
     * e.g., if there is only one server and we get a connect exception.
     * Return FALSE to keep run() from deleting the message.
     */
    return false;
}

From source file:org.sakaiproject.content.impl.BaseContentService.java

/**
 * Eliminate from the collection any duplicates as well as any items that are contained within another item whose resource-id is in the collection.
 * /*from w w  w .  j  av  a  2 s.  co  m*/
 * @param resourceIds
 *        A collection of strings (possibly empty) identifying items and/or collections.
 */
public void eliminateDuplicates(Collection resourceIds) {
    // eliminate exact duplicates
    Set others = new TreeSet(resourceIds);

    // eliminate items contained in other items
    Iterator itemIt = resourceIds.iterator();
    while (itemIt.hasNext()) {
        String item = (String) itemIt.next();
        Iterator otherIt = others.iterator();
        while (otherIt.hasNext()) {
            String other = (String) otherIt.next();
            if (other.startsWith(item)) {
                if (item.equals(other)) {
                    continue;
                }

                // item contains other
                otherIt.remove();
            }
        }
    }

    // if any items have been removed, update the original collection
    if (resourceIds.size() > others.size()) {
        resourceIds.clear();
        resourceIds.addAll(others);
    }

}