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: JAVA-   File: ThirdPartyLoginHelper.java   Source Code and License 7 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 2
Project: Divertio   File: AlbumMenuActivity.java   Source Code and License 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 3
Project: iTAP-controller   File: StorageTest.java   Source Code and License 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 4
Project: rental-calc   File: ItemizationActivityTest.java   Source Code and License 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 5
Project: smockin   File: GeneralUtilsTest.java   Source Code and License 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 6
Project: iTAP-controller   File: Controller.java   Source Code and License 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 7
Project: kaltura-ce-sakai-extension   File: ViewProfilingController.java   Source Code and License 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 8
Project: jdk8u-jdk   File: HttpURLConnection.java   Source Code and License 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 9
Project: osc-core   File: VirtualizationConnectorServiceData.java   Source Code and License 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 10
Project: neoscada   File: ScaleHandlerImpl.java   Source Code and License 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 11
Project: godlibrary   File: JsonUtils.java   Source Code and License 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 12
Project: git-rekt   File: BrowseRoomsScreenController.java   Source Code and License 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 13
Project: Hydrograph   File: SchemaPropagationHelper.java   Source Code and License 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 14
Project: googles-monorepo-demo   File: MapTestSuiteBuilderTests.java   Source Code and License 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 15
Project: YKCenterSDKExample_for_AS   File: AirControlActivity.java   Source Code and License 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 16
Project: sunbird-lms-mw   File: UserManagementActorTest.java   Source Code and License 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 17
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConsumerTest.java   Source Code and License 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 18
Project: JRediClients   File: GeoCommandsTest.java   Source Code and License 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   Source Code and License 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: TOSCA-Studio   File: Main.java   Source Code and License 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 21
Project: oscm   File: MarketingPermissionServiceBean.java   Source Code and License 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 22
Project: cuckoo   File: DelegationProcessor.java   Source Code and License 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 23
Project: cas-server-4.2.1   File: PrincipalAttributeRegisteredServiceUsernameProviderTests.java   Source Code and License 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 24
Project: PI-Web-API-Client-Java-Android   File: EventFrameApi.java   Source Code and License 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 25
Project: dubbocloud   File: UrlUtilsTest.java   Source Code and License 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 26
Project: openjdk-jdk10   File: ConnectionPool.java   Source Code and License 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 27
Project: generator-jhipster-grpc   File: _HealthService.java   Source Code and License 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 28
Project: stynico   File: MarriageAPIActivity.java   Source Code and License 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 29
Project: oreilly-reactive-architecture-student   File: CoffeeHouseAppTest.java   Source Code and License 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 30
Project: openNaEF   File: CiscoIosCommandParseUtil.java   Source Code and License 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 31
Project: full-javaee-app   File: AdministratorClientUpdateServlet.java   Source Code and License 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 32
Project: wx-idk   File: WifiQrcodeGetRequest.java   Source Code and License 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 33
Project: osquery-java   File: TablePluginTest.java   Source Code and License 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 34
Project: OpenJSharp   File: FontFamily.java   Source Code and License 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 35
Project: firebase-admin-java   File: Connection.java   Source Code and License 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 36
Project: thingweb-directory   File: ThingWebRepoTest.java   Source Code and License 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 37
Project: morf   File: ViewChanges.java   Source Code and License 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 38
Project: dotwebstack-framework   File: LdRepresentationRequestMapperTest.java   Source Code and License 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 39
Project: gradle-libraries-plugin   File: ProjectLibraries.java   Source Code and License 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;
}
 
Example 40
Project: debug   File: GLmetadata.java   Source Code and License 5 votes vote down vote up
private static Map<Integer, String> GL_ARB_shader_objects() {
  if (GL_ARB_shader_objects != null)
    return GL_ARB_shader_objects;
  GL_ARB_shader_objects = new HashMap<Integer, String>(34);
  GL_ARB_shader_objects.put(GL_SAMPLER_1D_SHADOW_ARB, "GL_SAMPLER_1D_SHADOW_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_2D_SHADOW_ARB, "GL_SAMPLER_2D_SHADOW_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_2D_RECT_ARB, "GL_SAMPLER_2D_RECT_ARB");
  GL_ARB_shader_objects.put(GL_BOOL_VEC3_ARB, "GL_BOOL_VEC3_ARB");
  GL_ARB_shader_objects.put(GL_PROGRAM_OBJECT_ARB, "GL_PROGRAM_OBJECT_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_COMPILE_STATUS_ARB, "GL_OBJECT_COMPILE_STATUS_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_DELETE_STATUS_ARB, "GL_OBJECT_DELETE_STATUS_ARB");
  GL_ARB_shader_objects.put(GL_INT_VEC4_ARB, "GL_INT_VEC4_ARB");
  GL_ARB_shader_objects.put(GL_SHADER_OBJECT_ARB, "GL_SHADER_OBJECT_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_VALIDATE_STATUS_ARB, "GL_OBJECT_VALIDATE_STATUS_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_ACTIVE_UNIFORMS_ARB, "GL_OBJECT_ACTIVE_UNIFORMS_ARB");
  GL_ARB_shader_objects.put(GL_INT_VEC3_ARB, "GL_INT_VEC3_ARB");
  GL_ARB_shader_objects.put(GL_BOOL_ARB, "GL_BOOL_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_VEC2_ARB, "GL_FLOAT_VEC2_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_2D_RECT_SHADOW_ARB, "GL_SAMPLER_2D_RECT_SHADOW_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_MAT2_ARB, "GL_FLOAT_MAT2_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_LINK_STATUS_ARB, "GL_OBJECT_LINK_STATUS_ARB");
  GL_ARB_shader_objects.put(GL_BOOL_VEC4_ARB, "GL_BOOL_VEC4_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, "GL_OBJECT_SHADER_SOURCE_LENGTH_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_ATTACHED_OBJECTS_ARB, "GL_OBJECT_ATTACHED_OBJECTS_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_3D_ARB, "GL_SAMPLER_3D_ARB");
  GL_ARB_shader_objects.put(GL_INT_VEC2_ARB, "GL_INT_VEC2_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_2D_ARB, "GL_SAMPLER_2D_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_MAT3_ARB, "GL_FLOAT_MAT3_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_VEC3_ARB, "GL_FLOAT_VEC3_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_MAT4_ARB, "GL_FLOAT_MAT4_ARB");
  GL_ARB_shader_objects.put(GL_BOOL_VEC2_ARB, "GL_BOOL_VEC2_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_1D_ARB, "GL_SAMPLER_1D_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_SUBTYPE_ARB, "GL_OBJECT_SUBTYPE_ARB");
  GL_ARB_shader_objects.put(GL_FLOAT_VEC4_ARB, "GL_FLOAT_VEC4_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_INFO_LOG_LENGTH_ARB, "GL_OBJECT_INFO_LOG_LENGTH_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_TYPE_ARB, "GL_OBJECT_TYPE_ARB");
  GL_ARB_shader_objects.put(GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, "GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB");
  GL_ARB_shader_objects.put(GL_SAMPLER_CUBE_ARB, "GL_SAMPLER_CUBE_ARB");
  return GL_ARB_shader_objects;
}
 
Example 41
Project: sstore-soft   File: TrivialCostModel.java   Source Code and License 5 votes vote down vote up
@Override
public double getPlanCost(PlanStatistics stats) {
    double cost = 0;

    // just add up the total tuples read for the plan
    for (int i = 0; i < stats.getLevelCount(); i++) {
        HashMap<StatsField, Long> level = stats.getStatisticsForLevel(i);
        Long levelValueObj = level.get(StatsField.TUPLES_READ);
        long levelValue = (levelValueObj == null) ? 0 : levelValueObj.longValue();
        cost += levelValue;
    }

    return cost;
}
 
Example 42
Project: xm-uaa   File: ExceptionTranslatorTestController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/test/parameterized-error2")
public void parameterizedError2() {
    Map<String, String> params = new HashMap<>();
    params.put("foo", "foo_value");
    params.put("bar", "bar_value");
    throw new BusinessException("test parameterized error", params);
}
 
Example 43
Project: PI-Web-API-Client-Java-Android   File: ElementTemplateApi.java   Source Code and License 5 votes vote down vote up
private okhttp3.Call getAnalysisTemplatesCall(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 = "/elementtemplates/{webId}/analysistemplates";
	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 44
Project: opentsdb-rpc-kafka   File: KafkaRpcPlugin.java   Source Code and License 5 votes vote down vote up
public Map<String, Double> getRates() {
  final Map<String, Double> map = 
      new HashMap<String, Double>(consumer_groups.size());
  for (final KafkaRpcPluginGroup group : consumer_groups) {
    map.put(group.getGroupID(), group.getRate());
  }
  return map;
}
 
Example 45
Project: alfresco-repository   File: AbstractQNameDAOImpl.java   Source Code and License 5 votes vote down vote up
public Map<QName, ? extends Object> convertIdMapToQNameMap(Map<Long, ? extends Object> idMap)
{
    Map<QName, Object> qnameMap = new HashMap<QName, Object>(idMap.size() + 3);
    for (Map.Entry<Long, ? extends Object> entry : idMap.entrySet())
    {
        QName qname = getQName(entry.getKey()).getSecond();         // getQName(id) is never null
        qnameMap.put(qname, entry.getValue());
    }
    return qnameMap;
}
 
Example 46
Project: CIA   File: Follow.java   Source Code and License 5 votes vote down vote up
/**
 * removes the sendFollowRequest request by deleting the instance of the sendFollowRequest objects
 * @param follower the user doing the following
 * @param followee the user being followed
 */
public static void removeFollowRequest(String follower, String followee) {
    Map<String, String> map = new HashMap<>();
    map.put("followerId", follower);
    map.put("followeeId", followee);
    map.put("accepted", "0");
    ElasticSearchUtilities.delete(Follow.TYPE_ID, Follow.class, map);
}
 
Example 47
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletCreateTest.java   Source Code and License 5 votes vote down vote up
/** Use the default "save prefix" on some parameters, and check that only those
 *  who have the prefix are saved.
 */
public void testDefaultSavePrefix() throws IOException {
    final Map <String, String> props = new HashMap <String, String> ();
    props.put("./a","123");
    props.put("./b","456");
    props.put("c","not saved");
    final String createdNodeUrl = testClient.createNode(postUrl + SLASH, props);
    final String content = getContent(createdNodeUrl + ".json", CONTENT_TYPE_JSON);
    assertJavascript("123456", content, "out.println(data.a + data.b)");
    assertJavascript("undefined", content, "out.println(typeof data.c)");
}
 
Example 48
Project: oneops   File: CmsUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void localVarRefersToGV2() {
  Map<String, String> localVars = new HashMap<>(3);
  localVars.put("lv1", "$OO_GLOBAL{gv1}");
  Map<String, String> globalVars = new HashMap<>(3);
  globalVars.put("gv1", "$OO_GLOBAL{gv2}");
  globalVars.put("gv2", "globalVar2");

  Map<String, String> cloudVars = new HashMap<>(3);
  cloudVars.put("cv1", "cloudVar1");

  CmsCI ci = new CmsCI();
  ci.setCiId(90);
  ci.setCiName("localVarRefersAnotherGVar");
  Map<String, CmsCIAttribute> attributes = new LinkedHashMap<>(2);
  CmsCIAttribute attr4 = new CmsCIAttribute();
  attr4.setDjValue("Prefix $OO_LOCAL{lv1} Suffix");
  attributes.put("localVarRefersAnotherLVar", attr4);
  ci.setAttributes(attributes);
  Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes();
  for (Map.Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) {
    System.out.println("*- b4   |" + e.getKey() + "->" + e.getValue().getDjValue());
  }
  CmsUtil util = getCmsUtil();
  dumpMaps(cloudVars, globalVars, localVars);
  dumpCmsCIAttributes(ci);
  util.processAllVars(ci, cloudVars, globalVars, localVars);
  dumpCmsCIAttributes(ci);

  for (Map.Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) {
    String djKey = a.getKey();
    String djAfter = a.getValue().getDjValue();
    System.out.println("*after k>" + djKey + " v->" + djAfter);
    if (djKey.equals("localVarRefersAnotherLVar")) {
      assertEquals(djAfter, "Prefix globalVar2 Suffix");
    }

  }

}
 
Example 49
Project: dswork   File: DsCommonRoleService.java   Source Code and License 5 votes vote down vote up
/**
 * 获得当前系统下的所有功能
 * @param systemid 系统主键
 * @return List&lt;DsCommonFunc&gt;
 */
public List<DsCommonFunc> queryFuncList(Long systemid)
{
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("systemid", systemid);
	map.put("pid", null);
	return funcDao.queryList(map);
}
 
Example 50
Project: Settings   File: SettingsApi.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param applicationName The applicationName parameter
 * @param environmentName The environmentName parameter
 * @param settings The settings parameter
 * @return Boolean
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public Boolean apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost(String applicationName, String environmentName, SettingsWriteModel settings) throws RestClientException {
    Object postBody = settings;
    
    // verify the required parameter 'applicationName' is set
    if (applicationName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost");
    }
    
    // verify the required parameter 'environmentName' is set
    if (environmentName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("applicationName", applicationName);
    uriVariables.put("environmentName", environmentName);
    String path = UriComponentsBuilder.fromPath("/api/settings/create-update/{applicationName}/{environmentName}").buildAndExpand(uriVariables).toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { 
        "text/plain", "application/json", "text/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/json-patch+json", "application/json", "text/json", "application/_*+json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Boolean> returnType = new ParameterizedTypeReference<Boolean>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 51
Project: oneops   File: TransUtil.java   Source Code and License 5 votes vote down vote up
public CmsRfcCI mergeCis(CmsCI baseCi, CmsCI overrideCi, String targetPrefix, String nsPath, String releaseNsPath) {
	
	CmsRfcCI newRfc = new CmsRfcCI();
	newRfc.setNsPath(nsPath);
	newRfc.setReleaseNsPath(releaseNsPath);
	
	String targetClazzName = null;
	if (baseCi != null) {
		targetClazzName = targetPrefix + "." + getLongShortClazzName(baseCi.getCiClassName());
	} else {
		targetClazzName = targetPrefix + "." + getLongShortClazzName(overrideCi.getCiClassName());
	}
	CmsClazz targetClazz = mdProcessor.getClazz(targetClazzName);
	
	
	newRfc.setCiClassId(targetClazz.getClassId());
	newRfc.setCiClassName(targetClazz.getClassName());
	
	//bootstrap the default values from Class definition and populate map for checks
	Map<String, CmsClazzAttribute> clazzAttrs = new HashMap<String, CmsClazzAttribute>();
    for (CmsClazzAttribute clAttr : targetClazz.getMdAttributes()) {
    	if (clAttr.getDefaultValue() != null) {
    		CmsRfcAttribute rfcAttr = new CmsRfcAttribute();
    		rfcAttr.setAttributeId(clAttr.getAttributeId());
    		rfcAttr.setAttributeName(clAttr.getAttributeName());
    		rfcAttr.setNewValue(clAttr.getDefaultValue());
    		newRfc.addAttribute(rfcAttr);
    	}
    	clazzAttrs.put(clAttr.getAttributeName(), clAttr);
    }
    
    //populate values from manifest template obj if it's not null
    applyCiToRfc(newRfc, baseCi, clazzAttrs, false, true);
    
    //populate vlues from design ci if not null;
    applyCiToRfc(newRfc, overrideCi, clazzAttrs, true, false);
    
	return newRfc;
}
 
Example 52
Project: sunbird-utils   File: DefaultAssessmentEvaluator.java   Source Code and License 5 votes vote down vote up
/**
 * this method can evaluate assessment for multiple user at a time
 */
@Override
public Map<String, List<Map<String, Object>>> evaluateAssessment(Map<String, List<Map<String, Object>>> data) {
	Map<String, List<Map<String, Object>>> response = new HashMap<String, List<Map<String,Object>>>();
	Map<String, List<Map<String, Object>>> request = data;
	if(request.size() > 0)
	for(Entry<String, List<Map<String, Object>>> entry : request.entrySet()){
		if(entry.getValue().size() > 0){
		  List<Map<String, Object>> assessmentList = getAssessmentListWithMaxScore(entry);
		  response.put(entry.getKey(), assessmentList);
		}
	}
	
	return response;
}
 
Example 53
Project: elasticsearch_my   File: TransportProxyClient.java   Source Code and License 5 votes vote down vote up
TransportProxyClient(Settings settings, TransportService transportService,
                            TransportClientNodesService nodesService, List<GenericAction> actions) {
    this.nodesService = nodesService;
    Map<Action, TransportActionNodeProxy> proxies = new HashMap<>();
    for (GenericAction action : actions) {
        if (action instanceof Action) {
            proxies.put((Action) action, new TransportActionNodeProxy(settings, action, transportService));
        }
    }
    this.proxies = unmodifiableMap(proxies);
}
 
Example 54
Project: ZooKeeper   File: JaasConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * Add a section to the jaas.conf
 * @param name Section name
 * @param loginModuleName Login module name
 * @param args login key/value args
 */
public void addSection(String name, String loginModuleName, String... args) {
    Map<String, String> conf = new HashMap<String, String>();
    // loop through the args (must be key/value sequence)
    for (int i = 0; i < args.length - 1; i += 2) {
        conf.put(args[i], args[i + 1]);
    }
    addSection(name, loginModuleName, conf);
}
 
Example 55
Project: zhkuas_ssm_maven   File: BaseClassDataController.java   Source Code and License 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/campusAndclass/rs", method = RequestMethod.POST)
public Map<String, Object> saveCampusAreaClassRS(HttpSession session, String classNos, Integer campusId) {
	if (classNos == null || campusId == null) {
		return WebUtils.webJsonError(Error.PARAMETER_ERROR);
	}
	int count = 0;
	String[] classNoArray = classNos.split(",");
	for (String classNo : classNoArray) {
		CampusAreaClassRS campusAreaClassRS = new CampusAreaClassRS();
		campusAreaClassRS.setCampusId(campusId);
		campusAreaClassRS.setClassNo(classNo);
		CampusAreaClassRS dbItem = campusAreaClassRSService.getCampusAreaClassRSByClassNo(classNo);
		if (dbItem == null) {
			BaseClass dbClass = baseClassService.getBaseClassByClassNo(classNo);
			if (dbClass != null) {
				campusAreaClassRSService.addCampusAreaClassRS(campusAreaClassRS);
				count++;
			}
		} else {
			if (!dbItem.getCampusId().equals(campusId)) {
				dbItem.setCampusId(campusId);
				campusAreaClassRSService.updateCampusAreaClassRS(dbItem);
			}
			count++;
		}
	}
	Map<String, Object> result = new HashMap<String, Object>();
	result.put("success", count);
	result.put("fail", classNoArray.length - count);
	return WebUtils.webJsonResult(result);
}
 
Example 56
Project: incubator-netbeans   File: SourceMap.java   Source Code and License 5 votes vote down vote up
private void registerInverseMapping(int line, Mapping mapping) {
    String sourcePath = getSourcePath(mapping.getSourceIndex());
    Map<Integer, List<Mapping>> imm = inverseMappings.get(sourcePath);
    if (imm == null) {
        imm = new HashMap<>();
        inverseMappings.put(sourcePath, imm);
    }
    int origLine = mapping.getOriginalLine();
    int origColumn = mapping.getOriginalColumn();
    List<Mapping> ims = imm.get(origLine);
    if (ims == null) {
        ims = new ArrayList<>(6);   // Typically, there's less columns in the inverse mapping
        imm.put(origLine, ims);
    }
    // Is the mapping there already?
    int index = binarySearch(ims, origColumn);
    if (index >= 0) {
        return ;
    }
    index = -index - 1;
    //if (index >= ims.size()) {
    //    index--;
    //}
    Mapping im = new Mapping();
    im.setOriginalLine(line);
    im.setColumn(origColumn);
    im.setOriginalColumn(mapping.getColumn());
    ims.add(index, im);
}
 
Example 57
Project: powsybl-core   File: TimeSeriesMetadataSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public TimeSeriesMetadata deserialize(DataInput2 input, int available) throws IOException {
    String name = input.readUTF();
    TimeSeriesDataType dataType = TimeSeriesDataType.valueOf(input.readUTF());
    Map<String, String> tags = new HashMap<>();
    int size = input.readInt();
    for (int i = 0; i < size; i++) {
        String key = input.readUTF();
        String value = input.readUTF();
        tags.put(key, value);
    }
    TimeSeriesIndex index = TimeSeriesIndexSerializer.INSTANCE.deserialize(input, available);
    return new TimeSeriesMetadata(name, dataType, tags, index);
}
 
Example 58
Project: FamilyBond   File: TextReminderFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPresenter = new TextReminderPresenter(this);
    mapList = new ArrayList<>();
    mReminderTime = new HashMap<>();
    mReminderDate = new HashMap<>();
    mReminderRepeat = new HashMap<>();

    mRepeatMode = 0;

    mAlertTime = Calendar.getInstance();

    Calendar current = Calendar.getInstance();
    mTime = TIME_FORMAT.format(current.getTime());
    mDate = DATE_FORMAT.format(current.getTime());
    mAlertTime.setTimeInMillis(current.getTimeInMillis());

    mReminderTime.put("mTitle", "时间");
    mReminderTime.put("subtext", mTime);
    mReminderDate.put("mTitle", "日期");
    mReminderDate.put("subtext", mDate);
    mReminderRepeat.put("mTitle", "重复");
    mReminderRepeat.put("subtext", REPEAT_MODES[mRepeatMode]);


    mapList.add(mReminderTime);
    mapList.add(mReminderDate);
    mapList.add(mReminderRepeat);
}
 
Example 59
Project: alfresco-test-assertions   File: WorkflowAssertTest.java   Source Code and License 5 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 60
Project: ovh-java-sdk   File: ApiOvhPartners.java   Source Code and License 5 votes vote down vote up
/**
 * Created a new company for the inscription
 *
 * REST: POST /partners/register/company
 * @param name [required] Name of the company
 * @param commercialName [required] The commercial name of the company
 * @param registrationNumber [required] Company's registration number
 * @param address [required] Company's street address
 * @param city [required] Company's city
 * @param zipCode [required] Company's zipCode
 * @param country [required] Company's country
 * @param phone [required] Company's phone
 * @param website [required] Company's website
 * @param description [required] Company's summary
 * @param email [required] Company's email
 * @param linkedin [required] Company's linkedin url, must resemble "https://www.linkedin.com/in/ovh")
 * @param facebook [required] Company's facebook url, must resemble "https://www.facebook.com/ovh")
 * @param twitter [required] Company's twitter url, must resemble "https://twitter.com/ovh")
 * @param logo [required] Company's logo url
 * @param employeesNumber [required] Estimation of the number of employees
 * @param revenue [required] Estimation of the revenue of the company
 * @param OVHKnowledgeResources [required] Estimation of the number of resources knowing OVH product the company has
 * @param OVHTechnicalAdvancedResources [required] Estimation of the number of resources that have technical skills on OVH solutions the company has
 * @param OVHTechnicalExpertResources [required] Estimation of the number of expert resources for OVH solutions the company has
 * @param OVHCustomersAdvised [required] Estimation of the number of accompanied customers in using OVH's solutions
 * @param expertises [required] Company's domain of expertises
 * @param OVHCertifications [required] OVH certification acquired
 * @param OVHProductsUsed [required] OVH's product the company's solutions relies on
 * @param clientKinds [required] Kind of client the company target
 * @param activitySectors [required] Company's sector of activity
 * @param productCountries [required] In which country the company products of solutions are available
 * @param externalCertifications [required] Certifications obtained from other enterprises
 * @param partnerKnowledges [required] How did you heard about the OVH's partnership program
 */
public OvhCompany register_company_POST(String name, String commercialName, String registrationNumber, String address, String city, String zipCode, OvhCountryEnum country, String phone, String website, String description, String email, String linkedin, String facebook, String twitter, String logo, OvhEmployeesNumberEnum employeesNumber, OvhRevenueRangeEnum revenue, OvhKnowledgeResourcesRangeEnum OVHKnowledgeResources, OvhTechnicalAdvancedResourcesRangeEnum OVHTechnicalAdvancedResources, OvhTechnicalExpertResourcesRangeEnum OVHTechnicalExpertResources, OvhOVHCustomersAdvisedEnum OVHCustomersAdvised, OvhExpertisesChoices expertises, OvhOVHCertifications OVHCertifications, OvhOVHProductsUsed OVHProductsUsed, OvhClientKinds clientKinds, OvhActivitySectors activitySectors, OvhProductCountries productCountries, OvhExternalCertifications externalCertifications, OvhPartnerKnowledges partnerKnowledges) throws IOException {
	String qPath = "/partners/register/company";
	StringBuilder sb = path(qPath);
	HashMap<String, Object>o = new HashMap<String, Object>();
	addBody(o, "name", name);
	addBody(o, "commercialName", commercialName);
	addBody(o, "registrationNumber", registrationNumber);
	addBody(o, "address", address);
	addBody(o, "city", city);
	addBody(o, "zipCode", zipCode);
	addBody(o, "country", country);
	addBody(o, "phone", phone);
	addBody(o, "website", website);
	addBody(o, "description", description);
	addBody(o, "email", email);
	addBody(o, "linkedin", linkedin);
	addBody(o, "facebook", facebook);
	addBody(o, "twitter", twitter);
	addBody(o, "logo", logo);
	addBody(o, "employeesNumber", employeesNumber);
	addBody(o, "revenue", revenue);
	addBody(o, "OVHKnowledgeResources", OVHKnowledgeResources);
	addBody(o, "OVHTechnicalAdvancedResources", OVHTechnicalAdvancedResources);
	addBody(o, "OVHTechnicalExpertResources", OVHTechnicalExpertResources);
	addBody(o, "OVHCustomersAdvised", OVHCustomersAdvised);
	addBody(o, "expertises", expertises);
	addBody(o, "OVHCertifications", OVHCertifications);
	addBody(o, "OVHProductsUsed", OVHProductsUsed);
	addBody(o, "clientKinds", clientKinds);
	addBody(o, "activitySectors", activitySectors);
	addBody(o, "productCountries", productCountries);
	addBody(o, "externalCertifications", externalCertifications);
	addBody(o, "partnerKnowledges", partnerKnowledges);
	String resp = exec(qPath, "POST", sb.toString(), o);
	return convertTo(resp, OvhCompany.class);
}