List of usage examples for java.util TreeMap values
public Collection<V> values()
From source file:com.qpark.eip.core.ToString.java
private static String toString(final String name, final Object o, final boolean outInputStreams) { StringBuffer sb = new StringBuffer(4098); if (o == null) { sb.append(outName(name, o));/*w ww .ja v a 2s . com*/ sb.append("null"); } else if (o.getClass().isEnum()) { sb.append(toString(name, (Enum<?>) o)); } else if (o.getClass().isArray()) { sb.append(toStringNativeArray(name, o)); } else if (Collection.class.isInstance(o)) { sb.append(toString(name, ((Collection<?>) o).toArray(new Object[0]))); } else if (InputStream.class.isInstance(o)) { sb.append(outName(name, o)); try { if (outInputStreams) { sb.append(new String(IOUtils.toByteArray((InputStream) o))); } else { sb.append(IOUtils.toByteArray((InputStream) o).length); } } catch (IOException e) { sb.append("Can not get bytes out of InputStream ").append(name); } } else if (Reader.class.isInstance(o)) { sb.append(outName(name, o)); try { sb.append(new String(IOUtils.toByteArray((Reader) o))); } catch (IOException e) { sb.append("Can not get bytes out of Reader ").append(name); } } else if (Throwable.class.isInstance(o)) { sb.append(outName(name, o)); sb.append(getStackTrace((Throwable) o)); } else if (hasToStringMethod(o)) { sb.append(outName(name, o)); sb.append(o.toString()); } else { sb.append(outName(name, o)); TreeMap<String, ObjectProperties> ops = PropertyDescriptorUtil.getObjectProperties(o); Object ox; int i = 0; for (ObjectProperties op : ops.values()) { if (i > 0) { sb.append(", "); } try { ox = op.read.invoke(o, PropertyDescriptorUtil.EMPTY); if (ox == null) { sb.append(outName(op.name, op.type)); sb.append("null"); } else { sb.append(toString(op.name, ox, outInputStreams)); } } catch (Exception e) { sb.append(outName(op.name, op.type)); sb.append(e.getMessage()); } i++; } // if (i > 0) { // sb.append(" "); // } } return sb.toString(); }
From source file:com.gallatinsystems.survey.dao.SurveyUtils.java
public static Question copyQuestion(Question source, Long newQuestionGroupId, Integer order, Long newSurveyId) { final QuestionDao qDao = new QuestionDao(); final QuestionOptionDao qoDao = new QuestionOptionDao(); final Question tmp = new Question(); final String[] questionExcludedProps = { "questionOptionMap", "questionHelpMediaMap", "scoringRules", "translationMap", "order", "questionId" }; final String[] allExcludedProps = (String[]) ArrayUtils.addAll(questionExcludedProps, Constants.EXCLUDED_PROPERTIES); BeanUtils.copyProperties(source, tmp, allExcludedProps); tmp.setOrder(order);// w ww .j av a 2s.c om if (source.getQuestionId() != null) { tmp.setQuestionId(source.getQuestionId() + "_copy"); } log.log(Level.INFO, "Copying `Question` " + source.getKey().getId()); final Question newQuestion = qDao.save(tmp, newQuestionGroupId); log.log(Level.INFO, "New `Question` ID: " + newQuestion.getKey().getId()); log.log(Level.INFO, "Copying question translations"); SurveyUtils.copyTranslation(source.getKey().getId(), newQuestion.getKey().getId(), newSurveyId, newQuestionGroupId, ParentType.QUESTION_NAME, ParentType.QUESTION_DESC, ParentType.QUESTION_TEXT, ParentType.QUESTION_TIP); if (!Question.Type.OPTION.equals(newQuestion.getType())) { // Nothing more to do return newQuestion; } final TreeMap<Integer, QuestionOption> options = qoDao.listOptionByQuestion(source.getKey().getId()); if (options == null) { return newQuestion; } log.log(Level.INFO, "Copying " + options.values().size() + " `QuestionOption`"); // Copying Question Options for (QuestionOption qo : options.values()) { SurveyUtils.copyQuestionOption(qo, newQuestion.getKey().getId(), newSurveyId, newQuestionGroupId); } return newQuestion; }
From source file:nl.b3p.kaartenbalie.service.LayerTreeSupport.java
private static void alphabetizeWfsRightsTree(JSONObject treeObject) throws JSONException { if (!treeObject.isNull("children")) { JSONArray childArray = treeObject.getJSONArray("children"); TreeMap tm = new TreeMap(); for (int i = 0; i < childArray.length(); i++) { JSONObject childObject = childArray.getJSONObject(i); alphabetizeWfsRightsTree(childObject); String title = childObject.getString("name"); tm.put(title, childObject);//w w w.j av a 2 s.co m } Collection c = tm.values(); treeObject.put("children", c); } return; }
From source file:com.liangc.hq.base.utils.MonitorUtils.java
public static List findServerTypes(List servers) { TreeMap serverTypeSet = new TreeMap(); for (Iterator i = servers.iterator(); i.hasNext();) { ServerValue thisAppSvc = (ServerValue) i.next(); if (thisAppSvc != null && thisAppSvc.getServerType() != null) { ServerTypeValue svcType = thisAppSvc.getServerType(); serverTypeSet.put(svcType.getName(), svcType); }/* ww w.j a v a 2 s. c o m*/ } return new ArrayList(serverTypeSet.values()); }
From source file:net.tradelib.apps.StrategyBacktest.java
public static void run(Strategy strategy) throws Exception { // Setup the logging System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n"); LogManager.getLogManager().reset(); Logger rootLogger = Logger.getLogger(""); if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) { FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true); logHandler.setFormatter(new SimpleFormatter()); logHandler.setLevel(Level.FINEST); rootLogger.addHandler(logHandler); }//from w w w . jav a2s. c om if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) { ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new SimpleFormatter()); consoleHandler.setLevel(Level.INFO); rootLogger.addHandler(consoleHandler); } rootLogger.setLevel(Level.INFO); // Setup Hibernate // Configuration configuration = new Configuration(); // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); // SessionFactory factory = configuration.buildSessionFactory(builder.build()); Context context = new Context(); context.dbUrl = BacktestCfg.instance().getProperty("db.url"); HistoricalDataFeed hdf = new SQLDataFeed(context); hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties")); context.historicalDataFeed = hdf; HistoricalReplay hr = new HistoricalReplay(context); context.broker = hr; strategy.initialize(context); strategy.cleanupDb(); long start = System.nanoTime(); strategy.start(); long elapsedTime = System.nanoTime() - start; System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); start = System.nanoTime(); strategy.updateEndEquity(); strategy.writeExecutionsAndTrades(); strategy.writeEquity(); elapsedTime = System.nanoTime() - start; System.out .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); System.out.println(); // Write the strategy totals to the database strategy.totalTradeStats(); // Write the strategy report to the database and obtain the JSON // for writing it to the console. JsonObject report = strategy.writeStrategyReport(); JsonArray asa = report.getAsJsonArray("annual_stats"); String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix"); if (!Strings.isNullOrEmpty(csvPath)) { csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + ".csv"; } String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix"); if (!Strings.isNullOrEmpty(ordersCsvPath)) { ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + ordersCsvPath; } String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix"); if (!Strings.isNullOrEmpty(actionsPath)) { actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + actionsPath; } // If emails are being send out String signalText = StrategyText.build(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), " ", csvPath, '|'); System.out.println(signalText); System.out.println(); if (!Strings.isNullOrEmpty(ordersCsvPath)) { StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), ordersCsvPath); } File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, signalText + System.getProperty("line.separator") + System.getProperty("line.separator")); } String message = ""; if (asa.size() > 0) { // Sort the array TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int ii = 0; ii < asa.size(); ++ii) { int year = asa.get(ii).getAsJsonObject().get("year").getAsInt(); map.put(year, ii); } for (int id : map.values()) { JsonObject jo = asa.get(id).getAsJsonObject(); String yearStr = String.valueOf(jo.get("year").getAsInt()); String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble()); String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt()); String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt()); String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble()); String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr; message += str + "\n"; } String pnlStr = String.format("$%,d", report.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble()); String ddStr = String.format("$%,d", report.get("avgdd").getAsInt()); String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble()); String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble()); String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr; message += str + "\n"; } else { message += "\n"; } // Global statistics JsonObject jo = report.getAsJsonObject("total_peak"); String dateStr = jo.get("date").getAsString(); int maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("total_maxdd"); double cash = jo.get("cash").getAsDouble(); double pct = jo.get("pct").getAsDouble(); message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; if (report.has("latest_peak") && report.has("latest_maxdd")) { jo = report.getAsJsonObject("latest_peak"); LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE); maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("latest_maxdd"); cash = jo.get("cash").getAsDouble(); pct = jo.get("pct").getAsDouble(); message += "\n" + Integer.toString(ld.getYear()) + " equity peak [" + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; } message += "\n" + "Avg Trade PnL: " + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: " + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: " + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: " + Integer.toString(report.get("num_trades").getAsInt()); System.out.println(message); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true); } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.sendgrid.net"); props.put("mail.smtp.port", "587"); String user = BacktestCfg.instance().getProperty("email.user"); String pass = BacktestCfg.instance().getProperty("email.pass"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } }); MimeMessage msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from"))); msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients")); msg.setSubject(strategy.getName() + " Report [" + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]"); msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message); Transport.send(msg); } catch (Exception ee) { Logger.getLogger("").warning(ee.getMessage()); } } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) { HashMap<String, String> fileMap = new HashMap<String, String>(); if (!Strings.isNullOrEmpty(actionsPath)) fileMap.put(actionsPath, actionsPath); if (!Strings.isNullOrEmpty(ordersCsvPath)) fileMap.put(ordersCsvPath, ordersCsvPath); String user = BacktestCfg.instance().getProperty("sftp.user"); String pass = BacktestCfg.instance().getProperty("sftp.pass"); String host = BacktestCfg.instance().getProperty("sftp.host"); SftpUploader sftp = new SftpUploader(host, user, pass); sftp.upload(fileMap); } }
From source file:org.kitodo.dataeditor.ruleset.Labeled.java
/** * Lists the entries alphabetically by the translated label, taking into * account the language preferred by the user for alphabetical sorting. In * the auxiliary map, the keys are sorted by the sequence translated label + * separator + key, to account for the case where multiple keys are * (inadvertently) translated equally.//from w w w . jav a 2s . c o m * * @param ruleset * The ruleset. From the ruleset, we learn which language is a * label that does not have a language attribute, that is what is * the default language of the rule set. * @param elements * The items to sort. The function is so generic that you can * sort divisions, keys, and options with it. * @param keyGetter * A function to extract from the element the value used in the * result map as key. * @param labelGetter * A function that allows you to extract the list of labels from * the element and then select the best translated one. * @param priorityList * The list of languages spoken by the user human * @return a map in the order of the best-fitting translated label */ public static <T> LinkedHashMap<String, String> listByTranslatedLabel(Ruleset ruleset, Collection<T> elements, Function<T, String> keyGetter, Function<T, Collection<Label>> labelGetter, List<LanguageRange> priorityList) { Locale sortLocale = Locale.lookup(priorityList, Arrays.asList(Collator.getAvailableLocales())); TreeMap<String, Pair<String, String>> byLabelSorter = sortLocale != null ? new TreeMap<>(Collator.getInstance(sortLocale)) : new TreeMap<>(); for (T element : elements) { String key = keyGetter.apply(element); Labeled labeled = new Labeled(ruleset, key, labelGetter.apply(element)); String label = labeled.getLabel(priorityList); byLabelSorter.put(label + '\037' + key, Pair.of(key, label)); } LinkedHashMap<String, String> result = new LinkedHashMap<>((int) Math.ceil(elements.size() / 0.75)); for (Pair<String, String> entry : byLabelSorter.values()) { result.put(entry.getKey(), entry.getValue()); } return result; }
From source file:cit360.sandbox.BackEndMenu.java
public static void ticketPrices() { TreeMap ageGroup = new TreeMap(); // Add some ageGroup. ageGroup.put("Adult", 8.75); ageGroup.put("Child", 5.50); ageGroup.put("Senior Citizen", 5.25); ageGroup.put("Military Veteran", 5.00); // Iterate over all ageGroup, using the keySet method. for (Object key : ageGroup.keySet()) System.out.println(key + " - $" + ageGroup.get(key)); System.out.println();/*w w w .j a v a 2 s.c o m*/ System.out.println("Highest key: " + ageGroup.lastKey()); System.out.println("Lowest key: " + ageGroup.firstKey()); System.out.println("\nPrinting all values: "); for (Object val : ageGroup.values()) System.out.println("$" + val); System.out.println(); // Clear all values. ageGroup.clear(); // Equals to zero. System.out.println("After clear operation, size: " + ageGroup.size()); }
From source file:com.jrummyapps.busybox.signing.ZipSigner.java
/** Add the SHA1 of every file to the manifest, creating it if necessary. */ private static Manifest addDigestsToManifest(final JarFile jar) throws IOException, GeneralSecurityException { final Manifest input = jar.getManifest(); final Manifest output = new Manifest(); final Attributes main = output.getMainAttributes(); main.putValue("Manifest-Version", MANIFEST_VERSION); main.putValue("Created-By", CREATED_BY); // We sort the input entries by name, and add them to the output manifest in sorted order. // We expect that the output map will be deterministic. final TreeMap<String, JarEntry> byName = new TreeMap<>(); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); byName.put(entry.getName(), entry); }/*from www.j a va2 s . c om*/ final MessageDigest md = MessageDigest.getInstance("SHA1"); final byte[] buffer = new byte[4096]; int num; for (JarEntry entry : byName.values()) { final String name = entry.getName(); if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME) && !name.equals(CERT_RSA_NAME)) { InputStream data = jar.getInputStream(entry); while ((num = data.read(buffer)) > 0) { md.update(buffer, 0, num); } Attributes attr = null; if (input != null) { attr = input.getAttributes(name); } attr = attr != null ? new Attributes(attr) : new Attributes(); attr.putValue("SHA1-Digest", base64encode(md.digest())); output.getEntries().put(name, attr); } } return output; }
From source file:de.thingweb.desc.ThingDescriptionParser.java
@Deprecated private static Thing parseOld(JsonNode td) throws IOException { try {/*from www .j a va2s .c om*/ Thing thing = new Thing(td.get("metadata").get("name").asText()); Iterator<String> tdIterator = td.fieldNames(); while (tdIterator.hasNext()) { switch (tdIterator.next()) { case "metadata": Iterator<String> metaIterator = td.get("metadata").fieldNames(); while (metaIterator.hasNext()) { switch (metaIterator.next()) { case "encodings": for (JsonNode encoding : td.get("metadata").get("encodings")) { thing.getMetadata().add("encodings", encoding); } break; case "protocols": TreeMap<Long, String> orderedURIs = new TreeMap<>(); for (JsonNode protocol : td.get("metadata").get("protocols")) { orderedURIs.put(protocol.get("priority").asLong(), protocol.get("uri").asText()); } if (orderedURIs.size() == 1) { thing.getMetadata().add("uris", factory.textNode(orderedURIs.get(0))); } else { ArrayNode an = factory.arrayNode(); for (String uri : orderedURIs.values()) { // values returned in ascending order an.add(uri); } thing.getMetadata().add("uris", an); } break; } } break; case "interactions": for (JsonNode inter : td.get("interactions")) { if (inter.get("@type").asText().equals("Property")) { Property.Builder builder = Property.getBuilder(inter.get("name").asText()); Iterator<String> propIterator = inter.fieldNames(); while (propIterator.hasNext()) { switch (propIterator.next()) { case "outputData": builder.setValueType(inter.get("outputData")); break; case "writable": builder.setWriteable(inter.get("writable").asBoolean()); break; } } thing.addProperty(builder.build()); } else if (inter.get("@type").asText().equals("Action")) { Action.Builder builder = Action.getBuilder(inter.get("name").asText()); Iterator<String> actionIterator = inter.fieldNames(); while (actionIterator.hasNext()) { switch (actionIterator.next()) { case "inputData": builder.setInputType(inter.get("inputData").asText()); break; case "outputData": builder.setOutputType(inter.get("outputData").asText()); break; } } thing.addAction(builder.build()); } else if (inter.get("@type").asText().equals("Event")) { Event.Builder builder = Event.getBuilder(inter.get("name").asText()); Iterator<String> actionIterator = inter.fieldNames(); while (actionIterator.hasNext()) { switch (actionIterator.next()) { case "outputData": builder.setValueType(inter.get("outputData")); break; } } thing.addEvent(builder.build()); } } break; } } return thing; } catch (Exception e) { // anything could happen here throw new IOException("unable to parse Thing Description"); } }
From source file:org.sourcepit.common.utils.zip.EntrySizeBasedZipPartitioner.java
public Collection<Callable<Integer>> computePartitions(ZipInputStreamFactory streamFactory, ZipEntryHandler entryHandler, int nrOfThreads) throws IOException { List<Set<Integer>> workScopes = new ArrayList<Set<Integer>>(); for (int i = 0; i < nrOfThreads; i++) { workScopes.add(new HashSet<Integer>()); }//from ww w . ja v a 2 s .c om TreeMap<ZipEntry, Integer> zipEntryNames = getZipEntryNames(streamFactory); Collection<Integer> workIndices = zipEntryNames.values(); int idx = 0; for (Integer integer : workIndices) { workScopes.get(idx).add(integer); idx = idx < nrOfThreads - 1 ? idx + 1 : 0; } final Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); for (Set<Integer> work : workScopes) { IndexBasedZipPartitionProcessor task = new IndexBasedZipPartitionProcessor(streamFactory, entryHandler, work); tasks.add(task); } return tasks; }