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

The following are Jave code examples for showing how to use put() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ULCRS   File: Scheduler.java   View Source Code Vote up 6 votes
private static Node generateRootWithGhostTutor(List<Tutor> tutors, List<Course> courses, List<Shift> shifts) {
    HashMap<Rank, Set<Course>> ghostCoursePreferences = new HashMap<>();
    ghostCoursePreferences.put(Rank.PREFER, new HashSet<>(courses));

    HashMap<Rank, Set<Shift>> ghostShiftPreferences = new HashMap<>();
    ghostShiftPreferences.put(Rank.PREFER, new HashSet<>(shifts));

    HashMap<Rank, Integer> ghostShiftFrequencyPreferences = new HashMap<>();
    ghostShiftFrequencyPreferences.put(Rank.PREFER, Integer.MAX_VALUE);

    TutorPreferences ghostTutorPreference = new TutorPreferences(ghostCoursePreferences, ghostShiftPreferences, ghostShiftFrequencyPreferences);
    Tutor ghostTutor = new Tutor(-1, "Ghost", "Tutor", ghostTutorPreference, TutorStatus.ACTIVE);

    tutors.add(ghostTutor);
    return generateRoot(tutors, courses, shifts);
}
 
Example 2
Project: personium-core   File: ReadTest.java   View Source Code Vote up 6 votes
/**
 * Cellの取得で存在しないIDを指定した場合にjsonフォーマットでNotFoundが返却されること. $format → atom Accept → application/atom+xml
 */
@Test
public final void $formatがatomかつacceptがatomでCellの取得で存在しないIDを指定した場合にjsonフォーマットでNotFoundが返却されること() {
    this.settleCell();
    // $format atom
    // Acceptヘッダ application/atom+xml
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_ATOM_XML);
    this.setHeaders(headers);

    PersoniumResponse res = this.restGet(getUrl(this.cellId, QUERY_FORMAT_ATOM));

    // TODO $formatのxml対応が完了したら確認内容を修正する
    assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode());
    assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());
    this.checkErrorResponse(res.bodyAsJson(), "PR404-OD-0002");
}
 
Example 3
Project: edgex-java-connector   File: EdgexClient.java   View Source Code Vote up 6 votes
/**
 * Get response headers returned by last call
 *
 * @return response heades as Map
 */
public Map<String, String> getHeaders() {
	Map<String, List<String>> map = con.getHeaderFields();
	HashMap<String, String> res = new HashMap<String, String>(map.size());
	for (String key : map.keySet()) {
		List<String> list = map.get(key);
		StringBuilder tmp = new StringBuilder();
		int n = 0;
		if (list.size() == 1) {
			res.put(key, list.get(0));
			continue;
		}
		if (list.size() == 0) {
			res.put(key, "");
			continue;
		}
		for (String one : list) {
			if (n > 0)
				tmp.append(";");
			tmp.append(one);
			n++;
		}
		res.put(key, tmp.toString());
	}
	return res;
}
 
Example 4
Project: marathon-auth-plugin   File: ServletContextHandler.java   View Source Code Vote up 6 votes
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations()
{
    if (!_enabled)
        throw new UnsupportedOperationException();

    HashMap<String, FilterRegistration> registrations = new HashMap<String, FilterRegistration>();
    ServletHandler handler=ServletContextHandler.this.getServletHandler();
    FilterHolder[] holders=handler.getFilters();
    if (holders!=null)
    {
        for (FilterHolder holder : holders)
            registrations.put(holder.getName(),holder.getRegistration());
    }
    return registrations;
}
 
Example 5
Project: ProjectAres   File: KDMSession.java   View Source Code Vote up 6 votes
/**
 * Attempts to calculate the winner, returning either the winning {@link Entrant},
 * or <code>null</code>, if the winner can not yet be determined. Optionally records the winning match.
 *
 * @return The winning {@link Entrant}, or <code>null</code>, if the winner
 * can not yet be determined.
 */
public @Nullable Entrant calculateWinner() {
    HashMap<Entrant, Integer> wins = new HashMap<>();
    for (Map.Entry<String, Entrant> match : this.winnerStore.entrySet()) {
        Entrant winner = match.getValue();
        if (winner != null) {
            int winCount = Optional.fromNullable(wins.get(winner)).or(0) + 1;
            wins.put(winner, winCount);
            if (winCount > 1) {
                tourney.recordMatch(match.getKey());
                return winner;
            }
        }
    }

    if (this.getMatchesPlayed() > 2) tourney.recordMatch(this.winnerStore.keySet().iterator().next());
    return null;
}
 
Example 6
Project: server   File: RegistrationDataPropertySerializer.java   View Source Code Vote up 5 votes
@Override
public void doSerialize(RegistrationData registrationData, IAccount account) throws IOException {
	HashMap<String, Object> data = new HashMap<String, Object>();
	data.put("publicKey", Format.convert(registrationData.getPublicKey()));

	account.putProperty(new AccountProperty(PropertyType.REGISTRATION, data));
}
 
Example 7
Project: sunbird-lms-mw   File: CourseBatchManagementActorTest.java   View Source Code Vote up 5 votes
public void testC3getBatchDetails(){
     
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.GET_BATCH.getValue());
  HashMap<String, Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.BATCH_ID ,batchId );
  reqObj.getRequest().put(JsonKey.BATCH, innerMap);
  subject.tell(reqObj, probe.getRef());
  Response response = probe.expectMsgClass(duration("1000 second"),Response.class);
  String hashtagId = (String) ((Map<String,Object>)response.getResult().get(JsonKey.RESPONSE)).get(JsonKey.HASHTAGID);
  assertEquals(true,hashtagId.equalsIgnoreCase(hashTagId));
}
 
Example 8
Project: Viajes   File: HotelsPresenterTest.java   View Source Code Vote up 5 votes
private Hotel getNewHotel(int num){
    Hotel hotel = new Hotel();
    HashMap<String, String> mUploadedImages = new HashMap<>();
    mUploadedImages.put("image1","http://i.imgur.com/DvpvklR.png");
    mUploadedImages.put("image2","http://i.imgur.com/DvpvklR.png");
    mUploadedImages.put("image3","http://i.imgur.com/DvpvklR.png");
    mUploadedImages.put("image4","http://i.imgur.com/DvpvklR.png");
    switch (num){
        case 1:
            hotel.setName("Hotel Name");
            hotel.setUid("1234");
            hotel.setBreakfast(true);
            hotel.setBeach(false);
            hotel.setGym(true);
            hotel.setLat(27.257895700000002);
            hotel.setLon(33.8116067);
            hotel.setPets(true);
            hotel.setPhone("01066770250");
            hotel.setPool(false);
            hotel.setPrice(1300);
            hotel.setRate(4);
            hotel.setResturant(false);
            hotel.setSpa(true);
            hotel.setWebsite("www.website.com");
            hotel.setWifi(true);
            hotel.setImagesUrls(mUploadedImages);
    }


    return hotel;
}
 
Example 9
Project: karate   File: RestDocsHttpClient.java   View Source Code Vote up 5 votes
@Override
public HttpResponse invoke(HttpRequestBuilder request, ScriptContext context) {
    COUNTER.incrementAndGet();
    if (request.getMultiPartItems() != null) {
        for (MultiPartItem item : request.getMultiPartItems()) {
            if (item.getValue().isStream()) {
                String s = item.getValue().getAsString();
                if (item.getContentType() == null) {
                    item.setContentType(APPLICATION_OCTET_STREAM);
                }
                item.setValue(new ScriptValue(s));
            }
        }
    }
    HttpResponse response = super.invoke(request, context);
    ManualRestDocumentation restDocumentation = new ManualRestDocumentation();
    restDocumentation.beforeTest(this.getClass(), "invoke");
    KarateRestDocumentationConfigurer configurer = new KarateRestDocumentationConfigurer(restDocumentation);
    configurer.apply();        
    HashMap<String, Object> configuration = configurer.getConfiguration();
    RestDocumentationContext restDocumentationContext = configurer.getContext();
    configuration.put(RestDocumentationContext.class.getName(), restDocumentationContext);        
    getDelegate().handle(request, response, configuration);
    restDocumentation.afterTest();
    return response;

}
 
Example 10
Project: Hotspot-master-devp   File: AppApi.java   View Source Code Vote up 5 votes
/**通知机顶盒声音关*/
public static void notifyTvBoxVolOff(Context context, String url,String projectId, ApiRequestListener handler) {
    final HashMap<String, String> params = new HashMap<>();
    params.put("action", 1+"");
    params.put("projectId", projectId);
    final HashMap<String, String> bodyParams = new HashMap<>();
    if(!TextUtils.isEmpty(url)) {
        new AppServiceOk(context,formatProUrl(context,url+"/volume?",params),Action.POST_NOTIFY_VOL_OFF_JSON,handler,bodyParams).get();
    }
}
 
Example 11
Project: JavaQuarkBBS   File: QuarkChatProtocol.java   View Source Code Vote up 5 votes
/**
 * SysUserInfo
 * @param users
 * @return
 */
public static String buildSysUserInfo(Set<User> users){
    HashMap<String, Object> map = new HashMap<>();
    map.put("count",users.size());
    map.put("userinfo",users);
    return buildProto(SYS_USERSINFO_CODE,map);
}
 
Example 12
Project: QN-ACTR-Release   File: LDStrategyEditor.java   View Source Code Vote up 5 votes
/**
 * Uses reflection to return an HashMap of distributions suitable for LDStrategy.
 * (With mean value specifiable) Search's key is distribution name and value is the
 * Class of found distribution
 * @return found distributions
 */
protected static HashMap<String, Distribution> findDistributions() {
	Distribution[] all = Distribution.findAllWithMean();
	HashMap<String, Distribution> tmp = new HashMap<String, Distribution>();
	for (Distribution element : all) {
		tmp.put(element.getName(), element);
	}
	return tmp;
}
 
Example 13
Project: personium-core   File: ImplicitFlowTest.java   View Source Code Vote up 5 votes
/**
 * Cookie認証で自分セルローカルトークンを取得できること.
 */
@Test
public final void Cookie認証で自分セルローカルトークンを取得できること() {

    // パスワード認証で自分セルリフレッシュトークン取得
    String addbody = "&username=account2&password=password2";
    PersoniumResponse res = requesttoAuthz(addbody);
    assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, res.getStatusCode());
    // cookieの値と有効期限の確認
    String sessionId = checkSessionId(false, Setup.TEST_CELL1);

    // 認証前のアカウントの最終ログイン時刻を取得しておく
    Long lastAuthenticatedTime = AuthTestCommon.getAccountLastAuthenticated(Setup.TEST_CELL1, "account2");
    // Cookie認証
    String body = "response_type=token&client_id=" + UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)
            + "&redirect_uri=" + UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + REDIRECT_HTML
            + "&state=" + DEFAULT_STATE;
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("session-id", sessionId);
    res = requesttoAuthzWithBody(Setup.TEST_CELL1, body, headers);

    checkSessionId(true, Setup.TEST_CELL1);
    // アカウントの最終ログイン時刻が更新されていないことの確認
    AuthTestCommon.accountLastAuthenticatedNotUpdatedCheck(Setup.TEST_CELL1, "account2", lastAuthenticatedTime);

    // {redirect_uri}#access_token={access_token}&token_type=Bearer&expires_in={expires_in}&state={state}
    Map<String, String> response = parseResponse(res);
    try {
        AccountAccessToken aToken = AccountAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN),
                UrlUtils.cellRoot(Setup.TEST_CELL1));
        assertNotNull("access token parse error.", aToken);
        assertEquals(OAuth2Helper.Scheme.BEARER, response.get(OAuth2Helper.Key.TOKEN_TYPE));
        assertEquals("3600", response.get(OAuth2Helper.Key.EXPIRES_IN));
        assertEquals(DEFAULT_STATE, response.get(OAuth2Helper.Key.STATE));
    } catch (TokenParseException e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}
 
Example 14
Project: Treebolic   File: MainActivity.java   View Source Code Vote up 5 votes
/**
 * Dummy provider for rescan action
 *
 * @return dummy provider
 */
@NonNull
private HashMap<String, Object> makeRescanDummy()
{
	final HashMap<String, Object> result = new HashMap<>();
	final String name = getString(R.string.title_rescan);
	result.put(Providers.NAME, name);
	result.put(Providers.ICON, R.drawable.ic_refresh);
	result.put(Providers.PACKAGE, null);
	result.put(RESCAN_KEY, true);
	return result;
}
 
Example 15
Project: fastAOP   File: ASMContentHandler.java   View Source Code Vote up 5 votes
@Override
public final void begin(final String name, final Attributes attrs) {
    labels = new HashMap<Object, Label>();
    HashMap<String, Object> vals = new HashMap<String, Object>();
    vals.put("access", attrs.getValue("access"));
    vals.put("name", attrs.getValue("name"));
    vals.put("desc", attrs.getValue("desc"));
    vals.put("signature", attrs.getValue("signature"));
    vals.put("exceptions", new ArrayList<String>());
    push(vals);
    // values will be extracted in ExceptionsRule.end();
}
 
Example 16
Project: Cluster   File: MoveCentroidStepTest.java   View Source Code Vote up 5 votes
/**
 * Test of moveCentroids method, of class MoveCentroidStep.
 */
@Test
public void testMoveCentroids() {
    Coordinate dp1 = new Coordinate(2,2);
    Coordinate dp2 = new Coordinate(0,0);
    Coordinate dp3 = new Coordinate(0,2);
    Coordinate dp4 = new Coordinate(2,0);
    
    Coordinate dp5 = new Coordinate(4,4);
    Coordinate dp6 = new Coordinate(4,6);
    Coordinate dp7 = new Coordinate(6,4);
    Coordinate dp8 = new Coordinate(6,6);
    
    HashMap<Integer, ArrayList<Coordinate>> data_to_centroid = new HashMap();
    ArrayList<Coordinate> data_for_centroid_one = new ArrayList();
    data_for_centroid_one.add(dp1);
    data_for_centroid_one.add(dp2);
    data_for_centroid_one.add(dp3);
    data_for_centroid_one.add(dp4);
    data_to_centroid.put(0, data_for_centroid_one);
    
    ArrayList<Coordinate> data_for_centroid_two = new ArrayList();
    data_for_centroid_two.add(dp5);
    data_for_centroid_two.add(dp6);
    data_for_centroid_two.add(dp7);
    data_for_centroid_two.add(dp8);
    data_to_centroid.put(1, data_for_centroid_two);
    
    
    Coordinate new_centroid_1 = new Coordinate(1,1);
    Coordinate new_centroid_2 = new Coordinate(5,5);
    
    HashMap<Integer, Coordinate> result = MoveCentroidStep.moveCentroids(data_to_centroid);
    assertEquals(2, result.size());
    assertEquals(new_centroid_1, result.get(0));
    assertEquals(new_centroid_2, result.get(1));
}
 
Example 17
Project: Nearby   File: SearchMedicineActivity.java   View Source Code Vote up 5 votes
private void getMedicineList(){
    if(!isLoadFinish) {
        loading.show();
        HashMap<String, String> map = new HashMap<>();
        map.put("service", "getMedicineList");
        map.put("page", Integer.toString(page));

        if (searchName != null && (!"".equals(searchName))) {
            map.put("name", searchName);
        }
        new ParsePHP(Information.MAIN_SERVER_ADDRESS, map) {

            @Override
            protected void afterThreadFinish(String data) {

                if (page <= 0) {
                    list.clear();

                    list = Medicine.getMedicineList(data);

                    handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MAKE_LIST));
                } else {

                    tempList.clear();
                    tempList = Medicine.getMedicineList(data);
                    if (tempList.size() < 30) {
                        isLoadFinish = true;
                    }
                    handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MAKE_ENDLESS_LIST));

                }

            }
        }.start();
    }else{
        if(adapter != null){
            adapter.setLoaded();
        }
    }
}
 
Example 18
Project: Android-BLE-to-Arduino   File: DeviceControlActivity.java   View Source Code Vote up 4 votes
private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null)
        return;
    String uuid = null;
    String unknownServiceString = getResources().getString(
            R.string.unknown_service);
    String unknownCharaString = getResources().getString(
            R.string.unknown_characteristic);
    ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
    ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
        HashMap<String, String> currentServiceData = new HashMap<String, String>();
        uuid = gattService.getUuid().toString();
        currentServiceData.put(LIST_NAME,
                SampleGattAttributes.lookup(uuid, unknownServiceString));
        currentServiceData.put(LIST_UUID, uuid);
        gattServiceData.add(currentServiceData);

        ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                .getCharacteristics();
        ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

        // Loops through available Characteristics.
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            charas.add(gattCharacteristic);
            HashMap<String, String> currentCharaData = new HashMap<String, String>();
            uuid = gattCharacteristic.getUuid().toString();
            currentCharaData.put(LIST_NAME,
                    SampleGattAttributes.lookup(uuid, unknownCharaString));
            currentCharaData.put(LIST_UUID, uuid);
            gattCharacteristicGroupData.add(currentCharaData);
        }
        mGattCharacteristics.add(charas);
        gattCharacteristicData.add(gattCharacteristicGroupData);

    }

    SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
            this, gattServiceData,
            android.R.layout.simple_expandable_list_item_2, new String[]{
            LIST_NAME, LIST_UUID}, new int[]{android.R.id.text1,
            android.R.id.text2}, gattCharacteristicData,
            android.R.layout.simple_expandable_list_item_2, new String[]{
            LIST_NAME, LIST_UUID}, new int[]{android.R.id.text1,
            android.R.id.text2});
    mGattServicesList.setAdapter(gattServiceAdapter);

}
 
Example 19
Project: personium-core   File: DeleteTest.java   View Source Code Vote up 4 votes
/**
 * CellにExtCellが存在する.
 */
@Test
public final void Cell削除のExtCellが存在する時のテスト() {

    String extCellUrl = UrlUtils.cellRoot(Setup.TEST_CELL1);

    try {
        // ExtCell作成
        ExtCellUtils.create(MASTER_TOKEN_NAME, this.cellInfo.cellName, extCellUrl,
                HttpStatus.SC_CREATED);

        // Cellを削除
        PersoniumRestAdapter rest = new PersoniumRestAdapter();
        PersoniumResponse res = null;
        // リクエストヘッダをセット
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
        requestheaders.put(HttpHeaders.IF_MATCH, "*");
        try {
            // リクエスト
            // 本来は、LOCATIONヘッダにURLが格納されているが、jerseyTestFrameworkに向け直すため、再構築する
            res = rest.del(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME, this.cellInfo.cellId), requestheaders);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        // レスポンスコードのチェック
        assertEquals(HttpStatus.SC_CONFLICT, res.getStatusCode());
        assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());

        // ExtCell削除
        ExtCellUtils.delete(MASTER_TOKEN_NAME, this.cellInfo.cellName, extCellUrl,
                HttpStatus.SC_NO_CONTENT);

        // Cellを削除(Role削除済のため、削除可能)
        CellUtils.delete(MASTER_TOKEN_NAME, this.cellInfo.cellId, HttpStatus.SC_NO_CONTENT);

    } finally {
        // Cell作成
        CellUtils.create(this.cellInfo.cellName, MASTER_TOKEN_NAME, -1);
        // ExtCell削除
        ExtCellUtils.delete(MASTER_TOKEN_NAME, this.cellInfo.cellName, extCellUrl, -1);
    }
}
 
Example 20
Project: monarch   File: PRClientServerRegionFunctionExecutionDUnitTest.java   View Source Code Vote up 4 votes
public static void serverSingleKeyExecution(Boolean isByName, Boolean toRegister)
    throws Exception {
  Region region = cache.getRegion(PartitionedRegionName);
  assertNotNull(region);
  final String testKey = "execKey";
  final Set testKeysSet = new HashSet();
  testKeysSet.add(testKey);
  DistributedSystem.setThreadsSocketPolicy(false);

  Function function = new TestFunction(true, TEST_FUNCTION2);

  if (toRegister.booleanValue()) {
    FunctionService.registerFunction(function);
  } else {
    FunctionService.unregisterFunction(function.getId());
    assertNull(FunctionService.getFunction(function.getId()));
  }
  Execution dataSet = FunctionService.onRegion(region);
  try {
    execute(dataSet, testKeysSet, Boolean.TRUE, function, isByName);
  } catch (Exception ex) {
    if (!(ex.getMessage().contains("No target node found for KEY = " + testKey)
        || ex.getMessage().startsWith("Server could not send the reply")
        || ex.getMessage().startsWith("Unexpected exception during"))) {
      throw ex;
    }
  }
  region.put(testKey, new Integer(1));

  ResultCollector rs = execute(dataSet, testKeysSet, Boolean.TRUE, function, isByName);
  assertEquals(Boolean.TRUE, ((List) rs.getResult()).get(0));

  ResultCollector rs2 = execute(dataSet, testKeysSet, testKey, function, isByName);
  assertEquals(new Integer(1), ((List) rs2.getResult()).get(0));

  HashMap putData = new HashMap();
  putData.put(testKey + "1", new Integer(2));
  putData.put(testKey + "2", new Integer(3));

  ResultCollector rs1 = execute(dataSet, testKeysSet, putData, function, isByName);
  assertEquals(Boolean.TRUE, ((List) rs1.getResult()).get(0));

  assertEquals(new Integer(2), region.get(testKey + "1"));
  assertEquals(new Integer(3), region.get(testKey + "2"));
}