Example usage for java.util TreeSet addAll

List of usage examples for java.util TreeSet addAll

Introduction

In this page you can find the example usage for java.util TreeSet addAll.

Prototype

public boolean addAll(Collection<? extends E> c) 

Source Link

Document

Adds all of the elements in the specified collection to this set.

Usage

From source file:org.exoplatform.services.wcm.extensions.publication.WCMPublicationServiceImpl.java

/**
 * This default implementation uses "States and versions based publication" as
 * a default lifecycle for all sites and "Simple Publishing" for the root
 * user./* w  w w . j  a v  a  2s.c o  m*/
 */
public void enrollNodeInLifecycle(Node node, String siteName, String remoteUser) {
    try {
        if (LOG.isInfoEnabled())
            LOG.info(node.getPath() + "::" + siteName + "::" + remoteUser);

        PublicationManagerImpl publicationManagerImpl = WCMCoreUtils.getService(PublicationManagerImpl.class);

        ContextComparator comparator = new ContextComparator();
        TreeSet<Context> treeSetContext = new TreeSet<Context>(comparator);
        treeSetContext.addAll(publicationManagerImpl.getContexts());
        for (Context context : treeSetContext) {
            boolean pathVerified = true;
            boolean nodetypeVerified = true;
            boolean siteVerified = true;
            boolean membershipVerified = true;
            String path = context.getPath();
            String nodetype = context.getNodetype();
            String site = context.getSite();
            List<String> memberships = new ArrayList<String>();
            if (context.getMembership() != null) {
                memberships.add(context.getMembership());
            }
            if (context.getMemberships() != null) {
                memberships.addAll(context.getMemberships());
            }
            if (path != null) {
                String workspace = node.getSession().getWorkspace().getName();
                ManageableRepository manaRepository = (ManageableRepository) node.getSession().getRepository();
                String repository = manaRepository.getConfiguration().getName();
                String[] pathTab = path.split(":");
                pathVerified = node.getPath().contains(pathTab[2]) && (repository.equals(pathTab[0]))
                        && (workspace.equals(pathTab[1]));
            }
            if (nodetype != null)
                nodetypeVerified = nodetype.equals(node.getPrimaryNodeType().getName());
            if (site != null)
                siteVerified = site.equals(siteName);
            if (memberships.size() > 0) {
                for (String membership : memberships) {
                    String[] membershipTab = membership.split(":");
                    IdentityRegistry identityRegistry = WCMCoreUtils.getService(IdentityRegistry.class);
                    Identity identity = identityRegistry.getIdentity(remoteUser);
                    membershipVerified = identity.isMemberOf(membershipTab[1], membershipTab[0]);
                    if (membershipVerified)
                        break;
                }
            }
            if (pathVerified && nodetypeVerified && siteVerified && membershipVerified) {
                Lifecycle lifecycle = publicationManagerImpl.getLifecycle(context.getLifecycle());
                String lifecycleName = this.getWebpagePublicationPlugins().get(lifecycle.getPublicationPlugin())
                        .getLifecycleName();
                if (node.canAddMixin("publication:authoring")) {
                    node.addMixin("publication:authoring");
                    node.setProperty("publication:lastUser", remoteUser);
                    node.setProperty("publication:lifecycle", lifecycle.getName());
                    node.getSession().save();

                }
                enrollNodeInLifecycle(node, lifecycleName);
                setInitialState(node, lifecycle, remoteUser);
                break;
            }
        }
    } catch (Exception ex) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Couldn't complete the enrollement : ", ex);
        }
    }
}

From source file:org.openeos.services.ui.form.abstractform.UIBeanSelectorProvider.java

@Override
@Transactional(readOnly = true)/*from  w  w  w  .  jav a  2  s .  c  o  m*/
public SortedSet<T> getElements() {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(beanClass);
    if (sqlRestriction != null && formInstance instanceof BFormInstance<?, ?>) {
        Object value = ((BFormInstance<?, ?>) formInstance).getValue();
        if (value instanceof UIBeanImpl) {
            value = ((UIBeanImpl) value).getBeanWrapped();
        }
        crit.add(buildSqlRestriction(sqlRestriction, value));
    }
    final List<T> listElements = crit.list();
    TreeSet<T> result = new TreeSet<T>(new Comparator<T>() {

        @Override
        public int compare(T o1, T o2) {
            return Integer.compare(listElements.indexOf(o1), listElements.indexOf(o2));
        }
    });
    result.addAll(listElements);
    return result;
}

From source file:org.apache.hadoop.hbase.backup.impl.RestoreTablesClient.java

/**
 * Restore operation. Stage 2: resolved Backup Image dependency
 * @param backupManifestMap : tableName, Manifest
 * @param sTableArray The array of tables to be restored
 * @param tTableArray The array of mapping tables to restore to
 * @throws IOException exception/*from   ww  w.  j  a v a  2  s  .  co  m*/
 */
private void restore(HashMap<TableName, BackupManifest> backupManifestMap, TableName[] sTableArray,
        TableName[] tTableArray, boolean isOverwrite) throws IOException {
    TreeSet<BackupImage> restoreImageSet = new TreeSet<>();

    for (int i = 0; i < sTableArray.length; i++) {
        TableName table = sTableArray[i];

        BackupManifest manifest = backupManifestMap.get(table);
        // Get the image list of this backup for restore in time order from old
        // to new.
        List<BackupImage> list = new ArrayList<>();
        list.add(manifest.getBackupImage());
        TreeSet<BackupImage> set = new TreeSet<>(list);
        List<BackupImage> depList = manifest.getDependentListByTable(table);
        set.addAll(depList);
        BackupImage[] arr = new BackupImage[set.size()];
        set.toArray(arr);
        restoreImages(arr, table, tTableArray[i], isOverwrite);
        restoreImageSet.addAll(list);
        if (restoreImageSet != null && !restoreImageSet.isEmpty()) {
            LOG.info("Restore includes the following image(s):");
            for (BackupImage image : restoreImageSet) {
                LOG.info("Backup: " + image.getBackupId() + " "
                        + HBackupFileSystem.getTableBackupDir(image.getRootDir(), image.getBackupId(), table));
            }
        }
    }
    LOG.debug("restoreStage finished");
}

From source file:org.apache.rocketmq.tools.command.cluster.ClusterListSubCommand.java

private void printClusterBaseInfo(final DefaultMQAdminExt defaultMQAdminExt) throws RemotingConnectException,
        RemotingTimeoutException, RemotingSendRequestException, InterruptedException, MQBrokerException {

    ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();

    System.out.printf("%-16s  %-22s  %-4s  %-22s %-16s %19s %19s %10s %5s %6s%n", "#Cluster Name",
            "#Broker Name", "#BID", "#Addr", "#Version", "#InTPS(LOAD)", "#OutTPS(LOAD)", "#PCWait(ms)",
            "#Hour", "#SPACE");

    Iterator<Map.Entry<String, Set<String>>> itCluster = clusterInfoSerializeWrapper.getClusterAddrTable()
            .entrySet().iterator();//from  ww  w.j  ava  2 s  .  com
    while (itCluster.hasNext()) {
        Map.Entry<String, Set<String>> next = itCluster.next();
        String clusterName = next.getKey();
        TreeSet<String> brokerNameSet = new TreeSet<String>();
        brokerNameSet.addAll(next.getValue());

        for (String brokerName : brokerNameSet) {
            BrokerData brokerData = clusterInfoSerializeWrapper.getBrokerAddrTable().get(brokerName);
            if (brokerData != null) {

                Iterator<Map.Entry<Long, String>> itAddr = brokerData.getBrokerAddrs().entrySet().iterator();
                while (itAddr.hasNext()) {
                    Map.Entry<Long, String> next1 = itAddr.next();
                    double in = 0;
                    double out = 0;
                    String version = "";
                    String sendThreadPoolQueueSize = "";
                    String pullThreadPoolQueueSize = "";
                    String sendThreadPoolQueueHeadWaitTimeMills = "";
                    String pullThreadPoolQueueHeadWaitTimeMills = "";
                    String pageCacheLockTimeMills = "";
                    String earliestMessageTimeStamp = "";
                    String commitLogDiskRatio = "";
                    try {
                        KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(next1.getValue());
                        String putTps = kvTable.getTable().get("putTps");
                        String getTransferedTps = kvTable.getTable().get("getTransferedTps");
                        sendThreadPoolQueueSize = kvTable.getTable().get("sendThreadPoolQueueSize");
                        pullThreadPoolQueueSize = kvTable.getTable().get("pullThreadPoolQueueSize");

                        sendThreadPoolQueueSize = kvTable.getTable().get("sendThreadPoolQueueSize");
                        pullThreadPoolQueueSize = kvTable.getTable().get("pullThreadPoolQueueSize");

                        sendThreadPoolQueueHeadWaitTimeMills = kvTable.getTable()
                                .get("sendThreadPoolQueueHeadWaitTimeMills");
                        pullThreadPoolQueueHeadWaitTimeMills = kvTable.getTable()
                                .get("pullThreadPoolQueueHeadWaitTimeMills");
                        pageCacheLockTimeMills = kvTable.getTable().get("pageCacheLockTimeMills");
                        earliestMessageTimeStamp = kvTable.getTable().get("earliestMessageTimeStamp");
                        commitLogDiskRatio = kvTable.getTable().get("commitLogDiskRatio");

                        version = kvTable.getTable().get("brokerVersionDesc");
                        {
                            String[] tpss = putTps.split(" ");
                            if (tpss.length > 0) {
                                in = Double.parseDouble(tpss[0]);
                            }
                        }

                        {
                            String[] tpss = getTransferedTps.split(" ");
                            if (tpss.length > 0) {
                                out = Double.parseDouble(tpss[0]);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    double hour = 0.0;
                    double space = 0.0;

                    if (earliestMessageTimeStamp != null && earliestMessageTimeStamp.length() > 0) {
                        long mills = System.currentTimeMillis() - Long.valueOf(earliestMessageTimeStamp);
                        hour = mills / 1000.0 / 60.0 / 60.0;
                    }

                    if (commitLogDiskRatio != null && commitLogDiskRatio.length() > 0) {
                        space = Double.valueOf(commitLogDiskRatio);
                    }

                    System.out.printf("%-16s  %-22s  %-4s  %-22s %-16s %19s %19s %10s %5s %6s%n", clusterName,
                            brokerName, next1.getKey(), next1.getValue(), version,
                            String.format("%9.2f(%s,%sms)", in, sendThreadPoolQueueSize,
                                    sendThreadPoolQueueHeadWaitTimeMills),
                            String.format("%9.2f(%s,%sms)", out, pullThreadPoolQueueSize,
                                    pullThreadPoolQueueHeadWaitTimeMills),
                            pageCacheLockTimeMills, String.format("%2.2f", hour), String.format("%.4f", space));
                }
            }
        }

        if (itCluster.hasNext()) {
            System.out.printf("");
        }
    }
}

From source file:com.hichinaschool.flashcards.libanki.Tags.java

/** Strip duplicates and sort. */
public TreeSet<String> canonify(List<String> tagList) {
    TreeSet<String> tree = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    tree.addAll(tagList);
    return tree;/*from   w w w  . java 2 s  . co  m*/
}

From source file:com.joliciel.jochre.graphics.WhiteAreaFinder.java

List<Rectangle> getWhiteAreas(ImageGrid imageGrid, int blackThreshold, List<? extends Rectangle> blackAreas,
        int left, int top, int right, int bottom, double minWhiteAreaWidth, double minWhiteAreaHeight) {
    // figure out white areas based on shapes, not isPixelBlack
    List<Rectangle> whiteAreas = new ArrayList<Rectangle>();
    List<WhiteArea> openWhiteAreas = new ArrayList<WhiteArea>();
    TreeSet<Rectangle> blackAreasToConsider = new TreeSet<Rectangle>(new RectangleTopToBottomComparator());
    if (blackAreas != null)
        blackAreasToConsider.addAll(blackAreas);

    // stop "false" column separators from appearing at the top row, below a series of titles
    // these can be recognise because they radically narrow what is already a long strip
    // Now - doing this by getting horizontal boxes first
    //      double minRatioForExtension = 0.5;

    for (int y = top; y <= bottom; y++) {
        // get all white horizontal lines on current row
        List<WhiteLine> whiteLines = new ArrayList<WhiteLine>();
        boolean[] pixels = new boolean[right + 1];
        List<Rectangle> blackAreasToRemove = new ArrayList<Rectangle>();
        for (Rectangle blackArea : blackAreasToConsider) {
            if (blackArea.getBottom() < y)
                blackAreasToRemove.add(blackArea);
            if (blackArea.getTop() > y)
                break;
            if (blackArea.getBottom() >= y) {
                int maxLeft = blackArea.getLeft() > left ? blackArea.getLeft() : left;
                int minRight = blackArea.getRight() < right ? blackArea.getRight() : right;
                for (int i = maxLeft; i <= minRight; i++) {
                    pixels[i] = true;/*from w  w  w.j a v a2s .c  o m*/
                }
            }
        }
        blackAreasToConsider.removeAll(blackAreasToRemove);
        boolean inWhite = false;
        int startWhite = 0;
        for (int x = left; x <= right; x++) {
            boolean isBlack = pixels[x];
            // alternate method to a list of rectangles: get black pixel directly
            if (imageGrid != null) {
                isBlack = imageGrid.isPixelBlack(x, y, blackThreshold);
            }
            if (!inWhite && !isBlack) {
                startWhite = x;
                inWhite = true;
            } else if (inWhite && isBlack) {
                WhiteLine whiteLine = new WhiteLine(startWhite, x - 1);
                whiteLines.add(whiteLine);
                inWhite = false;
            }
        }
        if (inWhite) {
            WhiteLine whiteLine = new WhiteLine(startWhite, right);
            whiteLines.add(whiteLine);
        }

        // check if the white horizontal lines extend existing rectangles
        List<WhiteArea> currentWhiteAreas = new ArrayList<WhiteArea>();
        for (WhiteLine whiteLine : whiteLines) {
            for (WhiteArea whiteArea : openWhiteAreas) {
                int maxLeft = whiteLine.start >= whiteArea.getLeft() ? whiteLine.start : whiteArea.getLeft();
                int minRight = whiteLine.end <= whiteArea.getRight() ? whiteLine.end : whiteArea.getRight();
                if (minRight - maxLeft >= minWhiteAreaWidth) {
                    // there is an overlap that's wide enough, add it
                    // but first check the ratio is above the minimum
                    //                  if ((double)(minRight - maxLeft) / (double) (whiteArea.getRight() - whiteArea.getLeft()) > minRatioForExtension) {
                    WhiteArea newWhiteArea = new WhiteArea(maxLeft, whiteArea.getTop(), minRight, y);
                    currentWhiteAreas.add(newWhiteArea);
                    //                  }
                }
            }
            WhiteArea whiteLineArea = new WhiteArea(whiteLine.start, y, whiteLine.end, y);
            currentWhiteAreas.add(whiteLineArea);
        }
        currentWhiteAreas.addAll(openWhiteAreas);

        // get rid of white areas with full overlap
        List<WhiteArea> whiteAreasToDelete = new ArrayList<WhiteArea>();
        for (int i = 0; i < currentWhiteAreas.size() - 1; i++) {
            WhiteArea whiteArea1 = currentWhiteAreas.get(i);
            for (int j = i + 1; j < currentWhiteAreas.size(); j++) {
                WhiteArea whiteArea2 = currentWhiteAreas.get(j);
                if (whiteArea1.getLeft() >= whiteArea2.getLeft() && whiteArea1.getTop() >= whiteArea2.getTop()
                        && whiteArea1.getRight() <= whiteArea2.getRight()
                        && whiteArea1.getBottom() <= whiteArea2.getBottom()) {
                    whiteAreasToDelete.add(whiteArea1);
                } else if (whiteArea2.getLeft() >= whiteArea1.getLeft()
                        && whiteArea2.getTop() >= whiteArea1.getTop()
                        && whiteArea2.getRight() <= whiteArea1.getRight()
                        && whiteArea2.getBottom() <= whiteArea1.getBottom()) {
                    whiteAreasToDelete.add(whiteArea2);
                }
            }
        }
        currentWhiteAreas.removeAll(whiteAreasToDelete);

        openWhiteAreas = new ArrayList<WhiteArea>();
        for (WhiteArea whiteArea : currentWhiteAreas) {
            if (whiteArea.getBottom() < y
                    && (whiteArea.getBottom() - whiteArea.getTop() >= minWhiteAreaHeight)) {
                LOG.debug("Adding " + whiteArea.toString());
                whiteAreas.add(whiteArea);
            } else if (whiteArea.getBottom() == y) {
                openWhiteAreas.add(whiteArea);
            }
        }
    }
    for (WhiteArea whiteArea : openWhiteAreas) {
        if (whiteArea.getBottom() - whiteArea.getTop() >= minWhiteAreaHeight) {
            LOG.debug("Adding " + whiteArea.toString());
            whiteAreas.add(whiteArea);
        }
    }
    return whiteAreas;
}

From source file:com.offbynull.voip.kademlia.FindSubcoroutine.java

@Override
public List<Node> run(Continuation cnt) throws Exception {
    Context ctx = (Context) cnt.getContext();

    ctx.addOutgoingMessage(subAddress, logAddress, info("Finding {}", findId));

    // Set up subcoroutine router
    Address routerAddress = subAddress.appendSuffix("finderreq" + idGenerator.generate());
    SubcoroutineRouter msgRouter = new SubcoroutineRouter(routerAddress, ctx);
    Controller msgRouterController = msgRouter.getController();

    // Get initial set of nodes to query from routing table
    List<Node> startNodes = router.find(findId, maxResults, false); // do not include stale nodes, we only want to contact alive nodes
    ctx.addOutgoingMessage(subAddress, logAddress,
            info("Route table entries closest to {}: {}", findId, startNodes));

    // Create sorted set of nodes to contact
    IdXorMetricComparator idClosenessComparator = new IdXorMetricComparator(findId);
    TreeSet<Node> contactSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));
    contactSet.addAll(startNodes);

    // Create a sorted set of nodes to retain closest nodes in
    TreeSet<Node> closestSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));

    // Execute requests
    Map<Subcoroutine<?>, Node> requestSubcoroutineToNodes = new HashMap<>(); // executing requests
    Set<Id> queriedSet = new HashSet<>(); // ids that have already been queried
    while (true) {
        // If there's room left to query more contacts that are closer to findId, do so... 
        while (msgRouterController.size() < maxConcurrentRequests && !contactSet.isEmpty()) {
            // Get next farthest away node to contact
            Node contactNode = contactSet.pollLast();

            // Add it to set of set of ids that have already been queried.. if it's already there, it means that it's already been
            // queried by this find, so skip it...
            boolean added = queriedSet.add(contactNode.getId());
            if (!added) {
                continue;
            }//from  w w  w  .j  av a 2  s. com

            // Add it to the set of closest nodes (will be removed if node fails to respond)
            closestSet.add(contactNode);

            // If we already have maxResult closer nodes to findId, skip this node
            if (closestSet.size() > maxResults) {
                Node removedNode = closestSet.pollLast();
                if (removedNode == contactNode) {
                    continue;
                }
            }

            // Initialize query
            Address destinationAddress = addressTransformer.toAddress(contactNode.getLink())
                    .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS);
            RequestSubcoroutine<FindResponse> reqSubcoroutine = new RequestSubcoroutine.Builder<FindResponse>()
                    .sourceAddress(routerAddress, idGenerator).destinationAddress(destinationAddress)
                    .timerAddress(timerAddress)
                    .request(new FindRequest(advertiseSelf ? baseId : null, findId, maxResults))
                    .addExpectedResponseType(FindResponse.class).attemptInterval(Duration.ofSeconds(2L))
                    .maxAttempts(5).throwExceptionIfNoResponse(false).build();

            ctx.addOutgoingMessage(subAddress, logAddress, info("Querying node {}", contactNode));

            // Add query to router
            msgRouterController.add(reqSubcoroutine, AddBehaviour.ADD_PRIME_NO_FINISH);
            requestSubcoroutineToNodes.put(reqSubcoroutine, contactNode);
        }

        // If there are no more requests running, it means we're finished
        if (msgRouterController.size() == 0) {
            ctx.addOutgoingMessage(subAddress, logAddress, info("Find complete: {}", closestSet));
            return new ArrayList<>(closestSet);
        }

        // Wait for next messange forward to the router
        cnt.suspend();
        ForwardResult fr = msgRouter.forward();

        // If a request completed from the forwarded message
        if (fr.isForwarded() && fr.isCompleted()) { // calling isCompleted by itself may throw an exception, check isForwarded first
            // Get response
            FindResponse findResponse = (FindResponse) fr.getResult();

            if (findResponse == null) {
                // If failure, then mark as stale and remove from closest
                // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY
                // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE!
                Node contactedNode = requestSubcoroutineToNodes.remove(fr.getSubcoroutine());
                try {
                    // not allowed to mark self as stale -- we may want to find self, but if we do and it's not responsive dont try to
                    // mark it as stale
                    if (!contactedNode.getId().equals(baseId)) {
                        router.stale(contactedNode);
                    }
                } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree
                    // Do nothing
                }
                closestSet.remove(contactedNode);
            } else {
                // If success, then add returned nodes to contacts
                Node[] nodes = findResponse.getNodes();
                contactSet.addAll(Arrays.asList(nodes));

                // If we don't want to find our own ID / query ourselves... remove any reference to our own ID in the contactSet
                // TODO: optimize this by removing before it's added to contactSet
                if (ignoreSelf) {
                    contactSet.removeIf(x -> x.getId().equals(baseId));
                }
            }
        }
    }
}

From source file:module.mission.presentationTier.action.MissionOrganizationAction.java

public ActionForward showDelegationsForAuthorization(final HttpServletRequest request,
        final Accountability accountability) {
    String sortBy = request.getParameter("sortBy");
    String order = request.getParameter("order");
    request.setAttribute("sortBy", (sortBy == null) ? "parentUnitName" : sortBy);
    request.setAttribute("order", (order == null) ? "asc" : order);
    request.setAttribute("accountability", accountability);

    Comparator<FunctionDelegation> comparator;
    if (StringUtils.equals(sortBy, "childPartyName")) {
        comparator = FunctionDelegation.COMPARATOR_BY_DELEGATEE_CHILD_PARTY_NAME;
    } else {/*www.j a v  a2  s  .c  o  m*/
        comparator = FunctionDelegation.COMPARATOR_BY_DELEGATEE_PARENT_UNIT_NAME;
    }
    if (StringUtils.equals(order, "desc")) {
        comparator = ComparatorUtils.reversedComparator(comparator);
    }
    TreeSet<FunctionDelegation> functionDelegationDelegated = new TreeSet<FunctionDelegation>(comparator);
    functionDelegationDelegated.addAll(accountability.getFunctionDelegationDelegated());
    request.setAttribute("functionDelegationDelegated", functionDelegationDelegated);

    return forward("/mission/showDelegationForAuthorization.jsp");
}

From source file:com.thoughtworks.go.domain.MaterialRevision.java

public Set<String> getCardNumbersFromComments() {
    TreeSet<String> cardNumbers = new TreeSet<>();
    for (Modification modification : modifications) {
        cardNumbers.addAll(modification.getCardNumbersFromComment());
    }/*from   w ww . ja v  a2  s .c  o m*/
    return cardNumbers;
}