List of usage examples for java.util SortedMap get
V get(Object key);
From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java
/** * Computes the hierarchical data for new issues /*from w w w . ja v a 2s. co m*/ * @return */ public static SortedMap<Integer, SortedMap<Integer, Map<Integer, Integer>>> calculateNewWorkItems( List<TWorkItemBean> workItemBeans, Date dateFrom, Date dateTo, int selectedTimeInterval) { SortedMap<Integer, SortedMap<Integer, Map<Integer, Integer>>> yearToPeriodToProjectIDToWorkItemNumbersMap = new TreeMap<Integer, SortedMap<Integer, Map<Integer, Integer>>>(); if (workItemBeans == null || workItemBeans.isEmpty()) { LOGGER.debug("No workItems in datasource"); return yearToPeriodToProjectIDToWorkItemNumbersMap; } SortedMap<Integer, SortedMap<Integer, List<TWorkItemBean>>> periodNewWorkItems = getNewWorkItemsMap( workItemBeans, selectedTimeInterval, dateFrom, dateTo); List entityList = new ArrayList(); //for new WorkItems we have a single entity (a single graphic), hardcoded with Integer(0) //Integer hardCodedentityID = Integer.valueOf(0); entityList.add(ENTITY_PLACEHOLDER); Iterator<Integer> yearIterator = periodNewWorkItems.keySet().iterator(); while (yearIterator.hasNext()) { Integer year = (Integer) yearIterator.next(); SortedMap<Integer, List<TWorkItemBean>> intervalToStatusChangeBeans = periodNewWorkItems.get(year); Iterator<Integer> periodIterator = intervalToStatusChangeBeans.keySet().iterator(); while (periodIterator.hasNext()) { Integer period = (Integer) periodIterator.next(); List<TWorkItemBean> workItemBeansForInterval = intervalToStatusChangeBeans.get(period); if (workItemBeansForInterval != null) { Iterator<TWorkItemBean> workItemBeansIterator = workItemBeansForInterval.iterator(); while (workItemBeansIterator.hasNext()) { TWorkItemBean workItemBean = (TWorkItemBean) workItemBeansIterator.next(); if (workItemBean != null) { setCount(yearToPeriodToProjectIDToWorkItemNumbersMap, year, period, ENTITY_PLACEHOLDER, 1); } } } } } addZerosForEmptyIntervals(dateFrom, dateTo, selectedTimeInterval, yearToPeriodToProjectIDToWorkItemNumbersMap, entityList); //addTimeSeries(timeSeriesCollection, yearToPeriodToProjectIDToWorkItemNumbersMap, null, selectedTimeInterval, accumulated); return yearToPeriodToProjectIDToWorkItemNumbersMap; }
From source file:org.bibsonomy.rest.utils.HeaderUtils.java
/** * /*from w ww . j a v a2 s . co m*/ * @param acceptHeader * the HTML ACCEPT Header * <br/>example: * <code>ACCEPT: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png</code> * would be interpreted in the following precedence: * <ol> * <li>text/xml</li> * <li>image/png</li> * <li>text/html</li> * <li>text/plain</li> * </ol> * ) * @return a sorted map with the precedences */ public static SortedMap<Double, Vector<String>> getPreferredTypes(final String acceptHeader) { // maps the q-value to output format (reverse order) final SortedMap<Double, Vector<String>> preferredTypes = new TreeMap<Double, Vector<String>>( new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { if (o1.doubleValue() > o2.doubleValue()) return -1; else if (o1.doubleValue() < o2.doubleValue()) return 1; else return o1.hashCode() - o2.hashCode(); } }); if (!present(acceptHeader)) { return preferredTypes; } // fill map with q-values and formats final Scanner scanner = new Scanner(acceptHeader.toLowerCase()); scanner.useDelimiter(","); while (scanner.hasNext()) { final String[] types = scanner.next().split(";"); final String type = types[0]; double qValue = 1; if (types.length != 1) { /* * FIXME: we get * java.lang.NumberFormatException: For input string: "screen" * in the error log because the format we assume seems to be * different by some clients. Until we find out, what is really * wrong (our parsing or the client), we are more careful with * parsing external data. */ try { qValue = Double.parseDouble(types[1].split("=")[1]); } catch (NumberFormatException e) { qValue = 0; log.error("Couldn't parse accept header '" + acceptHeader + "'"); } } Vector<String> v = preferredTypes.get(qValue); if (!preferredTypes.containsKey(qValue)) { v = new Vector<String>(); preferredTypes.put(qValue, v); } v.add(type); } return preferredTypes; }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step11GoldDataStatistics.java
/** * Other statistics: we want to report how many documents and sentences * were judged and how many were found relevant among those. * Having the total + standard deviation over queries is enough. *///from w ww .j a v a 2 s . c o m public static void statistics5(File inputDir, File outputDir) throws IOException { PrintWriter pw = new PrintWriter(new FileWriter(new File(outputDir, "stats5.csv"))); SortedMap<String, DescriptiveStatistics> result = new TreeMap<>(); result.put("annotatedDocumentsPerQuery", new DescriptiveStatistics()); result.put("annotatedSentencesPerQuery", new DescriptiveStatistics()); result.put("relevantSentencesPerQuery", new DescriptiveStatistics()); // print header for (String mapKey : result.keySet()) { pw.printf(Locale.ENGLISH, "%s\t%sStdDev\t", mapKey, mapKey); } pw.println(); // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); System.out.println("Processing " + f); int annotatedDocuments = 0; int relevantSentences = 0; int totalSentences = 0; for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.plainText != null && !rankedResult.plainText.isEmpty()) { annotatedDocuments++; if (rankedResult.goldEstimatedLabels != null) { for (QueryResultContainer.SingleSentenceRelevanceVote sentenceRelevanceVote : rankedResult.goldEstimatedLabels) { totalSentences++; if (Boolean.valueOf(sentenceRelevanceVote.relevant)) { relevantSentences++; } } } } } result.get("annotatedDocumentsPerQuery").addValue(annotatedDocuments); result.get("annotatedSentencesPerQuery").addValue(totalSentences); result.get("relevantSentencesPerQuery").addValue(relevantSentences); } // print results // print header for (String mapKey : result.keySet()) { pw.printf(Locale.ENGLISH, "%.3f\t%.3f\t", result.get(mapKey).getMean(), result.get(mapKey).getStandardDeviation()); } pw.close(); }
From source file:org.apache.falcon.resource.proxy.ExtensionManagerProxy.java
@POST @Path("update/{job-name}") @Consumes({ MediaType.TEXT_XML, MediaType.TEXT_PLAIN, MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.TEXT_XML, MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) public APIResult update(@PathParam("job-name") String jobName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @FormDataParam("processes") List<FormDataBodyPart> processForms, @FormDataParam("feeds") List<FormDataBodyPart> feedForms, @FormDataParam("config") InputStream config) { checkIfExtensionServiceIsEnabled();//from w w w .j a v a 2s. co m SortedMap<EntityType, List<Entity>> entityMap; String extensionName = getExtensionName(jobName); checkIfExtensionIsEnabled(extensionName); try { entityMap = getEntityList(extensionName, jobName, feedForms, processForms, config); if (entityMap.get(EntityType.FEED).isEmpty() && entityMap.get(EntityType.PROCESS).isEmpty()) { // return failure if the extension job doesn't exist return new APIResult(APIResult.Status.FAILED, "Extension job " + jobName + " doesn't exist."); } updateEntities(extensionName, jobName, entityMap, config, request); } catch (FalconException | IOException | JAXBException e) { LOG.error("Error while updating extension job: " + jobName, e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Updated successfully"); }
From source file:tajo.master.GlobalPlanner.java
@VisibleForTesting public static Map<String, Map<ScanNode, List<URI>>> hashFetches(Map<ScanNode, List<URI>> uriMap) { SortedMap<String, Map<ScanNode, List<URI>>> hashed = new TreeMap<String, Map<ScanNode, List<URI>>>(); String uriPath, key;/*from w ww .j av a 2s . co m*/ Map<ScanNode, List<URI>> m = null; List<URI> uriList = null; for (Entry<ScanNode, List<URI>> e : uriMap.entrySet()) { for (URI uri : e.getValue()) { uriPath = uri.toString(); key = uriPath.substring(uriPath.lastIndexOf("=") + 1); if (hashed.containsKey(key)) { m = hashed.get(key); } else { m = new HashMap<ScanNode, List<URI>>(); } if (m.containsKey(e.getKey())) { uriList = m.get(e.getKey()); } else { uriList = new ArrayList<URI>(); } uriList.add(uri); m.put(e.getKey(), uriList); hashed.put(key, m); } } SortedMap<String, Map<ScanNode, List<URI>>> finalHashed = new TreeMap<String, Map<ScanNode, List<URI>>>(); for (Entry<String, Map<ScanNode, List<URI>>> entry : hashed.entrySet()) { finalHashed.put(entry.getKey(), combineURIByHostForBinary(entry.getValue())); } return finalHashed; }
From source file:at.tuwien.ifs.somtoolbox.apps.viewer.controls.ClusteringControl.java
/** Makes sure all controls are displayed as needed. Currently deals with the {@link #kmeansInitialisationPanel} */ public void updateControlDisplay() { kmeansInitialisationPanel.setVisible(mapPane.getMap().getCurrentClusteringTree() != null && mapPane.getMap().getClusteringTreeBuilder() instanceof KMeansTreeBuilder); ClusteringTree clusteringTree = mapPane.getMap().getCurrentClusteringTree(); if (clusteringTree == null) return;//from w ww . ja v a 2 s . com Tree<ClusterNode, Integer> tree = clusteringTree.getJUNGTree(); TreeLayout<ClusterNode, Integer> layout = new TreeLayout<ClusterNode, Integer>(tree, 30, 100); final double maxMergeCost = clusteringTree.getMaxMergeCost(); final double minMergeCost = clusteringTree.getMinMergeCost(); final VisualizationViewer<ClusterNode, Integer> vv = new VisualizationViewer<ClusterNode, Integer>(layout); // setup edge rendering vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<ClusterNode, Integer>()); vv.getRenderContext().setEdgeStrokeTransformer(new Transformer<Integer, Stroke>() { @Override public Stroke transform(Integer integer) { return new BasicStroke(1.0f); } }); vv.getRenderContext().setEdgeArrowPredicate( PredicateUtils.<Context<Graph<ClusterNode, Integer>, Integer>>falsePredicate()); vv.getRenderContext().setEdgeDrawPaintTransformer(new Transformer<Integer, Paint>() { @Override public Paint transform(Integer edge) { return Color.BLACK; } }); // setup vertex rendering vv.getRenderContext().setVertexLabelTransformer(new Transformer<ClusterNode, String>() { @Override public String transform(ClusterNode clusterNode) { Point2D.Double centroid = clusterNode.getCentroid(); return String.format("%d @ (%f, %f)", clusterNode.getNodes().length, centroid.getX(), centroid.getY()); } }); vv.getRenderContext().setVertexFillPaintTransformer(new Transformer<ClusterNode, Paint>() { @Override public Paint transform(ClusterNode clusterNode) { Palette palette = mapPane.getState().getSOMViewer().getCurrentlySelectedPalette(); double pos = clusterNode.getMergeCost() - minMergeCost; pos /= maxMergeCost - minMergeCost; pos *= palette.getNumberOfColours() - 1; return palette.getColor((int) pos); } }); vv.getRenderContext().setVertexStrokeTransformer(new Transformer<ClusterNode, Stroke>() { @Override public Stroke transform(ClusterNode clusterNode) { if (vv.getPickedVertexState().isPicked(clusterNode)) return new BasicStroke(3.0f); else return new BasicStroke(1.0f); } }); vv.setVertexToolTipTransformer(new Transformer<ClusterNode, String>() { @Override public String transform(ClusterNode clusterNode) { StringBuilder result = new StringBuilder(); result.append("Level: ").append(clusterNode.getLevel()).append("\r\n"); result.append("Merge-cost: ").append(String.format("%.2f", clusterNode.getMergeCost())) .append("\r\n"); result.append("Centroid: ").append(String.format("%.2f", clusterNode.getCentroid().getX())) .append(", ").append(String.format("%.2f", clusterNode.getCentroid().getY())) .append("\r\n"); result.append("Factor-value: ").append(String.format("%.2f", clusterNode.getFactorValue())) .append("\r\n"); result.append("#Nodes: ").append(clusterNode.getUnitNodes().length).append("\r\n"); result.append("Mean-vector: "); for (double d : clusterNode.getMeanVector()) result.append(String.format("%.2f", d)).append(", "); result.append("\r\n"); result.append("Bounds: (x=").append(String.format("%.2f", clusterNode.getX())).append(", y=") .append(String.format("%.2f", clusterNode.getY())).append(", w=") .append(String.format("%.2f", clusterNode.getWidth())).append(", h=") .append(String.format("%.2f", clusterNode.getHeight())).append(")\r\n"); return result.toString(); } }); GraphZoomScrollPane vv2 = new GraphZoomScrollPane(vv); vv2.setPreferredSize(new Dimension(dendogramPanel.getParent().getWidth(), 200)); vv2.setVisible(true); DefaultModalGraphMouse<ClusterNode, Integer> graphMouse = new DefaultModalGraphMouse<ClusterNode, Integer>(); vv.setGraphMouse(graphMouse); graphMouse.setMode(ModalGraphMouse.Mode.PICKING); vv.addGraphMouseListener(new GraphMouseListener<ClusterNode>() { private ClusterNode previouslySelected; @Override public void graphClicked(ClusterNode clusterNode, MouseEvent me) { if (previouslySelected != null) previouslySelected.setSelected(false); clusterNode.setSelected(true); previouslySelected = clusterNode; numClusters = clusterNode.getLevel(); SortedMap<Integer, ClusterElementsStorage> m = mapPane.getMap().getCurrentClusteringTree() .getAllClusteringElements(); if (m.containsKey(numClusters)) { st = m.get(numClusters).sticky; } else { st = false; } sticky.setSelected(st); redrawClustering(); } @Override public void graphPressed(ClusterNode clusterNode, MouseEvent me) { } @Override public void graphReleased(ClusterNode clusterNode, MouseEvent me) { } }); dendogramPanel.removeAll(); dendogramPanel.add(vv2); getContentPane().validate(); }
From source file:com.palantir.atlasdb.cleaner.KeyValueServiceScrubberStore.java
private SortedMap<Long, Multimap<String, Cell>> transformRows(List<RowResult<Value>> input) { SortedMap<Long, Multimap<String, Cell>> scrubTimestampToTableNameToCell = Maps.newTreeMap(); for (RowResult<Value> rowResult : input) { for (Map.Entry<Cell, Value> entry : rowResult.getCells()) { Cell cell = entry.getKey();/*from www . jav a2 s . c om*/ Value value = entry.getValue(); long scrubTimestamp = value.getTimestamp(); String[] tableNames = StringUtils.split(PtBytes.toString(value.getContents()), AtlasDbConstants.SCRUB_TABLE_SEPARATOR_CHAR); if (!scrubTimestampToTableNameToCell.containsKey(scrubTimestamp)) { scrubTimestampToTableNameToCell.put(scrubTimestamp, HashMultimap.<String, Cell>create()); } for (String tableName : tableNames) { scrubTimestampToTableNameToCell.get(scrubTimestamp).put(tableName, cell); } } } return scrubTimestampToTableNameToCell; }
From source file:guru.nidi.languager.PropertiesFinder.java
public SortedMap<String, Message> findProperties() throws IOException { SortedMap<String, Message> messages = new TreeMap<>(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); for (String propertyLocation : propertyLocations) { Resource[] resources = resolver.getResources(propertyLocation + "*" + PROPERTIES); for (Resource resource : resources) { String lang = resource.getFilename(); lang = lang.substring(Math.max(0, lang.length() - 20), lang.length() - PROPERTIES.length()); int pos = lang.indexOf('_'); if (pos < 0) { lang = ""; } else { lang = lang.substring(pos + 1); }/* w w w.j a va2 s . c o m*/ Properties props = new Properties(); props.load(resource.getInputStream()); for (String name : props.stringPropertyNames()) { Message message = messages.get(name); if (message == null) { message = new Message(name, FOUND, null); messages.put(name, message); } message.addValue(lang, props.getProperty(name)); } } } return messages; }
From source file:lti.oauth.OAuthMessageSigner.java
/** * This method double encodes the parameter keys and values. * Thus, it expects the keys and values contained in the 'parameters' SortedMap * NOT to be encoded.//from w w w . j a va 2 s .co m * * @param secret * @param algorithm * @param method * @param url * @param parameters * @return oauth signature * @throws Exception */ public String sign(String secret, String algorithm, String method, String url, SortedMap<String, String> parameters) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec((secret.concat(OAuthUtil.AMPERSAND)).getBytes(), algorithm); Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm()); mac.init(secretKeySpec); StringBuilder signatureBase = new StringBuilder(OAuthUtil.percentEncode(method)); signatureBase.append(OAuthUtil.AMPERSAND); signatureBase.append(OAuthUtil.percentEncode(url)); signatureBase.append(OAuthUtil.AMPERSAND); int count = 0; for (String key : parameters.keySet()) { count++; signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(key))); signatureBase.append(URLEncoder.encode(OAuthUtil.EQUAL, OAuthUtil.ENCODING)); signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(parameters.get(key)))); if (count < parameters.size()) { signatureBase.append(URLEncoder.encode(OAuthUtil.AMPERSAND, OAuthUtil.ENCODING)); } } if (log.isDebugEnabled()) { log.debug(signatureBase.toString()); } byte[] bytes = mac.doFinal(signatureBase.toString().getBytes()); byte[] encodedMacBytes = Base64.encodeBase64(bytes); return new String(encodedMacBytes); }
From source file:org.wrml.runtime.rest.Resource.java
/** * Generates the "href" URI used to refer to this resource from the specified referrer {@link Model} instance using * the specified {@link LinkRelation} {@link URI} value. *//*from w w w .jav a2 s . c o m*/ public URI getHrefUri(final Model referrer, final URI referenceRelationUri) { if (referrer == null) { return null; } /* * Given the nature of the Api's ResourceTemplate metadata tree, the runtime resource can determine its own * UriTemplate (and it only needs to determine/compute this once). */ final UriTemplate uriTemplate = getUriTemplate(); if (uriTemplate == null) { return null; } /* * Get the end point id's templated parameter names, for example: a UriTemplate might have slots that look like * {teamId} or {highScoreId} or {name} appearing where legal (according to UriTemplate syntax, see: * http://tools.ietf.org/html/rfc6570). A fixed URI, meaning a UriTemplate with no variables, will return null * here. */ final String[] uriTemplateParameterNames = this._UriTemplate.getParameterNames(); Map<String, Object> parameterMap = null; if (uriTemplateParameterNames != null && uriTemplateParameterNames.length > 0) { // Get the Link slot's bindings, which may be used to provide an alternative source for one or more URI // template parameter values. final Prototype referrerPrototype = referrer.getPrototype(); final SortedMap<URI, LinkProtoSlot> linkProtoSlots = referrerPrototype.getLinkProtoSlots(); Map<String, ProtoValueSource> linkSlotBindings = null; if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) { final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(referenceRelationUri); if (linkProtoSlot != null) { linkSlotBindings = linkProtoSlot.getLinkSlotBindings(); } } parameterMap = new LinkedHashMap<>(uriTemplateParameterNames.length); for (final String paramName : uriTemplateParameterNames) { final Object paramValue; if (linkSlotBindings != null && linkSlotBindings.containsKey(paramName)) { // The link slot has declared a binding to an alternate source for this URI template parameter's // value. final ProtoValueSource valueSource = linkSlotBindings.get(paramName); paramValue = valueSource.getValue(referrer); } else { // By default, if the end point's UriTemplate has parameters (blanks) to fill in, then by convention // we // assume that the referrer model has the corresponding slot values to match the UriTemplate's // inputs/slots. // // Put simply, (by default) referrer model slot names "match" UriTemplate param names. // // This enforces that the model's own represented resource state is the only thing used to // (automatically) drive the link-based graph traversal (aka HATEOAS). Its also a simple convention // that // is (reasonably) easy to comprehend, hopefully even intuitive. paramValue = referrer.getSlotValue(paramName); } parameterMap.put(paramName, paramValue); } } final URI uri = this._UriTemplate.evaluate(parameterMap); return uri; }