类java.util.TreeMap源码实例Demo

下面列出了怎么用java.util.TreeMap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: fenixedu-academic   文件: RegistrationDA.java
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");
}
 
源代码2 项目: openjdk-jdk9   文件: Type.java
/**
 * 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;
}
 
源代码3 项目: game-server   文件: TriangleGraph.java
/**
 * 创建每个三角形的共享边列表 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;
}
 
源代码4 项目: DailyCodingProblem   文件: Solution.java
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;
}
 
源代码5 项目: jpms-module-names   文件: Utility.java
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;
}
 
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();
    }
 
源代码7 项目: Paguro   文件: Tuple2Test.java
@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)));
}
 
源代码8 项目: we-cmdb   文件: MultiValueFeildOperationUtils.java
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;
}
 
源代码9 项目: jdk8u60   文件: JTop.java
/**
 * 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;
}
 
源代码10 项目: sarl   文件: ExtraLanguageGeneratorContext.java
@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;
}
 
源代码11 项目: openjdk-jdk9   文件: TreeMapTest.java
/**
 * 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")));
    }
}
 
源代码12 项目: hbase   文件: TestTableInputFormatBase.java
@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;
}
 
源代码13 项目: LAML   文件: Matlab.java
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;
	}
}
 
源代码14 项目: HuobiRobot   文件: HuobiService.java
/**
 * 下单接口
 * 
 * @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);
}
 
源代码15 项目: otroslogviewer   文件: AllNotesTextAreaObserver.java
@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());

}
 
源代码16 项目: java-ocr-api   文件: FileSystemPreferences.java
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);
    }
}
 
源代码17 项目: cordova-android-chromeview   文件: RawHeaders.java
/**
 * 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);
}
 
源代码18 项目: JMCCC   文件: JSONObject.java
/**
 * 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;
}
 
源代码19 项目: jdk8u60   文件: SparseArrayData.java
@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;
}
 
源代码20 项目: openjdk-jdk8u   文件: UnmodifiableMapEntrySet.java
@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][]);
}
 
源代码21 项目: DWSurvey   文件: ServletUtils.java
/**
 * 取得带相同前缀的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;
}
 
源代码22 项目: ade   文件: StatisticsChart.java
/** Apply mapping on a given map.
 * Map keys are renamed, and those missing are removed
 * 
 * @param src Map to be processed.
 * @param mapping Mapping according to which to process src
 * @return
 */
static <T> TreeMap<String, T> applyResultMapping(SortedMap<String, T> src, SortedMap<String, String> mapping) {
    if (src == null) {
        return null;
    }
    final TreeMap<String, T> result = new TreeMap<String, T>();
    for (SortedMap.Entry<String, T> entry : src.entrySet()) {
        final String newName = mapping.get(entry.getKey());
        if (newName != null) {
            result.put(newName, entry.getValue());
        }
    }
    return result;
}
 
源代码23 项目: Doradus   文件: RESTRegistry.java
private Map<String, RESTCommand> getCmdNameMap(String cmdOwner) {
    SortedMap<String, RESTCommand> cmdNameMap = m_cmdsByOwnerMap.get(cmdOwner);
    if (cmdNameMap == null) {
        cmdNameMap = new TreeMap<>();
        m_cmdsByOwnerMap.put(cmdOwner, cmdNameMap);
    }
    return cmdNameMap;
}
 
源代码24 项目: mq-http-java-sdk   文件: AbstractAction.java
private String getSignature(RequestMessage request) throws ClientException {
    Map<String, String> headers = request.getHeaders();

    StringBuffer canonicalizedHeaders = new StringBuffer();
    StringBuffer stringToSign = new StringBuffer();
    String contentMd5 = safeGetHeader(Constants.CONTENT_MD5, headers);
    String contentType = safeGetHeader(Constants.CONTENT_TYPE, headers);
    String date = safeGetHeader(Constants.DATE, headers);
    String canonicalizedResource = getRelativeResourcePath(request
            .getResourcePath());

    TreeMap<String, String> tmpHeaders = sortHeader(request.getHeaders());
    if (tmpHeaders.size() > 0) {
        Set<String> keySet = tmpHeaders.keySet();
        for (String key : keySet) {
            if (key.toLowerCase().startsWith(
                    Constants.X_HEADER_PREFIX)) {
                canonicalizedHeaders.append(key).append(":")
                        .append(tmpHeaders.get(key)).append("\n");
            }
        }
    }
    stringToSign.append(method).append("\n").append(contentMd5)
            .append("\n").append(contentType).append("\n").append(date)
            .append("\n").append(canonicalizedHeaders)
            .append(canonicalizedResource);
    String signature;

    try {
        signature = ServiceSignature.create().computeSignature(
                credentials.getAccessKeySecret(), stringToSign.toString());
    } catch (Exception e) {
        throw new ClientException("Signature fail", null, e);
    }

    return signature;
}
 
private SortedMap<String, File> mapFiles(final List<File> files) {

        final SortedMap<String, File> toReturn = new TreeMap<String, File>();
        for (File current : files) {
            toReturn.put(current.getPath(), current);
        }

        return toReturn;
    }
 
源代码26 项目: droidkaigi2016   文件: SessionsFragment.java
protected void groupByDateSessions(List<Session> sessions) {
    Map<String, List<Session>> sessionsByDate = new TreeMap<>();
    for (Session session : sessions) {
        String key = DateUtil.getMonthDate(session.stime, getActivity());
        if (sessionsByDate.containsKey(key)) {
            sessionsByDate.get(key).add(session);
        } else {
            List<Session> list = new ArrayList<>();
            list.add(session);
            sessionsByDate.put(key, list);
        }
    }

    adapter = new SessionsPagerAdapter(getFragmentManager());

    for (Map.Entry<String, List<Session>> e : sessionsByDate.entrySet()) {
        addFragment(e.getKey(), e.getValue());
    }

    binding.viewPager.setAdapter(adapter);
    binding.tabLayout.setupWithViewPager(binding.viewPager);
    binding.tabLayout.setOnTabSelectedListener(new CustomViewPagerOnTabSelectedListener(binding.viewPager));

    hideLoadingView();
    if (sessions.isEmpty()) {
        showEmptyView();
    } else {
        hideEmptyView();
    }
}
 
源代码27 项目: incubator-taverna-language   文件: DataBundles.java
public static NavigableMap<String, Path> getPorts(Path path)
		throws IOException {
	NavigableMap<String, Path> ports = new TreeMap<>();
	try (DirectoryStream<Path> ds = newDirectoryStream(path)) {
		for (Path p : ds)
			ports.put(filenameWithoutExtension(p), p);
	}
	return ports;
}
 
源代码28 项目: j2objc   文件: TestFmwk.java
/**
 * Log the known issue.
 * This method returns true unless -prop:logKnownIssue=no is specified
 * in the argument list.
 *
 * @param ticket A ticket number string. For an ICU ticket, use numeric characters only,
 * such as "10245". For a CLDR ticket, use prefix "cldrbug:" followed by ticket number,
 * such as "cldrbug:5013".
 * @param comment Additional comment, or null
 * @return true unless -prop:logKnownIssue=no is specified in the test command line argument.
 */
protected static boolean logKnownIssue(String ticket, String comment) {
    if (!getBooleanProperty("logKnownIssue", true)) {
        return false;
    }

    StringBuffer descBuf = new StringBuffer();
    // TODO(junit) : what to do about this?
    //getParams().stack.appendPath(descBuf);
    if (comment != null && comment.length() > 0) {
        descBuf.append(" (" + comment + ")");
    }
    String description = descBuf.toString();

    String ticketLink = "Unknown Ticket";
    if (ticket != null && ticket.length() > 0) {
        boolean isCldr = false;
        ticket = ticket.toLowerCase(Locale.ENGLISH);
        if (ticket.startsWith(CLDR_TICKET_PREFIX)) {
            isCldr = true;
            ticket = ticket.substring(CLDR_TICKET_PREFIX.length());
        }
        ticketLink = (isCldr ? CLDR_TRAC_URL : ICU_TRAC_URL) + ticket;
    }

    if (getParams().knownIssues == null) {
        getParams().knownIssues = new TreeMap<String, List<String>>();
    }
    List<String> lines = getParams().knownIssues.get(ticketLink);
    if (lines == null) {
        lines = new ArrayList<String>();
        getParams().knownIssues.put(ticketLink, lines);
    }
    if (!lines.contains(description)) {
        lines.add(description);
    }

    return true;
}
 
源代码29 项目: java-pilosa   文件: OrmTest.java
@Test
public void setRowAttrsTest() {
    Map<String, Object> attrsMap = new TreeMap<>();
    attrsMap.put("quote", "\"Don't worry, be happy\"");
    attrsMap.put("active", true);
    PqlQuery q = collabField.setRowAttrs(5, attrsMap);
    assertEquals(
            "SetRowAttrs(collaboration,5,active=true,quote=\"\\\"Don't worry, be happy\\\"\")",
            q.serialize().getQuery());
    q = collabField.setRowAttrs("foo", attrsMap);
    assertEquals(
            "SetRowAttrs('collaboration','foo',active=true,quote=\"\\\"Don't worry, be happy\\\"\")",
            q.serialize().getQuery());
}
 
源代码30 项目: pravega   文件: StreamSegments.java
public StreamSegments withReplacementRange(Segment segment, StreamSegmentsWithPredecessors replacementRanges) {
    SegmentWithRange replacedSegment = findReplacedSegment(segment);
    verifyReplacementRange(replacedSegment, replacementRanges);
    NavigableMap<Double, SegmentWithRange> result = new TreeMap<>();
    Map<Long, List<SegmentWithRange>> replacedRanges = replacementRanges.getReplacementRanges();
    List<SegmentWithRange> replacements = replacedRanges.get(segment.getSegmentId());
    Preconditions.checkNotNull(replacements, "Empty set of replacements for: {}", segment.getSegmentId());
    replacements.sort(Comparator.comparingDouble((SegmentWithRange s) -> s.getRange().getHigh()).reversed());
    verifyContinuous(replacements);
    for (Entry<Double, SegmentWithRange> existingEntry : segments.descendingMap().entrySet()) { // iterate from the highest key.
        final SegmentWithRange existingSegment = existingEntry.getValue();
        if (existingSegment.equals(replacedSegment)) { // Segment needs to be replaced.
            // Invariant: The successor segment(s)'s range should be limited to the replaced segment's range, thereby
            // ensuring that newer writes to the successor(s) happen only for the replaced segment's range.
            for (SegmentWithRange segmentWithRange : replacements) {
                Double lowerBound = segments.lowerKey(existingEntry.getKey()); // Used to skip over items not in the clients view yet.
                if (lowerBound == null || segmentWithRange.getRange().getHigh() >= lowerBound) { 
                    result.put(Math.min(segmentWithRange.getRange().getHigh(), existingEntry.getKey()), segmentWithRange);
                }
            }
        } else {
            // update remaining values.
            result.put(existingEntry.getKey(), existingEntry.getValue());
        }
    }
    removeDuplicates(result);
    return new StreamSegments(result, delegationToken);
}
 
 类所在包
 同包方法