Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

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

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

/**
 * Configures the server to have the default role names and role hierarchy.
 *
 * @param cc/*from   ww  w  .j  a v a 2s. co  m*/
 * @throws DatastoreFailureException
 * @throws AccessDeniedException
 */
public static final void setDefaultRoleNamesAndHierarchy(CallingContext cc)
        throws DatastoreFailureException, AccessDeniedException {

    ArrayList<UserSecurityInfo> users = new ArrayList<UserSecurityInfo>();
    ArrayList<GrantedAuthorityName> allGroups = new ArrayList<GrantedAuthorityName>();

    // Grant the Anonymous user the ability to submit data to ODK Aggregate
    // Enables users to anonymously publish from ODK Collect into ODK Aggregate
    UserSecurityInfo anonymous = new UserSecurityInfo(User.ANONYMOUS_USER, User.ANONYMOUS_USER_NICKNAME, null,
            UserSecurityInfo.UserType.ANONYMOUS);
    TreeSet<GrantedAuthorityName> userGroups = new TreeSet<GrantedAuthorityName>();
    userGroups.add(GrantedAuthorityName.GROUP_DATA_COLLECTORS);
    userGroups.add(GrantedAuthorityName.GROUP_FORM_MANAGERS); // issue 710
    anonymous.setAssignedUserGroups(userGroups);
    users.add(anonymous);
    // NOTE: No users are defined at this point (including the superUser) see
    // superUserBootstrap below...
    setStandardSiteAccessConfiguration(users, allGroups, cc);
}

From source file:com.atolcd.pentaho.di.trans.steps.gisgeoprocessing.GisGeoprocessing.java

private static LineString[] splitLineStringAtCoordinates(Coordinate[] splitCoordinates,
        LineString inputLineString, double distance) {

    List<LineString> lineStrings = new ArrayList<LineString>();
    LengthIndexedLine lengthIndexedLine = new LengthIndexedLine(inputLineString);

    TreeSet<Double> indexesTree = new TreeSet<Double>();
    indexesTree.add(lengthIndexedLine.getStartIndex());
    indexesTree.add(lengthIndexedLine.getEndIndex());

    for (Coordinate splitCoordinate : splitCoordinates) {

        if (geometryFactory.createPoint(splitCoordinate).distance(inputLineString) <= distance) {

            indexesTree.add(lengthIndexedLine.project(splitCoordinate));

        }//from   w  w  w  .  j  a  va  2s.c o m
    }

    Double[] indexes = indexesTree.toArray(new Double[indexesTree.size()]);
    for (int i = 0; i < indexes.length - 1; i++) {

        LineString splitedLineString = (LineString) lengthIndexedLine.extractLine(indexes[i], indexes[i + 1]);
        if (splitedLineString != null && !splitedLineString.isEmpty()) {
            lineStrings.add(splitedLineString);
        }

    }

    return lineStrings.toArray(new LineString[lineStrings.size()]);
}

From source file:at.alladin.rmbt.qos.QoSUtil.java

/**
 * compares test results with expected results and increases success/failure counter 
 * @param testResult the test result/*  w  ww.j  av a2  s  .  co  m*/
 * @param result the parsed test result
 * @param resultKeys result key map
 * @param testType test type
 * @param resultOptions result options
 * @throws HstoreParseException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static void compareTestResults(final QoSTestResult testResult, final AbstractResult<?> result,
        final Map<TestType, TreeSet<ResultDesc>> resultKeys, final TestType testType,
        final ResultOptions resultOptions)
        throws HstoreParseException, IllegalArgumentException, IllegalAccessException {

    //if expected resuls not null, compare them to the test results
    if (testResult.getExpectedResults() != null) {
        final Class<? extends AbstractResult<?>> clazz = testType.getClazz();

        //create a parsed abstract result set sorted by priority
        final Set<AbstractResult<?>> expResultSet = new TreeSet<AbstractResult<?>>(
                new Comparator<AbstractResult<?>>() {
                    @Override
                    public int compare(final AbstractResult<?> o1, final AbstractResult<?> o2) {
                        return o1.priority.compareTo(o2.priority);
                    }
                });

        int priority = Integer.MAX_VALUE;

        if (testResult.getExpectedResults() != null) {
            for (int i = 0; i < testResult.getExpectedResults().length(); i++) {
                final JSONObject expectedResults = testResult.getExpectedResults().optJSONObject(i);
                if (expectedResults != null) {
                    //parse hstore string to object
                    final AbstractResult<?> expResult = QoSUtil.HSTORE_PARSER.fromJSON(expectedResults, clazz);
                    if (expResult.getPriority() == Integer.MAX_VALUE) {
                        expResult.setPriority(priority--);
                    }
                    expResultSet.add(expResult);
                }
            }
        }

        for (final AbstractResult<?> expResult : expResultSet) {
            //compare expected result to test result and save the returned id
            ResultDesc resultDesc = ResultComparer.compare(result, expResult, QoSUtil.HSTORE_PARSER,
                    resultOptions);
            if (resultDesc != null) {
                resultDesc.addTestResultUid(testResult.getUid());
                resultDesc.setTestType(testType);

                final ResultHolder resultHolder = calculateResultCounter(testResult, expResult, resultDesc);

                //check if there is a result message
                if (resultHolder != null) {
                    TreeSet<ResultDesc> resultDescSet;
                    if (resultKeys.containsKey(testType)) {
                        resultDescSet = resultKeys.get(testType);
                    } else {
                        resultDescSet = new TreeSet<>();
                        resultKeys.put(testType, resultDescSet);
                    }

                    resultDescSet.add(resultDesc);

                    testResult.getResultKeyMap().put(resultDesc.getKey(), resultHolder.resultKeyType);

                    if (AbstractResult.BEHAVIOUR_ABORT.equals(resultHolder.event)) {
                        break;
                    }
                }
            }
        }
    }
}

From source file:at.alladin.rmbt.qos.QoSUtil.java

/**
 * //from   ww  w  . ja  v a2  s .  co m
 * @param settings
 * @param conn
 * @param answer
 * @param lang
 * @param errorList
 * @throws SQLException 
 * @throws JSONException 
 * @throws HstoreParseException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public static void evaluate(final ResourceBundle settings, final Connection conn, final TestUuid uuid,
        final JSONObject answer, String lang, final ErrorList errorList) throws SQLException,
        HstoreParseException, JSONException, IllegalArgumentException, IllegalAccessException {
    // Load Language Files for Client

    final List<String> langs = Arrays.asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

    if (langs.contains(lang)) {
        errorList.setLanguage(lang);
    } else {
        lang = settings.getString("RMBT_DEFAULT_LANGUAGE");
    }

    if (conn != null) {

        final Client client = new Client(conn);
        final Test test = new Test(conn);

        boolean necessaryDataAvailable = false;

        if (uuid != null && uuid.getType() != null && uuid.getUuid() != null) {
            switch (uuid.getType()) {
            case OPEN_TEST_UUID:
                if (test.getTestByOpenTestUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            case TEST_UUID:
                if (test.getTestByUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            }
        }

        final long timeStampFullEval = System.currentTimeMillis();

        if (necessaryDataAvailable) {

            final Locale locale = new Locale(lang);
            final ResultOptions resultOptions = new ResultOptions(locale);
            final JSONArray resultList = new JSONArray();

            QoSTestResultDao resultDao = new QoSTestResultDao(conn);
            List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid());
            if (testResultList == null || testResultList.isEmpty()) {
                throw new UnsupportedOperationException("test " + test + " has no result list");
            }
            //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison
            Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>();

            //test description set:
            Set<String> testDescSet = new TreeSet<>();
            //test summary set:
            Set<String> testSummarySet = new TreeSet<>();

            //Staring timestamp for evaluation time measurement
            final long timeStampEval = System.currentTimeMillis();

            //iterate through all result entries
            for (final QoSTestResult testResult : testResultList) {

                //reset test counters
                testResult.setFailureCounter(0);
                testResult.setSuccessCounter(0);

                //get the correct class of the result;
                TestType testType = null;
                try {
                    testType = TestType.valueOf(testResult.getTestType().toUpperCase(Locale.US));
                } catch (IllegalArgumentException e) {
                    final String errorMessage = "WARNING: QoS TestType '"
                            + testResult.getTestType().toUpperCase(Locale.US)
                            + "' not supported by ControlServer. Test with UID: " + testResult.getUid()
                            + " skipped.";
                    System.out.println(errorMessage);
                    errorList.addErrorString(errorMessage);
                    testType = null;
                }

                if (testType == null) {
                    continue;
                }

                Class<? extends AbstractResult<?>> clazz = testType.getClazz();
                //parse hstore data
                final JSONObject resultJson = new JSONObject(testResult.getResults());
                AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson, clazz);
                result.setResultJson(resultJson);

                if (result != null) {
                    //add each test description key to the testDescSet (to fetch it later from the db)
                    if (testResult.getTestDescription() != null) {
                        testDescSet.add(testResult.getTestDescription());
                    }
                    if (testResult.getTestSummary() != null) {
                        testSummarySet.add(testResult.getTestSummary());
                    }
                    testResult.setResult(result);

                }

                //compare test results
                compareTestResults(testResult, result, resultKeys, testType, resultOptions);

                //resultList.put(testResult.toJson());

                //save all test results after the success and failure counters have been set
                //resultDao.updateCounter(testResult);
            }

            //ending timestamp for evaluation time measurement
            final long timeStampEvalEnd = System.currentTimeMillis();

            //-------------------------------------------------------------
            //fetch all result strings from the db
            QoSTestDescDao descDao = new QoSTestDescDao(conn, locale);

            //FIRST: get all test descriptions
            Set<String> testDescToFetchSet = testDescSet;
            testDescToFetchSet.addAll(testSummarySet);

            Map<String, String> testDescMap = descDao.getAllByKeyToMap(testDescToFetchSet);

            for (QoSTestResult testResult : testResultList) {

                //and set the test results + put each one to the result list json array
                String preParsedDesc = testDescMap.get(testResult.getTestDescription());
                if (preParsedDesc != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestDescription()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestDescription(description);
                }

                //do the same for the test summary:
                String preParsedSummary = testDescMap.get(testResult.getTestSummary());
                if (preParsedSummary != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestSummary()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestSummary(description);
                }

                resultList.put(testResult.toJson(uuid.getType()));
            }

            //finally put results to json
            answer.put("testresultdetail", resultList);

            JSONArray resultDescArray = new JSONArray();

            //SECOND: fetch all test result descriptions 
            for (TestType testType : resultKeys.keySet()) {
                TreeSet<ResultDesc> descSet = resultKeys.get(testType);
                //fetch results to same object
                descDao.loadToTestDesc(descSet);

                //another tree set for duplicate entries:
                //TODO: there must be a better solution 
                //(the issue is: compareTo() method returns differnt values depending on the .value attribute (if it's set or not))
                TreeSet<ResultDesc> descSetNew = new TreeSet<>();
                //add fetched results to json

                for (ResultDesc desc : descSet) {
                    if (!descSetNew.contains(desc)) {
                        descSetNew.add(desc);
                    } else {
                        for (ResultDesc d : descSetNew) {
                            if (d.compareTo(desc) == 0) {
                                d.getTestResultUidList().addAll(desc.getTestResultUidList());
                            }
                        }
                    }
                }

                for (ResultDesc desc : descSetNew) {
                    if (desc.getValue() != null) {
                        resultDescArray.put(desc.toJson());
                    }
                }

            }
            //System.out.println(resultDescArray);
            //put result descriptions to json
            answer.put("testresultdetail_desc", resultDescArray);

            QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
            JSONArray testTypeDescArray = new JSONArray();
            for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                final JSONObject testTypeDesc = desc.toJson();
                if (testTypeDesc != null) {
                    testTypeDescArray.put(testTypeDesc);
                }
            }

            //put result descriptions to json
            answer.put("testresultdetail_testdesc", testTypeDescArray);
            JSONObject evalTimes = new JSONObject();
            evalTimes.put("eval", (timeStampEvalEnd - timeStampEval));
            evalTimes.put("full", (System.currentTimeMillis() - timeStampFullEval));
            answer.put("eval_times", evalTimes);

            //System.out.println(answer);
        } else
            errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

    } else
        errorList.addError("ERROR_DB_CONNECTION");
}

From source file:com.greenpepper.server.rpc.xmlrpc.XmlRpcDataMarshaller.java

/**
 * Rebuild a List of runners based on the vector of runners parameters.
 * </p>// ww  w. j av a 2 s  .co  m
 *
 * @param runnersParams a {@link java.util.Vector} object.
 * @return a List of runners based on the vector of runners parameters.
 * @see #toRunner(Vector)
 */
@SuppressWarnings("unchecked")
public static TreeSet<Runner> toRunnerList(Vector<Object> runnersParams) {
    TreeSet<Runner> runners = new TreeSet<Runner>();
    for (Object runnerParams : runnersParams) {
        runners.add(toRunner((Vector<Object>) runnerParams));
    }

    return runners;
}

From source file:com.greenpepper.server.rpc.xmlrpc.XmlRpcDataMarshaller.java

/**
 * Rebuild a List of Environment types based on the vector of Environment types parameters.
 * </p>/*from   w ww.  j a v  a2 s . c o m*/
 *
 * @param envTypesParams a {@link java.util.Vector} object.
 * @return a List of Environment types based on the vector of Environment types parameters.
 * @see #toEnvironmentType(Vector)
 */
@SuppressWarnings("unchecked")
public static TreeSet<EnvironmentType> toEnvironmentTypeList(Vector<Object> envTypesParams) {
    TreeSet<EnvironmentType> envTypes = new TreeSet<EnvironmentType>();
    for (Object envTypeParams : envTypesParams) {
        envTypes.add(toEnvironmentType((Vector<Object>) envTypeParams));
    }

    return envTypes;
}

From source file:edu.umass.cs.gigapaxos.testing.TESTPaxosConfig.java

/**
 * Sets consistent, random groups starting with the same random seed.
 * //from   ww  w.j a  v a 2  s  .  c  om
 * @param numGroups
 */
public static void setRandomGroups(int numGroups) {
    // if(!getCleanDB()) return;
    Random r = new Random(RANDOM_SEED);
    for (int i = 0; i < Math.min(Config.getGlobalInt(TC.PRE_CONFIGURED_GROUPS), numGroups); i++) {
        groups.put(Config.getGlobalString(TC.TEST_GUID_PREFIX) + i, defaultGroup);
        if (i == 0)
            continue;// first group is always default group
        TreeSet<Integer> members = new TreeSet<Integer>();
        for (int id : TESTPaxosConfig.getNodes()) {
            if (r.nextDouble() > Config.getGlobalDouble(TC.NODE_INCLUSION_PROB)) {
                members.add(id);
            }
        }
        TESTPaxosConfig.setGroup(TESTPaxosConfig.getGroupName(i), members);
    }
}

From source file:org.opendatakit.persistence.table.GrantedAuthorityHierarchyTable.java

public static final TreeSet<String> getAllPermissionsAssignableGrantedAuthorities(Datastore ds, User user)
        throws ODKDatastoreException {

    GrantedAuthorityHierarchyTable relation;
    relation = GrantedAuthorityHierarchyTable.assertRelation(ds, user);
    Query query;//w w w .  ja  v a  2  s  .c  o m

    TreeSet<String> assignableGroups = new TreeSet<String>();

    {
        List<?> domGroupsList;
        query = ds.createQuery(relation,
                "GrantedAuthorityHierarchyTable.getAllPermissionsAssignableGrantedAuthorities", user);
        domGroupsList = query
                .executeDistinctValueForDataField(GrantedAuthorityHierarchyTable.DOMINATING_GRANTED_AUTHORITY);

        for (Object o : domGroupsList) {
            String groupName = (String) o;
            if (!GrantedAuthorityName.permissionsCanBeAssigned(groupName))
                continue;
            assignableGroups.add(groupName);
        }
    }

    {
        List<?> subGroupsList;
        query = ds.createQuery(relation,
                "GrantedAuthorityHierarchyTable.getAllPermissionsAssignableGrantedAuthorities", user);
        subGroupsList = query
                .executeDistinctValueForDataField(GrantedAuthorityHierarchyTable.SUBORDINATE_GRANTED_AUTHORITY);

        for (Object o : subGroupsList) {
            String groupName = (String) o;
            if (!GrantedAuthorityName.permissionsCanBeAssigned(groupName))
                continue;
            assignableGroups.add(groupName);
        }
    }

    return assignableGroups;
}

From source file:edu.lternet.pasta.portal.search.AuthorSearch.java

/**
 * Parses the Solr query results using regular expression matching (as
 * opposed to XML parsing)//from w  w  w  .j  a  v a 2 s .  co  m
 * 
 * @param xml             the Solr query results, an XML document string
 * @param fieldName       the field name to parse out of the XML, e.g. "author"
 * @return                a String array of field values parsed from the XML
 */
private static String[] parseQueryResults(String xml, String fieldName) {
    String[] values = null;
    final String patternStr = String.format("^\\s*<%s>(.+)</%s>\\s*$", fieldName, fieldName);
    Pattern pattern = Pattern.compile(patternStr);
    TreeSet<String> valueSet = new TreeSet<String>();

    if (xml != null) {
        String[] lines = xml.split("\n");
        for (String line : lines) {
            Matcher matcher = pattern.matcher(line);
            if (matcher.matches()) {
                String capturedValue = matcher.group(1).trim();
                String unescapedXML = StringEscapeUtils.unescapeXml(capturedValue);
                String trimmedXML = unescapedXML.replace("\r", " ").replace("\n", " ").replaceAll("\\s+", " ")
                        .trim();
                String escapedXML = StringEscapeUtils.escapeXml(trimmedXML);
                valueSet.add(escapedXML);
            }
        }

        values = valueSet.toArray(new String[valueSet.size()]);
    }

    return values;
}

From source file:com.opendoorlogistics.core.utils.strings.Strings.java

public static TreeSet<String> toTreeSet(String... strs) {
    TreeSet<String> ret = new TreeSet<>();
    for (String s : strs) {
        ret.add(s);
    }//from www. ja  v a  2  s  . c  o  m
    return ret;
}