Example usage for java.util LinkedHashSet isEmpty

List of usage examples for java.util LinkedHashSet isEmpty

Introduction

In this page you can find the example usage for java.util LinkedHashSet isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:edu.internet2.middleware.psp.Psp.java

/**
 * This method returns all source object identifiers. The map keys are the identifiers, and the map values are the
 * {@link SchemaEntityRef}s applicable for each identifier.
 * //from ww w  .  jav a  2  s .  co m
 * The identifiers are returned by the attribute resolver via a {@link BulkCalcRequest} whose return data is
 * "identifier".
 * 
 * @param bulkProvisioningRequest the bulk provisioning request
 * @return a possibly empty map consisting of all source identifiers and their corresponding provisioned objects
 * @throws PspException
 * @throws AttributeRequestException
 */
public Map<String, List<SchemaEntityRef>> getAllSourceIdentifiers(
        BulkProvisioningRequest bulkProvisioningRequest) throws PspException, AttributeRequestException {

    BulkCalcRequest bulkCalcRequest = new BulkCalcRequest();
    bulkCalcRequest.setSchemaEntities(bulkProvisioningRequest.getSchemaEntities());
    bulkCalcRequest.setReturnData(ReturnData.IDENTIFIER);
    bulkCalcRequest.setId(BulkProvisioningRequest.BULK_REQUEST_ID);

    // provisioning context
    PspContext pspContext = new PspContext();
    pspContext.setProvisioningServiceProvider(this);
    pspContext.setProvisioningRequest(bulkCalcRequest);

    // attribute request context
    BaseSAMLProfileRequestContext attributeRequestContext = new BaseSAMLProfileRequestContext();
    attributeRequestContext.setPrincipalName(bulkCalcRequest.getId());

    // get targets specified in request before building the context
    Map<String, List<Pso>> map = getTargetAndObjectDefinitions(bulkCalcRequest);

    // determine attribute resolver requested attributes
    LinkedHashSet<String> attributeIds = new LinkedHashSet<String>();
    for (String psoTargetDefinition : map.keySet()) {
        for (Pso psoDefinition : map.get(psoTargetDefinition)) {
            if (!DatatypeHelper.isEmpty(psoDefinition.getAllSourceIdentifiersRef())) {
                attributeIds.add(DatatypeHelper.safeTrim(psoDefinition.getAllSourceIdentifiersRef()));
            }
        }
    }
    attributeRequestContext.setRequestedAttributes(attributeIds);

    // return null if there are no attribute ids to resovle
    if (attributeIds.isEmpty()) {
        LOG.debug("PSP '{}' - No source identifier refs are configured.");
        return null;
    }

    // resolve attributes
    LOG.debug("PSP '{}' - Calc {} Resolving attributes '{}'.",
            new Object[] { getId(), bulkCalcRequest, attributeIds });
    Map<String, BaseAttribute<?>> attributes = getAttributeAuthority().getAttributes(attributeRequestContext);
    LOG.debug("PSP '{}' - Calc {} Resolved attributes '{}'.",
            new Object[] { getId(), bulkCalcRequest, attributeIds });
    pspContext.setAttributes(attributes);

    Map<String, List<SchemaEntityRef>> identifierMap = new LinkedHashMap<String, List<SchemaEntityRef>>();

    for (String targetId : map.keySet()) {
        for (Pso psoDefinition : map.get(targetId)) {
            String allSourceIdentifiersRef = psoDefinition.getAllSourceIdentifiersRef();
            if (DatatypeHelper.isEmpty(allSourceIdentifiersRef)) {
                continue;
            }

            BaseAttribute attribute = attributes.get(allSourceIdentifiersRef);
            if (attribute == null) {
                LOG.warn("PSP '{}' - Unable to resolve attribute '{}'", getId(), allSourceIdentifiersRef);
                continue;
            }

            for (Object value : attribute.getValues()) {
                if (value == null) {
                    throw new PspException("TODO null value");
                }

                String id = null;
                if (value instanceof PSOIdentifier) {
                    id = ((PSOIdentifier) value).getID();
                } else {
                    id = value.toString();
                }

                if (!identifierMap.containsKey(id)) {
                    identifierMap.put(id, new ArrayList<SchemaEntityRef>());
                }

                SchemaEntityRef entity = new SchemaEntityRef();
                entity.setEntityName(psoDefinition.getId());
                entity.setTargetID(targetId);

                identifierMap.get(id).add(entity);
            }
        }
    }

    return identifierMap;
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * A very simple crawler, pulling URLs to fetch from a backlog and then
 * recurses N levels deep if recursive>0. Links are parsed from HTML
 * through first getting an XHTML version using SolrCell with extractOnly,
 * and followed if they are local. The crawler pauses for a default delay
 * of 10 seconds between each fetch, this can be configured in the delay
 * variable. This is only meant for test purposes, as it does not respect
 * robots or anything else fancy :)/*w ww.j av  a  2 s  . com*/
 * @param level which level to crawl
 * @param out output stream to write to
 * @return number of pages crawled on this level and below
 */
protected int webCrawl(int level, OutputStream out) {
    int numPages = 0;
    LinkedHashSet<URL> stack = backlog.get(level);
    int rawStackSize = stack.size();
    stack.removeAll(visited);
    int stackSize = stack.size();
    LinkedHashSet<URL> subStack = new LinkedHashSet<>();
    info("Entering crawl at level " + level + " (" + rawStackSize + " links total, " + stackSize + " new)");
    for (URL u : stack) {
        try {
            visited.add(u);
            PageFetcherResult result = pageFetcher.readPageFromUrl(u);
            if (result.httpStatus == 200) {
                u = (result.redirectUrl != null) ? result.redirectUrl : u;
                URL postUrl = new URL(
                        appendParam(solrUrl.toString(), "literal.id=" + URLEncoder.encode(u.toString(), "UTF-8")
                                + "&literal.url=" + URLEncoder.encode(u.toString(), "UTF-8")));
                boolean success = postData(new ByteArrayInputStream(result.content), null, out,
                        result.contentType, postUrl);
                if (success) {
                    info("POSTed web resource " + u + " (depth: " + level + ")");
                    Thread.sleep(delay * 1000);
                    numPages++;
                    // Pull links from HTML pages only
                    if (recursive > level && result.contentType.equals("text/html")) {
                        Set<URL> children = pageFetcher.getLinksFromWebPage(u,
                                new ByteArrayInputStream(result.content), result.contentType, postUrl);
                        subStack.addAll(children);
                    }
                } else {
                    warn("An error occurred while posting " + u);
                }
            } else {
                warn("The URL " + u + " returned a HTTP result status of " + result.httpStatus);
            }
        } catch (IOException e) {
            warn("Caught exception when trying to open connection to " + u + ": " + e.getMessage());
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }
    if (!subStack.isEmpty()) {
        backlog.add(subStack);
        numPages += webCrawl(level + 1, out);
    }
    return numPages;
}

From source file:net.rim.ejde.internal.packaging.PackagingJob.java

@Override
public void run(IProgressMonitor monitor) throws CoreException {
    // remove the code signing error
    ResourceBuilderUtils.cleanProblemMarkers(ResourcesPlugin.getWorkspace().getRoot(),
            new String[] { IRIMMarker.SIGNATURE_TOOL_PROBLEM_MARKER }, IResource.DEPTH_ONE);
    // open the packaging console
    PackagingConsole.getInstance().activate();
    LinkedHashSet<BlackBerryProject> projectSet = ProjectUtils.getProjectsByBuildOrder(_projects);
    monitor.beginTask(IConstants.EMPTY_STRING, projectSet.size() * 10);
    monitor.subTask(Messages.PackagingJob_Name);
    boolean needSign = false;
    // collect projects which need to be signed
    LinkedHashSet<BlackBerryProject> projectsNeedSigning = new LinkedHashSet<BlackBerryProject>();
    // collect projects whose dependent projects need to be signed
    LinkedHashSet<BlackBerryProject> projectsDependencyNeedSigning = new LinkedHashSet<BlackBerryProject>();
    // collect projects which are packaged successfully
    LinkedHashSet<BlackBerryProject> succesfullyPackagedProjects = new LinkedHashSet<BlackBerryProject>();
    for (BlackBerryProject bbProject : projectSet) {
        // 1. run java build on the project
        if (!isBuildAutomaticallyOn()) {
            try {
                bbProject.getProject().build(IncrementalProjectBuilder.AUTO_BUILD,
                        new SubProgressMonitor(monitor, 1));
            } catch (CoreException e) {
                _log.error(e);/*from   ww  w  .java 2  s  .  com*/
            }
        }
        monitor.worked(3);
        // 2. package the project
        if (!needPackaging(bbProject)) {
            if (needGenerateALXFile(bbProject)) {
                PackagingManager.generateALXForProject(bbProject);
            }
        } else {
            // remove the package problems
            ResourceBuilderUtils.cleanProblemMarkers(bbProject.getProject(),
                    new String[] { IRIMMarker.PACKAGING_PROBLEM }, IResource.DEPTH_INFINITE);
            try {
                PackagingManager.packageProject(bbProject);
                if (!needSign) {
                    needSign = true;
                }
            } catch (CoreException e) {
                _log.error(e.getMessage());
                try {
                    ResourceBuilderUtils.createProblemMarker(
                            e.getStatus().getCode() == DiagnosticFactory.CREATE_FOLDER_ERR_ID
                                    ? bbProject.getMetaFileHandler()
                                    : bbProject.getProject(),
                            IRIMMarker.PACKAGING_PROBLEM, e.getMessage(), -1, IMarker.SEVERITY_ERROR);
                } catch (Exception e1) {
                    _log.error(e1.getMessage());
                }
            }
            PackagingJob.setBuiltByJavaBuilders(bbProject.getProject(), false);
        }
        monitor.worked(4);
        // 3. run post-build command
        runPostBuild(bbProject);
        monitor.worked(1);
        // 4. check if the project needs to be signed or not
        if (!hasPackagingProblems(bbProject.getProject())) {
            succesfullyPackagedProjects.add(bbProject);
            if (PackagingUtils.isSigningNeeded(bbProject)) {
                projectsNeedSigning.add(bbProject);
            } else {
                if (PackagingUtils.isSigningNeededForDependency(bbProject)) {
                    projectsDependencyNeedSigning.add(bbProject);
                } else {
                    // if a project and its dependent projects do not need to be signed, copy the cod files to the web folder
                    // copy the cod files of dependency projects to the deployment folders
                    copyDependencyDeploymentFiles(bbProject);
                    // copy files from "Standard" to "Web"
                    copyToWebDeploymentFolder(bbProject);
                }
            }
        }
        monitor.worked(2);
        if (monitor.isCanceled()) {
            monitor.done();
            return;
        }
    }
    // Code signing
    switch (_signingFlag) {
    case SIGN_FORCE: {
        if (!succesfullyPackagedProjects.isEmpty()) {
            signCodFile(succesfullyPackagedProjects, monitor);
        }
        break;
    }
    case SIGN_IF_PROTECTED_API_USED: {
        if (!projectsNeedSigning.isEmpty()) {
            signCodFile(projectsNeedSigning, monitor);
            for (BlackBerryProject project : projectsDependencyNeedSigning) {
                // copy the cod files of dependency projects to the deployment folders
                copyDependencyDeploymentFiles(project);
                // copy files from "Standard" to "Web"
                copyToWebDeploymentFolder(project);
            }
        }
        break;
    }
    case SIGN_IF_NECESSARY: {
        if (needSign) {
            if (!projectsNeedSigning.isEmpty()) {
                signCodFile(projectsNeedSigning, monitor);
                for (BlackBerryProject project : projectsDependencyNeedSigning) {
                    // copy the cod files of dependency projects to the deployment folders
                    copyDependencyDeploymentFiles(project);
                    // copy files from "Standard" to "Web"
                    copyToWebDeploymentFolder(project);
                }
            }
        }
        break;
    }
    }
    monitor.done();
    return;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

@Override
public void updateEventObject(int calendarId, String href, net.fortuna.ical4j.model.Calendar iCalendar)
        throws WTException {
    final UserProfile.Data udata = WT.getUserData(getTargetProfileId());
    int eventId = getEventIdByCategoryHref(calendarId, href, true);

    ICalendarInput in = new ICalendarInput(udata.getTimeZone()).withDefaultAttendeeNotify(true)
            .withIncludeVEventSourceInOutput(true);
    ArrayList<EventInput> eis = in.fromICalendarFile(iCalendar, null);
    if (eis.isEmpty())
        throw new WTException("iCalendar object does not contain any events");

    EventInput refInput = eis.remove(0);
    if (refInput.exRefersToPublicUid != null)
        throw new WTException("First iCalendar event should not have a RECURRENCE-ID set");

    // Collect dates exceptions and prepare broken event to be inserted
    ArrayList<EventInput> eiExs = new ArrayList<>();
    LinkedHashSet<LocalDate> exDates = new LinkedHashSet<>();
    for (EventInput ei : eis) {
        if (!StringUtils.equals(ei.exRefersToPublicUid, refInput.event.getPublicUid()))
            continue;
        if (exDates.contains(ei.addsExOnMaster))
            continue;

        exDates.add(ei.addsExOnMaster);//  w  w w. j  a v a  2 s.c om
        if (!ei.isSourceEventCancelled())
            eiExs.add(ei);
    }

    // Adds new collected exceptions and then updates master event
    if (!exDates.isEmpty()) {
        if (refInput.event.hasExcludedDates()) {
            refInput.event.getExcludedDates().addAll(exDates);
        } else {
            refInput.event.setExcludedDates(exDates);
        }
    }
    refInput.event.setEventId(eventId);
    refInput.event.setCalendarId(calendarId);
    refInput.event.setExcludedDates(exDates);
    updateEvent(refInput.event, true);

    // Here we do not support creating broken events related to the
    // main event series (re-attach unavailable). Instance exceptions 
    // should have been created above as date exception into the main
    // event; so simply create exceptions as new events.

    if (!eiExs.isEmpty()) {
        for (EventInput eiEx : eiExs) {
            eiEx.event.setCalendarId(calendarId);
            eiEx.event.setPublicUid(null); // reset uid
            //TODO: handle raw value to persist custom properties
            try {
                addEvent(eiEx.event, null, true);
            } catch (Throwable t) {
                logger.error("Unable to insert exception on {} as new event", eiEx.addsExOnMaster, t);
            }
        }
    }
}