Java Code Examples for java.util.SortedMap

The following examples show how to use java.util.SortedMap. 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
@Override
public long calculateCompactionIndex(SortedMap<Long, Long> snapshotTimestamps, Journal journal) {
    long index = -1;
    long now = System.currentTimeMillis();

    if (retentionMin > 0) {
        long compactTimestamp = now - retentionMin * 60 * 1000L;

        for (Map.Entry<Long, Long> entry : snapshotTimestamps.entrySet()) {
            long snapshotIndex = entry.getKey();
            long snapshotTimestamp = entry.getValue();
            if (snapshotTimestamp <= compactTimestamp) {
                index = snapshotIndex;
            } else {
                break;
            }
        }
        logger.info("Calculate journal compaction index: {}, current timestamp: {}.", index, ThreadSafeFormat.format(new Date(now)));
    }
    return index;
}
 
Example 2
Source Project: jvm-sandbox-repeater   Source File: MapDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
private Map createMap()
  throws IOException
{
  
  if (_type == null)
    return new HashMap();
  else if (_type.equals(Map.class))
    return new HashMap();
  else if (_type.equals(SortedMap.class))
    return new TreeMap();
  else {
    try {
      return (Map) _ctor.newInstance();
    } catch (Exception e) {
      throw new IOExceptionWrapper(e);
    }
  }
}
 
Example 3
Source Project: netbeans   Source File: InstructionsConverter.java    License: Apache License 2.0 6 votes vote down vote up
public static SortedMap<String, Boolean> computeExportList (Map<Integer, String> exportInstructions, Project project) {
    SortedMap<String, Boolean> pkgMap = new TreeMap<String, Boolean>();
    SortedSet<String> pkgNames = FileUtilities.getPackageNames(project);
    for (String name : pkgNames) {
        pkgMap.put(name, Boolean.FALSE);
    }
    String exportIns = exportInstructions.get(EXPORT_PACKAGE);
    if (exportIns != null) {
        StringTokenizer strTok = new StringTokenizer(exportIns, DELIMITER);

        while(strTok.hasMoreTokens()) {
            String cur = strTok.nextToken();
            pkgMap.remove(cur);
            pkgMap.put(cur, Boolean.TRUE);
        }
    }

    return pkgMap;
}
 
Example 4
/**
 * Convenient method to connect parts across pages.
 * This method is to be used when merging the results of several pages.
 * Here we work directly with Audiveris Page entities
 *
 * @param pages the sequence of pages, as (audiveris) Page instances
 */
public static PartConnection connectScorePages (
        SortedMap<Integer, Page> pages)
{
    // Build candidates (here a candidate is a ScorePart)
    Set<List<Candidate>> sequences = new LinkedHashSet<>();

    for (Entry<Integer, Page> entry : pages.entrySet()) {
        Page page = entry.getValue();
        List<ScorePart> partList = page.getPartList();
        List<Candidate> parts = new ArrayList<>();

        for (ScorePart scorePart : partList) {
            parts.add(new ScorePartCandidate(scorePart, page));
        }

        sequences.add(parts);
    }

    return new PartConnection(sequences);
}
 
Example 5
Source Project: cloudbreak   Source File: CustomHTMLReporter.java    License: Apache License 2.0 6 votes vote down vote up
private SortedMap<IClass, List<ITestResult>> sortByTestClass(IResultMap results) {
    SortedMap<IClass, List<ITestResult>> sortedResults = new TreeMap<IClass, List<ITestResult>>(CLASS_COMPARATOR);
    for (ITestResult result : results.getAllResults()) {
        List<ITestResult> resultsForClass = sortedResults.get(result.getTestClass());
        if (resultsForClass == null) {
            resultsForClass = new ArrayList<>();
            sortedResults.put(result.getTestClass(), resultsForClass);
        }
        int index = Collections.binarySearch(resultsForClass, result, RESULT_COMPARATOR);
        if (index < 0) {
            index = Math.abs(index + 1);
        }
        resultsForClass.add(index, result);
    }
    return sortedResults;
}
 
Example 6
Source Project: nifi   Source File: CSVRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
private List<RecordField> getRecordFields() {
    if (this.recordFields != null) {
        return this.recordFields;
    }

    // Use a SortedMap keyed by index of the field so that we can get a List of field names in the correct order
    final SortedMap<Integer, String> sortedMap = new TreeMap<>();
    for (final Map.Entry<String, Integer> entry : csvParser.getHeaderMap().entrySet()) {
        sortedMap.put(entry.getValue(), entry.getKey());
    }

    final List<RecordField> fields = new ArrayList<>();
    final List<String> rawFieldNames = new ArrayList<>(sortedMap.values());
    for (final String rawFieldName : rawFieldNames) {
        final Optional<RecordField> option = schema.getField(rawFieldName);
        if (option.isPresent()) {
            fields.add(option.get());
        } else {
            fields.add(new RecordField(rawFieldName, RecordFieldType.STRING.getDataType()));
        }
    }

    this.recordFields = fields;
    return fields;
}
 
Example 7
/**
 * Returns a sorted list of all transformers sorted by name.
 * @param transformerName to restrict the collection to one entry
 * @return a new Collection of sorted transformers
 * @throws IllegalArgumentException if transformerName is not found.
 * @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
 */
@Deprecated
public Collection<ContentTransformer> sortTransformersByName(String transformerName)
{
    Collection<ContentTransformer> transformers = (transformerName != null)
            ? Collections.singleton(transformerRegistry.getTransformer(transformerName))
            : transformerRegistry.getAllTransformers();

    SortedMap<String, ContentTransformer> map = new TreeMap<String, ContentTransformer>();
    for (ContentTransformer transformer: transformers)
    {
        String name = transformer.getName();
        map.put(name, transformer);
    }
    Collection<ContentTransformer> sorted = map.values();
    return sorted;
}
 
Example 8
Source Project: big-c   Source File: Message.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * construct a full wire message including data and annotations payloads.
 */
public Message(int msgType, byte[] databytes, int serializer_id, int flags, int seq, SortedMap<String, byte[]> annotations, byte[] hmac)
{
	this(msgType, serializer_id, flags, seq);
	this.data = databytes;
	this.data_size = databytes.length;
	this.annotations = annotations;
	if(null==annotations)
		this.annotations = new TreeMap<String, byte[]>();
	
	if(hmac!=null)
		this.annotations.put("HMAC", this.hmac(hmac));		// do this last because it hmacs the other annotation chunks
	
	this.annotations_size = 0;
	for(Entry<String, byte[]> a: this.annotations.entrySet())
		this.annotations_size += a.getValue().length+6;
}
 
Example 9
Source Project: batfish   Source File: BgpFilterInactiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNoAdvertiseInactive() throws IOException {
  Batfish batfish =
      BatfishTestUtils.getBatfishFromTestrigText(
          TestrigText.builder()
              .setConfigurationFiles(
                  SNAPSHOT_PATH, AS1_NAME, AS2_NO_ADVERTISE_INACTIVE_NAME, AS3_NAME)
              .build(),
          _folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  IncrementalDataPlane dataplane =
      (IncrementalDataPlane) batfish.loadDataPlane(batfish.getSnapshot());
  SortedMap<String, SortedMap<String, Set<AbstractRoute>>> routes =
      IncrementalBdpEngine.getRoutes(dataplane);

  assertRoute(routes, RoutingProtocol.STATIC, AS1_NAME, Prefix.ZERO, 0, STATIC_NEXT_HOP);
  assertRoute(
      routes,
      RoutingProtocol.STATIC,
      AS2_NO_ADVERTISE_INACTIVE_NAME,
      Prefix.ZERO,
      0,
      STATIC_NEXT_HOP);
  assertNoRoute(routes, AS3_NAME, Prefix.ZERO);
}
 
Example 10
private static String toID(SortedMap<Character, Extension> map) {
    StringBuilder buf = new StringBuilder();
    Extension privuse = null;
    for (Entry<Character, Extension> entry : map.entrySet()) {
        char singleton = entry.getKey();
        Extension extension = entry.getValue();
        if (LanguageTag.isPrivateusePrefixChar(singleton)) {
            privuse = extension;
        } else {
            if (buf.length() > 0) {
                buf.append(LanguageTag.SEP);
            }
            buf.append(extension);
        }
    }
    if (privuse != null) {
        if (buf.length() > 0) {
            buf.append(LanguageTag.SEP);
        }
        buf.append(privuse);
    }
    return buf.toString();
}
 
Example 11
/** Run BIDE algorithm */
public static SortedMap<Sequence, Integer> mineFrequentClosedSequencesBIDE(final String dataset,
		final String saveFile, final double minSupp) throws IOException {

	final SequenceDatabase sequenceDatabase = new SequenceDatabase();
	sequenceDatabase.loadFile(dataset);

	// Convert to absolute support (rounding down)
	final int absMinSupp = (int) (sequenceDatabase.size() * minSupp);

	final AlgoBIDEPlus algo = new AlgoBIDEPlus();
	algo.setShowSequenceIdentifiers(false);
	final SequentialPatterns patterns = algo.runAlgorithm(sequenceDatabase, saveFile, absMinSupp);
	// algo.printStatistics(sequenceDatabase.size());

	return toMap(patterns);
}
 
Example 12
Source Project: j2objc   Source File: ConcurrentSkipListSubMapTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * headMap returns map with keys in requested range
 */
public void testHeadMapContents() {
    ConcurrentNavigableMap map = map5();
    SortedMap sm = map.headMap(four);
    assertTrue(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(one, k);
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    sm.clear();
    assertTrue(sm.isEmpty());
    assertEquals(2, map.size());
    assertEquals(four, map.firstKey());
}
 
Example 13
Source Project: openjdk-jdk9   Source File: TreeSubMapTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * headMap returns map with keys in requested range
 */
public void testDescendingHeadMapContents() {
    NavigableMap map = dmap5();
    SortedMap sm = map.headMap(m4);
    assertTrue(sm.containsKey(m1));
    assertTrue(sm.containsKey(m2));
    assertTrue(sm.containsKey(m3));
    assertFalse(sm.containsKey(m4));
    assertFalse(sm.containsKey(m5));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(m1, k);
    k = (Integer)(i.next());
    assertEquals(m2, k);
    k = (Integer)(i.next());
    assertEquals(m3, k);
    assertFalse(i.hasNext());
    sm.clear();
    assertTrue(sm.isEmpty());
    assertEquals(2, map.size());
    assertEquals(m4, map.firstKey());
}
 
Example 14
/** Convert frequent sequences to sorted Map<Sequence, Integer> */
public static SortedMap<Sequence, Integer> toMap(final SequentialPatterns patterns) {
	if (patterns == null) {
		return null;
	} else {
		final HashMap<Sequence, Integer> sequences = new HashMap<>();
		for (final List<SequentialPattern> level : patterns.levels) {
			for (final SequentialPattern pattern : level) {
				final Sequence seq = new Sequence();
				for (final Itemset set : pattern.getItemsets())
					seq.add(set.get(0)); // Assumes a seq is just singleton
											// itemsets
				sequences.put(seq, pattern.getAbsoluteSupport());
			}
		}
		// Sort patterns by support
		final Ordering<Sequence> comparator = Ordering.natural().reverse().onResultOf(Functions.forMap(sequences))
				.compound(Ordering.usingToString());
		return ImmutableSortedMap.copyOf(sequences, comparator);
	}
}
 
Example 15
Source Project: collect-earth   Source File: AbstractPlacemarkDataController.java    License: MIT License 6 votes vote down vote up
/**
 * Sort parameters based on schema order (BFS)
 * @param parameters Parameters to be sorted
 * @return The parameters sorted alphabetically
 */
public Map<String, String> sortParameters(Map<String, String> parameters) {
	NavigableMap<String, String> navigableParameters = new TreeMap<String, String>(parameters);
	//extract parameter names in order
	BalloonInputFieldsUtils collectParametersHandler = new BalloonInputFieldsUtils();
	Map<String, String> sortedParameterNameByNodePath = collectParametersHandler.getHtmlParameterNameByNodePath(earthSurveyService.getRootEntityDefinition());
	List<String> sortedParameterNames = new ArrayList<String>(sortedParameterNameByNodePath.values());
	
	//create a new map and put the parameters in order there
	Map<String, String> result = new LinkedHashMap<String, String>(navigableParameters.size());
	for (String parameterName : sortedParameterNames) {
		//get all the entries with key starting with parameterName
		SortedMap<String,String> subMap = new TreeMap<String, String>( navigableParameters.subMap(parameterName, parameterName + Character.MAX_VALUE) );
		Set<Entry<String,String>> entrySet = subMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
				result.put(entry.getKey(), entry.getValue());
				navigableParameters.remove(entry.getKey());
		}
	}
	//add remaining parameters (if any)
	result.putAll(navigableParameters);
	return result;
}
 
Example 16
Source Project: hbase   Source File: MemStoreFlusher.java    License: Apache License 2.0 6 votes vote down vote up
private HRegion getBiggestMemStoreOfRegionReplica(
    SortedMap<Long, Collection<HRegion>> regionsBySize,
    Set<HRegion> excludedRegions) {
  synchronized (regionsInQueue) {
    for (Map.Entry<Long, Collection<HRegion>> entry : regionsBySize.entrySet()) {
      for (HRegion region : entry.getValue()) {
        if (excludedRegions.contains(region)) {
          continue;
        }

        if (RegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) {
          continue;
        }
        return region;
      }
    }
  }
  return null;
}
 
Example 17
Source Project: batfish   Source File: TraceroutePolicyBasedRoutingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWithNoPolicy() throws IOException {
  /*
   Construct TCP flow to 9.9.9.9, but don't set up PBR. Flow should take V1's static route out i1.
  */
  SortedMap<String, Configuration> configs = pbrNetwork(false);
  Batfish batfish = BatfishTestUtils.getBatfish(configs, _folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  PacketHeaderConstraints header =
      PacketHeaderConstraints.builder()
          .setSrcIp("1.1.1.222")
          .setDstIp("9.9.9.9")
          .setIpProtocols(ImmutableSet.of(IpProtocol.TCP))
          .build();

  TracerouteQuestion question =
      new TracerouteQuestion(SOURCE_LOCATION_STR, header, false, DEFAULT_MAX_TRACES);
  TracerouteAnswerer answerer = new TracerouteAnswerer(question, batfish);
  Map<Flow, List<Trace>> traces = answerer.getTraces(batfish.getSnapshot(), question);

  assertThat(traces.entrySet(), hasSize(1));
  assertThat(
      traces.values().iterator().next(),
      contains(hasHop(hasOutputInterface(NodeInterfacePair.of("c1", "i1")))));
}
 
Example 18
private SortedMap<Long, WALEdit> resolvePendingTransaction(final SortedMap<Long, WALEdit> pendingTransactionsById)
        throws IOException {

    SortedMap<Long, WALEdit> commitedTransactionsById = new TreeMap<Long, WALEdit>();

    LOG.info("Region log has " + pendingTransactionsById.size()
            + " unfinished transactions. Going to the transaction log to resolve");

    for (Entry<Long, WALEdit> entry : pendingTransactionsById.entrySet()) {
        TransactionLogger.TransactionStatus transactionStatus;
        transactionStatus = getGlobalTransactionLog().getStatusForTransaction(entry.getKey());

        if (transactionStatus == null) {
            throw new RuntimeException("Cannot resolve tranasction [" + entry.getKey() + "] from global tx log.");
        }
        switch (transactionStatus) {
            case ABORTED:
                break;
            case COMMITTED:
                commitedTransactionsById.put(entry.getKey(), entry.getValue());
                break;
            case PENDING:
                LOG.warn("Transaction [" + entry.getKey() + "] is still pending. Asumming it will not commit.");
                // FIXME / REVIEW validate this behavior/assumption
                // Can safely ignore this because if we don't see a commit or abort in the regions WAL, the we must
                // not have been
                // asked to vote yet.
                break;
        }
    }
    return commitedTransactionsById;
}
 
Example 19
Source Project: chart-fx   Source File: IndexedTreeMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.
 * This method runs in linear time.
 *
 * @param m the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort
 *        this map
 * @throws NullPointerException if the specified map is null
 */
public IndexedTreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException | ClassNotFoundException cannotHappen) {
        // do nothing
    }
}
 
Example 20
Source Project: Eagle   Source File: IndexDefinition.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] generateIndexRowkey(TaggedLogAPIEntity entity) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	if (entity.getClass() != entityDef.getEntityClass()) {
		throw new IllegalArgumentException("Expected entity class: " + entityDef.getEntityClass().getName() + ", but got class " + entity.getClass().getName());
	}
	final byte[][] indexValues = generateIndexValues(entity);
	final int[] partitionHashCodes = generatePartitionHashCodes(entity);
	SortedMap<Integer, Integer> tagMap = null;
	if (!index.unique()) {
		// non cluster index
		tagMap = RowkeyBuilder.generateSortedTagMap(entityDef.getPartitions(), entity.getTags());
	}
	
	return generateUniqueIndexRowkey(indexValues, partitionHashCodes, tagMap);
}
 
Example 21
Source Project: Time4A   Source File: DayPeriod.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Creates an instance based on user-defined data. </p>
 *
 * @param   timeToLabels    map containing the day-periods where the keys represent starting points
 *                          and the values represent the associated labels intended for representation
 * @return  user-specific instance
 * @throws  IllegalArgumentException if given map is empty or contains empty values
 * @since   3.13/4.10
 */
/*[deutsch]
 * <p>Erzeugt eine Instanz, die auf benutzerdefinierten Daten beruht. </p>
 *
 * @param   timeToLabels    map containing the day-periods where the keys represent starting points
 *                          and the values represent the associated labels intended for representation
 * @return  user-specific instance
 * @throws  IllegalArgumentException if given map is empty or contains empty values
 * @since   3.13/4.10
 */
public static DayPeriod of(Map<PlainTime, String> timeToLabels) {

    if (timeToLabels.isEmpty()) {
        throw new IllegalArgumentException("Label map is empty.");
    }

    SortedMap<PlainTime, String> map = new TreeMap<PlainTime, String>(timeToLabels);

    for (PlainTime key : timeToLabels.keySet()) {
        if (key.getHour() == 24) {
            map.put(PlainTime.midnightAtStartOfDay(), timeToLabels.get(key));
            map.remove(key);
        } else if (timeToLabels.get(key).isEmpty()) {
            throw new IllegalArgumentException("Map has empty label: " + timeToLabels);
        }
    }

    return new DayPeriod(null, "", map);

}
 
Example 22
@Test
public void testOneGroupOfTwoInRange() {
    // 12 AM - 1 AM
    long start_time0_ms = new DateTime(2000, 1, 1, 0, 0, 0, 0, DTZ).getMillis();
    long start_time0_s = TimeUnit.MILLISECONDS.toSeconds(start_time0_ms);
    long end_time0_ms = start_time0_ms + TimeUnit.HOURS.toMillis(1);
    long end_time0_s = TimeUnit.MILLISECONDS.toSeconds(end_time0_ms);
    AgendaItem item0 = new AgendaItem();
    item0.setEpochStartTime(start_time0_s);
    item0.setEpochEndTime(end_time0_s);

    // 12 AM - 1 AM
    AgendaItem item1 = new AgendaItem();
    item1.setEpochStartTime(start_time0_s);
    item1.setEpochEndTime(end_time0_s);

    long look_ahead = TimeUnit.DAYS.toMillis(1);
    long now = start_time0_ms - look_ahead + 1;  // Just inside of range
    final List<AgendaItem> items_in = Arrays.asList(item0, item1);
    final SortedMap<DateRange, List<AgendaItem>> map =
        AgendaItems.upNext(items_in, now, TimeUnit.DAYS.toMillis(1), 0);

    assertEquals(1, map.size());
    final DateRange dr = map.firstKey();
    assertNotNull(dr);
    assertEquals(start_time0_ms, dr.start);
    assertEquals(end_time0_ms, dr.end);
    final List<AgendaItem> items_out = map.get(dr);
    assertEquals(2, items_out.size());
    assertSame(item0, items_out.get(0));
    assertSame(item1, items_out.get(1));
}
 
Example 23
Source Project: gemfirexd-oss   Source File: UpdateResultSet.java    License: Apache License 2.0 5 votes vote down vote up
private Map<Integer, Boolean> getReferencedUpdateCols(TIntObjectHashMap tempRefColUpdtd2DependentCols) {
  int[] refKeyCols = this.container.getExtraTableInfo()
      .getReferencedKeyColumns();
  // check if any of the modified cols is a ref key column of a
  // reference
  // integrity constraint
  // refKeyCols = fkInfo.colArray;
  if (refKeyCols != null) {
    SortedMap<Integer, Boolean> referencedImpactedColsMap = new TreeMap<Integer, Boolean>();
    // SortedSet<Integer> onlyRefUpadtedCols = new TreeSet();
    for (int i = 0; i < constants.changedColumnIds.length; ++i) {
      int modColID = constants.changedColumnIds[i];
      for (int refKeyColID : refKeyCols) {
        if (refKeyColID == modColID) {
          // onlyRefUpadtedCols.add(refKeyColID);
          TIntHashSet dependentCols = new TIntHashSet(refKeyCols.length);
          tempRefColUpdtd2DependentCols.put(refKeyColID, dependentCols);
          referencedImpactedColsMap.put(refKeyColID, Boolean.TRUE);
          addCompanionRefColsToMap(refKeyColID, referencedImpactedColsMap,
              dependentCols);
        }
      }
    }
    return referencedImpactedColsMap;

  }
  else {
    return null;
  }
}
 
Example 24
Source Project: hadoop   Source File: DataJoinReducerBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is the function that re-groups values for a key into sub-groups based
 * on a secondary key (input tag).
 * 
 * @param arg1
 * @return
 */
private SortedMap<Object, ResetableIterator> regroup(Object key,
                                                     Iterator arg1, Reporter reporter) throws IOException {
  this.numOfValues = 0;
  SortedMap<Object, ResetableIterator> retv = new TreeMap<Object, ResetableIterator>();
  TaggedMapOutput aRecord = null;
  while (arg1.hasNext()) {
    this.numOfValues += 1;
    if (this.numOfValues % 100 == 0) {
      reporter.setStatus("key: " + key.toString() + " numOfValues: "
                         + this.numOfValues);
    }
    if (this.numOfValues > this.maxNumOfValuesPerGroup) {
      continue;
    }
    aRecord = ((TaggedMapOutput) arg1.next()).clone(job);
    Text tag = aRecord.getTag();
    ResetableIterator data = retv.get(tag);
    if (data == null) {
      data = createResetableIterator();
      retv.put(tag, data);
    }
    data.add(aRecord);
  }
  if (this.numOfValues > this.largestNumOfValues) {
    this.largestNumOfValues = numOfValues;
    LOG.info("key: " + key.toString() + " this.largestNumOfValues: "
             + this.largestNumOfValues);
  }
  return retv;
}
 
Example 25
Source Project: buck   Source File: AbstractQueryCommand.java    License: Apache License 2.0 5 votes vote down vote up
private SortedMap<String, Object> resolveAllUnconfiguredAttributesForTarget(
    CommandRunnerParams params, BuckQueryEnvironment env, QueryBuildTarget target)
    throws QueryException {
  Map<String, Object> attributes = getAllUnconfiguredAttributesForTarget(params, env, target);
  PatternsMatcher patternsMatcher = new PatternsMatcher(outputAttributes());

  SortedMap<String, Object> convertedAttributes = new TreeMap<>();
  if (!patternsMatcher.isMatchesNone()) {
    for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
      String attributeName = attribute.getKey();
      String snakeCaseKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, attributeName);
      if (!patternsMatcher.matches(snakeCaseKey)) {
        continue;
      }

      Object jsonObject = attribute.getValue();
      if (!(jsonObject instanceof ListWithSelects)) {
        convertedAttributes.put(snakeCaseKey, jsonObject);
        continue;
      }

      convertedAttributes.put(
          snakeCaseKey, resolveUnconfiguredAttribute((ListWithSelects) jsonObject));
    }
  }

  if (patternsMatcher.matches(InternalTargetAttributeNames.DIRECT_DEPENDENCIES)) {
    convertedAttributes.put(
        InternalTargetAttributeNames.DIRECT_DEPENDENCIES,
        env.getNode(target).getParseDeps().stream()
            .map(Object::toString)
            .collect(ImmutableList.toImmutableList()));
  }

  return convertedAttributes;
}
 
Example 26
Source Project: beam   Source File: AvroCoder.java    License: Apache License 2.0 5 votes vote down vote up
private void checkMap(String context, TypeDescriptor<?> type, Schema schema) {
  if (!isSubtypeOf(type, SortedMap.class)) {
    reportError(context, "%s may not be deterministically ordered", type);
  }

  // Avro (currently) asserts that all keys are strings.
  // In case that changes, we double check that the key was a string:
  Class<?> keyType = type.resolveType(Map.class.getTypeParameters()[0]).getRawType();
  if (!String.class.equals(keyType)) {
    reportError(context, "map keys should be Strings, but was %s", keyType);
  }

  recurse(context, type.resolveType(Map.class.getTypeParameters()[1]), schema.getValueType());
}
 
Example 27
Source Project: j2objc   Source File: TreeMapTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testNavigableSubMapSerialization() {
    // Updated golden value since we have a different serialVersionUID in OpenJDK.
    String s = "aced0005737200216a6176612e7574696c2e547265654d617024417363656e646"
            + "96e675375624d61700cab946d1f0fab1c020000787200216a6176612e7574696c2"
            + "e547265654d6170244e6176696761626c655375624d617026617d4eacdd5933020"
            + "0075a000966726f6d53746172745a000b6869496e636c75736976655a000b6c6f4"
            + "96e636c75736976655a0005746f456e644c000268697400124c6a6176612f6c616"
            + "e672f4f626a6563743b4c00026c6f71007e00024c00016d7400134c6a6176612f7"
            + "574696c2f547265654d61703b7870000100007400016374000161737200116a617"
            + "6612e7574696c2e547265654d61700cc1f63e2d256ae60300014c000a636f6d706"
            + "17261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b78707"
            + "372002a6a6176612e6c616e672e537472696e672443617365496e73656e7369746"
            + "97665436f6d70617261746f7277035c7d5c50e5ce0200007870770400000004710"
            + "07e000671007e00067400016271007e000c71007e000571007e000574000164710"
            + "07e000d78";
    TreeMap<String, String> map = new TreeMap<String, String>(
            String.CASE_INSENSITIVE_ORDER);
    map.put("a", "a");
    map.put("b", "b");
    map.put("c", "c");
    map.put("d", "d");
    SortedMap<String, String> subMap = map.subMap("a", false, "c", true);
    new SerializationTester<SortedMap<String, String>>(subMap, s) {
        @Override protected void verify(SortedMap<String, String> deserialized) {
            try {
                deserialized.put("e", "e");
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    }.test();
}
 
Example 28
Source Project: jdk1.8-source-analysis   Source File: EnvHelp.java    License: Apache License 2.0 5 votes vote down vote up
public static <V> Map<String, V> filterAttributes(Map<String, V> attributes) {
    if (logger.traceOn()) {
        logger.trace("filterAttributes", "starts");
    }

    SortedMap<String, V> map = new TreeMap<String, V>(attributes);
    purgeUnserializable(map.values());
    hideAttributes(map);
    return map;
}
 
Example 29
/**
 * GenPolynomial subtraction.
 * 
 * @param S
 *            GenPolynomial.
 * @return this-S.
 */
@Override
public SymbolicPolynomial subtract(SymbolicPolynomial S) {
	if (S == null) {
		return this;
	}
	if (S.isZERO()) {
		return this;
	}
	if (this.isZERO()) {
		return S.negate();
	}
	assert (ring.nvar == S.ring.nvar);
	SymbolicPolynomial n = this.copy(); // new GenPolynomial(ring, val);
	SortedMap<ExpVectorSymbolic, IExpr> nv = n.val;
	SortedMap<ExpVectorSymbolic, IExpr> sv = S.val;
	for (Map.Entry<ExpVectorSymbolic, IExpr> me : sv.entrySet()) {
		ExpVectorSymbolic e = me.getKey();
		IExpr y = me.getValue(); // sv.get(e); // assert y != null
		IExpr x = nv.get(e);
		if (x != null) {
			x = x.subtract(y);
			if (!x.isZERO()) {
				nv.put(e, x);
			} else {
				nv.remove(e);
			}
		} else {
			nv.put(e, y.negate());
		}
	}
	return n;
}
 
Example 30
Source Project: hbase-indexer   Source File: IndexerMetricsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void shutdownMetrics(String indexerName) {
    SortedMap<String, SortedMap<MetricName, Metric>> groupedMetrics = Metrics.defaultRegistry().groupedMetrics(
            new IndexerMetricPredicate(indexerName));
    for (SortedMap<MetricName, Metric> metricMap : groupedMetrics.values()) {
        for (MetricName metricName : metricMap.keySet()) {
            Metrics.defaultRegistry().removeMetric(metricName);
        }
    }
}