java.util.TreeMap Java Examples
The following examples show how to use
java.util.TreeMap.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Matlab.java From LAML with Apache License 2.0 | 6 votes |
public static SparseVector sparse(Vector V) { if (V instanceof DenseVector) { double[] values = ((DenseVector) V).getPr(); TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(); for (int k = 0; k < values.length; k++) { if (values[k] != 0) { map.put(k, values[k]); } } int nnz = map.size(); int[] ir = new int[nnz]; double[] pr = new double[nnz]; int dim = values.length; int ind = 0; for (Entry<Integer, Double> entry : map.entrySet()) { ir[ind] = entry.getKey(); pr[ind] = entry.getValue(); ind++; } return new SparseVector(ir, pr, nnz, dim); } else { return (SparseVector) V; } }
Example #2
Source File: ExtraLanguageGeneratorContext.java From sarl with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public <K, V> List<V> getMultimapValues(String id, K multimapKey) { if (this.temporaryData == null) { this.temporaryData = new TreeMap<>(); } Map<K, List<V>> multimap = (Map<K, List<V>>) this.temporaryData.get(id); if (multimap == null) { multimap = new HashMap<>(); this.temporaryData.put(id, multimap); } List<V> list = multimap.get(multimapKey); if (list == null) { list = new ArrayList<>(); multimap.put(multimapKey, list); } return list; }
Example #3
Source File: TreeMapTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * descendingEntrySet contains all pairs */ public void testDescendingEntrySet() { TreeMap map = map5(); Set s = map.descendingMap().entrySet(); assertEquals(5, s.size()); Iterator it = s.iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); assertTrue( (e.getKey().equals(one) && e.getValue().equals("A")) || (e.getKey().equals(two) && e.getValue().equals("B")) || (e.getKey().equals(three) && e.getValue().equals("C")) || (e.getKey().equals(four) && e.getValue().equals("D")) || (e.getKey().equals(five) && e.getValue().equals("E"))); } }
Example #4
Source File: FileSystemPreferences.java From java-ocr-api with GNU Affero General Public License v3.0 | 6 votes |
private FileSystemPreferences(FileSystemPreferences parent, String name) { super(parent, name); isUserNode = parent.isUserNode; dir = new File(parent.dir, dirName(name)); prefsFile = new File(dir, "prefs.xml"); tmpFile = new File(dir, "prefs.tmp"); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { newNode = !dir.exists(); return null; } }); if (newNode) { prefsCache = new TreeMap<String, String>(); nodeCreate = new NodeCreate(); changeLog.add(nodeCreate); } }
Example #5
Source File: HuobiService.java From HuobiRobot with Apache License 2.0 | 6 votes |
/** * 下单接口 * * @param coinType * @param price * @param amount * @param tradePassword * @param tradeid * @param method * @return * @throws Exception */ public String buy(int coinType, String price, String amount, String tradePassword, Integer tradeid, String method) throws Exception { TreeMap<String, Object> paraMap = new TreeMap<String, Object>(); paraMap.put("method", method); paraMap.put("created", getTimestamp()); paraMap.put("access_key", huobiAccessKey); paraMap.put("secret_key", huobiSecretKey); paraMap.put("coin_type", coinType); paraMap.put("price", price); paraMap.put("amount", amount); String md5 = sign(paraMap); paraMap.remove("secret_key"); paraMap.put("sign", md5); if (StringUtils.isNotEmpty(tradePassword)) { paraMap.put("trade_password", tradePassword); } if (null != tradeid) { paraMap.put("trade_id", tradeid); } return post(paraMap, huobiApiUrl); }
Example #6
Source File: JTop.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
/** * Get the thread list with CPU consumption and the ThreadInfo * for each thread sorted by the CPU time. */ private List<Map.Entry<Long, ThreadInfo>> getThreadList() { // Get all threads and their ThreadInfo objects // with no stack trace long[] tids = tmbean.getAllThreadIds(); ThreadInfo[] tinfos = tmbean.getThreadInfo(tids); // build a map with key = CPU time and value = ThreadInfo SortedMap<Long, ThreadInfo> map = new TreeMap<Long, ThreadInfo>(); for (int i = 0; i < tids.length; i++) { long cpuTime = tmbean.getThreadCpuTime(tids[i]); // filter out threads that have been terminated if (cpuTime != -1 && tinfos[i] != null) { map.put(new Long(cpuTime), tinfos[i]); } } // build the thread list and sort it with CPU time // in decreasing order Set<Map.Entry<Long, ThreadInfo>> set = map.entrySet(); List<Map.Entry<Long, ThreadInfo>> list = new ArrayList<Map.Entry<Long, ThreadInfo>>(set); Collections.reverse(list); return list; }
Example #7
Source File: MultiValueFeildOperationUtils.java From we-cmdb with Apache License 2.0 | 6 votes |
public static DynamicEntityMeta createDynamicEntityMetaForMultiReference(AdmCiTypeAttr multiSelAttr) { DynamicEntityMeta meta = new DynamicEntityMeta(); AdmCiType ciType = multiSelAttr.getAdmCiType(); meta.setType(DynamicEntityType.MultiRefIntermedia); String intermediaTableName = multiSelAttr.retrieveJoinTalbeName(); meta.setQulifiedName(DynamicEntityUtils.getEntityQuanlifiedName(intermediaTableName)); meta.setTableName(intermediaTableName); meta.setCiTypeId(ciType.getIdAdmCiType()); SortedMap<String, FieldNode> fieldNodeMap = new TreeMap<String, FieldNode>(); FieldNode fieldNode = new FieldNode(DynamicEntityType.MultiRefIntermedia, null, "id", Integer.class, "id", true); fieldNodeMap.put("id", fieldNode); fieldNode = new FieldNode(DynamicEntityType.MultiSelIntermedia, null, "from_guid", String.class, "from_guid"); fieldNodeMap.put("from_guid", fieldNode); fieldNode = new FieldNode(DynamicEntityType.MultiSelIntermedia, null, "to_guid", String.class, "to_guid"); fieldNodeMap.put("to_guid", fieldNode); fieldNode = new FieldNode(DynamicEntityType.MultiSelIntermedia, null, "seq_no", Integer.class, "seq_no"); fieldNodeMap.put("seq_no", fieldNode); meta.setFieldMap(fieldNodeMap); return meta; }
Example #8
Source File: Tuple2Test.java From Paguro with Apache License 2.0 | 6 votes |
@Test public void treeMapEntryTest() { TreeMap<String,Integer> control = new TreeMap<>(); control.put("one", 1); Map.Entry<String,Integer> realEntry = control.entrySet().iterator().next(); Tuple2<String,Integer> test = Tuple2.of("one", 1); assertEquals(realEntry.hashCode(), test.hashCode()); assertEquals(realEntry.hashCode(), serializeDeserialize(test).hashCode()); assertTrue(test.equals(realEntry)); assertTrue(realEntry.equals(test)); assertTrue(serializeDeserialize(test).equals(realEntry)); assertTrue(realEntry.equals(serializeDeserialize(test))); }
Example #9
Source File: RawHeaders.java From cordova-android-chromeview with Apache License 2.0 | 6 votes |
/** * Returns an immutable map containing each field to its list of values. The * status line is mapped to null. */ public Map<String, List<String>> toMultimap(boolean response) { Map<String, List<String>> result = new TreeMap<String, List<String>>(FIELD_NAME_COMPARATOR); for (int i = 0; i < namesAndValues.size(); i += 2) { String fieldName = namesAndValues.get(i); String value = namesAndValues.get(i + 1); List<String> allValues = new ArrayList<String>(); List<String> otherValues = result.get(fieldName); if (otherValues != null) { allValues.addAll(otherValues); } allValues.add(value); result.put(fieldName, Collections.unmodifiableList(allValues)); } if (response && statusLine != null) { result.put(null, Collections.unmodifiableList(Collections.singletonList(statusLine))); } else if (requestLine != null) { result.put(null, Collections.unmodifiableList(Collections.singletonList(requestLine))); } return Collections.unmodifiableMap(result); }
Example #10
Source File: XxlRpcLoadBalanceConsistentHashStrategy.java From datax-web with MIT License | 6 votes |
public String doRoute(String serviceKey, TreeSet<String> addressSet) { // ------A1------A2-------A3------ // -----------J1------------------ TreeMap<Long, String> addressRing = new TreeMap<Long, String>(); for (String address: addressSet) { for (int i = 0; i < VIRTUAL_NODE_NUM; i++) { long addressHash = hash("SHARD-" + address + "-NODE-" + i); addressRing.put(addressHash, address); } } long jobHash = hash(serviceKey); SortedMap<Long, String> lastRing = addressRing.tailMap(jobHash); if (!lastRing.isEmpty()) { return lastRing.get(lastRing.firstKey()); } return addressRing.firstEntry().getValue(); }
Example #11
Source File: JSONObject.java From JMCCC with MIT License | 6 votes |
/** * Returns a java.util.Map containing all of the entrys in this object. If * an entry in the object is a JSONArray or JSONObject it will also be * converted. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a java.util.Map containing the entrys of this object */ public Map<String, Object> toMap() { Map<String, Object> results = new TreeMap<String, Object>(); for (Entry<String, Object> entry : this.map.entrySet()) { Object value; if (entry.getValue() == null || NULL.equals(entry.getValue())) { value = null; } else if (entry.getValue() instanceof JSONObject) { value = ((JSONObject) entry.getValue()).toMap(); } else if (entry.getValue() instanceof JSONArray) { value = ((JSONArray) entry.getValue()).toList(); } else { value = entry.getValue(); } results.put(entry.getKey(), value); } return results; }
Example #12
Source File: SparseArrayData.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
@Override public ArrayData shiftRight(final int by) { final TreeMap<Long, Object> newSparseMap = new TreeMap<>(); final long len = underlying.length(); if (len + by > maxDenseLength) { for (long i = maxDenseLength - by; i < len; i++) { if (underlying.has((int) i)) { newSparseMap.put(Long.valueOf(i + by), underlying.getObject((int) i)); } } underlying = underlying.shrink((int) (maxDenseLength - by)); } underlying.shiftRight(by); for (final Map.Entry<Long, Object> entry : sparseMap.entrySet()) { final long newIndex = entry.getKey().longValue() + by; newSparseMap.put(Long.valueOf(newIndex), entry.getValue()); } sparseMap = newSparseMap; setLength(length() + by); return this; }
Example #13
Source File: AllNotesTextAreaObserver.java From otroslogviewer with Apache License 2.0 | 6 votes |
@Override public void update(NoteEvent noteEvent) { StringBuilder sb = new StringBuilder(); NotableTableModel model = noteEvent.getSource(); TreeMap<Integer, Note> allNotes = model.getAllNotes(); for (Integer idx : allNotes.keySet()) { Note note = allNotes.get(idx); sb.append(idx).append(": ").append(note.getNote()); sb.append('\n'); } if (sb.length() == 0) { sb.append("No notes."); } allNotesTextArea.setText(sb.toString()); }
Example #14
Source File: Utility.java From jpms-module-names with MIT License | 6 votes |
static <V> Map<String, V> loadFromProperties(Path path, Function<String, V> valueFactory) { LOG.log(DEBUG, "Loading properties from `%s`...", path); var map = new TreeMap<String, V>(); if (Files.notExists(path)) { return map; } try (var lines = Files.lines(path)) { lines .map(String::trim) .filter(not(String::isEmpty)) .filter(line -> line.charAt(0) != '#') .forEach( line -> { var values = line.split("="); var key = values[0].trim(); var value = valueFactory.apply(values[1].trim()); if (map.put(key, value) != null) { throw new IllegalStateException("Duplicate key found: " + key); } }); } catch (IOException e) { throw new UncheckedIOException("Loading properties failed for: " + path, e); } LOG.log(DEBUG, "Loaded {0} properties from: {1}", map.size(), path); return map; }
Example #15
Source File: Solution.java From DailyCodingProblem with GNU Lesser General Public License v3.0 | 6 votes |
public static int getRequiredRoomsAmount(Interval[] intervals) { Map<Integer, Integer> map = new TreeMap<>(); for (Interval interval : intervals) { map.put(interval.start, map.getOrDefault(interval.start, 0) + 1); map.put(interval.end, map.getOrDefault(interval.end, 0) - 1); } int res = 0; int count = 0; for (int delta : map.values()) res = Math.max(res, count += delta); return res; }
Example #16
Source File: TriangleGraph.java From game-server with MIT License | 6 votes |
/** * 创建每个三角形的共享边列表 Creates a map over each triangle and its Edge connections to * other triangles. Each edge must follow the vertex winding order of the * triangle associated with it. Since all triangles are assumed to have the same * winding order, this means if two triangles connect, each must have its own * edge connection data, where the edge follows the same winding order as the * triangle which owns the edge data. * * @param indexConnections * @param triangles * @param vertexVectors * @return */ private static Map<Triangle, List<TriangleEdge>> createSharedEdgesMap(Set<IndexConnection> indexConnections, List<Triangle> triangles, List<Vector3> vertexVectors) { Map<Triangle, List<TriangleEdge>> connectionMap = new TreeMap<Triangle, List<TriangleEdge>>( (o1, o2) -> o1.getIndex() - o2.getIndex()); // connectionMap.ordered = true; for (Triangle tri : triangles) { connectionMap.put(tri, new ArrayList<TriangleEdge>()); } for (IndexConnection indexConnection : indexConnections) { Triangle fromNode = triangles.get(indexConnection.fromTriIndex); Triangle toNode = triangles.get(indexConnection.toTriIndex); Vector3 edgeVertexA = vertexVectors.get(indexConnection.edgeVertexIndex1); Vector3 edgeVertexB = vertexVectors.get(indexConnection.edgeVertexIndex2); TriangleEdge edge = new TriangleEdge(fromNode, toNode, edgeVertexA, edgeVertexB); connectionMap.get(fromNode).add(edge); fromNode.connections.add(edge); // LOGGER.debug("三角形:{} -->{} // {}-->{}",fromNode.getIndex(),toNode.getIndex(),fromNode.toString(),toNode.toString()); } return connectionMap; }
Example #17
Source File: TestTableInputFormatBase.java From hbase with Apache License 2.0 | 6 votes |
@Override public RegionLocator getRegionLocator(TableName tableName) throws IOException { final Map<byte[], HRegionLocation> locationMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); for (byte[] startKey : START_KEYS) { HRegionLocation hrl = new HRegionLocation( RegionInfoBuilder.newBuilder(tableName).setStartKey(startKey).build(), ServerName.valueOf("localhost", 0, 0)); locationMap.put(startKey, hrl); } RegionLocator locator = mock(RegionLocator.class); when(locator.getRegionLocation(any(byte [].class), anyBoolean())). thenAnswer(new Answer<HRegionLocation>() { @Override public HRegionLocation answer(InvocationOnMock invocationOnMock) throws Throwable { Object [] args = invocationOnMock.getArguments(); byte [] key = (byte [])args[0]; return locationMap.get(key); } }); when(locator.getStartEndKeys()). thenReturn(new Pair<byte[][], byte[][]>(START_KEYS, END_KEYS)); return locator; }
Example #18
Source File: Type.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Read a map of {@code int} to {@code Type} from an input stream. This is used to store deoptimization state. * * @param input data input * @return type map * @throws IOException if read cannot be completed */ public static Map<Integer, Type> readTypeMap(final DataInput input) throws IOException { final int size = input.readInt(); if (size <= 0) { return null; } final Map<Integer, Type> map = new TreeMap<>(); for(int i = 0; i < size; ++i) { final int pp = input.readInt(); final int typeChar = input.readByte(); final Type type; switch (typeChar) { case 'L': type = Type.OBJECT; break; case 'D': type = Type.NUMBER; break; case 'J': type = Type.LONG; break; default: continue; } map.put(pp, type); } return map; }
Example #19
Source File: UnmodifiableMapEntrySet.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@DataProvider(name="maps") static Object[][] mapCases() { if (collections != null) { return collections; } List<Object[]> cases = new ArrayList<>(); for (int size : new int[] {1, 2, 16}) { cases.add(new Object[] { String.format("new HashMap(%d)", size), (Supplier<Map<Integer, Integer>>) () -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) }); cases.add(new Object[] { String.format("new TreeMap(%d)", size), (Supplier<Map<Integer, Integer>>) () -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) }); } return cases.toArray(new Object[0][]); }
Example #20
Source File: ServletUtils.java From DWSurvey with GNU Affero General Public License v3.0 | 6 votes |
/** * 取得带相同前缀的Request Parameters. * * 返回的结果的Parameter名已去除前缀. */ public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) { AssertUtils.notNull(request, "Request must not be null"); Enumeration paramNames = request.getParameterNames(); Map<String, Object> params = new TreeMap<String, Object>(); if (prefix == null) { prefix = ""; } while (paramNames != null && paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if ("".equals(prefix) || paramName.startsWith(prefix)) { String unprefixed = paramName.substring(prefix.length()); String[] values = request.getParameterValues(paramName); if (values == null || values.length == 0) { // Do nothing, no values found at all. } else if (values.length > 1) { params.put(unprefixed, values); } else { params.put(unprefixed, values[0]); } } } return params; }
Example #21
Source File: RegistrationDA.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 6 votes |
public ActionForward viewAttends(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { RenderUtils.invalidateViewState(); final Registration registration = getAndSetRegistration(request); request.setAttribute("registration", registration); if (registration != null) { final SortedMap<ExecutionSemester, SortedSet<Attends>> attendsMap = new TreeMap<ExecutionSemester, SortedSet<Attends>>(); for (final Attends attends : registration.getAssociatedAttendsSet()) { final ExecutionSemester executionSemester = attends.getExecutionPeriod(); SortedSet<Attends> attendsSet = attendsMap.get(executionSemester); if (attendsSet == null) { attendsSet = new TreeSet<Attends>(Attends.ATTENDS_COMPARATOR); attendsMap.put(executionSemester, attendsSet); } attendsSet.add(attends); } request.setAttribute("attendsMap", attendsMap); } return mapping.findForward("viewAttends"); }
Example #22
Source File: TestCloudSchemaless.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public SortedMap<ServletHolder,String> getExtraServlets() { final SortedMap<ServletHolder,String> extraServlets = new TreeMap<>(); final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class); solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi"); extraServlets.put(solrRestApi, "/schema/*"); // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...' return extraServlets; }
Example #23
Source File: CurrentAppResolver.java From always-on-amoled with GNU General Public License v3.0 | 5 votes |
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1) private String getActivePackages() { UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 200 * 200, time); if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } return mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } return context.getPackageName(); }
Example #24
Source File: MasterBatchCoordinator.java From jstorm with Apache License 2.0 | 5 votes |
private TreeMap<Long, Integer> getStoredCurrAttempts(long currTransaction, int maxBatches) { TreeMap<Long, Integer> ret = new TreeMap<>(); for (TransactionalState state : _states) { Map<Object, Number> attempts = (Map) state.getData(CURRENT_ATTEMPTS); if (attempts == null) attempts = new HashMap<>(); for (Entry<Object, Number> e : attempts.entrySet()) { // this is because json doesn't allow numbers as keys... // TODO: replace json with a better form of encoding Number txidObj; if (e.getKey() instanceof String) { txidObj = Long.parseLong((String) e.getKey()); } else { txidObj = (Number) e.getKey(); } long txid = txidObj.longValue(); int attemptId = e.getValue().intValue(); Integer curr = ret.get(txid); if (curr == null || attemptId > curr) { ret.put(txid, attemptId); } } } ret.headMap(currTransaction).clear(); ret.tailMap(currTransaction + maxBatches - 1).clear(); return ret; }
Example #25
Source File: TestWSDLCorbaWriterImpl.java From cxf with Apache License 2.0 | 5 votes |
protected void printBindingFaults(@SuppressWarnings("rawtypes") Map bindingFaults, Definition def, java.io.PrintWriter pw) throws WSDLException { Map<Object, Object> bfaults = new TreeMap<>(comparator); bfaults.putAll(CastUtils.cast(bindingFaults)); super.printBindingFaults(bfaults, def, pw); }
Example #26
Source File: MalletCalculator.java From TagRec with GNU Affero General Public License v3.0 | 5 votes |
private List<Map<Integer, Double>> getMaxTopicsByDocs(ParallelTopicModel LDA, int maxTopicsPerDoc) { List<Map<Integer, Double>> docList = new ArrayList<Map<Integer, Double>>(); Map<Integer, Double> unsortedMostPopularTopics = new LinkedHashMap<Integer, Double>(); int numDocs = this.instances.size(); for (int doc = 0; doc < numDocs; ++doc) { Map<Integer, Double> topicList = new LinkedHashMap<Integer, Double>(); double[] topicProbs = LDA.getTopicProbabilities(doc); //double probSum = 0.0; for (int topic = 0; topic < topicProbs.length && topic < maxTopicsPerDoc; topic++) { if (topicProbs[topic] > TOPIC_THRESHOLD) { // TODO double newTopicProb = topicProbs[topic]; topicList.put(topic, newTopicProb); Double oldTopicProb = unsortedMostPopularTopics.get(topic); unsortedMostPopularTopics.put(topic, oldTopicProb == null ? newTopicProb : oldTopicProb.doubleValue() + newTopicProb); //probSum += topicProbs[topic]; } } //System.out.println("Topic Sum: " + probSum); Map<Integer, Double> sortedTopicList = new TreeMap<Integer, Double>(new DoubleMapComparator(topicList)); sortedTopicList.putAll(topicList); docList.add(sortedTopicList); } Map<Integer, Double> sortedMostPopularTopics = new TreeMap<Integer, Double>(new DoubleMapComparator(unsortedMostPopularTopics)); sortedMostPopularTopics.putAll(unsortedMostPopularTopics); for (Map.Entry<Integer, Double> entry : sortedMostPopularTopics.entrySet()) { if (this.mostPopularTopics.size() < MAX_RECOMMENDATIONS) { this.mostPopularTopics.put(entry.getKey(), entry.getValue()); } } return docList; }
Example #27
Source File: TzdbZoneRulesProvider.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
@Override protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) { TreeMap<String, ZoneRules> map = new TreeMap<>(); ZoneRules rules = getRules(zoneId, false); if (rules != null) { map.put(versionId, rules); } return map; }
Example #28
Source File: ThriftCodecByteCodeGenerator.java From drift with Apache License 2.0 | 5 votes |
/** * Defines the code to read all of the data from the protocol into local variables. */ private Map<Short, Variable> readFieldValues(MethodDefinition method, Variable reader) { // declare and init local variables here Map<Short, Variable> structData = new TreeMap<>(); for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) { Variable variable = method.getScope().declareVariable( toParameterizedType(field.getThriftType()), "f_" + field.getName()); structData.put(field.getId(), variable); method.getBody().append(variable.set(defaultValue(variable.getType()))); } // protocol.readStructBegin(); method.getBody().append(reader.invoke("readStructBegin", void.class)); // while (protocol.nextField()) WhileLoop whileLoop = new WhileLoop() .condition(reader.invoke("nextField", boolean.class)); // switch (protocol.getFieldId()) SwitchBuilder switchBuilder = switchBuilder() .expression(reader.invoke("getFieldId", short.class)); // cases for field.id buildFieldIdSwitch(method, reader, structData, switchBuilder); // default case switchBuilder.defaultCase(new BytecodeBlock() .append(reader.invoke("skipFieldData", void.class))); // finish loop whileLoop.body(switchBuilder.build()); method.getBody().append(whileLoop); // protocol.readStructEnd(); method.getBody().append(reader.invoke("readStructEnd", void.class)); return structData; }
Example #29
Source File: BlazeVersionInfoTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void testFancySummaryFormatting() { Map<String, String> data = new HashMap<>(); data.put("Some entry", "foo"); data.put("Another entry", "bar"); data.put("And a third entry", "baz"); BlazeVersionInfo info = new BlazeVersionInfo(data); Map<String, String> sortedData = new TreeMap<>(data); assertThat(info.getSummary()).isEqualTo(StringUtilities.layoutTable(sortedData)); }
Example #30
Source File: GfxdConfigMessage.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
@Override public Object process(Object arg, Set<DistributedMember> members, GfxdConfigMessage<?> msg) { final TreeMap<Object, Object> props = new TreeMap<Object, Object>(); addGFXDProps(props); return props; }