Example usage for java.util Set remove

List of usage examples for java.util Set remove

Introduction

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

Prototype

boolean remove(Object o);

Source Link

Document

Removes the specified element from this set if it is present (optional operation).

Usage

From source file:edu.cornell.mannlib.vitro.webapp.visualization.coprincipalinvestigator.CoPIVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode// ww  w  .  ja v  a2 s .com
 * @param visContainer
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which
     * the vis was rendered we dont want to be influenced by the
     * "DEFAULT_GRANT_YEAR".
     */
    Set<String> investigatedYears = new HashSet<String>(yearToUniqueCoPIs.keySet());
    investigatedYears.remove(VOConstants.DEFAULT_GRANT_YEAR);

    /*
     * We are setting the default value of minGrantYear to be 10 years
     * before the current year (which is suitably represented by the
     * shortSparkMinYear), this in case we run into invalid set of investigated
     * years.
     */
    int minGrantYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToUniqueCoPIs.size() > 0) {
        try {
            minGrantYear = Integer.parseInt(Collections.min(investigatedYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToUniqueCoPIs.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToUniqueCoPIs.toString());
        }
    }

    int minGrantYearConsidered = 0;

    /*
     * There might be a case that the person investigated his first grant
     * within the last 10 years but we want to make sure that the sparkline
     * is representative of at least the last 10 years, so we will set the
     * minGrantYearConsidered to "currentYear - 10" which is also given by
     * "shortSparkMinYear".
     */
    if (minGrantYear > shortSparkMinYear) {
        minGrantYearConsidered = shortSparkMinYear;
    } else {
        minGrantYearConsidered = minGrantYear;
    }

    numOfYearsToBeRendered = currentYear - minGrantYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int uniqueCoPICounter = 0;
    Set<Collaborator> allCoPIsWithKnownGrantShipYears = new HashSet<Collaborator>();
    List<YearToEntityCountDataElement> yearToUniqueInvestigatorsCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int grantYear = minGrantYearConsidered; grantYear <= currentYear; grantYear++) {

        String grantYearAsString = String.valueOf(grantYear);
        Set<Collaborator> currentCoPIs = yearToUniqueCoPIs.get(grantYearAsString);

        Integer currentUniqueCoPIs = null;

        if (currentCoPIs != null) {
            currentUniqueCoPIs = currentCoPIs.size();
            allCoPIsWithKnownGrantShipYears.addAll(currentCoPIs);
        } else {
            currentUniqueCoPIs = 0;
        }

        yearToUniqueInvestigatorsCountDataTable.add(
                new YearToEntityCountDataElement(uniqueCoPICounter, grantYearAsString, currentUniqueCoPIs));

        uniqueCoPICounter++;
    }

    /*
     * For the purpose of this visualization I have come up with a term
     * "Sparks" which essentially means data points. Sparks that will be
     * rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     */
    sparklineData.setRenderedSparks(allCoPIsWithKnownGrantShipYears.size());

    sparklineData.setYearToEntityCountDataTable(yearToUniqueInvestigatorsCountDataTable);

    /*
     * This is required only for the sparklines which convey collaborationships like 
     * coinvestigatorships and coauthorship. There are edge cases where a collaborator can be 
     * present for in a collaboration with known & unknown year. We do not want to repeat the 
     * count for this collaborator when we present it in the front-end. 
     * */
    Set<Collaborator> totalUniqueCoInvestigators = new HashSet<Collaborator>(allCoPIsWithKnownGrantShipYears);

    /*
     * Total grants will also consider grants that have no year
     * associated with them. Hence.
     */
    Integer unknownYearGrants = 0;
    if (yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR) != null) {
        unknownYearGrants = yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR).size();
        totalUniqueCoInvestigators.addAll(yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR));
    }

    sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());

    sparklineData.setUnknownYearGrants(unknownYearGrants);

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in
     * case of "short" sparkline mode we will set the Earliest
     * RenderedGrant year to "currentYear - 10".
     */
    sparklineData.setEarliestYearConsidered(minGrantYearConsidered);
    sparklineData.setEarliestRenderedGrantYear(minGrantYear);
    sparklineData.setLatestRenderedGrantYear(currentYear);

    /*
     * The Full Sparkline will be rendered by default. Only if the url has
     * specific mention of SHORT_SPARKLINE_MODE_KEY then we render the short
     * sparkline and not otherwise.
     */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedGrantYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    if (yearToUniqueCoPIs.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COPI_VIS_MODE));

        sparklineData.setDownloadDataLink(
                UtilityFunctions.getCSVDownloadURL(individualURI, VisualizationFrameworkConstants.CO_PI_VIS,
                        VisualizationFrameworkConstants.COPIS_COUNT_PER_YEAR_VIS_MODE));

        Map<String, Integer> yearToUniqueCoPIsCount = new HashMap<String, Integer>();
        for (Map.Entry<String, Set<Collaborator>> currentYearToUniqueCoPIsCount : yearToUniqueCoPIs
                .entrySet()) {

            yearToUniqueCoPIsCount.put(currentYearToUniqueCoPIsCount.getKey(),
                    currentYearToUniqueCoPIsCount.getValue().size());
        }

        sparklineData.setYearToActivityCount(yearToUniqueCoPIsCount);

    }

    return sparklineData;
}

From source file:edu.uci.ics.hyracks.api.client.impl.ActivityClusterGraphBuilder.java

private void merge(Map<ActivityId, Set<ActivityId>> eqSetMap, Set<Set<ActivityId>> eqSets, ActivityId t1,
        ActivityId t2) {/* w w w . j  a v  a  2 s .c o m*/
    Set<ActivityId> stage1 = eqSetMap.get(t1);
    Set<ActivityId> stage2 = eqSetMap.get(t2);

    Set<ActivityId> mergedSet = new HashSet<ActivityId>();
    mergedSet.addAll(stage1);
    mergedSet.addAll(stage2);

    eqSets.remove(stage1);
    eqSets.remove(stage2);
    eqSets.add(mergedSet);

    for (ActivityId t : mergedSet) {
        eqSetMap.put(t, mergedSet);
    }
}

From source file:de.codecentric.boot.admin.discovery.ApplicationDiscoveryListener.java

protected void discover() {
    final Set<String> staleApplicationIds = getAllApplicationIdsFromRegistry();
    for (String serviceId : discoveryClient.getServices()) {
        if (!ignoredServices.contains(serviceId)) {
            for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
                String applicationId = register(instance);
                staleApplicationIds.remove(applicationId);
            }/*from  w ww  . j  a v  a  2s .  c  om*/
        }
    }
    for (String staleApplicationId : staleApplicationIds) {
        LOGGER.info("Application ({}) missing in DiscoveryClient services ", staleApplicationId);
        registry.deregister(staleApplicationId);
    }
}

From source file:helma.swarm.SwarmSessionManager.java

void broadcastIds(int operation, Set idSet) {
    try {//from  w w w . j  av a2  s .c  o m
        if (!idSet.isEmpty()) {
            Object[] ids = idSet.toArray();
            for (int i = 0; i < ids.length; i++)
                idSet.remove(ids[i]);
            Serializable idlist = new SessionIdList(operation, ids);
            adapter.send(new Message(null, address, idlist));
        }
    } catch (Exception x) {
        log.error("Error broadcasting session list", x);
    }
}

From source file:com.capstone.giveout.controllers.GiftsController.java

@PreAuthorize("hasRole(mobile)")
@RequestMapping(value = Routes.GIFTS_TOUCH_PATH, method = RequestMethod.PUT)
public @ResponseBody Gift touchOrUntouch(@PathVariable("id") long id,
        @RequestParam(value = Routes.REGRET_PARAMETER, required = false, defaultValue = "false") boolean regret,
        Principal p, HttpServletResponse response) {
    Gift gift = gifts.findOne(id);//from  ww w. ja  va 2 s  .  co  m
    if (gift == null) {
        response.setStatus(404);
        return null;
    }
    gift.allowAccessToGiftChain = true;

    long userId = users.findByUsername(p.getName()).getId();
    Set<Long> touchedBy = gift.getTouchedByUserIds();

    // Touching or untouching more than once will have no effect.
    if (regret) {
        touchedBy.remove(userId);
    } else {
        touchedBy.add(userId);
    }

    gifts.save(gift);
    return gift;
}

From source file:org.shredzone.cilla.ws.impl.PageWsImpl.java

/**
 * Commits all sections of a page.//  w  w w. j ava 2 s.c om
 *
 * @param dto
 *            {@link PageDto} containing the sections
 * @param entity
 *            {@link Page} to commit the sections to
 */
private void commitSections(PageDto dto, Page entity) throws CillaServiceException {
    Set<Section> deletableSec = new HashSet<>(entity.getSections());
    for (SectionDto sec : dto.getSections()) {
        Section persistedSec = sectionFacade.persistSection(sec, entity);
        deletableSec.remove(persistedSec);
    }
    for (Section deleteSec : deletableSec) {
        sectionFacade.deleteSection(deleteSec);
    }
}

From source file:org.zenoss.zep.impl.PluginServiceImpl.java

/**
 * Recursive method used to find plug-in cycles.
 *
 * @param plugins/* ww w  .ja  v  a  2s. co  m*/
 *            The plug-ins to analyze.
 * @param existingDeps
 *            Any existing dependencies which will be scanned to avoid
 *            {@link MissingDependencyException} from being thrown.
 * @param plugin
 *            The plug-in which is currently being analyzed.
 * @param analyzed
 *            The previously analyzed plug-ins which are not analyzed again.
 * @param dependencies
 *            The current dependency chain which is being analyzed.
 * @throws MissingDependencyException
 *             If a missing dependency is discovered.
 * @throws DependencyCycleException
 *             If a cycle in dependencies is detected.
 */
private static void detectPluginCycles(Map<String, ? extends EventPlugin> plugins, Set<String> existingDeps,
        EventPlugin plugin, Set<String> analyzed, Set<String> dependencies)
        throws MissingDependencyException, DependencyCycleException {
    // Don't detect cycles again on the same plug-in.
    if (!analyzed.add(plugin.getId())) {
        return;
    }
    dependencies.add(plugin.getId());
    Set<String> pluginDependencies = plugin.getDependencies();
    if (pluginDependencies != null) {
        for (String dependencyId : pluginDependencies) {
            EventPlugin dependentPlugin = plugins.get(dependencyId);
            if (dependentPlugin == null) {
                if (!existingDeps.contains(dependencyId)) {
                    throw new MissingDependencyException(plugin.getId(), dependencyId);
                }
            } else {
                if (dependencies.contains(dependencyId)) {
                    throw new DependencyCycleException(dependencyId);
                }
                detectPluginCycles(plugins, existingDeps, dependentPlugin, analyzed, dependencies);
            }
        }
    }
    dependencies.remove(plugin.getId());
}

From source file:com.michelin.cio.hudson.plugins.rolestrategy.RoleMap.java

/**
 * Clear all the roles associated to the given sid
 * @param sid The sid for thwich you want to clear the {@link Role}s
 *///from   w  w  w  .  j  a  v  a 2s  . c om
public void deleteSids(String sid) {
    for (Map.Entry<Role, Set<String>> entry : grantedRoles.entrySet()) {
        Role role = entry.getKey();
        Set<String> sids = entry.getValue();
        if (sids.contains(sid)) {
            sids.remove(sid);
        }
    }
}

From source file:com.imaginea.mongodb.controllers.DocumentController.java

/**
 * Maps GET Request to get all keys of document inside a collection inside a
 * database present in mongo db to a service function that returns the list.
 * Also forms the JSON response for this request and sent it to client. In
 * case of any exception from the service files an error object if formed.
 *
 * @param dbName         Name of Database
 * @param collectionName Name of Collection
 * @param connectionId   Mongo Db Configuration provided by user to connect to.
 * @param request        Get the HTTP request context to extract session parameters
 * @return A String of JSON format with all keys in a collection.
 *//*from www . j  a v  a2s.  c o  m*/
@GET
@Path("/keys")
@Produces(MediaType.APPLICATION_JSON)
public String getKeysRequest(@PathParam("dbName") final String dbName,
        @PathParam("collectionName") final String collectionName, @QueryParam("allKeys") final Boolean allKeys,
        @QueryParam("connectionId") final String connectionId, @Context final HttpServletRequest request) {

    String response = new ResponseTemplate().execute(logger, connectionId, request, new ResponseCallback() {
        public Object execute() throws Exception {
            // Perform the operation here only.
            Mongo mongoInstance = authService.getMongoInstance(connectionId);
            long count = mongoInstance.getDB(dbName).getCollection(collectionName).count();
            DBCursor cursor = mongoInstance.getDB(dbName).getCollection(collectionName).find();
            if (!allKeys)
                cursor.limit(10);
            DBObject doc = new BasicDBObject();
            Set<String> completeSet = new HashSet<String>();
            while (cursor.hasNext()) {
                doc = cursor.next();
                getNestedKeys(doc, completeSet, "");
            }
            completeSet.remove("_id");
            JSONObject result = new JSONObject();
            result.put("keys", completeSet);
            result.put("count", count);
            return result;
        }
    });
    return response;
}

From source file:com.qcadoo.model.internal.units.UnitConversionServiceImpl.java

private Set<UnitConversion> findMatchingConversions(final String unitToFind, final Set<UnitConversion> domain) {
    Preconditions.checkArgument(StringUtils.isNotEmpty(unitToFind));
    final Set<UnitConversion> matchingConversions = Sets.newHashSet();
    for (final UnitConversion unitConversion : Sets.newHashSet(domain)) {
        if (unitToFind.equals(unitConversion.getUnitFrom())) {
            matchingConversions.add(unitConversion);
            domain.remove(unitConversion);
        } else if (unitToFind.equals(unitConversion.getUnitTo())) {
            matchingConversions.add(unitConversion.reverse());
            domain.remove(unitConversion);
        }/*from ww w  .  j  ava  2 s  .com*/
    }
    return matchingConversions;
}