Java Code Examples for java.util.SortedMap#keySet()

The following examples show how to use java.util.SortedMap#keySet() . These examples are extracted from open source projects. 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
public static JSONArray sortJsonByKey(JSONArray json, String key)
{
    JSONArray sorted = new JSONArray();
    SortedMap map = new TreeMap();

    for (Object o : json) {
        JSONObject tmp = (JSONObject) o;
        map.put(tmp.get(key),tmp);
    }

    Set<String> numbers = map.keySet();

    for (String number : numbers) {
        sorted.add(map.get(number));
    }

    return sorted;
}
 
Example 2
Source Project: genomewarp   File: GenomeWarpSerialTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateBEDFromVCF() {
  String file = GenomeWarpSerialTest.class.getClassLoader().getResource(VCF_PATH).getFile();
  VCFFileReader testVcf = new VCFFileReader(new File(file), false);

  SortedMap<String, List<GenomeRange>> want = new TreeMap<String, List<GenomeRange>>() {{
    put("chr1", new ArrayList<GenomeRange>() {{
      add(new GenomeRange("chr1", 49, 50));
      add(new GenomeRange("chr1", 51, 52));
      add(new GenomeRange("chr1", 119, 122));
      add(new GenomeRange("chr1", 136, 137));
      add(new GenomeRange("chr1", 189, 190));
    }});
    put("chr2", new ArrayList<GenomeRange>() {{
      add(new GenomeRange("chr2", 139, 141));
    }});
  }};

  SortedMap<String, List<GenomeRange>> got = GenomeRangeUtils.generateBEDFromVCF(testVcf, null);
  assertEquals(got.size(), want.size());
  for(String key: got.keySet()) {
    assertTrue(GenomeWarpTestUtils.equivalentRanges(got.get(key), want.get(key)));
  }
}
 
Example 3
Source Project: ache   File: MetricsManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Saves the metrics to a file for it to be reloaded when the crawler restarts
 * 
 * @param metricsRegistry
 * @param directoryPath
 * @throws IOException
 */
private void saveMetrics(MetricRegistry metricsRegistry, String directoryPath) {
    String directoryName = directoryPath + "/metrics/";
    File file = new File(directoryName);
    if (file.exists()) {
        file.delete();
    }
    file.mkdir();
    try {
        File outputFile = new File(directoryName + "metrics_counters.data");
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
        SortedMap<String, Counter> counters = metrics.getCounters();
        for (String counter : counters.keySet()) {
            Counter c = counters.get(counter);
            writer.write(counter + ":" + c.getCount());
            writer.newLine();
            writer.flush();
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        logger.error("Unable to save metrics to a file." + e.getMessage());
    }
}
 
Example 4
Source Project: big-c   File: HandshakeExample.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void responseAnnotations(SortedMap<String, byte[]> annotations, int msgtype)
{
	System.out.println("    Got response (type=" + msgtype + "). Annotations:");
	for(String ann: annotations.keySet()) {
		String value;
		if(ann.equals("CORR")) {
			ByteBuffer bb = ByteBuffer.wrap(annotations.get(ann));
			value = new UUID(bb.getLong(), bb.getLong()).toString();
		} else if (ann.equals("HMAC")) {
			value = "[...]";
		} else {
			value = annotations.get(ann).toString();
		}
		System.out.println("      " + ann + " -> " + value);
	}
	
}
 
Example 5
public static void main(String[] args) throws IOException {
    SortedMap<String, Charset> map = Charset.availableCharsets();
    for (String name : map.keySet()) {
        Charset charset = map.get(name);
        if (charset.canEncode() && !charset.name().equals("x-COMPOUND_TEXT")) {
            testNormalSurrogate(charset, NORMAL_SURROGATE);
            testMalformedSurrogate(charset, MALFORMED_SURROGATE);
            testMalformedSurrogate(charset, REVERSED_SURROGATE);
            testMalformedSurrogate(charset, SOLITARY_HIGH_SURROGATE);
            testMalformedSurrogate(charset, SOLITARY_LOW_SURROGATE);
            testSurrogateWithReplacement(charset, NORMAL_SURROGATE);
            testSurrogateWithReplacement(charset, MALFORMED_SURROGATE);
            testSurrogateWithReplacement(charset, REVERSED_SURROGATE);
            testSurrogateWithReplacement(charset, SOLITARY_HIGH_SURROGATE);
            testSurrogateWithReplacement(charset, SOLITARY_LOW_SURROGATE);
        }
    }
}
 
Example 6
Source Project: warnings-ng-plugin   File: IssuesTablePortlet.java    License: MIT License 6 votes vote down vote up
private void populateRows(final List<Job<?, ?>> visibleJobs, final SortedMap<String, String> toolNamesById) {
    for (Job<?, ?> job : visibleJobs) {
        TableRow row = new TableRow(job);
        for (String id : toolNamesById.keySet()) {
            Run<?, ?> lastCompletedBuild = job.getLastCompletedBuild();
            if (lastCompletedBuild == null) {
                row.add(Result.EMPTY);
            }
            else {
                Result result = lastCompletedBuild.getActions(ResultAction.class)
                        .stream()
                        .filter(action -> action.getId().equals(id))
                        .findFirst()
                        .map(Result::new)
                        .orElse(Result.EMPTY);
                row.add(result);
            }
        }
        rows.add(row);
    }
}
 
Example 7
/**
 * Returns Key if value is found in SortedMap, including also simple wildcard *
 */
public static <V> String simpleWildcardKeyFind(SortedMap<String,V> baseMap, String value) {
    if (value == null) {
        return null;
    }
    
    if (baseMap.get(value) != null) {
        //System.out.println("======= " + value);
        return value;
    } else if (value.length() > 0){
        String v = value;
        v = v.substring(0, v.length() - 1);
            
        while (v.length() > 0) {
            char nextLetter = (char)(v.charAt(v.length() -1) + 1);
            String end = v.substring(0, v.length()-1) + nextLetter;
            SortedMap<String, V> b = baseMap.subMap(v, end);
            
            for (String key : b.keySet()) {
                if ((key.length() == v.length() + 1) && key.endsWith("*")) {
                    //System.out.println("======= " + key);
                    return key;
                }
            }
            
            v = v.substring(0, v.length() - 1);
        }        
    }   
    return null;
}
 
Example 8
public JSONArray getDataToSend(List<SampleResult> list) {
    JSONArray data = new JSONArray();

    SortedMap<Long, List<SampleResult>> sortedResults = sortResults(list);
    for (Long sec : sortedResults.keySet()) {
        data.add(getAggregateSecond(sec, sortedResults.get(sec)));
    }
    return data;
}
 
Example 9
Source Project: Nicobar   File: JBossModuleLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find the highest revision for the given scriptModuleId
 * @param scriptModuleId name to search for
 * @return the highest revision number or -1 if no revisions exist
 */
public long getLatestRevisionNumber(ModuleId scriptModuleId) {
    Objects.requireNonNull(scriptModuleId, "scriptModuleId");
    ModuleIdentifier searchIdentifier = JBossModuleUtils.createRevisionId(scriptModuleId, 0);
    SortedMap<ModuleIdentifier,ModuleSpec> tailMap = moduleSpecs.tailMap(searchIdentifier);
    long revisionNumber = -1;
    for (ModuleIdentifier revisionId : tailMap.keySet()) {
        if (revisionId.getName().equals(scriptModuleId.toString())) {
            revisionNumber = getRevisionNumber(revisionId);
        } else {
            break;
        }
    }
    return revisionNumber;
}
 
Example 10
Source Project: doclava   File: NavTree.java    License: Apache License 2.0 5 votes vote down vote up
public static Data makeYamlHDF(SortedMap<String, Object> sorted, String base, Data data) {
  
  String key = "docs.pages.";
  int i = 0;
  for (String s : sorted.keySet()) {
    Object o = sorted.get(s);   
    
    if (o instanceof PackageInfo) {
      PackageInfo pkg = (PackageInfo) o;
      
      data.setValue("docs.pages." + i + ".id", "" + i);
      data.setValue("docs.pages." + i + ".label", pkg.name());
      data.setValue("docs.pages." + i + ".shortname", "API");
      data.setValue("docs.pages." + i + ".link", pkg.htmlPage());
      data.setValue("docs.pages." + i + ".type", "package");
    } else if (o instanceof ClassInfo) {
      ClassInfo cl = (ClassInfo) o;
      
      // skip classes that are the child of another class, recursion will handle those.
      if (cl.containingClass() == null){
        
        data.setValue("docs.pages." + i + ".id", "" + i);

        data = makeYamlHDF(cl, "docs.pages."+i, data);
      }
    }
    
    i++;
  }
  return data;
}
 
Example 11
void assertSortedMapCharacteristics(SortedMap<Integer, String> m, int keyCharacteristics) {
    assertMapCharacteristics(m, keyCharacteristics, Spliterator.SORTED);

    Set<Integer> keys = m.keySet();
    if (m.comparator() != null) {
        assertNotNullComparator(keys);
    }
    else {
        assertNullComparator(keys);
    }

    assertISEComparator(m.values());

    assertNotNullComparator(m.entrySet());
}
 
Example 12
private final NavigableSet<FilesystemBulkImportItemVersion> constructImportItemVersions(final SortedMap<BigDecimal,Pair<File,File>> itemVersions)
    throws InterruptedException
{
    // PRECONDITIONS
    if (itemVersions        == null) throw new IllegalArgumentException("itemVersions cannot be null.");
    if (itemVersions.size() <= 0)    throw new IllegalArgumentException("itemVersions cannot be empty.");
    
    // Body
    final NavigableSet<FilesystemBulkImportItemVersion> result = new TreeSet<>();
    
    for (final BigDecimal versionNumber : itemVersions.keySet())
    {
        if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException(Thread.currentThread().getName() + " was interrupted. Terminating early.");
        
        final Pair<File,File>   contentAndMetadataFiles = itemVersions.get(versionNumber);
        final FilesystemBulkImportItemVersion version   = new FilesystemBulkImportItemVersion(serviceRegistry,
                                                                                              configuredContentStore,
                                                                                              metadataLoader,
                                                                                              versionNumber,
                                                                                              contentAndMetadataFiles.getFirst(),
                                                                                              contentAndMetadataFiles.getSecond());
        
        result.add(version);
    }
    
    return(result);
}
 
Example 13
/**
 * Outputs the file.
 */
private static void outputFile(File dstFile, String version, SortedMap<String, ZoneRules> builtZones, SortedMap<LocalDate, Byte> leapSeconds) {
    Map<String, SortedMap<String, ZoneRules>> loopAllBuiltZones = new TreeMap<String, SortedMap<String, ZoneRules>>();
    loopAllBuiltZones.put(version, builtZones);
    Set<String> loopAllRegionIds = new TreeSet<String>(builtZones.keySet());
    Set<ZoneRules> loopAllRules = new HashSet<ZoneRules>(builtZones.values());
    outputFile(dstFile, loopAllBuiltZones, loopAllRegionIds, loopAllRules, leapSeconds);
}
 
Example 14
Source Project: gemfirexd-oss   File: GfxdTestConfig.java    License: Apache License 2.0 5 votes vote down vote up
public String toString() {
  StringBuffer buf = new StringBuffer();
  SortedMap<String,Object> map = this.toSortedMap();
  for (String key : map.keySet()) {
    Object val = map.get(key);
    buf.append(key + "=" + val + "\n");
  }
  return buf.toString();
}
 
Example 15
@Test
public void testNewControl() {
    SortedMap<String, Charset> charsetsSortedMap = Charset.availableCharsets();
    for (String encoding : charsetsSortedMap.keySet()) {
        ResourceBundle.Control control = PropertyResourceBundleControl.newControl(encoding);
        Assert.assertNotNull(control);
    }
}
 
Example 16
/**
 * Return the token index for the given position.
 *
 * @param sourceCode
 * @return
 */
protected static SortedMap<Integer, Integer> getTokenIndexForPostion(
		final SortedMap<Integer, String> tokenPositions) {
	final SortedMap<Integer, Integer> positionToIndex = Maps.newTreeMap();
	int i = 0;
	for (final int position : tokenPositions.keySet()) {
		positionToIndex.put(position, i);
		i++;
	}
	return positionToIndex;
}
 
Example 17
public BitSet getDuplicates(int pos) {
    if (duplicateBlocks == null) {
        return new BitSet();
    }
    BitSet current = new BitSet();
    current.set(pos);
    boolean changed;
    do {
        changed = false;
        for (SortedMap<Integer, Integer> duplicates : duplicateBlocks) {
            for (int i = current.nextSetBit(0); i >= 0; i = current.nextSetBit(i + 1)) {
                int offset = getOffset(duplicates, i);
                if (offset >= 0) {
                    for (Integer key : duplicates.keySet()) {
                        int dupPosition = positions[getInstructionNumber(positions, key) + offset];
                        if (!current.get(dupPosition)) {
                            changed = true;
                            current.set(dupPosition);
                        }
                    }
                }
            }
        }
    } while (changed && duplicateBlocks.size() > 1);
    current.clear(pos);
    return current;
}
 
Example 18
Source Project: Eagle   File: SiddhiPolicyEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
private void putAttrsIntoInputStream(List<Object> input, String streamName, SortedMap map) {
	if(!needValidation) {
		input.addAll(map.values());
		return;
	}
	for (Object key : map.keySet()) {
		Object value = map.get(key);
		if (value == null) {
			input.add(SiddhiStreamMetadataUtils.getAttrDefaultValue(streamName, (String)key));
		}
		else input.add(value);
	}
}
 
Example 19
private CompositeDataSupport(
        SortedMap<String, Object> items, CompositeType compositeType)
        throws OpenDataException {

    // Check compositeType is not null
    //
    if (compositeType == null) {
        throw new IllegalArgumentException("Argument compositeType cannot be null.");
    }

    // item names defined in compositeType:
    Set<String> namesFromType = compositeType.keySet();
    Set<String> namesFromItems = items.keySet();

    // This is just a comparison, but we do it this way for a better
    // exception message.
    if (!namesFromType.equals(namesFromItems)) {
        Set<String> extraFromType = new TreeSet<String>(namesFromType);
        extraFromType.removeAll(namesFromItems);
        Set<String> extraFromItems = new TreeSet<String>(namesFromItems);
        extraFromItems.removeAll(namesFromType);
        if (!extraFromType.isEmpty() || !extraFromItems.isEmpty()) {
            throw new OpenDataException(
                    "Item names do not match CompositeType: " +
                    "names in items but not in CompositeType: " + extraFromItems +
                    "; names in CompositeType but not in items: " + extraFromType);
        }
    }

    // Check each value, if not null, is of the open type defined for the
    // corresponding item
    for (String name : namesFromType) {
        Object value = items.get(name);
        if (value != null) {
            OpenType<?> itemType = compositeType.getType(name);
            if (!itemType.isValue(value)) {
                throw new OpenDataException(
                        "Argument value of wrong type for item " + name +
                        ": value " + value + ", type " + itemType);
            }
        }
    }

    // Initialize internal fields: compositeType and contents
    //
    this.compositeType = compositeType;
    this.contents = items;
}
 
Example 20
Source Project: JDKSourceCode1.8   File: CompositeDataSupport.java    License: MIT License 4 votes vote down vote up
private CompositeDataSupport(
        SortedMap<String, Object> items, CompositeType compositeType)
        throws OpenDataException {

    // Check compositeType is not null
    //
    if (compositeType == null) {
        throw new IllegalArgumentException("Argument compositeType cannot be null.");
    }

    // item names defined in compositeType:
    Set<String> namesFromType = compositeType.keySet();
    Set<String> namesFromItems = items.keySet();

    // This is just a comparison, but we do it this way for a better
    // exception message.
    if (!namesFromType.equals(namesFromItems)) {
        Set<String> extraFromType = new TreeSet<String>(namesFromType);
        extraFromType.removeAll(namesFromItems);
        Set<String> extraFromItems = new TreeSet<String>(namesFromItems);
        extraFromItems.removeAll(namesFromType);
        if (!extraFromType.isEmpty() || !extraFromItems.isEmpty()) {
            throw new OpenDataException(
                    "Item names do not match CompositeType: " +
                    "names in items but not in CompositeType: " + extraFromItems +
                    "; names in CompositeType but not in items: " + extraFromType);
        }
    }

    // Check each value, if not null, is of the open type defined for the
    // corresponding item
    for (String name : namesFromType) {
        Object value = items.get(name);
        if (value != null) {
            OpenType<?> itemType = compositeType.getType(name);
            if (!itemType.isValue(value)) {
                throw new OpenDataException(
                        "Argument value of wrong type for item " + name +
                        ": value " + value + ", type " + itemType);
            }
        }
    }

    // Initialize internal fields: compositeType and contents
    //
    this.compositeType = compositeType;
    this.contents = items;
}