Java Code Examples for java.util.TreeMap#putAll()

The following examples show how to use java.util.TreeMap#putAll() . 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: BrokerService.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@CmdTrace(cmdClazz = BrokerStatusSubCommand.class)
public Table brokerStats(String brokerAddr) throws Throwable {
    Throwable t = null;
    DefaultMQAdminExt defaultMQAdminExt = getDefaultMQAdminExt();
    try {
        defaultMQAdminExt.start();
        KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(brokerAddr);
        TreeMap<String, String> tmp = new TreeMap<String, String>();
        tmp.putAll(kvTable.getTable());
        return Table.Map2VTable(tmp);
    }
    catch (Throwable e) {
        logger.error(e.getMessage(), e);
        t = e;
    }
    finally {
        shutdownDefaultMQAdminExt(defaultMQAdminExt);
    }
    throw t;
}
 
Example 2
Source File: BrokerStatusSubCommand.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public void printBrokerRuntimeStats(final DefaultMQAdminExt defaultMQAdminExt, final String brokerAddr,
    final boolean printBroker) throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException {
    KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(brokerAddr);

    TreeMap<String, String> tmp = new TreeMap<String, String>();
    tmp.putAll(kvTable.getTable());

    Iterator<Entry<String, String>> it = tmp.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, String> next = it.next();
        if (printBroker) {
            System.out.printf("%-24s %-32s: %s%n", brokerAddr, next.getKey(), next.getValue());
        } else {
            System.out.printf("%-32s: %s%n", next.getKey(), next.getValue());
        }
    }
}
 
Example 3
Source File: BaseDataUtil.java    From sofa-acts with Apache License 2.0 6 votes vote down vote up
/**
 * save yaml
 * @param prepareDatas
 * @param file
 */
public static void storeToYaml(Map<String, PrepareData> prepareDatas, File file) {
    TreeMap<String, PrepareData> treeMap = new TreeMap<String, PrepareData>(
        new Comparator<String>() {
            @Override
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        });
    treeMap.putAll(prepareDatas);
    Yaml yaml = new Yaml(new BaseDataUtil.myRepresenter());
    String str = yaml.dump(treeMap);
    try {
        FileUtils.writeStringToFile(file, str);
    } catch (IOException e) {
        throw new ActsException("Throw an exception when saving yaml", e);
    }
}
 
Example 4
Source File: BrokerStatusSubCommand.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
public void printBrokerRuntimeStats(final DefaultMQAdminExt defaultMQAdminExt, final String brokerAddr,
    final boolean printBroker) throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException {
    KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(brokerAddr);

    TreeMap<String, String> tmp = new TreeMap<String, String>();
    tmp.putAll(kvTable.getTable());

    Iterator<Entry<String, String>> it = tmp.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, String> next = it.next();
        if (printBroker) {
            System.out.printf("%-24s %-32s: %s%n", brokerAddr, next.getKey(), next.getValue());
        } else {
            System.out.printf("%-32s: %s%n", next.getKey(), next.getValue());
        }
    }
}
 
Example 5
Source File: ChannelSpec.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return an as-complete-as-possible copy of the map of mipmap levels.
 */
public Map<Integer, ImageAndMask> getMipmapLevels() {

    final TreeMap<Integer, ImageAndMask> completeMipmapLevels = new TreeMap<>();
    completeMipmapLevels.putAll(mipmapLevels);

    if (mipmapPathBuilder != null)
        for (int level = 0; level < mipmapPathBuilder.getNumberOfLevels(); ++level)
            if (!completeMipmapLevels.containsKey(level)) {
                final Entry<Integer, ImageAndMask> entry =
                        mipmapPathBuilder.deriveImageAndMask(level, mipmapLevels.firstEntry(), true);
                if (entry != null)
                    completeMipmapLevels.put(entry.getKey(), entry.getValue());
            }

    return mipmapLevels;
}
 
Example 6
Source File: EntropyChunker.java    From Ngram-Graphs with Apache License 2.0 6 votes vote down vote up
protected Integer[] splitPointsByDelimiterList(String sStr, SortedMap lDelimiters) {
    ArrayList alRes = new ArrayList();
    TreeMap lLocal = new TreeMap();
    lLocal.putAll(lDelimiters);
    
    // For every candidate delimiter
    while (lLocal.size() > 0) {
        Object oNext = lLocal.lastKey();
        // Get all split points
        int iNextSplit = 0;
        int iLastSplit = 0;
        while ((iNextSplit = sStr.indexOf((String)lDelimiters.get(oNext), iLastSplit)) > -1) {
            // TODO : Check
            alRes.add(new Integer(iNextSplit + ((String)lDelimiters.get(oNext)).length()));
            iLastSplit = iNextSplit + 1;
        }
        
        lLocal.remove(oNext);
    }
    Integer [] iaRes = new Integer[alRes.size()];
    alRes.toArray(iaRes);
    gr.demokritos.iit.jinsect.utils.bubbleSortArray(iaRes);
    
    return iaRes;
}
 
Example 7
Source File: CROSSRecServiceImpl.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Recommendation getRecommendation(Query query) throws Exception {
	Recommendation result = new Recommendation();
	List<Dependency> dependencies = query.getProjectDependencies();
	Map<String, Double> sim = crossRecSimilarityCalculator.computeWeightCosineSimilarity(dependencies);
	Map<String, Double> res = userBasedRecommendation(dependencies, sim);
	ValueComparator bvc = new ValueComparator(res);
	TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
	sorted_map.putAll(res);
	int guard = 0;
	for (Map.Entry<String, Double> entry : sorted_map.entrySet()) {
		if (guard < numberOfRecommendedLibs) {
			Double value = entry.getValue();
			String coordinate = entry.getKey();
			RecommendationItem ri = new RecommendationItem();

			RecommendedLibrary rl = new RecommendedLibrary();

			String[] coordinateArray = coordinate.split(":");
			if (coordinateArray.length == 2) {
				MavenLibrary mvn = mvnRepository.findOneByGroupidAndArtifactidOrderByReleasedateDesc(coordinateArray[0],
						coordinateArray[1]);
				if (mvn != null)
					coordinate = coordinate + ":" + mvn.getVersion();
			}
			rl.setLibraryName(coordinate);
			rl.setUrl("https://mvnrepository.com/artifact/" + coordinate.replaceAll(":", "/"));
			ri.setRecommendedLibrary(rl);
			ri.setSignificance(value);
			ri.setRecommendationType("RecommendedLibrary");
			result.getRecommendationItems().add(ri);
			guard++;
		} else
			break;
	}
	return result;
}
 
Example 8
Source File: GlobalCharacterizer.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Double> characterize(final Instances instances) {

	if (this.logger.isTraceEnabled()) {
		this.logger.trace("Characterize dataset \"{}\" ...", instances.relationName());
	}

	TreeMap<String, Double> metaFeatures = new TreeMap<>();
	StopWatch watch = new StopWatch();

	for (Characterizer characterizer : this.characterizers) {
		try {
			watch.reset();
			watch.start();
			metaFeatures.putAll(characterizer.characterize(instances));
			watch.stop();
			this.computationTimes.put(characterizer.toString(), (double) watch.getTime());
		} catch (Exception e) {
			for (String metaFeature : characterizer.getIDs()) {
				metaFeatures.put(metaFeature, Double.NaN);
			}
			this.computationTimes.put(characterizer.toString(), Double.NaN);
		}
	}

	this.logger.trace("Done characterizing dataset. Feature length: {}", metaFeatures.size());

	return metaFeatures;
}
 
Example 9
Source File: MemoryTimerStore.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Long, TimerData> getTasks() {
    checkThread();
    final TreeMap<Long, TimerData> allTasks = new TreeMap<>(taskStore);
    for (final Long key : remove) {
        allTasks.remove(key);
    }
    allTasks.putAll(add);
    return Collections.unmodifiableMap(allTasks);
}
 
Example 10
Source File: TestTaskIdOrderSameAsDeclarationOrder.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<TaskState> sortTasksById(JobState jobState) {
    TreeMap<TaskId, TaskState> sortedTasks = new TreeMap<>(new Comparator<TaskId>() {
        @Override
        public int compare(TaskId o1, TaskId o2) {
            return Integer.parseInt(o1.value()) - Integer.parseInt(o2.value());
        }
    });
    sortedTasks.putAll(jobState.getHMTasks());
    return new ArrayList<>(sortedTasks.values());
}
 
Example 11
Source File: Suggester.java    From Ngram-Graphs with Apache License 2.0 5 votes vote down vote up
/** Create a DecisionSupport object for a set of membership estimations, an originally suggested category and a final
 * category.
 *@param hCategoryEstimations The membership estimations for a set of categories.
 *@param sSuggestedCategory The originally suggested category.
 *@param sCorrectCategory The final category.
 */
public DecisionSupport(Map hCategoryEstimations, String sSuggestedCategory, String sCorrectCategory) {
    CategoryEstimations = new TreeMap();
    
    CategoryEstimations.putAll(hCategoryEstimations);
    SuggestedCategory = new String(sSuggestedCategory);
    CorrectCategory = new String(sCorrectCategory);
}
 
Example 12
Source File: Blur022SegmentInfoWriter.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Directory dir, SegmentInfo si, FieldInfos fis, IOContext ioContext) throws IOException {
  final String fileName = IndexFileNames.segmentFileName(si.name, "", Blur022SegmentInfoFormat.SI_EXTENSION);
  si.addFile(fileName);

  final IndexOutput output = dir.createOutput(fileName, ioContext);

  boolean success = false;
  try {
    CodecUtil.writeHeader(output, Blur022SegmentInfoFormat.CODEC_NAME, Blur022SegmentInfoFormat.VERSION_CURRENT);
    output.writeString(si.getVersion());
    output.writeInt(si.getDocCount());

    output.writeByte((byte) (si.getUseCompoundFile() ? SegmentInfo.YES : SegmentInfo.NO));
    output.writeStringStringMap(si.getDiagnostics());
    Map<String, String> attributes = si.attributes();
    TreeMap<String, String> newAttributes = new TreeMap<String, String>();
    if (attributes != null) {
      newAttributes.putAll(attributes);
    }
    newAttributes.put(Blur022StoredFieldsFormat.STORED_FIELDS_FORMAT_CHUNK_SIZE,
        Integer.toString(_compressionChunkSize));
    newAttributes.put(Blur022StoredFieldsFormat.STORED_FIELDS_FORMAT_COMPRESSION_MODE, _compressionMode);
    output.writeStringStringMap(newAttributes);
    output.writeStringSet(si.files());

    success = true;
  } finally {
    if (!success) {
      IOUtils.closeWhileHandlingException(output);
      si.dir.deleteFile(fileName);
    } else {
      output.close();
    }
  }
}
 
Example 13
Source File: CachingOmemoStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public TreeMap<Integer, T_SigPreKey> loadOmemoSignedPreKeys(OmemoDevice userDevice) throws IOException {
    TreeMap<Integer, T_SigPreKey> sigPreKeys = getCache(userDevice).signedPreKeys;

    if (sigPreKeys.isEmpty() && persistent != null) {
        sigPreKeys.putAll(persistent.loadOmemoSignedPreKeys(userDevice));
    }

    return new TreeMap<>(sigPreKeys);
}
 
Example 14
Source File: BaseStep.java    From jenkins-client-plugin with Apache License 2.0 4 votes vote down vote up
protected Map<String, String> consolidateEnvVars(TaskListener listener,
        AbstractBuild<?, ?> build,
        Launcher launcher) {
    // EnvVars extends TreeMap
    TreeMap<String, String> overrides = new TreeMap<String, String>();
    // merge from all potential sources
    if (build != null) {
        try {
            EnvVars buildEnv = build.getEnvironment(listener);
            if (isVerbose())
                listener.getLogger()
                        .println("build env vars:  " + buildEnv);
            overrides.putAll(buildEnv);
        } catch (IOException | InterruptedException e) {
            if (isVerbose())
                e.printStackTrace(listener.getLogger());
        }
    }

    try {
        EnvVars computerEnv = null;
        Computer computer = Computer.currentComputer();
        if (computer != null) {
            computerEnv = computer.getEnvironment();
        } else {
            if (launcher != null)
                computer = launcher.getComputer();
            if (computer != null) {
                computerEnv = computer.getEnvironment();
            }
        }
        if (isVerbose())
            listener.getLogger().println(
                    "computer env vars:  " + computerEnv);
        if (computerEnv != null)
            overrides.putAll(computerEnv);
    } catch (IOException | InterruptedException e2) {
        if (isVerbose())
            e2.printStackTrace(listener.getLogger());
    }

    return overrides;
}
 
Example 15
Source File: Graph.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String toString() {
	StringBuilder sb = new StringBuilder();
	sb.append("Graph");
	sb.append(" attr {");
	boolean separator = false;

	TreeMap<String, Object> sortedAttrs = new TreeMap<>();
	sortedAttrs.putAll(attributesProperty);
	for (Object attrKey : sortedAttrs.keySet()) {
		if (separator) {
			sb.append(", ");
		} else {
			separator = true;
		}
		sb.append(attrKey.toString() + " : " + attributesProperty.get(attrKey));
	}
	sb.append("}");
	sb.append(".nodes {");
	separator = false;
	for (Node n : getNodes()) {
		if (separator) {
			sb.append(", ");
		} else {
			separator = true;
		}
		sb.append(n.toString());
	}
	sb.append("}");
	sb.append(".edges {");
	separator = false;
	for (Edge e : getEdges()) {
		if (separator) {
			sb.append(", ");
		} else {
			separator = true;
		}
		sb.append(e.toString());
	}
	sb.append("}");
	return sb.toString();
}
 
Example 16
Source File: ComparingPropertySorter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public Map sort(final Class type, final Map nameMap) {
    TreeMap map = new TreeMap(comparator);
    map.putAll(nameMap);
    return map;
}
 
Example 17
Source File: InternalValidator.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public float computeConnectivity(List<Cluster> clusterList, int numOfObjects) {
	clusters = new Cluster[clusterList.size()];
	clusters = clusterList.toArray(clusters);
	this.numberOfClusters = clusterList.size();

	float ret = 0, val = 0;
	int order = 0, count = 0;
	Set<String> tmp = null;
	Artifact medoid;
	Map<String, Float> similarity = new HashMap<String, Float>();
	for (int clusterID = 0; clusterID < this.numberOfClusters; clusterID++) {
		tmp = new HashSet<String>();
		medoid = clusters[clusterID].getMostRepresentative();
		tmp.add(medoid.getId());
		for (Artifact art : clusters[clusterID].getArtifacts()) {

			tmp.add(art.getId());
		}
		for (String object : tmp) {
			order = 0;
			count = 0;
			// TODO Changed
			similarity = readDistanceScores(object);
			ValueComparator bvc = new ValueComparator(similarity);
			TreeMap<String, Float> sorted_map = new TreeMap<String, Float>(bvc);
			sorted_map.putAll(similarity);
			Set<String> keySet = sorted_map.keySet();

			for (String key : keySet) {
				if (count < 10)
					if (!key.equals(object)) {
						if (tmp.contains(key))
							val = 0;
						else
							val = (float) 1 / order;
						ret += val;
						count++;
					}
				order += 1;
			}
		}
	}
	return ret;
}
 
Example 18
Source File: MultiSimilarity.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Set<OWLObject> sortMapByScore(Map<OWLObject,Similarity> map) {
	ValueComparator bvc =  new ValueComparator(map);
	TreeMap<OWLObject,Similarity> sorted_map = new TreeMap(bvc);
	sorted_map.putAll(map);
	return sorted_map.keySet();
}
 
Example 19
Source File: RealizationChooser.java    From kylin with Apache License 2.0 4 votes vote down vote up
private static Map<DataModelDesc, Set<IRealization>> makeOrderedModelMap(OLAPContext context) {
    OLAPContext first = context;
    KylinConfig kylinConfig = first.olapSchema.getConfig();
    String projectName = first.olapSchema.getProjectName();
    String factTableName = first.firstTableScan.getOlapTable().getTableName();
    Set<IRealization> realizations = ProjectManager.getInstance(kylinConfig).getRealizationsByTable(projectName,
            factTableName);

    final Map<DataModelDesc, Set<IRealization>> models = Maps.newHashMap();
    final Map<DataModelDesc, RealizationCost> costs = Maps.newHashMap();

    for (IRealization real : realizations) {
        if (real.isReady() == false) {
            context.realizationCheck.addIncapableCube(real,
                    RealizationCheck.IncapableReason.create(RealizationCheck.IncapableType.CUBE_NOT_READY));
            continue;
        }
        if (containsAll(real.getAllColumnDescs(), first.allColumns) == false) {
            context.realizationCheck.addIncapableCube(real, RealizationCheck.IncapableReason
                    .notContainAllColumn(notContain(real.getAllColumnDescs(), first.allColumns)));
            continue;
        }
        if (RemoveBlackoutRealizationsRule.accept(real) == false) {
            context.realizationCheck.addIncapableCube(real, RealizationCheck.IncapableReason
                    .create(RealizationCheck.IncapableType.CUBE_BLACK_OUT_REALIZATION));
            continue;
        }

        RealizationCost cost = new RealizationCost(real);
        DataModelDesc m = real.getModel();
        Set<IRealization> set = models.get(m);
        if (set == null) {
            set = Sets.newHashSet();
            set.add(real);
            models.put(m, set);
            costs.put(m, cost);
        } else {
            set.add(real);
            RealizationCost curCost = costs.get(m);
            if (cost.compareTo(curCost) < 0)
                costs.put(m, cost);
        }
    }

    // order model by cheapest realization cost
    TreeMap<DataModelDesc, Set<IRealization>> result = Maps.newTreeMap(new Comparator<DataModelDesc>() {
        @Override
        public int compare(DataModelDesc o1, DataModelDesc o2) {
            RealizationCost c1 = costs.get(o1);
            RealizationCost c2 = costs.get(o2);
            int comp = c1.compareTo(c2);
            if (comp == 0)
                comp = o1.getName().compareTo(o2.getName());
            return comp;
        }
    });
    result.putAll(models);

    return result;
}
 
Example 20
Source File: Props.java    From liteflow with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a map of all the flattened properties, the item in the returned map is sorted
 * alphabetically by the key value.
 *
 * @Return
 */
public Map<String, String> getFlattened() {
  final TreeMap<String, String> returnVal = new TreeMap<>();
  returnVal.putAll(getMapByPrefix(""));
  return returnVal;
}