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.jasig.portlet.calendar.processor.ICalendarContentProcessorTest.java

@Test
public void test() throws IOException {

    Resource calendarFile = applicationContext.getResource("classpath:/sampleEvents.ics");

    DateMidnight start = new DateMidnight(2010, 1, 1, DateTimeZone.UTC);
    Interval interval = new Interval(start, start.plusYears(3));

    InputStream in = calendarFile.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    IOUtils.copyLarge(in, buffer);/*from   www . ja va  2  s. co m*/

    TreeSet<VEvent> events = new TreeSet<VEvent>(new VEventStartComparator());
    net.fortuna.ical4j.model.Calendar c = processor.getIntermediateCalendar(interval,
            new ByteArrayInputStream(buffer.toByteArray()));
    events.addAll(processor.getEvents(interval, c));

    assertEquals(5, events.size());

    Iterator<VEvent> iterator = events.iterator();
    VEvent event = iterator.next();
    assertEquals("Independence Day", event.getSummary().getValue());
    assertNull(event.getStartDate().getTimeZone());

    event = iterator.next();
    assertEquals("Vikings @ Saints  [NBC]", event.getSummary().getValue());
    DateTime eventStart = new DateTime(event.getStartDate().getDate(), DateTimeZone.UTC);
    assertEquals(0, eventStart.getHourOfDay());
    assertEquals(30, eventStart.getMinuteOfHour());

    event = iterator.next();
    assertEquals("Independence Day", event.getSummary().getValue());
    assertNull(event.getStartDate().getTimeZone());

}

From source file:edu.udo.scaffoldhunter.model.clustering.evaluation.FileSaverMetaModule.java

/**
 * Construct and save the OrderedBySubsetSize CSV string / file
 * /*from   w  w  w  .  j  av a2  s  . c  o  m*/
 * @param results
 */
private void saveCSVOrderedBySubsetSize(Collection<EvaluationResult> results) {
    StringBuilder csvString = new StringBuilder();

    // ordered keys of all results
    TreeSet<String> keys = Sets.newTreeSet();
    for (EvaluationResult result : results) {
        keys.addAll(result.getResults().keySet());
    }

    // create csv header
    csvString.append("subset size,");
    for (String key : keys) {
        csvString.append(key);
        csvString.append(",");
    }
    csvString.deleteCharAt(csvString.length() - 1);

    // create csv data & store single result file (not storing
    // csv file at this point)
    for (EvaluationResult result : results) {
        csvString.append(System.getProperty("line.separator").toString());
        csvString.append(result.getSubsetSize());
        csvString.append(",");
        for (String key : keys) {
            String value = result.getResults().get(key);
            if (value != null) {
                csvString.append(value);
            }
            csvString.append(",");
        }
        csvString.deleteCharAt(csvString.length() - 1);
    }

    saveToFile(
            FilenameUtils.concat(FilenameUtils.getFullPathNoEndSeparator(path), FilenameUtils.getBaseName(path))
                    + FilenameUtils.EXTENSION_SEPARATOR + "csv",
            csvString.toString());
}

From source file:onl.netfishers.netshot.Database.java

/**
 * Find classes with a path./*from  ww  w.  j  a  va  2 s. c  om*/
 *
 * @param path the path
 * @param packageName the package name
 * @return the tree set
 * @throws MalformedURLException the malformed url exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static TreeSet<String> findClasses(String path, String packageName)
        throws MalformedURLException, IOException {
    TreeSet<String> classes = new TreeSet<String>();
    if (path.startsWith("file:") && path.contains("!")) {
        String[] split = path.split("!");
        URL jar = new URL(split[0]);
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            if (entry.getName().endsWith(".class")) {
                String className = entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "")
                        .replace('/', '.');
                if (className.startsWith(packageName)) {
                    classes.add(className);
                }
            }
        }
    }
    File dir = new File(path);
    if (!dir.exists()) {
        return classes;
    }
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            assert !file.getName().contains(".");
            classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName()));
        } else if (file.getName().endsWith(".class")) {
            String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
            classes.add(className);
        }
    }
    return classes;
}

From source file:com.effektif.adapter.helpers.RequestLogger.java

private Set<Map.Entry<String, List<String>>> getSortedHeaders(
        final Set<Map.Entry<String, List<String>>> headers) {
    final TreeSet<Map.Entry<String, List<String>>> sortedHeaders = new TreeSet<Map.Entry<String, List<String>>>(
            COMPARATOR);//from  w  ww.  j  a v a  2  s  . co m
    sortedHeaders.addAll(headers);
    return sortedHeaders;
}

From source file:com.alibaba.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  %-32s  %-4s  %-22s %-22s %11s %11s\n", //
            "#Cluster Name", //
            "#Broker Name", //
            "#BID", //
            "#Addr", //
            "#Version", //
            "#InTPS", //
            "#OutTPS"//
    );/*from  w w  w. j  a  va  2 s  .  com*/

    Iterator<Map.Entry<String, Set<String>>> itCluster = clusterInfoSerializeWrapper.getClusterAddrTable()
            .entrySet().iterator();
    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 = "";

                    try {
                        KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(next1.getValue());
                        String putTps = kvTable.getTable().get("putTps");
                        String getTransferedTps = kvTable.getTable().get("getTransferedTps");
                        version = kvTable.getTable().get("brokerVersionDesc");
                        {
                            String[] tpss = putTps.split(" ");
                            if (tpss != null && tpss.length > 0) {
                                in = Double.parseDouble(tpss[0]);
                            }
                        }

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

                    System.out.printf("%-16s  %-32s  %-4s  %-22s %-22s %11.2f %11.2f\n", //
                            clusterName, //
                            brokerName, //
                            next1.getKey().longValue(), //
                            next1.getValue(), //
                            version, //
                            in, //
                            out//
                    );
                }
            }
        }

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

From source file:com.alibaba.rocketmq.tools.command.cluster.ClusterListSubCommand.java

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

    ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();

    System.out.printf("%-16s  %-32s %14s %14s %14s %14s\n", //
            "#Cluster Name", //
            "#Broker Name", //
            "#InTotalYest", //
            "#OutTotalYest", //
            "#InTotalToday", //
            "#OutTotalToday"//
    );//  w w w  .  j a  v  a 2s  . c o m

    Iterator<Map.Entry<String, Set<String>>> itCluster = clusterInfoSerializeWrapper.getClusterAddrTable()
            .entrySet().iterator();
    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();
                    long InTotalYest = 0;
                    long OutTotalYest = 0;
                    long InTotalToday = 0;
                    long OutTotalToday = 0;

                    try {
                        KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(next1.getValue());
                        String msgPutTotalYesterdayMorning = kvTable.getTable()
                                .get("msgPutTotalYesterdayMorning");
                        String msgPutTotalTodayMorning = kvTable.getTable().get("msgPutTotalTodayMorning");
                        String msgPutTotalTodayNow = kvTable.getTable().get("msgPutTotalTodayNow");
                        String msgGetTotalYesterdayMorning = kvTable.getTable()
                                .get("msgGetTotalYesterdayMorning");
                        String msgGetTotalTodayMorning = kvTable.getTable().get("msgGetTotalTodayMorning");
                        String msgGetTotalTodayNow = kvTable.getTable().get("msgGetTotalTodayNow");

                        InTotalYest = Long.parseLong(msgPutTotalTodayMorning)
                                - Long.parseLong(msgPutTotalYesterdayMorning);
                        OutTotalYest = Long.parseLong(msgGetTotalTodayMorning)
                                - Long.parseLong(msgGetTotalYesterdayMorning);

                        InTotalToday = Long.parseLong(msgPutTotalTodayNow)
                                - Long.parseLong(msgPutTotalTodayMorning);
                        OutTotalToday = Long.parseLong(msgGetTotalTodayNow)
                                - Long.parseLong(msgGetTotalTodayMorning);

                    } catch (Exception e) {
                    }

                    System.out.printf("%-16s  %-32s %14d %14d %14d %14d\n", //
                            clusterName, //
                            brokerName, //
                            InTotalYest, //
                            OutTotalYest, //
                            InTotalToday, //
                            OutTotalToday//
                    );
                }
            }
        }

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

From source file:org.motechproject.server.omod.web.model.JSONLocationSerializer.java

public void populateJavascriptMaps(ModelMap model) {
    Map<String, TreeSet<String>> regionMap = new HashMap<String, TreeSet<String>>();
    Map<String, TreeSet<Community>> districtMap = new HashMap<String, TreeSet<Community>>();

    MotechService motechService = contextService.getMotechService();
    List<Facility> facilities = motechService.getAllFacilities();
    List<MessageLanguage> languages = motechService.getAllLanguages();

    for (Facility facility : facilities) {
        Location location = facility.getLocation();
        if (location != null) {
            String region = location.getRegion();
            String district = location.getCountyDistrict();
            TreeSet<String> districts = regionMap.get(region);
            if (districts == null) {
                districts = new TreeSet<String>();
            }//from  w  ww  . ja v  a2 s. co m
            if (StringUtils.isNotEmpty(district))
                districts.add(district);
            regionMap.put(region, districts);
            TreeSet<Community> communities = districtMap.get(district);
            if (communities == null) {
                communities = new TreeSet<Community>(communityNameComparator);
            }
            communities.addAll(facility.getCommunities());
            districtMap.put(district, communities);
        }
    }
    FacilityComparator facilityComparator = new FacilityComparator();
    Collections.sort(facilities, facilityComparator);

    model.addAttribute("languages", languages);
    model.addAttribute("regionMap", regionMap);
    model.addAttribute("districtMap", districtMap);
    model.addAttribute("facilities", facilities);
    model.addAttribute("country", new Country("Ghana").withFacilities(facilities));

}

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

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

    ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();

    System.out.printf("%-16s  %-32s %14s %14s %14s %14s%n", "#Cluster Name", "#Broker Name", "#InTotalYest",
            "#OutTotalYest", "#InTotalToday", "#OutTotalToday");

    Iterator<Map.Entry<String, Set<String>>> itCluster = clusterInfoSerializeWrapper.getClusterAddrTable()
            .entrySet().iterator();/*ww  w .  jav  a  2  s  .c  o m*/
    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();
                    long inTotalYest = 0;
                    long outTotalYest = 0;
                    long inTotalToday = 0;
                    long outTotalToday = 0;

                    try {
                        KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(next1.getValue());
                        String msgPutTotalYesterdayMorning = kvTable.getTable()
                                .get("msgPutTotalYesterdayMorning");
                        String msgPutTotalTodayMorning = kvTable.getTable().get("msgPutTotalTodayMorning");
                        String msgPutTotalTodayNow = kvTable.getTable().get("msgPutTotalTodayNow");
                        String msgGetTotalYesterdayMorning = kvTable.getTable()
                                .get("msgGetTotalYesterdayMorning");
                        String msgGetTotalTodayMorning = kvTable.getTable().get("msgGetTotalTodayMorning");
                        String msgGetTotalTodayNow = kvTable.getTable().get("msgGetTotalTodayNow");

                        inTotalYest = Long.parseLong(msgPutTotalTodayMorning)
                                - Long.parseLong(msgPutTotalYesterdayMorning);
                        outTotalYest = Long.parseLong(msgGetTotalTodayMorning)
                                - Long.parseLong(msgGetTotalYesterdayMorning);

                        inTotalToday = Long.parseLong(msgPutTotalTodayNow)
                                - Long.parseLong(msgPutTotalTodayMorning);
                        outTotalToday = Long.parseLong(msgGetTotalTodayNow)
                                - Long.parseLong(msgGetTotalTodayMorning);

                    } catch (Exception e) {
                    }

                    System.out.printf("%-16s  %-32s %14d %14d %14d %14d%n", clusterName, brokerName,
                            inTotalYest, outTotalYest, inTotalToday, outTotalToday);
                }
            }
        }

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

From source file:gr.cti.android.experimentation.controller.api.HistoryController.java

@ApiOperation(value = "experiment")
@ResponseBody//from  ww  w. jav  a2s  .c o m
@RequestMapping(value = { "/entities/{entity_id}/readings" }, method = RequestMethod.GET)
public HistoricDataDTO experimentView(@PathVariable("entity_id") final String entityId,
        @RequestParam(value = "attribute_id") final String attributeId,
        @RequestParam(value = "from") final String from, @RequestParam(value = "to") final String to,
        @RequestParam(value = "all_intervals", required = false, defaultValue = "true") final boolean allIntervals,
        @RequestParam(value = "rollup", required = false, defaultValue = "") final String rollup,
        @RequestParam(value = "function", required = false, defaultValue = "avg") final String function) {

    final HistoricDataDTO historicDataDTO = new HistoricDataDTO();
    historicDataDTO.setEntity_id(entityId);
    historicDataDTO.setAttribute_id(attributeId);
    historicDataDTO.setFunction(function);
    historicDataDTO.setRollup(rollup);
    historicDataDTO.setFrom(from);
    historicDataDTO.setTo(to);
    historicDataDTO.setReadings(new ArrayList<>());

    final List<TempReading> tempReadings = new ArrayList<>();

    long fromLong = parseDateMillis(from);
    long toLong = parseDateMillis(to);

    final String[] parts = entityId.split(":");
    final String phoneId = parts[parts.length - 1];

    LOGGER.info("phoneId: " + phoneId + " from: " + from + " to: " + to);

    final Set<Result> results = resultRepository.findByDeviceIdAndTimestampBetween(Integer.parseInt(phoneId),
            fromLong, toLong);

    final Set<Result> resultsCleanup = new HashSet<>();

    for (final Result result : results) {
        try {
            final JSONObject readingList = new JSONObject(result.getMessage());
            final Iterator keys = readingList.keys();
            while (keys.hasNext()) {
                final String key = (String) keys.next();
                if (key.contains(attributeId)) {
                    tempReadings.add(new TempReading(result.getTimestamp(), readingList.getDouble(key)));
                }
            }
        } catch (JSONException e) {
            resultsCleanup.add(result);
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
    }
    resultRepository.delete(resultsCleanup);

    List<TempReading> rolledUpTempReadings = new ArrayList<>();

    if ("".equals(rollup)) {
        rolledUpTempReadings = tempReadings;
    } else {
        final Map<Long, SummaryStatistics> dataMap = new HashMap<>();
        for (final TempReading tempReading : tempReadings) {
            Long millis = null;
            //TODO: make rollup understand the first integer part
            if (rollup.endsWith("m")) {
                millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0)
                        .getMillis();
            } else if (rollup.endsWith("h")) {
                millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0)
                        .withMinuteOfHour(0).getMillis();
            } else if (rollup.endsWith("d")) {
                millis = new DateTime(tempReading.getTimestamp()).withMillisOfDay(0).getMillis();
            }
            if (millis != null) {
                if (!dataMap.containsKey(millis)) {
                    dataMap.put(millis, new SummaryStatistics());
                }
                dataMap.get(millis).addValue(tempReading.getValue());
            }
        }

        final TreeSet<Long> treeSet = new TreeSet<>();
        treeSet.addAll(dataMap.keySet());

        if (allIntervals) {
            fillMissingIntervals(treeSet, rollup, toLong);
        }

        for (final Long millis : treeSet) {
            if (dataMap.containsKey(millis)) {
                rolledUpTempReadings.add(parse(millis, function, dataMap.get(millis)));
            } else {
                rolledUpTempReadings.add(new TempReading(millis, 0));
            }
        }
    }

    for (final TempReading tempReading : rolledUpTempReadings) {
        List<Object> list = new ArrayList<>();
        list.add(df.format(tempReading.getTimestamp()));
        list.add(tempReading.getValue());
        historicDataDTO.getReadings().add(list);
    }
    return historicDataDTO;
}

From source file:eu.fusepool.tests.BaseTest.java

@Before
public void waitForServerReady() throws Exception {
    log.debug("> before {}#waitForServerReady()", getClass().getSimpleName());
    if (serverReady) {
        log.debug(" ... server already marked as ready!");
        return;//  ww w . j  ava2 s . c  o m
    }

    // Timeout for readiness test
    final String sec = System.getProperty(SERVER_READY_TIMEOUT_PROP);
    final int timeoutSec = 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(System.getProperties().keySet());
    for (Object o : propertyNames) {
        final String key = (String) o;
        if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
            testPaths.add(System.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 matches the regexp supplied with the path
    long sleepTime = 100;
    readyLoop: while (!serverReady && System.currentTimeMillis() < endTime) {
        // Wait a bit between checks, to let the server come up
        Thread.sleep(sleepTime);
        sleepTime = Math.min(5000L, sleepTime * 2);

        // A test path is in the form path:substring or just path, in which case
        // we don't check that the content contains the substring 
        log.debug(" - check serverReady Paths");
        for (String p : testPaths) {
            log.debug("    > path: {}", p);
            final String[] s = p.split(":");
            final String path = s[0];
            final String substring = (s.length > 0 ? s[1] : null);
            final String url = serverBaseUrl + path;
            log.debug("    > url: {}", url);
            log.debug("    > content: {}", substring);
            final HttpGet get = new HttpGet(url);
            //authenticate as admin with password admin
            get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
            for (int i = 2; i + 1 < s.length; i = i + 2) {
                log.debug("    > header: {}:{}", s[i], s[i + 1]);
                if (s[i] != null && !s[i].isEmpty() && s[i + 1] != null && !s[i + 1].isEmpty()) {
                    get.setHeader(s[i], s[i + 1]);
                }
            }
            HttpEntity entity = null;
            try {
                log.debug("    > execute: {}", get);
                HttpResponse response = httpClient.execute(get);
                log.debug("    > response: {}", response);
                entity = response.getEntity();
                final int status = response.getStatusLine().getStatusCode();
                if (status != 200) {
                    log.info("Got {} at {} - will retry", status, url);
                    continue readyLoop;
                } else {
                    log.debug("Got {} at {} - will retry", status, url);
                }

                if (substring != null) {
                    if (entity == null) {
                        log.info("No entity returned for {} - will retry", url);
                        continue readyLoop;
                    }
                    final String content = EntityUtils.toString(entity);
                    final boolean checkAbsence = substring.startsWith("!");
                    final String notPresentString = substring.substring(1);
                    if ((!checkAbsence && content.contains(substring))
                            || (checkAbsence && content.contains(notPresentString))) {
                        log.debug("Returned content for {}  contains {} - ready", url, substring);
                    } else {
                        log.info("Returned content for {}  does not contain " + "{} - will retry", url,
                                substring);
                        continue readyLoop;

                    }
                }
            } catch (ConnectException e) {
                log.info("Got {} at {} - will retry", e.getClass().getSimpleName(), url);
                continue readyLoop;
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        log.info("Got expected content for all configured requests, server is ready");
        //Some additional wait time, as not everything can be tested with the paths
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        serverReady = true;
    }

    if (!serverReady) {
        throw new Exception("Server not ready after " + timeoutSec + " seconds");
    }
}