Java Code Examples for java.util.HashMap

The following examples show how to use java.util.HashMap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   Source File: MessageContextFirstHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    boolean isOutbound = (boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (isOutbound) {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headerMap = (Map<String, List<String>>)context
            .get(MessageContext.HTTP_REQUEST_HEADERS);
        if (headerMap == null) {
            headerMap = new HashMap<>();
        }
        // Add custom header.
        headerMap.put("MY_HEADER", Arrays.asList("FIRST_VALUE"));
        context.put(MessageContext.HTTP_REQUEST_HEADERS, headerMap);
    }
    return true;
}
 
Example 2
Source Project: dubbox   Source File: ParseUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsMatchGlobPatternsNeedInterpolate() throws Exception {
    Collection<String> patternsNeedInterpolate = new HashSet<String>();
    Map<String, String> interpolateParams = new HashMap<String, String>();
    
    boolean match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abc");
    assertFalse(match);
    
    patternsNeedInterpolate.add("abc*$var1");
    patternsNeedInterpolate.add("123${var2}*");
    
    interpolateParams.put("var1", "CAT");
    interpolateParams.put("var2", "DOG");
    
    match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abc");
    assertFalse(match);
    
    match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abcXXXCAT");
    assertTrue(match);
    match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "123DOGYYY");
    assertTrue(match);
}
 
Example 3
Source Project: rocketmq-read   Source File: InnerLoggerFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
    if (seenMap == null) {
        seenMap = new HashMap<Object[], Object>();
    }
    sbuf.append('[');
    if (!seenMap.containsKey(a)) {
        seenMap.put(a, null);
        int len = a.length;

        for (int i = 0; i < len; ++i) {
            deeplyAppendParameter(sbuf, a[i], seenMap);
            if (i != len - 1) {
                sbuf.append(", ");
            }
        }

        seenMap.remove(a);
    } else {
        sbuf.append("...");
    }

    sbuf.append(']');
}
 
Example 4
/**
 * @throws java.lang.Exception
 */
@Before
public void setUp() throws Exception {
    bom = new BusinessObjectModel();
    final BusinessObject bo = new BusinessObject();
    bo.setQualifiedName("org.bonita.test.Employee");
    final SimpleField firstName = new SimpleField();
    firstName.setName("firstName");
    firstName.setType(FieldType.STRING);
    bo.getFields().add(firstName);
    bom.getBusinessObjects().add(bo);
    operationUnderTest = spy(new DeployBDMOperation(bdmFileStore));
    doReturn(bom).when(bdmFileStore).getContent();
    final Map<String, byte[]> result = new HashMap<>();
    result.put("bdm-client", new byte[512]);
    doReturn(false).when(operationUnderTest).dropDBOnInstall();
    when(manager.getTenantAdministrationAPI((APISession) anyObject())).thenReturn(tenantAdminAPI);
    doReturn(manager).when(operationUnderTest).getEngineManager();
    doNothing().when(operationUnderTest).uninstallBDMAccessControl(any(IProgressMonitor.class));
    doNothing().when(operationUnderTest).forceH2Drop();
    parentFolder = new File("test");
    parentFolder.mkdirs();
    doReturn(parentFolder).when(operationUnderTest).getTargetFolder();
}
 
Example 5
Source Project: bce-sdk-java   Source File: QueryRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a string representation of the object.
 *
 * @return A string representation of the object.
 */
public String toString() {
    HashMap<String, Object> jsonObj = new HashMap<String, Object>();
    jsonObj.put(MolaDbConstants.JSON_TABLENAME, this.tableName);

    if (!this.attributesToGet.isEmpty()) {
        jsonObj.put(MolaDbConstants.JSON_ATTRIBUTES_TO_GET,
                this.attributesToGet);
    }
    if (null != this.exclusiveStartKey) {
        jsonObj.put(MolaDbConstants.JSON_EXCLUSIVE_START_KEY, this.exclusiveStartKey.toJsonObj());
    }
    if (this.consistentRead) {
        jsonObj.put(MolaDbConstants.JSON_CONSISTENT_READ, MolaDbConstants.JSON_TRUE);
    }

    if (this.limit > 0) {
        jsonObj.put(MolaDbConstants.JSON_LIMIT, Integer.toString(this.limit));
    }

    jsonObj.put(MolaDbConstants.JSON_KEY_CONDITION_EXPRESSION, this.keyConditionExpression);
    jsonObj.put(MolaDbConstants.JSON_EXPRESSION_ATTRIBUTEVALUES,
            this.attributeValueToJson(this.expressionAttributeValues));
    jsonObj.put(MolaDbConstants.JSON_ORDER, this.order);
    return JsonUtils.toJsonString(jsonObj);
}
 
Example 6
Source Project: jwala   Source File: JvmStateReceiverAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReceiveWithRuntimeException() throws Exception {
    final Identifier<Jvm> jvmId = new Identifier<>("1");
    Jvm jvm = new Jvm(jvmId, "jvm-name");

    final Map<Object, Object> serverInfoMap = new HashMap();
    serverInfoMap.put(JvmStateReceiverAdapter.NAME_KEY, jvm.getJvmName());
    serverInfoMap.put(JvmStateReceiverAdapter.STATE_KEY, LifecycleState.STOPPING);

    msg = new Message();
    msg.setObject(serverInfoMap);

    when (mockJvmPersistenceService.findJvmByExactName(jvm.getJvmName())).thenThrow(new NoResultException(""));

    jvmStateReceiverAdapter.receive(msg);
    verify(mockJvmStateService, never()).updateState(eq(jvm), eq(JvmState.JVM_STOPPING), eq(StringUtils.EMPTY));
}
 
Example 7
/**
 * 将查出的数字与目标文本进行相关的比较
 * @param findNumber
 * @param targetText
 * @return
 */
public Map<String, List<String>> compareNumber(List<String> sourceNumbers, List<String> targetNumbers){
	Map<String, List<String>> resultMap  = new HashMap<String, List<String>>();
	List<String> resultList = new LinkedList<String>();
	//下面查看其目标数字集合中是否有源文本中的数字,如果有,则将这个数字从目标数字集合中删除
	int tarIndex;
	if (targetNumbers.size() == 0) {
		resultMap.put("source", sourceNumbers);
		return resultMap;
	}
	for (int index = 0; index < sourceNumbers.size(); index++) {
		String sourceNumber = sourceNumbers.get(index);
		
		if ((tarIndex = targetNumbers.indexOf(sourceNumber)) >= 0) {
			targetNumbers.remove(tarIndex);
		}else {
			resultList.add(sourceNumber);
		}
	}
	resultMap.put("source", resultList);
	if (targetNumbers.size() > 0) {
		resultMap.put("target", targetNumbers);
	}
	return resultMap;
}
 
Example 8
Source Project: hugegraph   Source File: UsersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTarget() {
    HugeGraph graph = graph();
    UserManager userManager = graph.userManager();

    HugeTarget target = makeTarget("graph1", "127.0.0.1:8080");
    target.creator("admin");
    Id id = userManager.createTarget(target);

    target = userManager.getTarget(id);
    Assert.assertEquals("graph1", target.name());
    Assert.assertEquals("127.0.0.1:8080", target.url());
    Assert.assertEquals(target.create(), target.update());

    HashMap<String, Object> expected = new HashMap<>();
    expected.putAll(ImmutableMap.of("target_name", "graph1",
                                    "target_graph", "graph1",
                                    "target_url", "127.0.0.1:8080",
                                    "target_creator", "admin"));
    expected.putAll(ImmutableMap.of("target_create", target.create(),
                                    "target_update", target.update(),
                                    "id", target.id()));

    Assert.assertEquals(expected, target.asMap());
}
 
Example 9
Source Project: syncope   Source File: MailTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void requestPasswordReset() throws IOException {
    Map<String, Object> ctx = new HashMap<>();

    String username = "test" + UUID.randomUUID().toString();
    UserTO user = new UserTO();
    user.setUsername(username);
    ctx.put("user", user);

    String token = "token " + UUID.randomUUID().toString();
    List<String> input = new ArrayList<>();
    input.add(token);
    ctx.put("input", input);

    String textBody = evaluate(REQUEST_PASSWORD_RESET_TEMPLATE, ctx);

    assertNotNull(textBody);
    assertTrue(textBody.contains("a password reset was requested for " + username + "."));
    assertFalse(textBody.contains(
            "http://localhost:9080/syncope-enduser/app/#!/confirmpasswordreset?token="
            + token));
    assertTrue(textBody.contains(
            "http://localhost:9080/syncope-enduser/app/#!/confirmpasswordreset?token="
            + token.replaceAll(" ", "%20")));
}
 
Example 10
@Override
public ArrayList<Map<String, String>> loadInBackground() {
  Set<String> regions                    = PhoneNumberUtil.getInstance().getSupportedRegions();
  ArrayList<Map<String, String>> results = new ArrayList<>(regions.size());

  for (String region : regions) {
    Map<String, String> data = new HashMap<>(2);
    data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
    data.put("country_code", "+" +PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
    results.add(data);
  }

  Collections.sort(results, new RegionComparator());

  return results;
}
 
Example 11
Source Project: huaweicloud-sdk-java-obs   Source File: ObsService.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean doesObjectExistImpl(GetObjectMetadataRequest request) throws ServiceException {
    Map<String, String> headers = new HashMap<String, String>();
    this.transSseCHeaders(request.getSseCHeader(), headers, this.getIHeaders());
    this.transRequestPaymentHeaders(request, headers, this.getIHeaders());

    Map<String, String> params = new HashMap<String, String>();
    if (request.getVersionId() != null) {
        params.put(ObsRequestParams.VERSION_ID, request.getVersionId());
    }
    boolean doesObjectExist = false;
    try {
        Response response = performRestHead(request.getBucketName(), request.getObjectKey(), params, headers);
        if (200 == response.code()) {
            doesObjectExist = true;
        }
    } catch (ServiceException ex) {
        if (404 == ex.getResponseCode()) {
            doesObjectExist = false;
        } else {
            throw ex;
        }
    }
    return doesObjectExist;
}
 
Example 12
Source Project: mdw   Source File: ServiceValuesAccess.java    License: Apache License 2.0 6 votes vote down vote up
protected Map<String,String> getParameters(Map<String,String> headers) {
    Map<String,String> params = new HashMap<String,String>();
    String query = headers.get(Listener.METAINFO_REQUEST_QUERY_STRING);
    if (query == null)
        query = headers.get("request-query-string");
    if (query != null && !query.isEmpty()) {
        for (String pair : query.split("&")) {
            int idx = pair.indexOf("=");
            try {
                params.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
                        URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
            }
            catch (UnsupportedEncodingException ex) {
                // as if UTF-8 is going to be unsupported
            }
        }
    }
    return params;
}
 
Example 13
Source Project: bird-java   Source File: RabbitConfigurer.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化topic的Exchange并绑定到Queue,手动注入到Spring容器
 *
 * @param topic topic
 * @param queue queue
 */
private void initExchange(String topic, Queue queue) {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();

    BeanDefinitionBuilder exchangeBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition(FanoutExchange.class);
    exchangeBeanBuilder.addConstructorArgValue(topic);
    beanFactory.registerBeanDefinition("rabbit.exchange#" + topic, exchangeBeanBuilder.getRawBeanDefinition());

    BeanDefinitionBuilder bindingBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition(Binding.class);
    bindingBeanBuilder.addConstructorArgValue(queue.getName());
    bindingBeanBuilder.addConstructorArgValue(Binding.DestinationType.QUEUE);
    bindingBeanBuilder.addConstructorArgValue(topic);
    bindingBeanBuilder.addConstructorArgValue("");
    bindingBeanBuilder.addConstructorArgValue(new HashMap<>());
    beanFactory.registerBeanDefinition("rabbit.binding#" + topic, bindingBeanBuilder.getRawBeanDefinition());
}
 
Example 14
Source Project: birt   Source File: ExprManagerUtilTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
   public void testValidateNodes2( ) throws DataException
{

	ExprManager em = new ExprManager( null , cx);
	Map m = new HashMap( );
	m.put( "COL0",
			new ScriptExpression( "row[\"COL1\"]+row[\"COL2\"]+row[\"COL3\"]" ) );
	m.put( "COL2", new ScriptExpression( "dataSetRow[\"COL2\"]" ) );
	m.put( "COL1",
			new ScriptExpression( "row[\"COL0\"]+row[\"COL3\"]+dataSetRow[\"COL3\"]" ) );
	m.put( "COL3", new ScriptExpression( "row[\"COL2\"]+row[\"COL4\"]" ) );
	m.put( "COL4", new ScriptExpression( "row[\"COL2\"]" ) );

	em.addBindingExpr( null, getBindingMap(m), 0 );
	
	try
	{
		ExprManagerUtil.validateColumnBinding( em, null, cx );
		fail( "Should not arrive here" );
	}
	catch ( DataException e )
	{
	}
}
 
Example 15
@Named("remote") @Singleton @Provides BundleDataSource providesRemoteBundleDataSource(
    @Named("mature-pool-v7")
        BodyInterceptor<cm.aptoide.pt.dataprovider.ws.v7.BaseBody> bodyInterceptorPoolV7,
    @Named("default") OkHttpClient okHttpClient, Converter.Factory converter,
    BundlesResponseMapper mapper, TokenInvalidator tokenInvalidator,
    @Named("default") SharedPreferences sharedPreferences, AptoideAccountManager accountManager,
    PackageRepository packageRepository, Database database, IdsRepository idsRepository,
    QManager qManager, Resources resources, WindowManager windowManager,
    ConnectivityManager connectivityManager,
    AdsApplicationVersionCodeProvider adsApplicationVersionCodeProvider,
    OemidProvider oemidProvider, AppBundlesVisibilityManager appBundlesVisibilityManager,
    StoreCredentialsProvider storeCredentialsProvider) {
  return new RemoteBundleDataSource(5, new HashMap<>(), bodyInterceptorPoolV7, okHttpClient,
      converter, mapper, tokenInvalidator, sharedPreferences, new WSWidgetsUtils(),
      storeCredentialsProvider, idsRepository,
      AdNetworkUtils.isGooglePlayServicesAvailable(application.getApplicationContext()),
      oemidProvider.getOemid(), accountManager,
      qManager.getFilters(ManagerPreferences.getHWSpecsFilter(sharedPreferences)), resources,
      windowManager, connectivityManager, adsApplicationVersionCodeProvider, packageRepository,
      10, 10, appBundlesVisibilityManager);
}
 
Example 16
Source Project: distributedlog   Source File: DistributedLogTool.java    License: Apache License 2.0 6 votes vote down vote up
private Map<BookieSocketAddress, Integer> getBookieStats(LogSegmentMetadata segment) throws Exception {
    Map<BookieSocketAddress, Integer> stats = new HashMap<BookieSocketAddress, Integer>();
    LedgerHandle lh = bkc.client().get().openLedgerNoRecovery(segment.getLogSegmentId(),
            BookKeeper.DigestType.CRC32, getConf().getBKDigestPW().getBytes(UTF_8));
    long eidFirst = 0;
    for (SortedMap.Entry<Long, ArrayList<BookieSocketAddress>>
            entry : LedgerReader.bookiesForLedger(lh).entrySet()) {
        long eidLast = entry.getKey().longValue();
        long count = eidLast - eidFirst + 1;
        for (BookieSocketAddress bookie : entry.getValue()) {
            merge(stats, bookie, (int) count);
        }
        eidFirst = eidLast;
    }
    return stats;
}
 
Example 17
/**
 * load log configuration in application.properties
 *
 * @param environment
 * @return
 */
private Map<String, String> loadApplicationEnvironment(ConfigurableEnvironment environment) {
    Map<String, String> context = new HashMap<String, String>();
    readLogConfiguration(LOG_PATH, environment.getProperty(LOG_PATH), context,
        Constants.LOGGING_PATH_DEFAULT);
    readLogConfiguration(OLD_LOG_PATH, environment.getProperty(OLD_LOG_PATH), context,
        context.get(LOG_PATH));
    readLogConfiguration(LOG_ENCODING_PROP_KEY, environment.getProperty(LOG_ENCODING_PROP_KEY),
        context);
    LogEnvUtils.keepCompatible(context, true);

    Set<String> configKeys = new HashSet<String>();
    Iterator<PropertySource<?>> propertySourceIterator = environment.getPropertySources()
        .iterator();
    while (propertySourceIterator.hasNext()) {
        PropertySource propertySource = propertySourceIterator.next();
        if (propertySource instanceof EnumerablePropertySource) {
            configKeys.addAll(Arrays.asList(((EnumerablePropertySource) propertySource)
                .getPropertyNames()));
        }
    }
    for (String key : configKeys) {
        if (LogEnvUtils.filterAllLogConfig(key)) {
            addToGlobalSystemProperties(key, environment.getProperty(key));
            readLogConfiguration(key, environment.getProperty(key), context);
        }
    }
    return context;
}
 
Example 18
Source Project: neoscada   Source File: HttpSmartProxyHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the handshake processing.
 * 
 * @param nextFilter the next filter
 */
public void doHandshake(final NextFilter nextFilter) throws ProxyAuthException {
    logger.debug(" doHandshake()");

    if (authHandler != null) {
        authHandler.doHandshake(nextFilter);
    } else {
        if (requestSent) {
            // Safety check
            throw new ProxyAuthException("Authentication request already sent");
        }

        logger.debug("  sending HTTP request");

        // Compute request headers
        HttpProxyRequest req = (HttpProxyRequest) getProxyIoSession().getRequest();
        Map<String, List<String>> headers = req.getHeaders() != null ? req.getHeaders()
                : new HashMap<String, List<String>>();

        AbstractAuthLogicHandler.addKeepAliveHeaders(headers);
        req.setHeaders(headers);

        // Write request to the proxy
        writeRequest(nextFilter, req);
        requestSent = true;
    }
}
 
Example 19
public CorbaResponseWaitingRoomImpl(ORB orb, CorbaConnection connection)
{
    this.orb = orb;
    wrapper = ORBUtilSystemException.get( orb,
        CORBALogDomains.RPC_TRANSPORT ) ;
    this.connection = connection;
    out_calls =
        Collections.synchronizedMap(new HashMap<Integer, OutCallDesc>());
}
 
Example 20
/**
 * {@inheritDoc}
 */
public void requestParameterRefresh( final DrillDownParameterRefreshEvent event ) {
  final HashMap<String, DrillDownParameter> entries = new HashMap<String, DrillDownParameter>();
  final DrillDownParameter[] originalParams = event.getParameter();
  for ( int i = 0; i < originalParams.length; i++ ) {
    final DrillDownParameter param = originalParams[ i ];
    param.setType( DrillDownParameter.Type.MANUAL );
    entries.put( param.getName(), param );
  }

  final ReportDocumentContext activeContext = reportDesignerContext.getActiveContext();
  final MasterReport masterReportElement = activeContext.getContextRoot();
  final ReportParameterDefinition reportParams = masterReportElement.getParameterDefinition();
  final ParameterDefinitionEntry[] parameterDefinitionEntries = reportParams.getParameterDefinitions();

  for ( int i = 0; i < parameterDefinitionEntries.length; i++ ) {
    final ParameterDefinitionEntry entry = parameterDefinitionEntries[i];
    if ( entries.containsKey( entry.getName() ) == false ) {
      entries.put( entry.getName(),
              new DrillDownParameter( entry.getName(), null, DrillDownParameter.Type.PREDEFINED, false, false ) );
    } else {
      final DrillDownParameter parameter = entries.get( entry.getName() );
      parameter.setType( DrillDownParameter.Type.PREDEFINED );
    }
  }

  final DrillDownParameter[] parameters = entries.values().toArray( new DrillDownParameter[ entries.size() ] );
  modelWrapper.setDrillDownParameter( parameters );
  ( drillDownUi.<DrillDownParameterTable>getComponent(
      SwingRemoteDrillDownUi.ComponentLookup.PARAMETER_TABLE
  ) ).setDrillDownParameter( parameters );
}
 
Example 21
Source Project: cxf   Source File: JWTTokenValidatorRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, RealmProperties> getRealms() {
    // Create Realms
    Map<String, RealmProperties> realms = new HashMap<>();
    RealmProperties realm = new RealmProperties();
    realm.setIssuer("A-Issuer");
    realms.put("A", realm);
    realm = new RealmProperties();
    realm.setIssuer("B-Issuer");
    realms.put("B", realm);
    return realms;
}
 
Example 22
Source Project: mangopay2-java-sdk   Source File: PayInPaymentDetailsBankWire.java    License: MIT License 5 votes vote down vote up
/**
 * Gets map which property is an object and what type of object.
 *
 * @return Collection of field name-field type pairs.
 */
@Override
public Map<String, Type> getSubObjects() {

    HashMap<String, Type> result = new HashMap<>();

    result.put("DeclaredDebitedFunds", Money.class);
    result.put("DeclaredFees", Money.class);
    result.put("BankAccount", BankAccount.class);

    return result;
}
 
Example 23
Source Project: nifi-api-client-java   Source File: FlowApi.java    License: Apache License 2.0 5 votes vote down vote up
private com.squareup.okhttp.Call getPrioritizersCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;
    

    // create path and map variables
    String localVarPath = "/flow/prioritizers".replaceAll("\\{format\\}","json");

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

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

    final String[] localVarAccepts = {
        "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {
        "*_/_*"
    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if(progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                .build();
            }
        });
    }

    String[] localVarAuthNames = new String[] {  };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
 
Example 24
Source Project: sc-generator   Source File: VelocityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String writerGeneratorConfig(String url, String username, String password, String driverClass,
		String packagePath, String targetPath, List<String> tables) throws IOException, SQLException {
	VelocityContext ctx = new VelocityContext();
	Template template = getTempate("templates/generatorConfig.vm");
	ctx.put("url", url);
	ctx.put("username", username);
	ctx.put("password", password);
	ctx.put("driverClass", driverClass);
	ctx.put("tables", tables);

	Map<String, String> primaryKeys = new HashMap<>();

	Connection connection = DriverManager.getConnection(url, username, password);
	for (String tableName : tables) {
		String primaryKey = TblUtil.getPrimaryKey(connection, tableName);
		String key = toHump(primaryKey);
		primaryKeys.put(tableName, key);
	}
	ctx.put("primaryKeys", primaryKeys);
	List<String> models = new ArrayList<String>();
	for (String table : tables) {
		String modelName = tableNameConvertModelName(table);
		models.add(modelName);
	}
	ctx.put("models", models);
	ctx.put("packagePath", packagePath);
	ctx.put("targetPath", targetPath);
	StringWriter writer = new StringWriter();
	template.merge(ctx, writer);
	writer.flush();
	writer.close();
	return writer.toString();
}
 
Example 25
Source Project: medusa   Source File: MyGraph.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean goodDegree(HashMap<MyNode, Integer> degrees) {
	boolean b = true;
	for (Entry<MyNode, Integer> entry : degrees.entrySet()) {
		if (entry.getValue() > 2) {
			b = false;
		}
	}
	return b;
}
 
Example 26
Source Project: dubbo-samples   Source File: UserServiceIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("id", "1");
    map.put("name", "Charles");
    Params params = new Params(map);
    User user = userService.get(params);
    Assert.assertEquals(1, user.getId());
    Assert.assertEquals("Charles", user.getName());
}
 
Example 27
Source Project: Box   Source File: ResourceStorage.java    License: Apache License 2.0 5 votes vote down vote up
public Map<Integer, String> getResourcesNames() {
	Map<Integer, String> map = new HashMap<>();
	for (ResourceEntry entry : list) {
		map.put(entry.getId(), entry.getTypeName() + '/' + entry.getKeyName());
	}
	return map;
}
 
Example 28
Source Project: crate   Source File: UserPrivileges.java    License: Apache License 2.0 5 votes vote down vote up
UserPrivileges(Collection<Privilege> privileges) {
    privilegeByIdent = new HashMap<>(privileges.size());
    boolean anyClusterPrivilege = false;
    for (Privilege privilege : privileges) {
        PrivilegeIdent privilegeIdent = privilege.ident();
        privilegeByIdent.put(privilegeIdent, privilege);
        if (privilege.state() != Privilege.State.DENY) {
            switch (privilegeIdent.clazz()) {
                case CLUSTER:
                    anyClusterPrivilege = true;
                    break;
                case SCHEMA:
                    anySchemaPrivilege.add(privilegeIdent.ident());
                    break;
                case TABLE:
                    anyTablePrivilege.add(privilegeIdent.ident());
                    break;
                case VIEW:
                    anyViewPrivilege.add(privilegeIdent.ident());
                    break;
                default:
                    throw new IllegalStateException("Unsupported privilege class=" + privilegeIdent.clazz());
            }
        }
    }
    this.anyClusterPrivilege = anyClusterPrivilege;
}
 
Example 29
@Override
public Map<String, JPanel> getTabs() {
    try {
        return plugin.getTabs();
    } catch (RuntimeException e) {
        handleException(e);
    }
    return new HashMap<>();
}
 
Example 30
Source Project: xenon   Source File: ScriptingParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test03b_parseKeyValueLines_InputWithExtraSpaces_ResultMap() throws Exception {
    Map<String, String> expected = new HashMap<>();
    expected.put("key1", "value1");
    expected.put("key2", "value2");
    expected.put("key3", "value3");
    expected.put("key4", "value4");

    String input = "key1  =  value1\nkey2\t\t\t =   value2\n   key3 = value3  \n   key4   =value4    \n";

    Map<String, String> result = ScriptingParser.parseKeyValueLines(input, ScriptingParser.EQUALS_REGEX, "fake", "ignore this line");

    assertEquals("parser does not handle spaces in key/value input lines correctly", expected, result);
}