Java Code Examples for java.util.HashMap

The following are top voted examples for showing how to use java.util.HashMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Divertio   File: AlbumMenuActivity.java   View source code 6 votes vote down vote up
private void findSongsByAlbum() {

        // Create key list
        keyList = new ArrayList<>();
        songAlbumList = new HashMap<>();

        // Go through songs
        List<SongData> songList = getSongInfoList();
        for (SongData songData: songList) {
            String album = songData.getSongAlbum();

            // Create new if album does not exist
            if (!keyList.contains(album)) {
                keyList.add(album);
                songAlbumList.put(album, new ArrayList<SongData>());
            }
            songAlbumList.get(album).add(songData);
        }
    }
 
Example 2
Project: iTAP-controller   File: StorageTest.java   View source code 6 votes vote down vote up
@Test
public void testAsyncUpdateRow2() {
    Map<String,Object> updateValues = new HashMap<String,Object>();
    updateValues.put(PERSON_FIRST_NAME, "Tennis");
    updateValues.put(PERSON_AGE, 60);

    Future<?> future = storageSource.updateRowAsync(PERSON_TABLE_NAME, "777-77-7777", updateValues);
    waitForFuture(future);

    try {
        IResultSet resultSet = storageSource.getRow(PERSON_TABLE_NAME, "777-77-7777");
        Object[][] expectedPersons = {{"777-77-7777", "Tennis", "Borg", 60, true}};
        checkExpectedResults(resultSet, PERSON_COLUMN_LIST, expectedPersons);
    }
    catch (Exception e) {
        fail("Exception thrown in async storage operation: " + e.toString());
    }
}
 
Example 3
Project: rental-calc   File: ItemizationActivityTest.java   View source code 6 votes vote down vote up
@Test
public void startWithoutTitle()
{
    Intent intent = new Intent();

    final Bundle bundle = new Bundle();
    bundle.putInt("description", R.string.app_name);
    bundle.putSerializable("items", new HashMap<String, Integer>());
    intent.putExtras(bundle);

    ActivityController controller = Robolectric.buildActivity(ItemizeActivity.class, intent).create();
    Activity activity = (Activity)controller.get();

    controller.start();
    assertTrue(activity.isFinishing());

    String latestToast = ShadowToast.getTextOfLatestToast();
    assertNotNull(latestToast);
}
 
Example 4
Project: smockin   File: GeneralUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void findPathVarIgnoreCaseTest() {

    // Setup
    final Request req = Mockito.mock(Request.class);
    Mockito.when(req.params()).thenReturn(new HashMap<String, String>() {
        {
            put(":name", "Bob");
            put(":Age", "21");
        }
    });

    // Test
    final String nameResult = GeneralUtils.findPathVarIgnoreCase(req, "NAME");

    // Assertions
    Assert.assertNotNull(nameResult);
    Assert.assertEquals("Bob", nameResult);

    // Test
    final String ageResult = GeneralUtils.findPathVarIgnoreCase(req, "age");

    // Assertions
    Assert.assertNotNull(ageResult);
    Assert.assertEquals("21", ageResult);
}
 
Example 5
Project: iTAP-controller   File: Controller.java   View source code 6 votes vote down vote up
/**
 * Initialize internal data structures
 */
public void init(Map<String, String> configParams) throws FloodlightModuleException {

    this.moduleLoaderState = ModuleLoaderState.INIT;

    // These data structures are initialized here because other
    // module's startUp() might be called before ours        
    this.messageListeners = new ConcurrentHashMap<OFType, ListenerDispatcher<OFType, IOFMessageListener>>();
    this.haListeners = new ListenerDispatcher<HAListenerTypeMarker, IHAListener>();
    this.controllerNodeIPsCache = new HashMap<String, String>();
    this.updates = new LinkedBlockingQueue<IUpdate>();
    this.providerMap = new HashMap<String, List<IInfoProvider>>();
   
    setConfigParams(configParams);

    HARole initialRole = getInitialRole(configParams);
    this.notifiedRole = initialRole;
    this.shutdownService = new ShutdownServiceImpl();

    this.roleManager = new RoleManager(this, this.shutdownService,
                                       this.notifiedRole,
                                       INITIAL_ROLE_CHANGE_DESCRIPTION);
    this.timer = new HashedWheelTimer();

    // Switch Service Startup
    this.switchService.registerLogicalOFMessageCategory(LogicalOFMessageCategory.MAIN);
    this.switchService.addOFSwitchListener(new NotificationSwitchListener());

    this.counters = new ControllerCounters(debugCounterService);
 }
 
Example 6
Project: kaltura-ce-sakai-extension   File: ViewProfilingController.java   View source code 6 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Map<String,Object> model = new HashMap<String,Object>();

    model.put("summary", ProfilerControl.generateSummary());
    model.put("profiles", ProfilerControl.getMethodProfiles());

    return new ModelAndView("viewProfiling", model);
}
 
Example 7
Project: jdk8u-jdk   File: HttpURLConnection.java   View source code 6 votes vote down vote up
/**
 * Returns an unmodifiable Map of general request
 * properties for this connection. The Map keys
 * are Strings that represent the request-header
 * field names. Each Map value is a unmodifiable List
 * of Strings that represents the corresponding
 * field values.
 *
 * @return  a Map of the general request properties for this connection.
 * @throws IllegalStateException if already connected
 * @since 1.4
 */
@Override
public synchronized Map<String, List<String>> getRequestProperties() {
    if (connected)
        throw new IllegalStateException("Already connected");

    // exclude headers containing security-sensitive info
    if (setUserCookies) {
        return requests.getHeaders(EXCLUDE_HEADERS);
    }
    /*
     * The cookies in the requests message headers may have
     * been modified. Use the saved user cookies instead.
     */
    Map<String, List<String>> userCookiesMap = null;
    if (userCookies != null || userCookies2 != null) {
        userCookiesMap = new HashMap<>();
        if (userCookies != null) {
            userCookiesMap.put("Cookie", Arrays.asList(userCookies));
        }
        if (userCookies2 != null) {
            userCookiesMap.put("Cookie2", Arrays.asList(userCookies2));
        }
    }
    return requests.filterAndAddHeaders(EXCLUDE_HEADERS2, userCookiesMap);
}
 
Example 8
Project: osc-core   File: VirtualizationConnectorServiceData.java   View source code 6 votes vote down vote up
private static void setOpenStackParams(VirtualizationConnectorDto vcDto,
        String projectName,
        String domainId,
        String rabbitMquser,
        String rabbitMqpassword,
        String rabbitMqport,
        String controllerTypeStr){

    vcDto.setAdminDomainId(domainId);
    vcDto.setAdminProjectName(projectName);

    Map<String, String> providerAttributes = new HashMap<>();
    providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_USER, rabbitMquser);
    providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_USER_PASSWORD, rabbitMqpassword);
    providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_PORT, rabbitMqport);
    vcDto.setProviderAttributes(providerAttributes);

    if (controllerTypeStr != null && (!controllerTypeStr.isEmpty())) {
        vcDto.setControllerType(controllerTypeStr);
    }
}
 
Example 9
Project: neoscada   File: ScaleHandlerImpl.java   View source code 6 votes vote down vote up
@Override
protected WriteAttributeResults handleUpdate ( final Map<String, Variant> attributes, final OperationParameters operationParameters ) throws Exception
{
    final Map<String, String> data = new HashMap<String, String> ();

    final Variant active = attributes.get ( "active" ); //$NON-NLS-1$
    final Variant factor = attributes.get ( "factor" ); //$NON-NLS-1$
    final Variant offset = attributes.get ( "offset" ); //$NON-NLS-1$

    if ( active != null && !active.isNull () )
    {
        data.put ( "active", active.asString () ); //$NON-NLS-1$
    }
    if ( factor != null && !factor.isNull () )
    {
        data.put ( "factor", factor.asString () ); //$NON-NLS-1$
    }
    if ( offset != null && !offset.isNull () )
    {
        data.put ( "offset", offset.asString () ); //$NON-NLS-1$
    }

    return updateConfiguration ( data, attributes, false, operationParameters );
}
 
Example 10
Project: godlibrary   File: JsonUtils.java   View source code 6 votes vote down vote up
public static HashMap<String, Object> jsonToHasMap(JSONObject jsonObject) throws JSONException {
    HashMap<String, Object> hs = new HashMap<String, Object>();
    JSONObject object = jsonObject;
    Iterator<?> iterator = object.keys();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        Object value = object.get(key);

        if (value instanceof JSONObject) {
            JSONObject jsonObject2 = new JSONObject(value.toString());
            hs.put(key, jsonToHasMap(jsonObject2));
        } else {
            if (value instanceof JSONArray) {
                JSONArray array = new JSONArray(value.toString());
                List<HashMap<?, ?>> list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    list.add(jsonToHasMap(array.getJSONObject(i)));
                }
                hs.put(key, list);
            } else {
                hs.put(key, value);
            }
        }
    }
    return hs;
}
 
Example 11
Project: git-rekt   File: BrowseRoomsScreenController.java   View source code 6 votes vote down vote up
@FXML
private void onNextButtonClicked() {
    // Prevent proceeding when no rooms are selected
    if(selectedRooms.size() <= 0) {
        return;
    }

    Object temp = ScreenManager.getInstance().switchToScreen("/fxml/PlaceBookingScreen.fxml");
    PlaceBookingScreenController controller = (PlaceBookingScreenController) temp;
    Map<RoomCategory, Integer> roomsData = new HashMap<>();
    LocalDate checkInDate = checkInDatePicker.getValue();
    LocalDate checkOutDate = checkOutDatePicker.getValue();
    selectedRooms.forEach((r) -> {
        roomsData.merge(r.getRoomCategory(), 1, Integer::sum);
    });
    controller.initializeData(roomsData, this.packageQtys, checkInDate, checkOutDate);
}
 
Example 12
Project: Hydrograph   File: SchemaPropagationHelper.java   View source code 6 votes vote down vote up
/**
  * pull out basicSchemaGridRow object from Schema object.
  * 
 * @param targetTerminal  
 * @param link
 * @return list of BasicSchemaGridRow
 */
public List<BasicSchemaGridRow> getBasicSchemaGridRowList(String targetTerminal, Link link) {
	 List<BasicSchemaGridRow> basicSchemaGridRows=null;
	if(StringUtils.equalsIgnoreCase(Constants.INPUT_SUBJOB_COMPONENT_NAME, link.getSource().getComponentName())
	   ||StringUtils.equalsIgnoreCase(Constants.SUBJOB_COMPONENT, link.getSource().getComponentName()))
	{
		Map<String,Schema> inputSchemaMap=(HashMap<String,Schema>)link.getSource().getProperties().
				get(Constants.SCHEMA_FOR_INPUTSUBJOBCOMPONENT);
		if(inputSchemaMap!=null &&inputSchemaMap.get(targetTerminal)!=null)
		basicSchemaGridRows=SchemaSyncUtility.INSTANCE.
				convertGridRowsSchemaToBasicSchemaGridRows(inputSchemaMap.get(targetTerminal).getGridRow());
	}
	else 
	{	
	Schema previousComponentSchema=SchemaPropagation.INSTANCE.getSchema(link);
	if (previousComponentSchema != null)
	basicSchemaGridRows=SchemaSyncUtility.INSTANCE.
	convertGridRowsSchemaToBasicSchemaGridRows(previousComponentSchema.getGridRow());
	}
	return basicSchemaGridRows;
}
 
Example 13
Project: googles-monorepo-demo   File: MapTestSuiteBuilderTests.java   View source code 6 votes vote down vote up
private static Test testsForHashMapNullKeysForbidden() {
  return wrappedHashMapTests(new WrappedHashMapGenerator() {
    @Override Map<String, String> wrap(final HashMap<String, String> map) {
      if (map.containsKey(null)) {
        throw new NullPointerException();
      }
      return new AbstractMap<String, String>() {
        @Override public Set<Map.Entry<String, String>> entrySet() {
          return map.entrySet();
        }
        @Override public String put(String key, String value) {
          checkNotNull(key);
          return map.put(key, value);
        }
      };
    }
  }, "HashMap w/out null keys", ALLOWS_NULL_VALUES);
}
 
Example 14
Project: YKCenterSDKExample_for_AS   File: AirControlActivity.java   View source code 6 votes vote down vote up
private AirEvent getAirEvent(HashMap<String, KeyCode> codeDatas) {
        AirEvent airEvent = null;
        if (!Utility.isEmpty(codeDatas)) {
            if (airVerSion == V3) {
                airEvent = new AirV3Command(codeDatas);
            } else {
                airEvent = new AirV1Command(codeDatas);
            }
        }
//        Map.Entry<String,KeyCode> entry;
//        for(Iterator iterator = codeDatas.entrySet().iterator();iterator.hasNext();){
//            entry = (Map.Entry<String, KeyCode>) iterator.next();
//            entry.getKey();
//            YourKeyCode yourKeyCode = new YourKeyCode();
//            yourKeyCode.setSrcCode(entry.getValue().getSrcCode());
//        }
        return airEvent;
    }
 
Example 15
Project: sunbird-lms-mw   File: UserManagementActorTest.java   View source code 6 votes vote down vote up
@Test
public void Z18TestJoinUserOrganisation3(){
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.JOIN_USER_ORGANISATION.getValue());
  Map<String, Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.USER_ID,userId);
  innerMap.put(JsonKey.ORGANISATION_ID,(orgId2+"456as"));
  reqObj.getRequest().put(JsonKey.REQUESTED_BY,userIdnew);
  Map<String, Object> request = new HashMap<String, Object>();
  request.put(JsonKey.USER_ORG, innerMap);
  reqObj.setRequest(request);
  subject.tell(reqObj, probe.getRef());
  probe.expectMsgClass(duration("200 second"), ProjectCommonException.class);
}
 
Example 16
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConsumerTest.java   View source code 6 votes vote down vote up
private AtomicBoolean prepareOffsetCommitResponse(MockClient client, Node coordinator, final Map<TopicPartition, Long> partitionOffsets) {
    final AtomicBoolean commitReceived = new AtomicBoolean(true);
    Map<TopicPartition, Errors> response = new HashMap<>();
    for (TopicPartition partition : partitionOffsets.keySet())
        response.put(partition, Errors.NONE);

    client.prepareResponseFrom(new MockClient.RequestMatcher() {
        @Override
        public boolean matches(AbstractRequest body) {
            OffsetCommitRequest commitRequest = (OffsetCommitRequest) body;
            for (Map.Entry<TopicPartition, Long> partitionOffset : partitionOffsets.entrySet()) {
                OffsetCommitRequest.PartitionData partitionData = commitRequest.offsetData().get(partitionOffset.getKey());
                // verify that the expected offset has been committed
                if (partitionData.offset != partitionOffset.getValue()) {
                    commitReceived.set(false);
                    return false;
                }
            }
            return true;
        }
    }, offsetCommitResponse(response), coordinator);
    return commitReceived;
}
 
Example 17
Project: JAVA-   File: ThirdPartyLoginHelper.java   View source code 6 votes vote down vote up
/**
 * 获取微信的认证token和用户OpenID
 * 
 * @param code
 * @param type
 * @return
 */
public static final Map<String, String> getWxTokenAndOpenid(String code, String host) throws Exception {
	Map<String, String> map = new HashMap<String, String>();
	// 获取令牌
	String tokenUrl = Resources.THIRDPARTY.getString("accessTokenURL_wx");
	tokenUrl = tokenUrl + "?appid=" + Resources.THIRDPARTY.getString("app_id_wx") + "&secret="
			+ Resources.THIRDPARTY.getString("app_key_wx") + "&code=" + code + "&grant_type=authorization_code";
	String tokenRes = HttpUtil.httpClientPost(tokenUrl);
	if (tokenRes != null && tokenRes.indexOf("access_token") > -1) {
		Map<String, String> tokenMap = toMap(tokenRes);
		map.put("access_token", tokenMap.get("access_token"));
		// 获取微信用户的唯一标识openid
		map.put("openId", tokenMap.get("openid"));
	} else {
		throw new IllegalArgumentException(Resources.getMessage("THIRDPARTY.LOGIN.NOTOKEN", "weixin"));
	}
	return map;
}
 
Example 18
Project: JRediClients   File: GeoCommandsTest.java   View source code 6 votes vote down vote up
private void prepareGeoData() {
  Map<String, GeoCoordinate> coordinateMap = new HashMap<String, GeoCoordinate>();
  coordinateMap.put("a", new GeoCoordinate(3, 4));
  coordinateMap.put("b", new GeoCoordinate(2, 3));
  coordinateMap.put("c", new GeoCoordinate(3.314, 2.3241));

  long size = jedis.geoadd("foo", coordinateMap);
  assertEquals(3, size);

  Map<byte[], GeoCoordinate> bcoordinateMap = new HashMap<byte[], GeoCoordinate>();
  bcoordinateMap.put(bA, new GeoCoordinate(3, 4));
  bcoordinateMap.put(bB, new GeoCoordinate(2, 3));
  bcoordinateMap.put(bC, new GeoCoordinate(3.314, 2.3241));

  size = jedis.geoadd(bfoo, bcoordinateMap);
  assertEquals(3, size);
}
 
Example 19
Project: crnk-framework   File: QueryBuilder.java   View source code 6 votes vote down vote up
public Map<String, Integer> applySelectionSpec() {
	MetaDataObject meta = query.getMeta();

	Map<String, Integer> selectionBindings = new HashMap<>();

	int index = 1;

	List<IncludeFieldSpec> includedFields = query.getIncludedFields();
	for (IncludeFieldSpec includedField : includedFields) {
		MetaAttributePath path = meta.resolvePath(includedField.getAttributePath(), attributeFinder);
		E attr = backend.getAttribute(path);

		backend.addSelection(attr, path.toString());
		selectionBindings.put(path.toString(), index++);
	}
	return selectionBindings;
}
 
Example 20
Project: alfresco-test-assertions   File: WorkflowAssertTest.java   View source code 6 votes vote down vote up
/**
 * Creates a workflow and attaches it to all of the node refs
 *
 * @param workflowParams - any extra parameters in a map
 * @param nodeRefs The node refs to attach the workflow to
 * @return the ID of the workflow that was created
 */
private WorkflowInstance createWorkflow(String workflowDefId, final NodeRef assignee, String description, final NodeRef... nodeRefs) {
    final NodeRef wfPackage = createWorkflowPackage(Arrays.asList(nodeRefs));

    final Map<QName, Serializable> parameters = new HashMap<>();
    parameters.put(WorkflowModel.ASSOC_ASSIGNEE, assignee);
    parameters.put(WorkflowModel.ASSOC_PACKAGE, wfPackage);
    parameters.put(WorkflowModel.PROP_CONTEXT, wfPackage);
    parameters.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, description);
    parameters.put(WorkflowModel.PROP_SEND_EMAIL_NOTIFICATIONS, false);

    final WorkflowPath wfPath = workflowService.startWorkflow(workflowDefId, parameters);
    final String workflowId = wfPath.getInstance().getId();
    final WorkflowTask startTask = workflowService.getStartTask(workflowId);
    workflowService.endTask(startTask.getId(), null);
    return wfPath.getInstance();
}
 
Example 21
Project: TOSCA-Studio   File: Main.java   View source code 6 votes vote down vote up
private Map<String, ?> concatCustomAndAddedTypes() throws Exception {
	Map customTypesMap = new LinkedHashMap<>(); // LinkedHashMap keeps the insertion order 
	Map nodes = new HashMap<>();
	Map capabilities = new HashMap<>();
	Map relationships = new HashMap<>();
	Map policies = new HashMap<>();
	readCustomAndAddedTypesInGivenDirectory("C:/Users/schallit/workspace-tosca2/plugins/org.eclipse.cmf.occi.tosca.parser/tosca-types/custom-types/", 
			nodes, capabilities, relationships, policies);
	readCustomAndAddedTypesInGivenDirectory("C:/Users/schallit/workspace-tosca2/plugins/org.eclipse.cmf.occi.tosca.parser/tosca-types/added-types/", 
			nodes, capabilities, relationships, policies);
	customTypesMap.put("tosca_definitions_version", "tosca_simple_yaml_1_0");
	customTypesMap.put("description",
			"This TOSCA definitions document contains the custom types definitions as expressed in the TOSCA specification document. It is composed by the files in the directory custom-types");
	customTypesMap.put("node_types", nodes);
	customTypesMap.put("capability_types", capabilities);
	customTypesMap.put("relationship_types", relationships);
	customTypesMap.put("policy_types", policies);
	YamlWriter writerNodes = new YamlWriter(new FileWriter(
			"C:/Users/schallit/workspace-tosca2/plugins/org.eclipse.cmf.occi.tosca.parser/tosca-types/custom-types.yml"));
	writerNodes.write(customTypesMap);
	writerNodes.close();
	return customTypesMap;
}
 
Example 22
Project: oscm   File: MarketingPermissionServiceBean.java   View source code 6 votes vote down vote up
/**
 * Reads the required marketing permissions and the suppliers from the
 * database.
 * 
 * @param organizationIds
 *            The identifiers of the organization to read the permissions
 *            for.
 * @param tpRef
 *            The technical product the permissions have to belong to.
 * @return A map containing the organization identifier as key and the
 *         marketing permission as value.
 */
private Map<String, MarketingPermission> getPermissionKeysAndSuppliers(
        List<String> organizationIds, TechnicalProduct tpRef) {
    List<String> searchList = new ArrayList<String>(organizationIds);
    searchList.add("");
    Query query = ds
            .createNamedQuery("MarketingPermission.findForSupplierIds");
    query.setParameter("tp", tpRef);
    query.setParameter("orgIds", searchList);
    query.setParameter("refType",
            OrganizationReferenceType.TECHNOLOGY_PROVIDER_TO_SUPPLIER);
    List<Object[]> result = ParameterizedTypes.list(query.getResultList(),
            Object[].class);
    Map<String, MarketingPermission> permissionForOrgId = new HashMap<String, MarketingPermission>();
    for (Object[] entry : result) {
        MarketingPermission permission = (MarketingPermission) entry[0];
        Organization supplier = (Organization) entry[1];
        permissionForOrgId.put(supplier.getOrganizationId(), permission);
    }
    return permissionForOrgId;
}
 
Example 23
Project: cuckoo   File: DelegationProcessor.java   View source code 6 votes vote down vote up
private Map<ExecutableElement, String> getMethodToFieldNameMap(RoundEnvironment roundEnvironment) {
    final Map<ExecutableElement, String> methodToFieldNameMap = new HashMap<>();

    for (Element byElement : roundEnvironment.getElementsAnnotatedWith(By.class)) {
        if (byElement.getKind() != ElementKind.FIELD) {
            continue;
        }
        VariableElement byField = (VariableElement) byElement;
        for (Element element : typeUtils.asElement(byField.asType()).getEnclosedElements()) {
            if (element.getKind() != ElementKind.METHOD) {
                continue;
            }
            ExecutableElement method = (ExecutableElement) element;
            methodToFieldNameMap.put(method, byField.getSimpleName().toString());
        }
    }

    return methodToFieldNameMap;
}
 
Example 24
Project: cas-server-4.2.1   File: PrincipalAttributeRegisteredServiceUsernameProviderTests.java   View source code 6 votes vote down vote up
@Test
public void verifyUsernameByPrincipalAttribute() {
    final PrincipalAttributeRegisteredServiceUsernameProvider provider =
            new PrincipalAttributeRegisteredServiceUsernameProvider("cn");
    
    final Map<String, Object> attrs = new HashMap<>();
    attrs.put("userid", "u1");
    attrs.put("cn", "TheName");
    
    final Principal p = mock(Principal.class);
    when(p.getId()).thenReturn("person");
    when(p.getAttributes()).thenReturn(attrs);
    
    final String id = provider.resolveUsername(p, TestUtils.getService("proxyService"));
    assertEquals(id, "TheName");
    
}
 
Example 25
Project: PI-Web-API-Client-Java-Android   File: EventFrameApi.java   View source code 5 votes vote down vote up
private okhttp3.Call getReferencedElementsCall(String webId, String selectedFields, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
	Object localVarPostBody =  null;
	// verify the required parameter 'webId' is set
	if (webId == null)
		throw new ApiException("Missing required parameter 'webId'");
	String localVarPath = "/eventframes/{webId}/referencedelements";
	Map<String, String> localVarHeaderParams = new HashMap<String, String>();
	Map<String, Object> localVarFormParams = new HashMap<String, Object>();
	List<Pair> localVarQueryParams = new ArrayList<Pair>();

	final String[] localVarAccepts = {"application/json", "text/json", "text/html", "application/x-ms-application"};

	final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

	if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);

	final String[] localVarContentTypes = {"application/json", "text/json" };

	final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
	localVarHeaderParams.put("Content-Type", localVarContentType);

	localVarPath = localVarPath.replaceAll("\\{webId\\}", apiClient.escapeString(webId.toString()));
	if (selectedFields != null)
		localVarQueryParams.addAll(apiClient.parameterToPairs("multi", "selectedFields", selectedFields));
	if (progressListener != null)
	{
		apiClient.getHttpClient().networkInterceptors().add(new okhttp3.Interceptor() {
		@Override
		public okhttp3.Response intercept(okhttp3.Interceptor.Chain chain) throws IOException {
			okhttp3.Response originalResponse = chain.proceed(chain.request());
			return originalResponse.newBuilder()
			.body(new ProgressResponseBody(originalResponse.body(), progressListener))
			.build();
			}
		});
	}
	String[] localVarAuthNames = new String[] {"Basic" };
	return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
 
Example 26
Project: dubbocloud   File: UrlUtilsTest.java   View source code 5 votes vote down vote up
@Test
public void testRevertNotify() {
    String key = "dubbo.test.api.HelloService";
    Map<String, Map<String, String>> notify = new HashMap<String, Map<String, String>>();
    Map<String, String> service = new HashMap<String, String>();
    service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
    notify.put(key, service);
    Map<String, Map<String, String>> newRegister = UrlUtils.revertNotify(notify);
    Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
    service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
    expectedRegister.put("perf/dubbo.test.api.HelloService:1.0.0", service);
    assertEquals(expectedRegister, newRegister);
}
 
Example 27
Project: openjdk-jdk10   File: ConnectionPool.java   View source code 5 votes vote down vote up
private void
putConnection(HttpConnection c,
              HashMap<CacheKey,LinkedList<HttpConnection>> pool) {
    CacheKey key = c.cacheKey();
    LinkedList<HttpConnection> l = pool.get(key);
    if (l == null) {
        l = new LinkedList<>();
        pool.put(key, l);
    }
    l.add(c);
}
 
Example 28
Project: generator-jhipster-grpc   File: _HealthService.java   View source code 5 votes vote down vote up
public HealthIndicator healthIndicatorToHealthIndicatorProto(org.springframework.boot.actuate.health.HealthIndicator healthIndicator) {
    final Map<String, String> details = new HashMap<>();
    healthIndicator.health().getDetails().forEach( (detailKey, detailValue) ->
        details.put(detailKey, detailValue.toString())
    );
    return HealthIndicator.newBuilder()
        .setStatus(Status.valueOf(healthIndicator.health().getStatus().toString()))
        .putAllDetails(details)
        .build();
}
 
Example 29
Project: stynico   File: MarriageAPIActivity.java   View source code 5 votes vote down vote up
public void onSuccess(API api, int action, Map<String, Object> result)
   {
HashMap<String, Object> res = forceCast(result.get("result"));
tvMarriageType.setText(com.mob.tools.utils.R.toString(res.get("marriageType")));
tvMenLunar.setText(com.mob.tools.utils.R.toString(res.get("menLunar")));
tvMenLunarTime.setText(com.mob.tools.utils.R.toString(res.get("menLunarTime")));
tvMenMarriage.setText(com.mob.tools.utils.R.toString(res.get("menMarriage")));
tvMenZodiac.setText(com.mob.tools.utils.R.toString(res.get("menZodiac")));
tvWomanLunar.setText(com.mob.tools.utils.R.toString(res.get("womanLunar")));
tvWonmanLuarTime.setText(com.mob.tools.utils.R.toString(res.get("wonmanLuarTime")));
tvWonmanMarriage.setText(com.mob.tools.utils.R.toString(res.get("wonmanMarriage")));
tvWonmanZodiac.setText(com.mob.tools.utils.R.toString(res.get("wonmanZodiac")));
   }
 
Example 30
Project: oreilly-reactive-architecture-student   File: CoffeeHouseAppTest.java   View source code 5 votes vote down vote up
@Test
public void applySystemPropertiesShouldConvertOptsToSystemProps() {
    System.setProperty("c", "");
    Map<String, String> opts = new HashMap<>();
    opts.put("a", "1");
    opts.put("-Dc", "2");
    CoffeeHouseApp.applySystemProperties(opts);
    assertThat(System.getProperty("c")).isEqualTo("2");
}
 
Example 31
Project: openNaEF   File: CiscoIosCommandParseUtil.java   View source code 5 votes vote down vote up
public static Map<String, String> getXconnectOptions(String line) {
    if (!line.startsWith(XCONNECT_COMMAND)) {
        throw new IllegalArgumentException();
    }

    String[] elements = line.split(" ");
    Map<String, String> result = new HashMap<String, String>();
    int pos = 0;
    while (pos < elements.length) {
        if (elements[pos].equals(XCONNECT_COMMAND)) {
            result.put(PW_PEER_IP_ADDRESS, elements[++pos]);
            result.put(PW_PEER_PW_ID, elements[++pos]);
        } else if (elements[pos].equals("encapsulation")) {
            if (pos + 2 < elements.length && elements[pos + 2].equals("manual")) {
                result.put(PW_ENCAPSULATION, elements[++pos] + "-manual");
                pos++;
            } else {
                result.put(PW_ENCAPSULATION, elements[++pos]);
            }
        } else if (elements[pos].equals(PW_CLASS)) {
            result.put(PW_CLASS, elements[++pos]);
        } else {
            throw new IllegalStateException("unknown option: [" + elements[pos] + "] in [" + line + "]");
        }
        pos++;
    }
    return result;
}
 
Example 32
Project: full-javaee-app   File: AdministratorClientUpdateServlet.java   View source code 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	HttpSession session = request.getSession();
	int clientID = Integer.parseInt(request.getParameter("clientID"));

	HashMap<String, String> details = new HashMap<String, String>();
	details.put("firstName", request.getParameter("firstName").trim());
	details.put("lastName", request.getParameter("lastName").trim());
	details.put("companyID", request.getParameter("companyID"));
	details.put("email", request.getParameter("email").trim().toLowerCase());
	details.put("password", request.getParameter("password").length() < 4 ? "Unchanged" : request.getParameter("password"));
	details.put("viewLimit", request.getParameter("viewLimit").trim());
	details.put("geoLimit", request.getParameter("geoLimit").trim());
	details.put("approved", request.getParameter("approved"));

	try {
		Clients client = ClientPersistence.getByID(clientID);
		client = ClientPersistence.update(details, client);
		List<Clients> clientList = ClientPersistence.getAll();
		session.setAttribute("clientList", clientList);
		response.sendRedirect("admin/admin-client-list.jsp");
	} catch (Exception e) {
		session.setAttribute("clientError", "Failed to create account. Code:" + e);
		response.sendRedirect("admin/admin-client-list.jsp");
	}
}
 
Example 33
Project: wx-idk   File: WifiQrcodeGetRequest.java   View source code 5 votes vote down vote up
/**
   * 获取请求参数的HashMap
   */
  public Map<String, Object> getWxHashMap(){
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("shop_id", this.shop_id);
      paraMap.put("ssid", this.ssid);
paraMap.put("img_id", this.img_id);
      return wxHashMap;
  }
 
Example 34
Project: osquery-java   File: TablePluginTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testCallActionColums() {
	final List<Map<String, String>> expected = new ArrayList<Map<String, String>>() {
		{
			add(new HashMap<String, String>() {
				{
					put("id", "column");
					put("name", "foo");
					put("type", "TEXT");
					put("op", "0");
				}

			});
			add(new HashMap<String, String>() {
				{
					put("id", "column");
					put("name", "baz");
					put("type", "TEXT");
					put("op", "0");
				}
			});
		}
	};
	final Map<String, String> request = new HashMap<String, String>() {
		{
			put("action", "columns");
		}
	};
	ExtensionResponse result = plugin.call(request);
	assertThat(result.response, is(expected));
}
 
Example 35
Project: OpenJSharp   File: FontFamily.java   View source code 5 votes vote down vote up
static synchronized void addLocaleNames(FontFamily family, String[] names){
    if (allLocaleNames == null) {
        allLocaleNames = new HashMap<String, FontFamily>();
    }
    for (int i=0; i<names.length; i++) {
        allLocaleNames.put(names[i].toLowerCase(), family);
    }
}
 
Example 36
Project: firebase-admin-java   File: Connection.java   View source code 5 votes vote down vote up
public void sendRequest(Map<String, Object> message, boolean isSensitive) {
  // This came from the persistent connection. Wrap it in an envelope and send it

  Map<String, Object> request = new HashMap<>();
  request.put(REQUEST_TYPE, REQUEST_TYPE_DATA);
  request.put(REQUEST_PAYLOAD, message);

  sendData(request, isSensitive);
}
 
Example 37
Project: thingweb-directory   File: ThingWebRepoTest.java   View source code 5 votes vote down vote up
@Test
public void testVocabularyManagement() throws Exception {
	RESTResource resource;
	String ontoId;

	Map<String,String> parameters = new HashMap<String,String>();
	
	// POST vocabulary
	String ontoUri = "http://purl.oclc.org/NET/ssnx/qu/qu-rec20";
	InputStream uriStream = new ByteArrayInputStream(ontoUri.getBytes("UTF-8"));
	resource = vch.post(new URI(baseUri + "/vocab"), parameters, uriStream);
	ontoId = resource.path;

	Assert.assertTrue("QU ontology not registered", VocabularyUtils.containsVocabulary(ontoUri));
	
	// GET vocabulary by SPARQL query
	parameters.clear();
	parameters.put("query", "?s ?p ?o");
	resource = vch.get(new URI(baseUri + "/vocab"), parameters);
	
	JsonValue ontoIds = JSON.parseAny(resource.content);
	Assert.assertTrue("Vocabulary collection is not an array", ontoIds.isArray());
	Assert.assertTrue("Vocabulary imports were not added", ontoIds.getAsArray().size() > 1);
	Assert.assertTrue("QU ontology not found", ontoIds.getAsArray().contains(new JsonString(ontoId)));
	
	// GET vocabulary by id
	VocabularyHandler vh = new VocabularyHandler(ontoId, ThingDirectory.servers);
	resource = vh.get(new URI(baseUri + ontoId), null);
	
	ByteArrayInputStream byteStream = new ByteArrayInputStream(resource.content.getBytes());
	Model m = ModelFactory.createDefaultModel();
	m.read(byteStream, "", "Turtle");
	Assert.assertFalse("QU ontology definition is not valid", m.isEmpty());

	// DELETE vocabulary
	vh.delete(new URI(baseUri + ontoId), null, null);
	Assert.assertFalse("QU ontology not deleted", VocabularyUtils.containsVocabulary(ontoUri));
}
 
Example 38
Project: morf   File: ViewChanges.java   View source code 5 votes vote down vote up
/**
 * @param extraViewsToDrop Additional views to drop
 * @return a new {@link ViewChanges} which also drops the specified views.
 */
public ViewChanges droppingAlso(Collection<View> extraViewsToDrop) {
  Set<String> extraViewNames = ImmutableSet.copyOf(Collections2.transform(extraViewsToDrop, viewToName()));

  // -- In case we have any new obsolete views in here, we need to make sure they're in the index...
  //
  Map<String, View> newIndex = new HashMap<>();
  newIndex.putAll(uniqueIndex(extraViewsToDrop, viewToName()));
  newIndex.putAll(viewIndex);

  return new ViewChanges(allViews,
    Sets.union(dropSet, extraViewNames),
    Sets.union(deploySet, Sets.intersection(extraViewNames, knownSet)),
    newIndex);
}
 
Example 39
Project: dotwebstack-framework   File: LdRepresentationRequestMapperTest.java   View source code 5 votes vote down vote up
@Test
public void loadRepresentations_MapRepresentation_WithoutStage() {
  // Arrange
  representation = new Representation.Builder(DBEERPEDIA.BREWERIES).informationProduct(
      informationProduct).urlPattern(DBEERPEDIA.URL_PATTERN_VALUE).build();
  Map<IRI, Representation> representationMap = new HashMap<>();
  representationMap.put(representation.getIdentifier(), representation);
  when(representationResourceProvider.getAll()).thenReturn(representationMap);

  // Act
  ldRepresentationRequestMapper.loadRepresentations(httpConfiguration);

  // Assert
  assertThat(httpConfiguration.getResources(), hasSize(0));
}
 
Example 40
Project: gradle-libraries-plugin   File: ProjectLibraries.java   View source code 5 votes vote down vote up
public Map<String, Library> getAliasMapping() {
  Map<String, Library> result = new HashMap<>();
  for (Library library : libraries) {
    result.put(library.getAlias(), library);
  }
  return result;
}