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.apache.sling.testing.tools.sling.SlingTestBase.java

/** Check a number of server URLs for readyness */
protected void waitForServerReady() throws Exception {
    if (slingTestState.isServerReady()) {
        return;/*  ww  w.  ja  v a2s .  c  o  m*/
    }
    if (slingTestState.isServerReadyTestFailed()) {
        fail("Server is not ready according to previous tests");
    }

    // Timeout for readiness test
    final String sec = systemProperties.getProperty(SERVER_READY_TIMEOUT_PROP);
    final int timeoutSec = TimeoutsProvider.getInstance().getTimeout(sec == null ? 60 : Integer.valueOf(sec));
    log.info("Will wait up to " + timeoutSec + " seconds for server to become ready");
    final long endTime = System.currentTimeMillis() + timeoutSec * 1000L;

    // Get the list of paths to test and expected content regexps
    final List<String> testPaths = new ArrayList<String>();
    final TreeSet<Object> propertyNames = new TreeSet<Object>();
    propertyNames.addAll(systemProperties.keySet());
    for (Object o : propertyNames) {
        final String key = (String) o;
        if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
            testPaths.add(systemProperties.getProperty(key));
        }
    }

    // Consider the server ready if it responds to a GET on each of
    // our configured request paths with a 200 result and content
    // that contains the pattern that's optionally supplied with the
    // path, separated by a colon
    log.info("Checking that GET requests return expected content (timeout={} seconds): {}", timeoutSec,
            testPaths);
    while (System.currentTimeMillis() < endTime) {
        boolean errors = false;
        for (String p : testPaths) {
            final String[] s = p.split(":");
            final String path = s[0];
            final String pattern = (s.length > 0 ? s[1] : "");
            try {
                executor.execute(builder.buildGetRequest(path).withCredentials(serverUsername, serverPassword))
                        .assertStatus(200).assertContentContains(pattern);
            } catch (AssertionError ae) {
                errors = true;
                log.debug("Request to {}@{}{} failed, will retry ({})",
                        new Object[] { serverUsername, slingTestState.getServerBaseUrl(), path, ae });
            } catch (Exception e) {
                errors = true;
                log.debug("Request to {}@{}{} failed, will retry ({})",
                        new Object[] { serverUsername, slingTestState.getServerBaseUrl(), path, pattern, e });
            }
        }

        if (!errors) {
            slingTestState.setServerReady(true);
            log.info("All {} paths return expected content, server ready", testPaths.size());
            break;
        }
        Thread.sleep(TimeoutsProvider.getInstance().getTimeout(1000L));
    }

    if (!slingTestState.isServerReady()) {
        slingTestState.setServerReadyTestFailed(true);
        final String msg = "Server not ready after " + timeoutSec + " seconds, giving up";
        log.info(msg);
        fail(msg);
    }
}

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

/**
 * Get all the sids referenced in this {@link RoleMap}.
 * @param includeAnonymous True if you want the {@code Anonymous} sid to be included in the set
 * @return A sorted set containing all the sids
 *//*from  w  w w  .j av  a2 s .  c  o  m*/
public SortedSet<String> getSids(Boolean includeAnonymous) {
    TreeSet<String> sids = new TreeSet<String>();
    for (Map.Entry entry : this.grantedRoles.entrySet()) {
        sids.addAll((Set) entry.getValue());
    }
    // Remove the anonymous sid if asked to
    if (!includeAnonymous) {
        sids.remove("anonymous");
    }
    return Collections.unmodifiableSortedSet(sids);
}

From source file:org.apache.jackrabbit.oak.plugins.blob.FileLineDifferenceIteratorTest.java

@Test
public void testRandomized() throws Exception {
    Random r = new Random(0);
    for (int i = 0; i < 10000; i++) {
        TreeSet<String> marked = new TreeSet<String>();
        TreeSet<String> all = new TreeSet<String>();
        TreeSet<String> diff = new TreeSet<String>();
        int size = r.nextInt(5);
        for (int a = 0; a < size; a++) {
            marked.add("" + r.nextInt(10));
        }/*  w  w  w. java2 s. c om*/
        size = r.nextInt(5);
        for (int a = 0; a < size; a++) {
            all.add("" + r.nextInt(10));
        }
        diff.addAll(all);
        diff.removeAll(marked);
        String m = marked.toString().replaceAll("[ \\[\\]]", "");
        String a = all.toString().replaceAll("[ \\[\\]]", "");
        assertDiff(m, a, new ArrayList<String>(diff));
    }
}

From source file:ca.uhn.fhir.rest.server.provider.ServerConformanceProvider.java

private void handleSearchMethodBinding(Rest rest, RestResource resource, String resourceName,
        RuntimeResourceDefinition def, TreeSet<String> includes, SearchMethodBinding searchMethodBinding) {
    includes.addAll(searchMethodBinding.getIncludes());

    List<IParameter> params = searchMethodBinding.getParameters();
    List<SearchParameter> searchParameters = new ArrayList<SearchParameter>();
    for (IParameter nextParameter : params) {
        if ((nextParameter instanceof SearchParameter)) {
            searchParameters.add((SearchParameter) nextParameter);
        }/*from   w  w w . j  av  a 2 s. c  o m*/
    }
    sortSearchParameters(searchParameters);
    if (!searchParameters.isEmpty()) {
        boolean allOptional = searchParameters.get(0).isRequired() == false;

        RestQuery query = null;
        if (!allOptional) {
            query = rest.addQuery();
            query.getDocumentation().setValue(searchMethodBinding.getDescription());
            query.addUndeclaredExtension(false, ExtensionConstants.QUERY_RETURN_TYPE, new CodeDt(resourceName));
            for (String nextInclude : searchMethodBinding.getIncludes()) {
                query.addUndeclaredExtension(false, ExtensionConstants.QUERY_ALLOWED_INCLUDE,
                        new StringDt(nextInclude));
            }
        }

        for (SearchParameter nextParameter : searchParameters) {

            String nextParamName = nextParameter.getName();

            // String chain = null;
            String nextParamUnchainedName = nextParamName;
            if (nextParamName.contains(".")) {
                // chain = nextParamName.substring(nextParamName.indexOf('.') + 1);
                nextParamUnchainedName = nextParamName.substring(0, nextParamName.indexOf('.'));
            }

            String nextParamDescription = nextParameter.getDescription();

            /*
             * If the parameter has no description, default to the one from the resource
             */
            if (StringUtils.isBlank(nextParamDescription)) {
                RuntimeSearchParam paramDef = def.getSearchParam(nextParamUnchainedName);
                if (paramDef != null) {
                    nextParamDescription = paramDef.getDescription();
                }
            }

            RestResourceSearchParam param;
            if (query == null) {
                param = resource.addSearchParam();
            } else {
                param = query.addParameter();
                param.addUndeclaredExtension(false, ExtensionConstants.PARAM_IS_REQUIRED,
                        new BooleanDt(nextParameter.isRequired()));
            }

            param.setName(nextParamName);
            // if (StringUtils.isNotBlank(chain)) {
            // param.addChain(chain);
            // }
            param.setDocumentation(nextParamDescription);
            param.getTypeElement().setValue(nextParameter.getParamType().getCode());
            for (Class<? extends IBaseResource> nextTarget : nextParameter.getDeclaredTypes()) {
                RuntimeResourceDefinition targetDef = myServerConfiguration.getFhirContext()
                        .getResourceDefinition(nextTarget);
                if (targetDef != null) {
                    ResourceTypeEnum code = ResourceTypeEnum.VALUESET_BINDER
                            .fromCodeString(targetDef.getName());
                    if (code != null) {
                        param.addTarget(code);
                    }
                }
            }
        }
    }
}

From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImpl.java

/**
 * Retrieve the {@link AvailableBlock}s between the specified dates for an owner in a {@link SortedSet}.
 * //from w w  w .ja  v  a2  s .co  m
 * Starts by retrieving all rows for the owner, then calculating the subSet between the start and end dates.
 * 
 * @param owner
 * @param startDate
 * @param endDate
 * @return
 */
protected SortedSet<AvailableBlock> internalRetrieveSchedule(final IScheduleOwner owner, final Date startDate,
        final Date endDate) {
    TreeSet<AvailableBlock> allStoredBlocks = new TreeSet<AvailableBlock>();
    allStoredBlocks.addAll(internalRetrieveSchedule(owner));
    TreeSet<AvailableBlock> expanded = new TreeSet<AvailableBlock>();
    expanded.addAll(AvailableBlockBuilder.expand(allStoredBlocks, 1));

    // we need the subset of blocks
    AvailableBlock startBlock = AvailableBlockBuilder.createSmallestAllowedBlock(startDate);
    AvailableBlock endBlock = AvailableBlockBuilder.createBlockEndsAt(endDate, 1);
    NavigableSet<AvailableBlock> innerSet = expanded.subSet(startBlock, true, endBlock, true);
    // combine the inner set before returning
    SortedSet<AvailableBlock> combinedInnerSet = AvailableBlockBuilder.combine(innerSet);
    return combinedInnerSet;
}

From source file:org.fenixedu.academic.thesis.ui.controller.ConfigurationController.java

@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView createConfigurationForm(Model model,
        @RequestParam ConfigurationBean thesisProposalsConfigurationBean) {

    ModelAndView mav = new ModelAndView("/configuration/create", "command", thesisProposalsConfigurationBean);

    TreeSet<ExecutionYear> executionYearsList = new TreeSet<ExecutionYear>(
            ExecutionYear.REVERSE_COMPARATOR_BY_YEAR);
    executionYearsList.addAll(Bennu.getInstance().getExecutionYearsSet());
    model.addAttribute("executionYearsList", executionYearsList);

    List<ExecutionDegree> executionDegreeList = Bennu.getInstance().getExecutionDegreesSet().stream()
            .collect(Collectors.toList());
    Collections.sort(executionDegreeList, ExecutionDegree.COMPARATOR_BY_DEGREE_NAME);
    mav.addObject("executionDegreeList", executionDegreeList);

    return mav;/*from   w  w w  .j a  va 2  s.  c  o  m*/
}

From source file:org.fenixedu.academic.service.services.person.SearchPerson.java

public CollectionPager<Person> run(SearchParameters searchParameters, Predicate predicate) {

    if (searchParameters.emptyParameters()) {
        return new CollectionPager<Person>(new ArrayList<Person>(), 25);
    }//www .jav  a 2s.com

    final Collection<Person> persons;

    if (searchParameters.getUsername() != null && searchParameters.getUsername().length() > 0) {

        final Person person = Person.readPersonByUsername(searchParameters.getUsername());
        persons = new ArrayList<Person>();
        if (person != null) {
            persons.add(person);
        }

    } else if (searchParameters.getDocumentIdNumber() != null
            && searchParameters.getDocumentIdNumber().length() > 0) {
        persons = Person.findPersonByDocumentID(searchParameters.getDocumentIdNumber());

    } else if (searchParameters.getStudentNumber() != null) {

        final Student student = Student.readStudentByNumber(searchParameters.getStudentNumber());
        persons = new ArrayList<Person>();
        if (student != null) {
            persons.add(student.getPerson());
        }

    } else if (searchParameters.getEmail() != null && searchParameters.getEmail().length() > 0) {

        final Person person = Person.readPersonByEmailAddress(searchParameters.getEmail());
        persons = new ArrayList<Person>();
        if (person != null) {
            persons.add(person);
        }

    } else if (searchParameters.getName() != null) {

        persons = new ArrayList<Person>();

        persons.addAll(Person.findPerson(searchParameters.getName()));
        final RoleType roleBd = searchParameters.getRole();
        if (roleBd != null) {
            for (final Iterator<Person> peopleIterator = persons.iterator(); peopleIterator.hasNext();) {
                final Person person = peopleIterator.next();
                if (!roleBd.isMember(person.getUser())) {
                    peopleIterator.remove();
                }
            }
        }
        final Department department = searchParameters.getDepartment();
        if (department != null) {
            for (final Iterator<Person> peopleIterator = persons.iterator(); peopleIterator.hasNext();) {
                final Person person = peopleIterator.next();
                final Teacher teacher = person.getTeacher();
                if (teacher == null || teacher.getDepartment() != department) {
                    peopleIterator.remove();
                }
            }
        }
    } else if (!StringUtils.isEmpty(searchParameters.getPaymentCode())) {
        persons = new ArrayList<Person>();

        PaymentCode paymentCode = PaymentCode.readByCode(searchParameters.getPaymentCode());

        if (paymentCode != null && paymentCode.getPerson() != null) {
            persons.add(paymentCode.getPerson());
        }
    } else {
        persons = new ArrayList<Person>(0);
    }

    TreeSet<Person> result = new TreeSet<Person>(Person.COMPARATOR_BY_NAME_AND_ID);
    result.addAll(CollectionUtils.select(persons, predicate));
    return new CollectionPager<Person>(result, 25);
}

From source file:org.fenixedu.academic.thesis.ui.controller.ConfigurationController.java

@RequestMapping(value = "", method = RequestMethod.GET)
public String listConfigurations(Model model) {

    TreeSet<ExecutionYear> executionYearsList = new TreeSet<ExecutionYear>(
            ExecutionYear.REVERSE_COMPARATOR_BY_YEAR);
    executionYearsList.addAll(Bennu.getInstance().getExecutionYearsSet());

    model.addAttribute("executionYearsList", executionYearsList);

    Set<ThesisProposalsConfiguration> configurationsSet = ThesisProposalsSystem.getInstance()
            .getThesisProposalsConfigurationSet();

    List<ThesisProposalsConfiguration> configurationsList = configurationsSet.stream().filter(
            (x) -> ThesisProposalsSystem.canManage(x.getExecutionDegree().getDegree(), Authenticate.getUser()))
            .collect(Collectors.toList());
    Collections.sort(configurationsList, ThesisProposalsConfiguration.COMPARATOR_BY_YEAR_AND_EXECUTION_DEGREE);

    model.addAttribute("configurationsList", configurationsList);

    List<ThesisProposalParticipantType> participantTypeList = ThesisProposalsSystem.getInstance()
            .getThesisProposalParticipantTypeSet().stream().collect(Collectors.toList());

    Collections.sort(participantTypeList, ThesisProposalParticipantType.COMPARATOR_BY_WEIGHT);

    model.addAttribute("participantTypeList", participantTypeList);

    model.addAttribute("isManager", Group.managers().isMember(Authenticate.getUser()));

    return "/configuration/list";
}

From source file:org.hyperic.hq.ui.action.portlet.availsummary.ViewAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    WebUser user = RequestUtils.getWebUser(session);
    DashboardConfig dashConfig = dashboardManager
            .findDashboard((Integer) session.getAttribute(Constants.SELECTED_DASHBOARD_ID), user, authzBoss);

    if (dashConfig == null) {
        return new ActionRedirect("/Dashboard.do");
    }//from   w w w. j  a va 2  s.c o  m

    ConfigResponse dashPrefs = dashConfig.getConfig();

    String token;
    long ts = System.currentTimeMillis();

    try {
        token = RequestUtils.getStringParameter(request, "token");
        if (token != null) {
            //token should be alpha-numeric
            if (!token.matches("^[\\w-]*$")) {
                log.warn("Token cleared by xss filter: " + token);
                token = null;
            }
        }
    } catch (ParameterNotFoundException e) {
        token = null;
    }

    String resKey = PropertiesForm.RESOURCES;
    String numKey = PropertiesForm.NUM_TO_SHOW;
    String titleKey = PropertiesForm.TITLE;

    if (token != null) {
        resKey += token;
        numKey += token;
        titleKey += token;
    }

    List<AppdefEntityID> entityIds = DashboardUtils.preferencesAsEntityIds(resKey, dashPrefs);

    // Can only do Platforms, Servers, and Services
    for (Iterator<AppdefEntityID> it = entityIds.iterator(); it.hasNext();) {
        AppdefEntityID aeid = it.next();

        if (aeid.isPlatform() || aeid.isServer() || aeid.isService()) {
            continue;
        }

        it.remove();
    }

    AppdefEntityID[] arrayIds = entityIds.toArray(new AppdefEntityID[entityIds.size()]);
    int count = Integer.parseInt(dashPrefs.getValue(numKey, "10"));
    int sessionId = user.getSessionId().intValue();

    CacheEntry[] ents = new CacheEntry[arrayIds.length];
    List<Integer> measurements = new ArrayList<Integer>(arrayIds.length);
    Map<String, AvailSummary> res = new HashMap<String, AvailSummary>();
    long interval = 0;
    ArrayList<String> toRemove = new ArrayList<String>();
    for (int i = 0; i < arrayIds.length; i++) {
        AppdefEntityID id = arrayIds[i];
        try {
            ents[i] = loadData(sessionId, id);
        } catch (AppdefEntityNotFoundException e) {
            toRemove.add(id.getAppdefKey());
        }

        if (ents[i] != null && ents[i].getMeasurement() != null) {
            measurements.add(i, ents[i].getMeasurement().getId());
            if (ents[i].getMeasurement().getInterval() > interval) {
                interval = ents[i].getMeasurement().getInterval();
            }
        } else {
            measurements.add(i, null);
        }
    }

    MetricValue[] vals = measurementBoss.getLastMetricValue(sessionId, measurements, interval);

    for (int i = 0; i < ents.length; i++) {
        CacheEntry ent = ents[i];
        MetricValue val = vals[i];

        // If no avail measurement is scheduled, skip this resource
        if (ent != null && val != null) {
            if (ent.getType() == null) {
                AppdefResourceValue resVal = appdefBoss.findById(sessionId, arrayIds[i]);
                if (resVal == null) {
                    continue;
                }
                ent.setType(resVal.getAppdefResourceTypeValue());
            }

            String name = ent.getType().getName();
            AvailSummary summary = res.get(name);
            if (summary == null) {
                summary = new AvailSummary(ent.getType());
                res.put(name, summary);
            }
            summary.setAvailability(val.getValue());
        }
    }

    JSONObject availSummary = new JSONObject();
    List<JSONObject> types = new ArrayList<JSONObject>();

    TreeSet<AvailSummary> sortedSet = new TreeSet<AvailSummary>(new AvailSummaryComparator());
    sortedSet.addAll(res.values());

    for (Iterator<AvailSummary> i = sortedSet.iterator(); i.hasNext() && count-- > 0;) {
        AvailSummary summary = i.next();
        JSONObject typeSummary = new JSONObject();
        typeSummary.put("resourceTypeName", summary.getTypeName());
        typeSummary.put("numUp", summary.getNumUp());
        typeSummary.put("numDown", summary.getNumDown());
        typeSummary.put("appdefType", summary.getAppdefType());
        typeSummary.put("appdefTypeId", summary.getAppdefTypeId());

        types.add(typeSummary);
    }

    availSummary.put("availSummary", types);

    if (token != null) {
        availSummary.put("token", token);
    } else {
        availSummary.put("token", JSONObject.NULL);
    }
    availSummary.put("title", dashPrefs.getValue(titleKey, ""));

    response.getWriter().write(availSummary.toString());

    log.debug("Availability summary loaded in " + (System.currentTimeMillis() - ts) + " ms");

    if (toRemove.size() > 0) {
        log.debug("Removing " + toRemove.size() + " missing resources.");
        DashboardUtils.removeResources(toRemove.toArray(new String[toRemove.size()]), resKey, dashPrefs);
    }

    return null;
}

From source file:net.spfbl.whois.Domain.java

private static synchronized TreeSet<String> getSetTLD() {
    TreeSet<String> set = new TreeSet<String>();
    set.addAll(TLD_SET);
    return set;/*  www.  j a  va  2s  . com*/
}