Example usage for java.util Collection remove

List of usage examples for java.util Collection remove

Introduction

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

Prototype

boolean remove(Object o);

Source Link

Document

Removes a single instance of the specified element from this collection, if it is present (optional operation).

Usage

From source file:ubic.gemma.loader.expression.arrayDesign.ArrayDesignSequenceProcessingServiceImpl.java

@Override
public Collection<BioSequence> processArrayDesign(ArrayDesign arrayDesign, InputStream sequenceIdentifierFile,
        String[] databaseNames, String blastDbHome, Taxon taxon, boolean force) throws IOException {
    checkForCompositeSequences(arrayDesign);

    Map<String, String> probe2acc = parseAccessionFile(sequenceIdentifierFile);
    Collection<BioSequence> finalResult = new HashSet<BioSequence>();
    Collection<String> notFound = new HashSet<String>();

    // values that were enot found
    notFound.addAll(probe2acc.values());

    // the actual thing values to search for (with version numbers)
    Collection<String> accessionsToFetch = new HashSet<String>();
    accessionsToFetch.addAll(probe2acc.values());

    // only 1 taxon should be on array design if taxon not supplied on command line
    taxon = validateTaxon(taxon, arrayDesign);

    /*/*from   w w  w.ja  v a 2 s  .c om*/
     * Fill in sequences from BLAST databases.
     */
    int versionNumber = 1;
    int numSwitched = 0;
    while (versionNumber < MAX_VERSION_NUMBER) {
        Collection<BioSequence> retrievedSequences = searchBlastDbs(databaseNames, blastDbHome, notFound);

        // map of accessions to sequence.
        Map<String, BioSequence> found = findOrUpdateSequences(accessionsToFetch, retrievedSequences, taxon,
                force);

        finalResult.addAll(retrievedSequences);

        // replace the sequences.
        for (CompositeSequence cs : arrayDesign.getCompositeSequences()) {
            String probeName = cs.getName();
            String acc = probe2acc.get(probeName);
            if (found.containsKey(acc)) {
                numSwitched++;
                log.debug("Setting seq. for " + cs + " to " + found.get(acc));
                cs.setBiologicalCharacteristic(found.get(acc));
            }
        }

        notFound = getUnFound(notFound, found);

        if (notFound.isEmpty()) {
            break; // we're done!
        }

        // bump up the version numbers for ones we haven't found yet.

        for (String accession : notFound) {
            if (log.isTraceEnabled())
                log.trace(accession + " not found, increasing version number to " + versionNumber);
            accessionsToFetch.remove(accession);

            // add or increase the version number.
            accession = accession.replaceFirst("\\.\\d+$", "");
            accession = accession + "." + Integer.toString(versionNumber);
            accessionsToFetch.add(accession);
        }
        notFound = accessionsToFetch;

        ++versionNumber;

    }

    if (!notFound.isEmpty() && taxon != null) {

        Collection<String> stillLooking = new HashSet<String>();
        stillLooking.addAll(notFound);
        notFound.clear();

        /*
         * clear the version number.
         */
        for (String accession : stillLooking) {
            notFound.remove(accession);
            accession = accession.replaceFirst("\\.\\d+$", "");
            notFound.add(accession);
        }
        assert notFound.size() > 0;
        /*
         * See if they're already in Gemma. This is good for sequences that are not in genbank but have been loaded
         * previously.
         */
        Map<String, BioSequence> found = findLocalSequences(notFound, taxon);
        finalResult.addAll(found.values());

        for (CompositeSequence cs : arrayDesign.getCompositeSequences()) {
            String probeName = cs.getName();
            String acc = probe2acc.get(probeName);
            if (found.containsKey(acc)) {
                numSwitched++;
                log.debug("Setting seq. for " + cs + " to " + found.get(acc));
                cs.setBiologicalCharacteristic(found.get(acc));
            }
        }
        notFound = getUnFound(notFound, found);
    }

    if (!notFound.isEmpty()) {
        logMissingSequences(arrayDesign, notFound);
    }

    log.info(numSwitched + " composite sequences had their biologicalCharacteristics changed");

    arrayDesignService.update(arrayDesign);

    arrayDesignReportService.generateArrayDesignReport(arrayDesign.getId());
    return finalResult;

}

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

protected void updateBindings(Map<Allocatable, AllocationChange> toUpdate, Reservation reservation,
        Appointment app, boolean remove) {

    Set<Allocatable> allocatablesToProcess = new HashSet<Allocatable>();
    allocatablesToProcess.add(null);/* w  w  w. j  a  v  a  2s  .c  o  m*/
    if (reservation != null) {
        Allocatable[] allocatablesFor = reservation.getAllocatablesFor(app);
        allocatablesToProcess.addAll(Arrays.asList(allocatablesFor));
        // This double check is very imperformant and will be removed in the future, if it doesnt show in test runs
        //         if ( remove)
        //         {
        //            Collection<Allocatable> allocatables = cache.getCollection(Allocatable.class);
        //            for ( Allocatable allocatable:allocatables)
        //            {
        //               SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId());
        //               if ( appointmentSet == null)
        //               {
        //                  continue;
        //               }
        //               for (Appointment app1:appointmentSet)
        //               {
        //                  if ( app1.equals( app))
        //                  {
        //                     if ( !allocatablesToProcess.contains( allocatable))
        //                     {
        //                        getLogger().error("Old reservation " + reservation.toString() + " has not the correct allocatable information. Using full search for appointment " + app + " and resource " + allocatable ) ;
        //                        allocatablesToProcess.add(allocatable);
        //                     }
        //                  }
        //               }
        //            }
        //         }
    } else {
        getLogger().error("Appointment without reservation found " + app + " ignoring.");
    }

    for (Allocatable allocatable : allocatablesToProcess) {
        AllocationChange updateSet;
        if (allocatable != null) {
            updateSet = toUpdate.get(allocatable);
            if (updateSet == null) {
                updateSet = new AllocationChange();
                toUpdate.put(allocatable, updateSet);
            }
        } else {
            updateSet = null;
        }
        if (remove) {
            Collection<Appointment> appointmentSet = getAndCreateList(appointmentMap, allocatable);
            // binary search could fail if the appointment has changed since the last add, which should not 
            // happen as we only put and search immutable objects in the map. But the method is left here as a failsafe 
            // with a log messaget
            if (!appointmentSet.remove(app)) {
                getLogger().error(
                        "Appointent has changed, so its not found in indexed binding map. Removing via full search");
                // so we need to traverse all appointment
                Iterator<Appointment> it = appointmentSet.iterator();
                while (it.hasNext()) {
                    if (app.equals(it.next())) {
                        it.remove();
                        break;
                    }
                }
            }
            if (updateSet != null) {
                updateSet.toRemove.add(app);
            }
        } else {
            SortedSet<Appointment> appointmentSet = getAndCreateList(appointmentMap, allocatable);
            appointmentSet.add(app);
            if (updateSet != null) {
                updateSet.toChange.add(app);
            }
        }
    }
}

From source file:org.jahia.services.templates.ModuleBuildHelper.java

public void regenerateImportFile(JCRSessionWrapper session, List<File> modifiedFiles, File sources,
        String moduleId, String moduleIdWithVersion)
        throws RepositoryException, SAXException, IOException, TransformerException {
    File f = File.createTempFile("import", null);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(ImportExportService.XSL_PATH,
            SettingsBean.getInstance().getJahiaEtcDiskPath() + "/repository/export/templatesCleanup.xsl");
    FileOutputStream out = new FileOutputStream(f);
    try {/*from ww  w .j a v  a2s  .c  o  m*/
        ImportExportBaseService.getInstance().exportZip(session.getNode("/modules/" + moduleIdWithVersion),
                session.getRootNode(), out, params);
    } finally {
        IOUtils.closeQuietly(out);
    }

    final String importFileBasePath = "content/modules/" + moduleId + "/";
    String filesNodePath = "/modules/" + moduleIdWithVersion;
    JCRNodeWrapper filesNode = null;
    if (session.nodeExists(filesNodePath)) {
        filesNode = session.getNode(filesNodePath);
    }
    // clean up files folder before unziping in it
    File sourcesImportFolder = new File(sources, "src/main/import");
    sourcesImportFolder.mkdirs();
    File filesDirectory = new File(sourcesImportFolder.getPath() + "/" + importFileBasePath);
    Collection<File> files = null;
    if (filesDirectory.exists()) {
        files = FileUtils.listFiles(filesDirectory, null, true);
    } else {
        files = new ArrayList<File>();
    }
    ZipInputStream zis = null;
    try {
        zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry zipentry;
        while ((zipentry = zis.getNextEntry()) != null) {
            if (!zipentry.isDirectory()) {
                try {
                    String name = zipentry.getName();
                    name = name.replace(moduleIdWithVersion, moduleId);
                    File sourceFile = new File(sourcesImportFolder, name);
                    boolean nodeMoreRecentThanSourceFile = true;
                    if (sourceFile.exists() && name.startsWith(importFileBasePath)) {
                        String relPath = name.substring(importFileBasePath.length());
                        if (relPath.endsWith(sourceFile.getName() + "/" + sourceFile.getName())) {
                            relPath = StringUtils.substringBeforeLast(relPath, "/");
                        }
                        if (filesNode != null && filesNode.hasNode(relPath)) {
                            JCRNodeWrapper node = filesNode.getNode(relPath);
                            if (node.hasProperty("jcr:lastModified")) {
                                nodeMoreRecentThanSourceFile = node.getProperty("jcr:lastModified").getDate()
                                        .getTimeInMillis() > sourceFile.lastModified();
                            }
                        }
                    }
                    if (nodeMoreRecentThanSourceFile && saveFile(zis, sourceFile)) {
                        modifiedFiles.add(sourceFile);
                    }

                    files.remove(sourceFile);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        for (File file : files) {
            try {
                deleteFileAndEmptyParents(file, sourcesImportFolder.getPath());
            } catch (Exception e) {
                logger.error("Cannot delete file " + file, e);
            }
        }
    } catch (Exception e) {
        logger.error("Cannot patch import file", e);
    } finally {
        if (zis != null) {
            IOUtils.closeQuietly(zis);
        }
    }
}

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

/**
 * Gets the merged relationships./*from www.j  a  v  a  2s  .co  m*/
 *
 * @param relationships1 the relationships1
 * @param relationships2 the relationships2
 * @param mergedRoleGroups the merged role groups
 * @return the merged relationships
 */
private Collection<SnomedRelationshipPropertyExpression> getMergedRelationships(
        Collection<SnomedRelationshipPropertyExpression> relationships1,
        Collection<SnomedRelationshipPropertyExpression> relationships2,
        Collection<SnomedRoleGroupExpression> mergedRoleGroups) {

    Collection<SnomedRelationshipPropertyExpression> mergedRelationships = new ArrayList<SnomedRelationshipPropertyExpression>();

    // create union set of both relationships1 and relationships2
    mergedRelationships.addAll(relationships1);
    mergedRelationships.addAll(relationships2);

    Collection<SnomedRelationshipPropertyExpression> mergedRelationshipsClone = new ArrayList<SnomedRelationshipPropertyExpression>(
            mergedRelationships);

    // merge relationships2  with role groups
    for (SnomedRelationshipPropertyExpression r : mergedRelationshipsClone) {
        // check if r exists in mergedRoleGroups
        for (SnomedRoleGroupExpression roleGroup : mergedRoleGroups) {
            for (SnomedRelationshipPropertyExpression relInRoleGroup : getContainedRelationshipPropertyExpressions(
                    roleGroup)) {
                ExpressionComparator.Subsumption_Relation relation = expressionComparator
                        .getSubsumptionRelation(r, getExpressionWithShortNormalFormAsValue(relInRoleGroup));
                /*
                 if the relation is anything but no relation, we know that the role group either contains
                 the an equivalent or a more specific type of the relationship, so we can remove it from
                 the merged relationships.
                */
                if (ExpressionComparator.Subsumption_Relation.NO_RELATION != relation) {
                    if (ExpressionComparator.Subsumption_Relation.SUBSUMED_BY == relation) {
                        // add more specific relationship to roleGroup and remove less specific relationship
                        roleGroup.addChildExpression(r);
                        roleGroup.removeChildExpression(relInRoleGroup);
                    }
                    // remove from mergedRelationships
                    mergedRelationships.remove(r);
                    break;
                }
            }
        }
    }

    return mergedRelationships;
}

From source file:lcmc.cluster.ui.ClusterBrowser.java

/** Updates VM nodes. */
public void updateVms() {
    LOG.debug1("updateVMS: status update");
    final Collection<String> domainNames = new TreeSet<String>();
    for (final Host host : getClusterHosts()) {
        final VmsXml vmsXml = getVmsXml(host);
        if (vmsXml != null) {
            domainNames.addAll(vmsXml.getDomainNames());
        }//from w w w.j  av a 2s . c  o  m
    }
    final Collection<DefaultMutableTreeNode> nodesToRemove = new ArrayList<DefaultMutableTreeNode>();
    final Collection<DomainInfo> currentVMSVDIs = new ArrayList<DomainInfo>();

    mVmsUpdateLock.lock();
    boolean nodeChanged = false;
    if (vmsNode != null) {
        for (final Object info : treeMenuController.nodesToInfos(vmsNode.children())) {
            final DomainInfo domainInfo = (DomainInfo) info;
            if (domainNames.contains(domainInfo.toString())) {
                /* keeping */
                currentVMSVDIs.add(domainInfo);
                domainNames.remove(domainInfo.toString());
                domainInfo.updateParameters(); /* update old */
            } else {
                if (!domainInfo.getResource().isNew()) {
                    /* remove not existing vms */
                    nodesToRemove.add(domainInfo.getNode());
                    domainInfo.setNode(null);
                    nodeChanged = true;
                }
            }
        }
    }

    treeMenuController.removeFromParent(nodesToRemove);
    if (vmsNode == null) {
        mVmsUpdateLock.unlock();
        return;
    }
    for (final String domainName : domainNames) {
        int i = 0;
        for (final Object info : treeMenuController.nodesToInfos(vmsNode.children())) {
            final DomainInfo domainInfo = (DomainInfo) info;
            final String name = domainInfo.getName();
            if (domainName != null && name != null && domainName.compareTo(domainInfo.getName()) < 0) {
                break;
            }
            i++;
        }
        /* add new vms nodes */
        final DomainInfo domainInfo = domainInfoProvider.get();
        domainInfo.einit(domainName, this);
        currentVMSVDIs.add(domainInfo);
        treeMenuController.createMenuItem(vmsNode, domainInfo, i);
        domainInfo.updateParameters();
        nodeChanged = true;
    }
    mVmsUpdateLock.unlock();
    if (nodeChanged) {
        treeMenuController.reloadNode(vmsNode, false);
    }
    for (final ServiceInfo si : getExistingServiceList(null)) {
        final DomainInfo vmsvdi = si.connectWithVMS();
        if (vmsvdi != null) {
            /* keep the not connected ones.*/
            currentVMSVDIs.remove(vmsvdi);
        }
    }
    for (final DomainInfo vmsvdi : currentVMSVDIs) {
        vmsvdi.setUsedByCRM(false);
    }
    final VMListInfo vmsi = (VMListInfo) vmsNode.getUserObject();
    if (vmsi != null) {
        vmsi.updateTable(VMListInfo.MAIN_TABLE);
    }
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

/**
 * Checks the revocation status of 'cert'; first by sending on OCSP request. If that fails for any reason, then through a CRL
 *//*  ww  w .  j a va  2 s  .c o  m*/
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {

    clearResult();
    Certificate cacert = getCaCert(cert);
    if (cacert == null) {
        final String msg = "No issuer CA certificate was found. An issuer CA certificate is needed to create an OCSP request and to get the right CRL";
        log.info(msg);
        throw new CertPathValidatorException(msg);
    }

    ArrayList<String> ocspurls = getOcspUrls(cert);
    if (!ocspurls.isEmpty()) {
        BigInteger certSerialnumber = CertTools.getSerialNumber(cert);
        byte[] nonce = new byte[16];
        final Random randomSource = new Random();
        randomSource.nextBytes(nonce);
        OCSPReq req = null;
        try {
            req = getOcspRequest(cacert, certSerialnumber, nonce);
        } catch (CertificateEncodingException | OCSPException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to create OCSP request. " + e.getLocalizedMessage());
            }
            fallBackToCrl(cert, CertTools.getSubjectDN(cacert));
            return;

        }

        SingleResp ocspResp = null;
        for (String url : ocspurls) {
            ocspResp = getOCSPResponse(url, req, cert, nonce, OCSPRespBuilder.SUCCESSFUL, 200);
            if (ocspResp != null) {
                log.info("Obtained OCSP response from " + url);
                break;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Failed to obtain an OCSP reponse from " + url);
                }
            }
        }

        if (ocspResp == null) {
            log.info(
                    "Failed to check certificate revocation status using OCSP. Falling back to check using CRL");
            fallBackToCrl(cert, CertTools.getSubjectDN(cacert));
        } else {
            CertificateStatus status = ocspResp.getCertStatus();
            this.ocspResponse = ocspResp;
            if (log.isDebugEnabled()) {
                log.debug("The certificate status is: " + (status == null ? "Good" : status.toString()));
            }
            if (status != null) { // status==null -> certificate OK
                throw new CertPathValidatorException("Certificate with serialnumber "
                        + CertTools.getSerialNumberAsString(cert) + " was revoked");
            }

            if (unresolvedCritExts != null) {
                unresolvedCritExts.remove(Extension.authorityInfoAccess.getId());
            }
        }

    } else {
        fallBackToCrl(cert, CertTools.getSubjectDN(cacert));

        if (unresolvedCritExts != null) {
            unresolvedCritExts.remove(Extension.cRLDistributionPoints.getId());
        }
    }

}

From source file:org.openremote.modeler.cache.LocalFileCache.java

@SuppressWarnings("unchecked")
private String getControllerXML(Collection<Screen> screens, long maxOid,
        ConfigurationFilesGenerationContext generationContext) {

    // PATCH R3181 BEGIN ---8<-----
    /*/*  w w w . ja va  2s  .  c om*/
     * Get all sensors and commands from database.
     */
    List<Sensor> dbSensors = currentUserAccount.getAccount().getSensors();
    List<Device> allDevices = currentUserAccount.getAccount().getDevices();
    List<DeviceCommand> allDBDeviceCommands = new ArrayList<DeviceCommand>();

    for (Device device : allDevices) {
        allDBDeviceCommands.addAll(deviceCommandService.loadByDevice(device.getOid()));
    }
    // PATCH R3181 END ---->8-----

    /*
     * store the max oid
     */
    MaxId maxId = new MaxId(maxOid + 1);

    /*
     * initialize UI component box.
     */
    UIComponentBox uiComponentBox = new UIComponentBox();
    initUIComponentBox(screens, uiComponentBox);
    Map<String, Object> context = new HashMap<String, Object>();
    ProtocolCommandContainer eventContainer = new ProtocolCommandContainer(protocolContainer);
    eventContainer.setAllDBDeviceCommands(allDBDeviceCommands);
    addDataBaseCommands(eventContainer, maxId);

    Collection<Sensor> sensors = getAllSensorWithoutDuplicate(screens, maxId, dbSensors);

    Collection<UISwitch> switchs = (Collection<UISwitch>) uiComponentBox.getUIComponentsByType(UISwitch.class);
    Collection<UIComponent> buttons = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(UIButton.class);
    Collection<UIComponent> gestures = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(Gesture.class);
    Collection<UIComponent> uiSliders = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(UISlider.class);
    Collection<UIComponent> uiImages = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(UIImage.class);
    Collection<UIComponent> uiLabels = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(UILabel.class);
    Collection<UIComponent> colorPickers = (Collection<UIComponent>) uiComponentBox
            .getUIComponentsByType(ColorPicker.class);
    Collection<ControllerConfig> configs = controllerConfigService.listAllConfigs();
    configs.removeAll(controllerConfigService.listAllexpiredConfigs());
    configs.addAll(controllerConfigService.listAllMissingConfigs());

    // TODO : BEGIN HACK (TO BE REMOVED)
    //
    // - the following removes the rules.editor configuration section from the
    // controller.xml
    // <config> section. The rules should not be defined in terms of controller
    // configuration
    // in the designer but as artifacts, similar to images (and multiple rule
    // files should
    // be supported).

    for (ControllerConfig controllerConfig : configs) {
        if (controllerConfig.getName().equals("rules.editor")) {
            configs.remove(controllerConfig);

            break; // this fixes a concurrent modification error in this hack..
        }
    }

    // TODO : END HACK -------------------

    context.put("switchs", switchs);
    context.put("buttons", buttons);
    context.put("screens", screens);
    context.put("eventContainer", eventContainer);
    context.put("localFileCache", this);
    context.put("protocolContainer", protocolContainer);
    context.put("sensors", sensors);
    context.put("dbSensors", dbSensors);
    context.put("gestures", gestures);
    context.put("uiSliders", uiSliders);
    context.put("labels", uiLabels);
    context.put("images", uiImages);
    context.put("colorPickers", colorPickers);
    context.put("maxId", maxId);
    context.put("configs", configs);
    context.put("generationContext", generationContext);

    try {
        return mergeXMLTemplateIntoString(CONTROLLER_XML_TEMPLATE, context);
    } catch (Exception e) {
        throw new XmlExportException("Failed to read panel.xml", e);
    }
}

From source file:org.jumpmind.symmetric.service.impl.RouterService.java

@SuppressWarnings("unchecked")
protected int routeData(ProcessInfo processInfo, Data data, ChannelRouterContext context) {
    int numberOfDataEventsInserted = 0;
    List<TriggerRouter> triggerRouters = getTriggerRoutersForData(data);
    Table table = symmetricDialect.getTable(data.getTriggerHistory(), true);
    if (triggerRouters != null && triggerRouters.size() > 0) {
        for (TriggerRouter triggerRouter : triggerRouters) {
            DataMetaData dataMetaData = new DataMetaData(data, table, triggerRouter.getRouter(),
                    context.getChannel());
            Collection<String> nodeIds = null;
            if (!context.getChannel().isIgnoreEnabled() && triggerRouter.isRouted(data.getDataEventType())) {

                String targetNodeIds = data.getNodeList();
                if (StringUtils.isNotBlank(targetNodeIds)) {
                    List<String> targetNodeIdsList = Arrays.asList(targetNodeIds.split(","));
                    nodeIds = CollectionUtils.intersection(targetNodeIdsList,
                            toNodeIds(findAvailableNodes(triggerRouter, context)));

                    if (nodeIds.size() == 0) {
                        log.info(//from  w  ww.ja  v  a  2  s  .c o  m
                                "None of the target nodes specified in the data.node_list field ({}) were qualified nodes.  {} will not be routed using the {} router",
                                new Object[] { targetNodeIds, data.getDataId(),
                                        triggerRouter.getRouter().getRouterId() });
                    }
                } else {
                    try {
                        IDataRouter dataRouter = getDataRouter(triggerRouter.getRouter());
                        context.addUsedDataRouter(dataRouter);
                        long ts = System.currentTimeMillis();
                        nodeIds = dataRouter.routeToNodes(context, dataMetaData,
                                findAvailableNodes(triggerRouter, context), false, false, triggerRouter);
                        context.incrementStat(System.currentTimeMillis() - ts,
                                ChannelRouterContext.STAT_DATA_ROUTER_MS);
                    } catch (RuntimeException ex) {
                        StringBuilder failureMessage = new StringBuilder("Failed to route data: ");
                        failureMessage.append(data.getDataId());
                        failureMessage.append(" for table: ");
                        failureMessage.append(data.getTableName());
                        failureMessage.append(".\n");
                        data.writeCsvDataDetails(failureMessage);
                        log.error(failureMessage.toString());
                        throw ex;
                    }
                }

                if (nodeIds != null) {
                    if (!triggerRouter.isPingBackEnabled() && data.getSourceNodeId() != null) {
                        nodeIds.remove(data.getSourceNodeId());
                    }

                    // should never route to self
                    nodeIds.remove(engine.getNodeService().findIdentityNodeId());

                }
            }

            numberOfDataEventsInserted += insertDataEvents(processInfo, context, dataMetaData, nodeIds);
        }

    } else {
        log.warn(
                "Could not find trigger routers for trigger history id of {}.  There is a good chance that data was captured and the trigger router link was removed before the data could be routed",
                data.getTriggerHistory().getTriggerHistoryId());
        log.info("Data with the id of {} will be assigned to an unrouted batch", data.getDataId());
        numberOfDataEventsInserted += insertDataEvents(processInfo, context,
                new DataMetaData(data, table, null, context.getChannel()), new HashSet<String>(0));

    }

    context.incrementStat(numberOfDataEventsInserted, ChannelRouterContext.STAT_DATA_EVENTS_INSERTED);
    return numberOfDataEventsInserted;

}

From source file:nl.strohalm.cyclos.services.elements.ElementServiceImpl.java

@Override
public void validate(final Element element, final WhenSaving when, final boolean manualPassword)
        throws ValidationException {
    Group group = element.getGroup();
    // We need a group in order to validate
    if (group == null || group.isTransient()) {
        if (element.isTransient()) {
            // Cannot validate a new member without a group
            throw new ValidationException("group", "member.group", new RequiredError());
        } else {/*w  w  w.ja  v  a  2s  .  c  o m*/
            // If no new group is supplied, just keep the old group
            final Element loaded = load(element.getId(), Element.Relationships.GROUP);
            group = loaded.getGroup();
            // Put the old group back on the element
            element.setGroup(group);
        }
    } else {
        group = fetchService.fetch(group);
    }
    if (element instanceof Member && element.isPersistent()) {
        // We must fill in the custom values by their default values if the member cannot edit it, so validation won't fail
        final Member member = (Member) element;
        final Collection<MemberCustomFieldValue> customValues = member.getCustomValues();
        List<MemberCustomField> fields = memberCustomFieldService.list();
        fields = customFieldHelper.onlyForGroup(fields, (MemberGroup) group);
        final Member current = (Member) load(element.getId(), Member.Relationships.CUSTOM_VALUES);
        final Collection<MemberCustomFieldValue> currentValues = current.getCustomValues();
        final Element loggedElement = LoggedUser.hasUser() ? LoggedUser.element() : null;
        final boolean byOwner = loggedElement != null && loggedElement.equals(current);
        boolean byBroker = false;
        if (loggedElement != null && LoggedUser.isBroker()) {
            byBroker = loggedElement.equals(current.getBroker());
        }
        final Group loggedGroup = LoggedUser.hasUser() ? LoggedUser.group() : null;
        for (final MemberCustomField field : fields) {
            if (loggedGroup != null && !field.getUpdateAccess().granted(loggedGroup, byOwner, byBroker, false,
                    when == WhenSaving.WEB_SERVICE)) {
                final MemberCustomFieldValue currentValue = customFieldHelper.findByField(field, currentValues);
                final MemberCustomFieldValue value = customFieldHelper.findByField(field, customValues);
                if (value != null) {
                    customValues.remove(value);
                }
                if (currentValue != null) {
                    customValues.add(currentValue);
                }
            }
        }
    }
    createValidator(group, element, when, manualPassword).validate(element);
}

From source file:org.cesecore.util.CertTools.java

/**
 * Check the certificate with a list of trusted certificates.
 * The trusted certificates list can either be end entity certificates, in this case, only this certificate by this issuer 
 * is trusted; or it could be CA certificates, in this case, all certificates issued by this CA are trusted.
 * /*w  ww  .  j  a  v a  2  s . c  om*/
 * @param certificate cert to verify
 * @param trustedCertificates collection of trusted X509Certificate
 * @return true if verified OK
 */
public static boolean verifyWithTrustedCertificates(Certificate certificate,
        Collection<Collection<Certificate>> trustedCertificates) {

    if (trustedCertificates == null) {
        if (log.isDebugEnabled()) {
            log.debug("Input of trustedCertificates was null. Trusting nothing.");
        }
        return false;
    }

    if (trustedCertificates.size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("Input of trustedCertificates was empty. Trusting everything.");
        }
        return true;
    }

    BigInteger certSN = getSerialNumber(certificate);
    for (Collection<Certificate> trustedCertChain : trustedCertificates) {
        Certificate trustedCert = trustedCertChain.iterator().next();
        BigInteger trustedCertSN = getSerialNumber(trustedCert);
        if (certSN.equals(trustedCertSN)) {
            // If the serial number of the certificate matches the serial number of a certificate in the list, make sure that it in 
            // fact is the same certificate by verifying that they were issued by the same issuer.
            // Removing this trusted certificate from the trustedCertChain will leave only the CA's certificate chain, which will be 
            // used to verify the issuer.
            if (trustedCertChain.size() > 1) {
                trustedCertChain.remove(trustedCert);
            }
        }
        try {
            verify(certificate, trustedCertChain);
            if (log.isDebugEnabled()) {
                log.debug("Trusting certificate with SubjectDN '" + getSubjectDN(certificate)
                        + "' and issuerDN '" + getIssuerDN(certificate) + "'.");
            }
            return true;
        } catch (Exception e) {
            //Do nothing. Just try the next trusted certificate chain in the list
        }

    }
    return false;
}