Java Code Examples for java.util.HashMap#put()

The following examples show how to use java.util.HashMap#put() . 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: TravelDocumentServiceImpl.java    From kfs with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 *
 * @see org.kuali.kfs.module.tem.document.service.TravelDocumentService#getTravelDocumentNumbersByTrip(java.lang.String)
 */
@Override
public Collection<String> getApprovedTravelDocumentNumbersByTrip(String travelDocumentIdentifier) {
    HashMap<String,String> documentNumbersToReturn = new HashMap<String,String>();

    List<TravelDocument> travelDocuments = new ArrayList<TravelDocument>();

    TravelDocument travelDocument = getParentTravelDocument(travelDocumentIdentifier);
    if (ObjectUtils.isNotNull(travelDocument)) {
        travelDocuments.add(travelDocument);
    }

    travelDocuments.addAll(getTravelDocumentDao().findDocuments(TravelReimbursementDocument.class, travelDocumentIdentifier));
    travelDocuments.addAll(getTravelDocumentDao().findDocuments(TravelEntertainmentDocument.class, travelDocumentIdentifier));
    travelDocuments.addAll(getTravelDocumentDao().findDocuments(TravelRelocationDocument.class, travelDocumentIdentifier));

    for(Iterator<TravelDocument> iter = travelDocuments.iterator(); iter.hasNext();) {
        TravelDocument document = iter.next();
        if (!documentNumbersToReturn.containsKey(document.getDocumentNumber()) && isDocumentStatusValidForReconcilingCharges(document)) {
            documentNumbersToReturn.put(document.getDocumentNumber(),document.getDocumentNumber());
        }
    }

    return documentNumbersToReturn.values();
}
 
Example 2
Source File: LibvirtComputingResource.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private HashMap<String, Pair<Long, Long>> syncNetworkGroups(final long id) {
    final HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();

    final String result = getRuleLogsForVms();
    s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result);
    final String[] rulelogs = result != null ? result.split(";") : new String[0];
    for (final String rulesforvm : rulelogs) {
        final String[] log = rulesforvm.split(",");
        if (log.length != 6) {
            continue;
        }
        try {
            states.put(log[0], new Pair<Long, Long>(Long.parseLong(log[1]), Long.parseLong(log[5])));
        } catch (final NumberFormatException nfe) {
            states.put(log[0], new Pair<Long, Long>(-1L, -1L));
        }
    }
    return states;
}
 
Example 3
Source File: Lavalink.java    From Lavalink-Client with MIT License 6 votes vote down vote up
/**
 *
 * @param name
 *         A name to identify this node. May show up in metrics and other places.
 * @param serverUri
 *         uri of the node to be added
 * @param password
 *         password of the node to be added
 * @throws IllegalStateException if no userId has been set.
 * @throws IllegalArgumentException if a node with that name already exists.
 * @see #setUserId(String)
 */
@SuppressWarnings("WeakerAccess")
public void addNode(@NonNull String name, @NonNull URI serverUri, @NonNull String password) {
    if (userId == null) {
        throw new IllegalStateException("We need a userId to connect to Lavalink");
    }

    if (nodes.stream().anyMatch(sock -> sock.getName().equals(name))) {
        throw new IllegalArgumentException("A node with the name " + name + " already exists.");
    }

    HashMap<String, String> headers = new HashMap<>();
    headers.put("Authorization", password);
    headers.put("Num-Shards", Integer.toString(numShards));
    headers.put("User-Id", userId);

    LavalinkSocket socket = new LavalinkSocket(name, this, serverUri, new Draft_6455(), headers);
    socket.connect();
    nodes.add(socket);
}
 
Example 4
Source File: ConsumerSchemaMeta.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public HashMap<ConsumerSchemaMeta, ProducerSink> build() throws SQLException {
  HashMap<ConsumerSchemaMeta, ProducerSink> res = new HashMap<>();
  HashMap<Consumer, List<SchemaMeta>> def2data = build(consumerSink.keySet());
  for (Entry<Consumer, ProducerSink> entry : consumerSink.entrySet()) {
    Consumer consumer = entry.getKey();
    List<SchemaMeta> metas = def2data.get(consumer);
    if (metas == null ||
        consumer.getRepos().size() != metas.size()) {
      logger.error("Fail to fetch meta info for {}", diff(consumer.getRepos(), metas));
      throw new InvalidConfigException("Fail to fetch meta info");
    }
    ConsumerSchemaMeta consumerSchemaMeta = new ConsumerSchemaMeta(consumer.getId());
    consumerSchemaMeta.schemaMetas.addAll(metas);
    res.put(consumerSchemaMeta, entry.getValue());
  }
  return res;
}
 
Example 5
Source File: TtsService.java    From android-app with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Thread-safety note: executed in a background thread: {@link TtsService#executor}.
 */
private void ttsSpeak(CharSequence text, int queueMode, String utteranceId) {
    if (state != State.PLAYING || !isTtsInitialized) {
        Log.w(TAG, "ttsSpeak() state=" + state + ", isTtsInitialized=" + isTtsInitialized);
        return;
    }

    if (text != null) {
        // TODO: check tts.getMaxSpeechInputLength()?

        Log.v(TAG, "ttsSpeak() speaking " + utteranceId + ": " + text);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tts.speak(text, queueMode, null, utteranceId);
        } else {
            HashMap<String, String> params = new HashMap<>(2);
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
            //noinspection deprecation
            tts.speak(text.toString(), queueMode, params);
        }

        Log.v(TAG, "ttsSpeak() call returned");
    }
}
 
Example 6
Source File: TestAccumulator.java    From spork with Apache License 2.0 6 votes vote down vote up
@Test
public void testAccumWithNegative() throws IOException{
    pigServer.registerQuery("A = load '" + INPUT_FILE1 + "' as (id:int, fruit);");
    pigServer.registerQuery("B = group A by id;");
    pigServer.registerQuery("C = foreach B generate group,  -org.apache.pig.test.utils.AccumulatorBagCount(A);");

    HashMap<Integer, Integer> expected = new HashMap<Integer, Integer>();
    expected.put(100, -2);
    expected.put(200, -1);
    expected.put(300, -3);
    expected.put(400, -1);


    Iterator<Tuple> iter = pigServer.openIterator("C");

    while(iter.hasNext()) {
        Tuple t = iter.next();
        assertEquals(expected.get((Integer)t.get(0)), (Integer)t.get(1));
    }
}
 
Example 7
Source File: Solution.java    From codekata with MIT License 6 votes vote down vote up
private StringBuilder getDecimal(long a, long b) {
    int index = 0;
    HashMap<Long, Integer> location = new HashMap<>();
    StringBuilder tmp = new StringBuilder();
    while (true) {
        if (a == 0) break;
        if (location.containsKey(a)) {
            tmp.insert(location.get(a), "(").append(")");
            break;
        } else {
            location.put(a, index++);
            tmp.append(a * 10 / b);
            a = a * 10 % b;
        }
    }
    return tmp;
}
 
Example 8
Source File: RollupServiceTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void getOldestWithSingleStampReturnsSame() {

    // given
    HashMap<Integer, UpdateStamp> stamps = new HashMap<Integer, UpdateStamp>();
    long time = 1234L;
    UpdateStamp stamp = new UpdateStamp(time, UpdateStamp.State.Active, false);
    stamps.put(0, stamp);
    when(context.getSlotStamps(Matchers.<Granularity>any(), anyInt()))
            .thenReturn(stamps)
            .thenReturn(null);

    SlotState slotState = new SlotState(Granularity.MIN_5, 0, stamp.getState())
            .withTimestamp(time);
    String expected = slotState.toString();

    // when
    Collection<String> result = service.getOldestUnrolledSlotPerGranularity(0);

    // then
    assertNotNull(result);
    assertEquals(1, result.size());
    assertTrue(result.contains(expected));
}
 
Example 9
Source File: JtableUtils.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
/**
 * returns the list of duplicated rows customized for test set Table
 *
 * @param table
 * @return the list
 *
 */
public static ArrayList<Integer> getDuplicateRows(JTable table) {
    removeEmptyRows(table);
    cancelEditing(table);
    ArrayList<Integer> dRows = new ArrayList<>();
    HashMap<String, Integer> uniqRows = new HashMap<>();
    List<Integer> dontCheckIndex = Arrays.asList(new Integer[]{0, 4});//left the first column [ececute] and 5 column status
    int colCount = table.getColumnCount(),
            rowCount = table.getModel().getRowCount(), i;
    for (i = 0; i < rowCount; i++) {
        String row = "";
        for (int j = 0; j < colCount; j++) {
            if (dontCheckIndex.contains(j)) {
                continue;
            }
            Object val = table.getValueAt(i, j);
            row += ((val == null) ? "" : val.toString());
        }
        if (uniqRows.containsKey(row)) {
            String exe = table.getValueAt(i, dontCheckIndex.get(0)).toString();
            String status = table.getValueAt(i, dontCheckIndex.get(1)).toString();
            if ("false".equals(exe)) {
                dRows.add(i);
            } else if ("norun".equalsIgnoreCase(status)) {
                dRows.add(i);
            } else {
                dRows.add(uniqRows.get(row));
                uniqRows.put(row, i);
            }
        } else {
            uniqRows.put(row, i);
        }
    }

    return dRows;
}
 
Example 10
Source File: PrivateMessagesTool.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private LRS_Statement getStatementForUserReadPvtMsg(String subject) {
	LRS_Actor student = learningResourceStoreService.getActor(sessionManager.getCurrentSessionUserId());

    String url = ServerConfigurationService.getPortalUrl();
    LRS_Verb verb = new LRS_Verb(SAKAI_VERB.interacted);
    LRS_Object lrsObject = new LRS_Object(url + "/privateMessage", "read-private-message");
    HashMap<String, String> nameMap = new HashMap<>();
    nameMap.put("en-US", "User read a private message");
    lrsObject.setActivityName(nameMap);
    HashMap<String, String> descMap = new HashMap<>();
    descMap.put("en-US", "User read a private message with subject: " + subject);
    lrsObject.setDescription(descMap);
    return new LRS_Statement(student, verb, lrsObject);
}
 
Example 11
Source File: AddSubjectBrokerGroupCommand.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final HashMap<String, String> params = new HashMap<>();
    params.put("action", "AddSubjectBrokerGroup");
    params.put("brokerGroup", brokerGroup);
    params.put("subject", subject);

    System.out.println(service.post(metaserver, apiToken, params));
}
 
Example 12
Source File: LeetCode160.java    From Project with Apache License 2.0 5 votes vote down vote up
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    HashMap<ListNode, Integer> map = new HashMap<>();
    while (headA != null) {
        map.put(headA, headA.val);
        headA = headA.next;
    }

    while (headB != null) {
        if (map.containsKey(headB)) {
            return headB;
        }
        headB = headB.next;
    }
    return null;
}
 
Example 13
Source File: DataExpression.java    From systemds with Apache License 2.0 5 votes vote down vote up
@Override
public Expression rewriteExpression(String prefix) {
	HashMap<String,Expression> newVarParams = new HashMap<>();
	for( Entry<String, Expression> e : _varParams.entrySet() ){
		String key = e.getKey();
		Expression newExpr = e.getValue().rewriteExpression(prefix);
		newVarParams.put(key, newExpr);
	}
	DataExpression retVal = new DataExpression(_opcode, newVarParams, this);
	retVal._strInit = this._strInit;
	
	return retVal;
}
 
Example 14
Source File: MouseModifiersUnitTest_Extra.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static HashMap<String, String> tokenizeParamString(String param){
        HashMap <String, String> params = new HashMap<>();
        StringTokenizer st = new StringTokenizer(param, ",=");
        while (st.hasMoreTokens()){
            String tmp = st.nextToken();
//            System.out.println("PARSER : "+tmp);
            if (tmp.equals("button") ||
                    tmp.equals("modifiers") ||
                    tmp.equals("extModifiers")) {
                params.put(tmp, st.nextToken());
            }
        }
        return params;
    }
 
Example 15
Source File: FailReport.java    From tinkerpatch-sdk with MIT License 4 votes vote down vote up
@Override
protected HashMap<String, String> toEncodeObject() {
    HashMap<String, String> map = super.toEncodeObject();
    map.put("code", String.valueOf(errCode));
    return map;
}
 
Example 16
Source File: ServiceConditionImpl.java    From AthenaServing with Apache License 2.0 4 votes vote down vote up
@Override
public List<com.iflytek.ccr.polaris.cynosure.domain.Service> findList(List<String> clusterIds) {
    HashMap<String, Object> map = new HashMap<>();
    map.put("clusterIds", clusterIds);
    return this.serviceMapper.findServiceList(map);
}
 
Example 17
Source File: PHPFormatterBlankLinesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testBLFields06() throws Exception {
    HashMap<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults());
    options.put(FmtOptions.INITIAL_INDENT, 0);
    reformatFileContents("testfiles/formatting/blankLines/Fields06.php", options);
}
 
Example 18
Source File: EventSplitterDocRelation.java    From StoryForest with GNU General Public License v3.0 4 votes vote down vote up
public HashMap<String, Double> docPairFeatureChinese(Document d1, Document d2, HashMap<String, Double> DF, int docAmount) {
    HashMap<String, Double> feature = new HashMap<>();

    double fContentKeywordsTFIDFSim = FeatureExtractor.cosineSimilarityByTFIDF(d1, d2, DF, docAmount);
    feature.put("ContentKeywordsTFIDFSim", fContentKeywordsTFIDFSim);

    double fContentKeywordsTFSim = FeatureExtractor.cosineSimilarityByTF(d1, d2);
    feature.put("ContentKeywordsTFSim", fContentKeywordsTFSim);

    double fContentTFSim = FeatureExtractor.cosineSimilarityByTF(d1.segContent, d2.segContent, parameters.stopwords);
    feature.put("ContentTFSim", fContentTFSim);

    double fFirst1SentenceTFSim = FeatureExtractor.firstNSentencesCosineSimilarityByTF(d1, d2, 1, parameters.stopwords, parameters.language);
    feature.put("First1SentenceTFSim", fFirst1SentenceTFSim);

    double fFirst2SentenceTFSim = FeatureExtractor.firstNSentencesCosineSimilarityByTF(d1, d2, 2, parameters.stopwords, parameters.language);
    feature.put("First2SentenceTFSim", fFirst2SentenceTFSim);

    double fFirst3SentenceTFSim = FeatureExtractor.firstNSentencesCosineSimilarityByTF(d1, d2, 3, parameters.stopwords, parameters.language);
    feature.put("First3SentenceTFSim", fFirst3SentenceTFSim);

    double fTitleTFSim = FeatureExtractor.cosineSimilarityByTF(d1.segTitle, d2.segTitle, parameters.stopwords);
    feature.put("TitleTFSim", fTitleTFSim);

    double fTitleCommonNum = FeatureExtractor.numCommonTitleKeyword(d1, d2);
    feature.put("TitleCommonNum", fTitleCommonNum);

    double fTitleCommonPercent = FeatureExtractor.percentCommonTitleKeyword(d1, d2);
    feature.put("TitleCommonPercent", fTitleCommonPercent);

    double fTitleLevenshteinDistance = StringUtils.calcLevenshteinDistance(d1.title, d2.title);
    feature.put("TitleLevenshteinDistance", fTitleLevenshteinDistance);

    double fTitleNormalizedLevenshteinDistance = StringUtils.calcNormalizedLevenshteinDistance(d1.title, d2.title);
    feature.put("TitleNormalizedLevenshteinDistance", fTitleNormalizedLevenshteinDistance);

    double fTitleDamerauLevenshteinDistance = StringUtils.calcDamerauLevenshteinDistance(d1.title, d2.title);
    feature.put("TitleDamerauLevenshteinDistance", fTitleDamerauLevenshteinDistance);

    double fTitleJaroWinklerSimilarity = StringUtils.calcJaroWinklerSimilarity(d1.title, d2.title);
    feature.put("TitleJaroWinklerSimilarity", fTitleJaroWinklerSimilarity);

    double fTitleLCSDistance = StringUtils.calcLCSDistance(d1.title, d2.title);
    feature.put("TitleLCSDistance", fTitleLCSDistance);

    double fTitleMetricLCSDistance = StringUtils.calcMetricLCSDistance(d1.title, d2.title);
    feature.put("TitleMetricLCSDistance", fTitleMetricLCSDistance);

    double fTitleNGramDistance = StringUtils.calcNGramDistance(d1.title, d2.title, 2);
    feature.put("TitleNGramDistance", fTitleNGramDistance);

    double fTitleQGramDistance = StringUtils.calcQGramDistance(d1.title, d2.title, 2);
    feature.put("TitleQGramDistance", fTitleQGramDistance);

    double fDocTopicType = Double.parseDouble(d1.topic);
    feature.put("DocTopicType", fDocTopicType);

    return feature;
}
 
Example 19
Source File: SetFileAttributesTest.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Throwable {
    h = new Helper();
    ts = new TestServer();
    ts.getServerExecutableSpecification().setCodeline(h.getServerVersion());
    ts.start();

    server = h.getServer(ts);
    server.setUserName(ts.getUser());
    server.connect();

    user = server.getUser(ts.getUser());

    client = h.createClient(server, "client1");
    server.setCurrentClient(client);

    testFile = new File(client.getRoot() + FILE_SEP + "foo.txt");
    List<IFileSpec> createdFileSpecs = h.createFile(testFile.getAbsolutePath(), "SetFileAttributeTest");
    IChangelist changelist = h.createChangelist(server, user, client);
    AddFilesOptions addFilesOptions = new AddFilesOptions();
    addFilesOptions.setUseWildcards(true);
    addFilesOptions.setChangelistId(changelist.getId());
    addFilesOptions.setFileType("text");
    client.addFiles(createdFileSpecs, addFilesOptions);

    // set the  propagated attribute
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("p_attrib_1", "p_aValue_1");
    SetFileAttributesOptions sfOpts = new SetFileAttributesOptions();
    sfOpts.setPropagateAttributes(true);
    server.setFileAttributes(createdFileSpecs, hm, sfOpts);

    changelist.refresh();
    changelist.submit(false);

    // we need an edit so we can see an attribute propagate
    pendingChange = h.createChangelist(server, user, client);
    h.editFile(testFile.getAbsolutePath(), "SetFileAttributesTest", pendingChange, client);
    pendingChange.submit(false);

    pendingChange = h.createChangelist(server, user, client);
}
 
Example 20
Source File: TestLambda.java    From bidder with Apache License 2.0 4 votes vote down vote up
public static void main(String []args) throws Exception {
	HashMap<Integer, Callable<String>> opcode_only = new HashMap<Integer, Callable<String>>();
	opcode_only.put(0, () -> { return "none"; });
	opcode_only.put(1, () -> { return "ONE!...."; });
	System.out.println(opcode_only.get(0).call());
}