Example usage for java.util Set removeAll

List of usage examples for java.util Set removeAll

Introduction

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

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this set all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:ch.unil.genescore.pathway.GeneSetLibrary.java

License:asdf

/** Compute enrichment for the given set using rank-sum-Test */
private void computeRankSumPvalue(GeneSet set) {

    Set<Gene> complementSet = new HashSet<Gene>(genesForSimulation_);
    complementSet.removeAll(set.genes_);
    double[] complementVals = new double[complementSet.size()];
    double[] setVals = new double[set.genes_.size()];
    int count = 0;
    for (Gene g : set.genes_) {
        setVals[count] = g.getChi2Stat();
        count++;//from  w ww . j  a  va  2  s .c om
    }
    count = 0;
    for (Gene g : complementSet) {
        complementVals[count] = g.getChi2Stat();
        count++;
    }
    //   TODO cleanup
    double pval = 1;
    double pval6 = 1;

    MannWhitneyUTest test = new MannWhitneyUTest();
    try {
        pval = test.mannWhitneyUTest(setVals, complementVals);
        RankSumTest test2 = new RankSumTest();
        double pval2 = test2.pValue("greater", setVals, complementVals);
        double pval3 = test2.pValue("equal", setVals, complementVals);
        MannWhitneyTest test3 = new MannWhitneyTest(setVals, complementVals);
        double pval5 = test3.approxSP();
        MannWhitneyTest test4 = new MannWhitneyTest(setVals, complementVals, H1.GREATER_THAN);
        pval6 = test4.approxSP();
    } catch (Exception e) {

        System.out.println("Couldn't compute ManWhitneyU:" + e.getMessage());
    }

    set.setRankSumPvalue(pval6);
}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.ResourceManager.java

/**
 * Try to remove the resource parameter and its children. Operation is recursive.
 * If one of the derived resources is already in use, an exception is thrown.
 * @param rpId/* www. j a  v a 2  s  . c  o  m*/
 */
public void removeResourceParameter(Long rpId) {
    // main parameter
    ResourceParameter rpdb = resourceParameterRepository.findOne(rpId);
    if (rpdb != null) {
        String clientId = rpdb.getClientId();
        Set<String> ids = new HashSet<String>();
        Set<String> scopes = new HashSet<String>();
        // aggregate all derived resource uris
        Collection<String> uris = findResourceURIs(rpdb).keySet();
        for (String uri : uris) {
            Resource r = resourceRepository.findByResourceUri(uri);
            if (r != null) {
                ids.add(r.getResourceId().toString());
                scopes.add(r.getResourceUri());
            }
        }
        ClientDetailsEntity owner = null;
        // check the resource uri usages
        for (ClientDetailsEntity cd : clientDetailsRepository.findAll()) {
            if (cd.getClientId().equals(clientId)) {
                owner = cd;
                continue;
            }
            if (!Collections.disjoint(cd.getResourceIds(), ids)) {
                throw new IllegalArgumentException("Resource is in use by other client app.");
            }
        }
        // delete main and its children
        for (String id : ids) {
            resourceRepository.delete(Long.parseLong(id));
        }
        if (owner != null) {
            Set<String> oldScopes = new HashSet<String>(owner.getScope());
            oldScopes.removeAll(scopes);
            owner.setScope(StringUtils.collectionToCommaDelimitedString(oldScopes));
            Set<String> oldIds = new HashSet<String>(owner.getResourceIds());
            oldIds.removeAll(ids);
            owner.setResourceIds(StringUtils.collectionToCommaDelimitedString(oldIds));
            clientDetailsRepository.save(owner);

        }
        resourceParameterRepository.delete(rpdb);
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

private void updateStocksAndQuotesFromYahoo(Set<StockProduct> askedContent) {
    if (askedContent.isEmpty()) {
        return;/*from  w  w  w.  j a v  a2  s  .c o m*/
    }

    Set<StockProduct> recentlyUpdated = askedContent.stream()
            .filter(t -> t.getLastUpdate() != null && DateUtil.isRecent(t.getLastUpdate(), 1))
            .collect(Collectors.toSet());

    if (askedContent.size() != recentlyUpdated.size()) {

        String guid = AuthenticationUtil.getPrincipal().getUsername();

        String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
        ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
        Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

        if (connection != null) {
            askedContent.removeAll(recentlyUpdated);

            Map<String, StockProduct> updatableTickers = askedContent.stream()
                    .collect(Collectors.toMap(StockProduct::getId, Function.identity()));

            List<YahooQuote> yahooQuotes = connection.getApi().financialOperations()
                    .getYahooQuotes(new ArrayList<String>(updatableTickers.keySet()), token);

            Set<StockProduct> updatableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isNotBlank(yq.getExchange()))
                    .filter(yq -> updatableTickers.get(yq.getId()) != null).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!updatableProducts.isEmpty()) {
                stockProductRepository.save(updatableProducts);
            }

            //This job below should decrease with the time
            Set<StockProduct> removableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isBlank(yq.getExchange())).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!removableProducts.isEmpty()) {
                stockProductRepository.delete(removableProducts);
            }
        }
    }
}

From source file:cz.cuni.amis.planning4j.external.impl.itsimple.ItSimplePlanningProcess.java

/**
 * Spawns a new planner process and sets {@link #processPid} to it's PID. To work correctly,
 * the code relies on the fact that no other method in this JVM runs processes with names
 * that would be correspond to our planners and
 * that no method kills a process unless it acquires lock on spawnProcessMutex.
 * @param procBuilder//from  w  ww.j a  v  a2  s. co  m
 * @param identifying process name / command line fragment
 * @return 
 */
private Process spawnPlanner(ProcessBuilder procBuilder, String processCommandFragment) throws IOException {
    synchronized (spawnProcessMutex) {
        JavaSysMon monitor = new JavaSysMon();
        DirectPlannerChildVisitor beforeVisitor = new DirectPlannerChildVisitor(processCommandFragment);
        monitor.visitProcessTree(monitor.currentPid(), beforeVisitor);
        Set<Integer> alreadySpawnedProcesses = beforeVisitor.getPids();

        Process proc = procBuilder.start();

        DirectPlannerChildVisitor afterVisitor = new DirectPlannerChildVisitor(processCommandFragment);

        Set<Integer> newProcesses = afterVisitor.getPids();
        long startTime = System.currentTimeMillis();
        while (newProcesses.isEmpty() && System.currentTimeMillis() - startTime < PROCESS_SPAWN_TIMEOUT) {
            monitor.visitProcessTree(monitor.currentPid(), afterVisitor);
            newProcesses = afterVisitor.getPids();

            newProcesses.removeAll(alreadySpawnedProcesses);
        }

        if (newProcesses.isEmpty()) {
            logger.warn("There is no new planner PID.");
        } else if (newProcesses.size() > 1) {
            logger.warn("Multiple new candidate planner PIDs");
        } else {
            processPid = newProcesses.iterator().next();
        }
        logger.info("Spawned planning process. Pid:" + processPid);
        return proc;
    }
}

From source file:org.waarp.common.filemonitor.FileMonitor.java

/**
 * /*from ww  w  . j  av a2 s .c o m*/
 * @return the status (updated only) in JSON format
 */
public String getStatus() {
    Set<String> removedFileItems = null;
    ConcurrentHashMap<String, FileItem> newFileItems = new ConcurrentHashMap<String, FileMonitor.FileItem>();
    if (!lastFileItems.isEmpty()) {
        removedFileItems = lastFileItems.keySet();
        removedFileItems.removeAll(fileItems.keySet());
        for (Entry<String, FileItem> key : fileItems.entrySet()) {
            if (!key.getValue().isStrictlySame(lastFileItems.get(key.getKey()))) {
                newFileItems.put(key.getKey(), key.getValue());
            }
        }
    } else {
        for (Entry<String, FileItem> key : fileItems.entrySet()) {
            newFileItems.put(key.getKey(), key.getValue());
        }
    }
    FileMonitorInformation fileMonitorInformation = new FileMonitorInformation(name, newFileItems,
            removedFileItems, directories, stopFile, statusFile, elapseTime, scanSubDir, globalok, globalerror,
            todayok, todayerror);
    for (Entry<String, FileItem> key : fileItems.entrySet()) {
        FileItem clone = key.getValue().clone();
        lastFileItems.put(key.getKey(), clone);
    }
    createChkFile();
    String status = JsonHandler.writeAsString(fileMonitorInformation);
    if (removedFileItems != null) {
        removedFileItems.clear();
    }
    newFileItems.clear();
    return status;
}

From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java

private void updateStocksAndQuotesFromYahoo(Set<StockProduct> askedContent) {
    if (askedContent.isEmpty()) {
        return;//from  w w  w .  j  a v  a 2  s . com
    }

    Set<StockProduct> recentlyUpdated = askedContent.stream()
            .filter(t -> t.getLastUpdate() != null && DateUtil.isRecent(t.getLastUpdate(), 1))
            .collect(Collectors.toSet());

    if (askedContent.size() != recentlyUpdated.size()) {

        String guid = AuthenticationUtil.getPrincipal().getUsername();
        SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
        if (socialUser == null) {
            return;
        }
        String token = socialUser.getAccessToken();
        Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

        if (connection != null) {
            askedContent.removeAll(recentlyUpdated);

            Map<String, StockProduct> updatableTickers = askedContent.stream()
                    .collect(Collectors.toMap(StockProduct::getId, Function.identity()));

            List<YahooQuote> yahooQuotes = connection.getApi().financialOperations()
                    .getYahooQuotes(new ArrayList<String>(updatableTickers.keySet()), token);

            Set<StockProduct> updatableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isNotBlank(yq.getExchange()))
                    .filter(yq -> updatableTickers.get(yq.getId()) != null).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!updatableProducts.isEmpty()) {
                stockProductRepository.save(updatableProducts);
            }

            //This job below should decrease with the time
            Set<StockProduct> removableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isBlank(yq.getExchange())).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!removableProducts.isEmpty()) {
                stockProductRepository.delete(removableProducts);
            }
        }
    }
}

From source file:webim.controller.WebimController.java

@RequestMapping(value = "/online", method = RequestMethod.POST)
@ResponseBody/*from   w  w  w  . j  a  va 2s  .  co  m*/
public Map<String, Object> online(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println("online.....");
    WebimEndpoint endpoint = currentEndpoint(request, response);
    String uid = endpoint.getId();
    String show = request.getParameter("show");
    if (show != null) {
        endpoint.setShow(show);
    }
    Map<String, Object> data = new HashMap<String, Object>();
    List<WebimEndpoint> buddies = this.plugin.buddies(uid);

    //pending buddies ids that need to read buddy
    Set<String> pendingIds = new HashSet<String>();
    String chatlinkIds = request.getParameter("chatlink_ids");
    if (chatlinkIds != null) {
        for (String id : chatlinkIds.split(",")) {
            pendingIds.add(id);
        }
        ;
    }
    List<WebimHistory> offlineHistories = this.model.offlineHistories(uid, 100);
    for (WebimHistory h : offlineHistories) {
        pendingIds.add(h.getFrom());
    }
    pendingIds.removeAll(buddyIds(buddies));

    if (pendingIds.size() > 0) {
        buddies.addAll(this.plugin.buddiesByIds(uid, pendingIds.toArray(new String[pendingIds.size()])));
    }

    List<WebimRoom> rooms = this.plugin.rooms(uid);
    rooms.addAll(this.model.rooms(uid));
    // Forward Online to IM Server
    WebimClient client = this.client(endpoint, request, "");
    Set<String> buddyIds = buddyIds(buddies);
    Set<String> roomIds = roomIds(rooms);
    try {
        data = client.online(buddyIds, roomIds);
        System.out.println(data.toString());

        // Online Buddies
        Map<String, WebimEndpoint> buddyMap = new HashMap<String, WebimEndpoint>();
        for (WebimEndpoint e : buddies) {
            buddyMap.put(e.getId(), e);
        }

        @SuppressWarnings("unchecked")
        Map<String, String> presences = (Map<String, String>) data.get("presences");
        Iterator<String> it = presences.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            WebimEndpoint buddy = buddyMap.get(key);
            show = presences.get(key);
            if (!show.equals("invisible")) {
                buddy.setPresence("online");
                buddy.setShow(show);
            }
        }

        Collection<WebimEndpoint> rtBuddies;
        if (this.config.getBoolean("show_unavailable")) {
            rtBuddies = buddyMap.values();
        } else {
            rtBuddies = new ArrayList<WebimEndpoint>();
            for (WebimEndpoint e : buddyMap.values()) {
                if (e.getPresence() == "online")
                    rtBuddies.add(e);
            }
        }
        // need test
        this.model.offlineHistoriesReaded(uid);
        //data.remove("presences");
        data.put("buddies", rtBuddies.toArray());
        data.put("rooms", rooms.toArray());
        data.put("new_messages", offlineHistories.toArray());
        data.put("server_time", System.currentTimeMillis()); // TODO: /
        data.put("user", endpoint);
    } catch (Exception e) {
        e.printStackTrace();
        data.put("success", false);
        data.put("error_msg", "IM Server is not found");
    }
    return data;
}

From source file:com.aurel.track.item.ItemBL.java

/**
 * Get all descendants which are not included in the original query result
 * @param baseWorkItemIDsArr//from   ww  w  . j a  v a2 s  .c o  m
 * @return
 */
public static List<TWorkItemBean> getAncestorItems(int[] baseWorkItemIDsArr) {
    List<TWorkItemBean> ancestorWorkItemBeans = new LinkedList<TWorkItemBean>();
    Set<Integer> allDescendentIDsSet = new HashSet<Integer>();
    Set<Integer> directChildrenIDsSet;
    int[] directChildrenArr = baseWorkItemIDsArr;
    Set<Integer> toRemoveSet = GeneralUtils.createSetFromIntArr(baseWorkItemIDsArr);
    do {
        //get the next level of children workItems
        List<TWorkItemBean> childWorkItemBeans = getChildren(directChildrenArr, false, null, null, null);
        ancestorWorkItemBeans.addAll(childWorkItemBeans);
        //get the ID set of children
        directChildrenIDsSet = GeneralUtils.createIntegerSetFromBeanList(childWorkItemBeans);
        //remove the children which are already present in the gathered list (theoretically remove might occur only first time)
        directChildrenIDsSet.removeAll(toRemoveSet);

        //gather the not yet present children to the list
        allDescendentIDsSet.addAll(directChildrenIDsSet);
        toRemoveSet = allDescendentIDsSet;
        directChildrenArr = GeneralUtils.createIntArrFromSet(directChildrenIDsSet);
    } while (directChildrenIDsSet != null && !directChildrenIDsSet.isEmpty());
    return ancestorWorkItemBeans;
}

From source file:org.itracker.services.implementations.UserServiceImpl.java

/**
 * @param userId         - id of update-user
 * @param newPermissions - set of new permissions for this user
 *//*from w  w w.  jav a2 s . c om*/
@Override
public boolean setUserPermissions(final Integer userId, final List<Permission> newPermissions) {

    boolean hasChanges = false;
    // rewriting this method

    TreeSet<Permission> pSet = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
    pSet.addAll(newPermissions);

    User usermodel = this.getUser(userId);

    Set<Permission> current = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);

    current.addAll(usermodel.getPermissions());

    // setup permissions to be removed
    Set<Permission> remove = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
    remove.addAll(current);
    remove.removeAll(pSet);
    // setup permissions to be added
    Set<Permission> add = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
    add.addAll(pSet);
    add.removeAll(current);

    // look permission
    Permission p;
    Iterator<Permission> pIt = remove.iterator();
    while (pIt.hasNext()) {
        p = find(usermodel.getPermissions(), (Permission) pIt.next());
        if (null == p) {
            continue;
        }
        if (usermodel.getPermissions().contains(p)) {
            usermodel.getPermissions().remove(p);
            permissionDAO.delete(p);
            hasChanges = true;
        }
    }

    pIt = add.iterator();
    while (pIt.hasNext()) {
        p = pIt.next();
        if (null == find(usermodel.getPermissions(), p) && !usermodel.getPermissions().contains(p)) {
            p.setUser(usermodel);
            usermodel.getPermissions().add(p);
            permissionDAO.save(p);
            hasChanges = true;
        }
    }

    if (hasChanges) {
        userDAO.saveOrUpdate(usermodel);
    }

    return hasChanges;
}