Example usage for java.util TreeSet contains

List of usage examples for java.util TreeSet contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:DecorateMutationsSNP.java

/**
 * The procedure creates a .txt file containing the information about the SNP mutations in the extant units
 * The first row represents the position of each mutation that is a double value in the interval (0,1)
 * The other rows represent the leave nodes as a matrix of 0 and 1 indicating the absence/presence of the corresponding mutation
 * @param wholePath path of the directory where the output file is stored
 * @param arg instance of the class PopulationARG that represents the ARG of a single population (in this case and actual population)
 * @see PopulationARG/*from   w w  w . j a va2s. com*/
 */
public static void createSNP_TxtFile(String wholePath, PopulationARG arg) {
    Writer writer = null;
    File file = new File("" + wholePath);

    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));

        TreeSet<Double> posMutations = GenerateAdmixturePopulations.getAllMutations();
        //System.out.println("Creating file SNPs for population "+arg.getId_pop());
        //System.out.println("# of all mutations in all populations "+posMutations.size());

        writer.write("Population " + arg.getId_pop() + "\n");
        writer.write("Number of extant units (rows): " + arg.getExtantUnits() + "\n");
        writer.write("Number of SNPs for each extant unit (columns): " + posMutations.size() + "\n\n");

        Iterator<Double> it_posMuts = posMutations.iterator();
        Double position;
        while (it_posMuts.hasNext()) {
            position = it_posMuts.next();
            String troncato = String.format("%.4f", position);
            writer.write(troncato + " ");
        }
        writer.write("\n\n");

        //For each leave print a row representing the absence or presence of SNP mutations
        for (int i = 0; i < arg.getExtantUnits(); i++) {

            it_posMuts = posMutations.iterator();

            while (it_posMuts.hasNext()) {

                position = it_posMuts.next();

                //check if the arg has the mutation
                if (arg.getMutationSet().containsKey(position)) {

                    //if yes then check if the leaf has the mutation
                    //Mutation mut = arg.getMutationSet().get(position);
                    TreeSet<Double> muts_set = arg.getNodeSet().get(i).getMutation_set();

                    if (muts_set.contains(position))
                        writer.write("1 ");
                    else
                        writer.write("0 ");
                } else
                    writer.write("0 ");
            }
            writer.write("\n");

        }

        writer.close();

    } //fine try 

    catch (IOException ex) {
        // report
    }
}

From source file:org.ariadne.oai.utils.HarvesterUtils.java

public static ReposProperties addRepository(ReposProperties repoProps) throws Exception {

    OAIRepository repository = new OAIRepository();
    String fallBackReposId = repoProps.getBaseURL().replaceFirst("http.?://", "").split("/", 2)[0].split(":",
            2)[0];/*from   w  ww . j  av  a  2s.c om*/
    String internalId = fallBackReposId.replaceAll("\\.", "_");

    Hashtable ids = PropertiesManager.getInstance().getPropertyStartingWith(internalId);
    TreeSet<String> allIds = new TreeSet<String>();
    for (Object o : ids.keySet()) {
        allIds.add(((String) o).split("\\.")[0]);
    }
    int i = 1;
    while (allIds.contains(internalId)) {
        internalId = internalId.split("_u_")[0] + "_u_" + i++;
    }

    String urlString = repoProps.getBaseURL() + "?verb=Identify";
    try {
        URL u = new URL(urlString);
        HttpURLConnection http = (HttpURLConnection) u.openConnection();
        if (http.getResponseCode() == 200) {
            repository.setBaseURL(repoProps.getBaseURL());
            String url = repository.getBaseURL();
        } else {
            throw new IOException(Integer.toString(http.getResponseCode()));
        }
    } catch (IOException ex) {
        throw new Exception("The given Url isn't a valid OAI Repository (Could not connect to Url \""
                + urlString + "\". ErrorMsg was : " + ex.getMessage() + ") ");
    } catch (OAIException e) {
        throw new Exception(
                "The given Url \"" + urlString + "\" isn't a valid OAI Repository (" + e.getMessage() + ").");
    } catch (IllegalStateException e) {
        try {
            throw new Exception(
                    "The baseUrl of the OAI Repository is not correct (found url in Identify verb : "
                            + repository.getBaseURL() + ")");
        } catch (OAIException e1) {
            throw new Exception(
                    "The baseUrl of the OAI Repository is not correct (Error : " + e1.getMessage() + ")");
        }
    } catch (Exception e) {
        throw new Exception(
                "The following error occured : (" + e.getClass().getName() + ") " + e.getMessage() + ".");
    }

    return addTarget(repoProps, repository, fallBackReposId, internalId);
}

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

/**
 * //from   w w w. j a v  a  2 s.c om
 * @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:org.apache.hadoop.hdfs.server.namenode.JspHelper.java

public static DatanodeInfo bestNode(LocatedBlock blk) throws IOException {
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
    DatanodeInfo chosenNode = null;/*from  ww  w  .j a v a  2 s  . co m*/
    int failures = 0;
    Socket s = null;
    DatanodeInfo[] nodes = blk.getLocations();
    if (nodes == null || nodes.length == 0) {
        throw new IOException("No nodes contain this block");
    }
    while (s == null) {
        if (chosenNode == null) {
            do {
                chosenNode = nodes[rand.nextInt(nodes.length)];
            } while (deadNodes.contains(chosenNode));
        }
        int index = rand.nextInt(nodes.length);
        chosenNode = nodes[index];

        //just ping to check whether the node is alive
        InetSocketAddress targetAddr = NetUtils
                .createSocketAddr(chosenNode.getHost() + ":" + chosenNode.getInfoPort());

        try {
            s = new Socket();
            s.connect(targetAddr, HdfsConstants.READ_TIMEOUT);
            s.setSoTimeout(HdfsConstants.READ_TIMEOUT);
        } catch (IOException e) {
            deadNodes.add(chosenNode);
            s.close();
            s = null;
            failures++;
        }
        if (failures == nodes.length)
            throw new IOException("Could not reach the block containing the data. Please try again");

    }
    s.close();
    return chosenNode;
}

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

public static String getFiltered(String s, char... acceptChars) {
    TreeSet<Character> set = new TreeSet<>();
    for (char c : acceptChars) {
        set.add(c);/*from w  ww. java2 s. c  o m*/
    }
    StringBuilder ret = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (set.contains(s.charAt(i))) {
            ret.append(s.charAt(i));
        }
    }
    return ret.toString();
}

From source file:net.spfbl.core.Reverse.java

public static String getListedIP(String ip, String server, Collection<String> valueSet) {
    String host = Reverse.getHostReverse(ip, server);
    if (host == null) {
        return null;
    } else {/*from ww w  .  j  av  a 2  s . c  om*/
        try {
            TreeSet<String> IPv4Set = null;
            TreeSet<String> IPv6Set = null;
            for (String value : valueSet) {
                if (SubnetIPv4.isValidIPv4(value)) {
                    if (IPv4Set == null) {
                        IPv4Set = getIPv4Set(host);
                    }
                    if (IPv4Set.contains(value)) {
                        return value;
                    }
                } else if (SubnetIPv6.isValidIPv6(value)) {
                    if (IPv6Set == null) {
                        IPv6Set = getIPv6Set(host);
                    }
                    if (IPv6Set.contains(value)) {
                        return value;
                    }
                }
            }
            return null;
        } catch (CommunicationException ex) {
            Server.logDebug("DNS service '" + server + "' unreachable.");
            return null;
        } catch (ServiceUnavailableException ex) {
            Server.logDebug("DNS service '" + server + "' unavailable.");
            return null;
        } catch (NameNotFoundException ex) {
            // No listado.
            return null;
        } catch (NamingException ex) {
            Server.logError(ex);
            return null;
        }
    }
}

From source file:net.spfbl.core.Reverse.java

public static String getListedHost(String host, String zone, Collection<String> valueSet) {
    host = Domain.normalizeHostname(host, false);
    if (host == null) {
        return null;
    } else {// www .  j  av  a2  s .c om
        try {
            host = host + '.' + zone;
            TreeSet<String> IPv4Set = null;
            TreeSet<String> IPv6Set = null;
            for (String value : valueSet) {
                if (SubnetIPv4.isValidIPv4(value)) {
                    if (IPv4Set == null) {
                        IPv4Set = getIPv4Set(host);
                    }
                    if (IPv4Set.contains(value)) {
                        return value;
                    }
                } else if (SubnetIPv6.isValidIPv6(value)) {
                    if (IPv6Set == null) {
                        IPv6Set = getIPv6Set(host);
                    }
                    if (IPv6Set.contains(value)) {
                        return value;
                    }
                }
            }
            return null;
        } catch (CommunicationException ex) {
            Server.logDebug("DNS service '" + zone + "' unreachable.");
            return null;
        } catch (ServiceUnavailableException ex) {
            Server.logDebug("DNS service '" + zone + "' unavailable.");
            return null;
        } catch (NameNotFoundException ex) {
            // No listado.
            return null;
        } catch (NamingException ex) {
            Server.logError(ex);
            return null;
        }
    }
}

From source file:desmoj.extensions.visualization2d.engine.modelGrafic.StatisticGrafic.java

/**
 * get all views (viewId's) with Statistic
 * @return//from  www  .j  a va2 s  . co  m
 */
public static String[] getViews(Model model) {
    TreeSet<String> views = new TreeSet<String>();
    String[] ids = model.getStatistics().getAllIds();
    for (int i = 0; i < ids.length; i++) {
        Statistic statistic = model.getStatistics().get(ids[i]);
        StatisticGrafic statisticGrafic = (StatisticGrafic) statistic.getGrafic();
        if (statisticGrafic != null) {
            String viewId = statisticGrafic.getViewId();
            if (!views.contains(viewId))
                views.add(viewId);
        }
    }
    String[] out = new String[views.size()];
    int i = 0;
    for (Iterator<String> it = views.iterator(); it.hasNext();) {
        out[i] = it.next();
        i++;
    }
    return out;

}

From source file:org.opendatakit.aggregate.odktables.impl.api.RealizedTableServiceImpl.java

@Override
public Response deleteTable() throws ODKDatastoreException, ODKTaskLockException, PermissionDeniedException {

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(cc);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }/*from  www .  ja v  a  2s .co  m*/

    tm.deleteTable(tableId);
    logger.info("tableId: " + tableId);
    Datastore ds = cc.getDatastore();
    if (ds instanceof DatastoreImpl) {
        ((DatastoreImpl) ds).getDam().logUsage();
    }
    return Response.ok().header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:org.opendatakit.aggregate.servlet.GetUsersAndPermissionsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getScheme().equals("http")) {
        logger.warn("Retrieving users and capabilities over http");
    }/*from  w w  w . j  a v  a  2  s  .c  om*/
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    ArrayList<UserSecurityInfo> allUsers;

    try {
        allUsers = SecurityServiceUtil.getAllUsers(true, cc);
    } catch (DatastoreFailureException e) {
        logger.error("Retrieving users and capabilities .csv persistence error: " + e.toString());
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
        return;
    } catch (AccessDeniedException e) {
        logger.error("Retrieving users and capabilities .csv access denied error: " + e.toString());
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }

    StringWriter buffer = new StringWriter();
    RFC4180CsvWriter writer = new RFC4180CsvWriter(buffer);

    String[] columnContent = new String[10];

    columnContent[0] = "Username";
    columnContent[1] = "Full Name";
    columnContent[2] = "Account Type";
    columnContent[3] = "Data Collector";
    columnContent[4] = "Data Viewer";
    columnContent[5] = "Form Manager";
    columnContent[6] = "Synchronize Tables";
    columnContent[7] = "Tables Super-user";
    columnContent[8] = "Administer Tables";
    columnContent[9] = "Site Administrator";

    writer.writeNext(columnContent);
    for (UserSecurityInfo i : allUsers) {

        if (i.getType() == UserType.REGISTERED) {
            if (i.getEmail() != null) {
                columnContent[0] = i.getEmail().substring(EmailParser.K_MAILTO.length());
                columnContent[2] = "Google";
            } else {
                columnContent[0] = i.getUsername();
                columnContent[2] = "ODK";
            }
            columnContent[1] = i.getFullName();
        } else {
            columnContent[0] = User.ANONYMOUS_USER;
            columnContent[1] = User.ANONYMOUS_USER_NICKNAME;
            columnContent[2] = null;
        }
        TreeSet<GrantedAuthorityName> grants = i.getAssignedUserGroups();
        columnContent[3] = grants.contains(GrantedAuthorityName.GROUP_DATA_COLLECTORS) ? "X" : null;
        columnContent[4] = grants.contains(GrantedAuthorityName.GROUP_DATA_VIEWERS) ? "X" : null;
        columnContent[5] = grants.contains(GrantedAuthorityName.GROUP_FORM_MANAGERS) ? "X" : null;
        columnContent[6] = grants.contains(GrantedAuthorityName.GROUP_SYNCHRONIZE_TABLES) ? "X" : null;
        columnContent[7] = grants.contains(GrantedAuthorityName.GROUP_SUPER_USER_TABLES) ? "X" : null;
        columnContent[8] = grants.contains(GrantedAuthorityName.GROUP_ADMINISTER_TABLES) ? "X" : null;
        columnContent[9] = grants.contains(GrantedAuthorityName.GROUP_SITE_ADMINS) ? "X" : null;
        writer.writeNext(columnContent);
    }
    writer.close();
    // do not cache...
    resp.setHeader("Cache-Control:", "no-cache, no-store, must-revalidate");
    resp.setHeader("Pragma:", "no-cache");
    resp.setHeader("Expires:", "0");

    resp.setHeader("Last-Modified:", WebUtils.rfc1123Date(new Date()));
    resp.setContentType(HtmlConsts.RESP_TYPE_CSV);
    resp.addHeader(HtmlConsts.CONTENT_DISPOSITION, "attachment; filename=\"UsersAndCapabilities.csv\"");
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getOutputStream().write(buffer.getBuffer().toString().getBytes(CharEncoding.UTF_8));
}