@Test public void testConfigLifecycleListener() throws InterruptedException { ClientConfig config = new ClientConfig(); final BlockingQueue<LifecycleEvent> q = new LinkedBlockingQueue<LifecycleEvent>(); config.addListener( new LifecycleListener() { public void stateChanged(final LifecycleEvent event) { q.offer(event); System.out.println(event); } }); Hazelcast.getDefaultInstance(); HazelcastClient client = HazelcastClient.newHazelcastClient(config); Assert.assertEquals(new LifecycleEvent(LifecycleState.STARTING), q.poll(3, TimeUnit.SECONDS)); Assert.assertEquals( new LifecycleEvent(LifecycleState.CLIENT_CONNECTION_OPENING), q.poll(3, TimeUnit.SECONDS)); Assert.assertEquals( new LifecycleEvent(LifecycleState.CLIENT_CONNECTION_OPENED), q.poll(3, TimeUnit.SECONDS)); Assert.assertEquals(new LifecycleEvent(LifecycleState.STARTED), q.poll(3, TimeUnit.SECONDS)); client.shutdown(); // Assert.assertEquals(new LifecycleEvent(LifecycleState.CLIENT_CONNECTION_LOST), // q.poll(3, TimeUnit.SECONDS)); Assert.assertEquals( new LifecycleEvent(LifecycleState.SHUTTING_DOWN), q.poll(3, TimeUnit.SECONDS)); Assert.assertEquals(new LifecycleEvent(LifecycleState.SHUTDOWN), q.poll(3, TimeUnit.SECONDS)); }
public static List<PatientSearchResult> getDynamicSearch( List<DynamicSearchCriteria> criteria, String stateRelation, String userToken) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); // stateRelation is how the criteria are logically related "AND", "OR" form.add("stateRelation", stateRelation); int i = 0; // Step through all criteria given, the form fields are appended with an integer // to maintain grouping in REST call (dataGroup0, dataGroup1...) for (DynamicSearchCriteria dcriteria : criteria) { form.add("sourceName" + i, dcriteria.getDataGroup()); form.add("itemName" + i, dcriteria.getField()); form.add("operator" + i, dcriteria.getOperator().getValue()); form.add("value" + i, dcriteria.getValue()); i++; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getDynamicSearch"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer " + userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientSearchResultImpl> myObjects; try { // Object json = mapper.readValue(output, Object.class); // String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>() {}); } catch (Exception e) { e.printStackTrace(); return null; } List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>(); for (PatientSearchResultImpl result : myObjects) { returnValue.add(result); } return returnValue; }
@Test public void testNearCacheConfigs() { assertEquals(1, clientConfig.getNearCacheConfigMap().size()); final NearCacheConfig nearCacheConfig = clientConfig.getNearCacheConfig("asd"); assertEquals(2000, nearCacheConfig.getMaxSize()); assertEquals(2000, nearCacheConfig.getEvictionConfig().getSize()); assertEquals(90, nearCacheConfig.getTimeToLiveSeconds()); assertEquals(100, nearCacheConfig.getMaxIdleSeconds()); assertEquals("LFU", nearCacheConfig.getEvictionPolicy()); assertEquals(EvictionPolicy.LFU, nearCacheConfig.getEvictionConfig().getEvictionPolicy()); assertTrue(nearCacheConfig.isInvalidateOnChange()); assertEquals(InMemoryFormat.OBJECT, nearCacheConfig.getInMemoryFormat()); }
private void start() { // 1. instance reactorManager = CommonUtils.newInstance(clientConfig.getReactorManagerClassName()); ioWorker = CommonUtils.newInstance(clientConfig.getIoWorkerClassName()); eventWorker = CommonUtils.newInstance(clientConfig.getEventWorkerClassName()); protocolFactory = CommonUtils.newInstance(clientConfig.getProtocolFactoryClassName()); messageHandler = CommonUtils.newInstance(clientConfig.getMessageHandlerClassName()); ioWorker.setReactorManager(reactorManager); eventWorker.setProtocolFactory(protocolFactory).setMessageHandler(messageHandler); reactorManager.setNIOConfig(clientConfig).setIoWorker(ioWorker).setEventWorker(eventWorker); reactorManager.start(); }
@Test public void testQueryCacheFullConfig() throws Exception { QueryCacheConfig queryCacheConfig = clientConfig.getQueryCacheConfigs().get("map-name").get("query-cache-name"); EntryListenerConfig entryListenerConfig = queryCacheConfig.getEntryListenerConfigs().get(0); assertEquals("query-cache-name", queryCacheConfig.getName()); assertTrue(entryListenerConfig.isIncludeValue()); assertFalse(entryListenerConfig.isLocal()); assertEquals("com.hazelcast.examples.EntryListener", entryListenerConfig.getClassName()); assertTrue(queryCacheConfig.isIncludeValue()); assertEquals(1, queryCacheConfig.getBatchSize()); assertEquals(16, queryCacheConfig.getBufferSize()); assertEquals(0, queryCacheConfig.getDelaySeconds()); assertEquals(EvictionPolicy.LRU, queryCacheConfig.getEvictionConfig().getEvictionPolicy()); assertEquals( EvictionConfig.MaxSizePolicy.ENTRY_COUNT, queryCacheConfig.getEvictionConfig().getMaximumSizePolicy()); assertEquals(10000, queryCacheConfig.getEvictionConfig().getSize()); assertEquals(InMemoryFormat.BINARY, queryCacheConfig.getInMemoryFormat()); assertFalse(queryCacheConfig.isCoalesce()); assertTrue(queryCacheConfig.isPopulate()); Iterator<MapIndexConfig> iterator = queryCacheConfig.getIndexConfigs().iterator(); while (iterator.hasNext()) { MapIndexConfig mapIndexConfig = iterator.next(); assertEquals("name", mapIndexConfig.getAttribute()); assertFalse(mapIndexConfig.isOrdered()); } assertEquals( "com.hazelcast.examples.ExamplePredicate", queryCacheConfig.getPredicateConfig().getClassName()); }
@Test public void testSerializationConfig() { final SerializationConfig serializationConfig = clientConfig.getSerializationConfig(); assertEquals(3, serializationConfig.getPortableVersion()); final Map<Integer, String> dsClasses = serializationConfig.getDataSerializableFactoryClasses(); assertEquals(1, dsClasses.size()); assertEquals("com.hazelcast.examples.DataSerializableFactory", dsClasses.get(1)); final Map<Integer, String> pfClasses = serializationConfig.getPortableFactoryClasses(); assertEquals(1, pfClasses.size()); assertEquals("com.hazelcast.examples.PortableFactory", pfClasses.get(2)); final Collection<SerializerConfig> serializerConfigs = serializationConfig.getSerializerConfigs(); assertEquals(1, serializerConfigs.size()); final SerializerConfig serializerConfig = serializerConfigs.iterator().next(); assertEquals("com.hazelcast.examples.DummyType", serializerConfig.getTypeClassName()); assertEquals("com.hazelcast.examples.SerializerFactory", serializerConfig.getClassName()); final GlobalSerializerConfig globalSerializerConfig = serializationConfig.getGlobalSerializerConfig(); assertEquals( "com.hazelcast.examples.GlobalSerializerFactory", globalSerializerConfig.getClassName()); assertEquals(ByteOrder.BIG_ENDIAN, serializationConfig.getByteOrder()); assertEquals(true, serializationConfig.isCheckClassDefErrors()); assertEquals(false, serializationConfig.isAllowUnsafe()); assertEquals(false, serializationConfig.isEnableCompression()); assertEquals(true, serializationConfig.isEnableSharedObject()); assertEquals(true, serializationConfig.isUseNativeByteOrder()); }
@Test public void testNetworkConfig() { final ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig(); assertEquals(2, networkConfig.getConnectionAttemptLimit()); assertEquals(2, networkConfig.getAddresses().size()); assertTrue(networkConfig.getAddresses().contains("127.0.0.1")); assertTrue(networkConfig.getAddresses().contains("127.0.0.2")); assertTrue(networkConfig.isSmartRouting()); assertTrue(networkConfig.isRedoOperation()); final SocketInterceptorConfig socketInterceptorConfig = networkConfig.getSocketInterceptorConfig(); assertTrue(socketInterceptorConfig.isEnabled()); assertEquals( "com.hazelcast.examples.MySocketInterceptor", socketInterceptorConfig.getClassName()); assertEquals("bar", socketInterceptorConfig.getProperty("foo")); final ClientAwsConfig awsConfig = networkConfig.getAwsConfig(); assertTrue(awsConfig.isEnabled()); assertTrue(awsConfig.isInsideAws()); assertEquals("TEST_ACCESS_KEY", awsConfig.getAccessKey()); assertEquals("TEST_ACCESS_KEY", awsConfig.getAccessKey()); assertEquals("TEST_SECRET_KEY", awsConfig.getSecretKey()); assertEquals("us-east-1", awsConfig.getRegion()); assertEquals("ec2.amazonaws.com", awsConfig.getHostHeader()); assertEquals("type", awsConfig.getTagKey()); assertEquals("hz-nodes", awsConfig.getTagValue()); assertEquals(11, awsConfig.getConnectionTimeoutSeconds()); }
@Activate public void activate(ClientConfig config) { handleIllegalConfiguration(validateClientId(config.clientId())); databaseName = config.databaseName(); // The uriProperty is a single string containing one or more server URIs. // When more than one URI is specified, it denotes a replica set and the // URIs must be separated by a comma (CSV). uris = new ArrayList<String>(); handleIllegalConfiguration(validateURI(config.uri(), uris)); MongoClientOptions options = createMongoClientOptions(config); mongoClient = createMongoClient(uris, options); }
@Test public void testProxyFactories() { final List<ProxyFactoryConfig> pfc = clientConfig.getProxyFactoryConfigs(); assertEquals(3, pfc.size()); assertTrue( pfc.contains(new ProxyFactoryConfig("com.hazelcast.examples.ProxyXYZ1", "sampleService1"))); assertTrue( pfc.contains(new ProxyFactoryConfig("com.hazelcast.examples.ProxyXYZ2", "sampleService1"))); assertTrue( pfc.contains(new ProxyFactoryConfig("com.hazelcast.examples.ProxyXYZ3", "sampleService3"))); }
@Test(timeout = 120000) public void testSuccessfulSocketInterceptor() { Config config = new Config(); SocketInterceptorConfig sic = new SocketInterceptorConfig(); MySocketInterceptor mySocketInterceptor = new MySocketInterceptor(true); sic.setImplementation(mySocketInterceptor); config.getNetworkConfig().setSocketInterceptorConfig(sic); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h4 = Hazelcast.newHazelcastInstance(config); int count = 1000; for (int i = 0; i < count; i++) { h1.getMap("default").put(i, "value" + i); h2.getMap("default").put(i, "value" + i); h3.getMap("default").put(i, "value" + i); h4.getMap("default").put(i, "value" + i); } assertEquals(4, h4.getCluster().getMembers().size()); assertTrue(mySocketInterceptor.getAcceptCallCount() >= 6); assertTrue(mySocketInterceptor.getConnectCallCount() >= 6); assertEquals(4, mySocketInterceptor.getInitCallCount()); assertEquals(0, mySocketInterceptor.getAcceptFailureCount()); assertEquals(0, mySocketInterceptor.getConnectFailureCount()); ClientConfig clientConfig = new ClientConfig(); clientConfig.setGroupConfig(new GroupConfig("dev", "dev-pass")).addAddress("localhost"); MySocketInterceptor myClientSocketInterceptor = new MySocketInterceptor(true); clientConfig.setSocketInterceptor(myClientSocketInterceptor); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); for (int i = 0; i < count; i++) { client.getMap("default").put(i, "value" + i); } assertTrue(mySocketInterceptor.getAcceptCallCount() >= 7); assertTrue(mySocketInterceptor.getConnectCallCount() >= 6); assertEquals(1, myClientSocketInterceptor.getConnectCallCount()); assertEquals(0, myClientSocketInterceptor.getAcceptCallCount()); assertEquals(0, mySocketInterceptor.getAcceptFailureCount()); assertEquals(0, mySocketInterceptor.getConnectFailureCount()); assertEquals(0, myClientSocketInterceptor.getAcceptFailureCount()); assertEquals(0, myClientSocketInterceptor.getConnectFailureCount()); }
@Test public void testLeftovers() { assertEquals(40, clientConfig.getExecutorPoolSize()); assertEquals( "com.hazelcast.security.UsernamePasswordCredentials", clientConfig.getSecurityConfig().getCredentialsClassname()); assertEquals(40, clientConfig.getExecutorPoolSize()); assertEquals( "com.hazelcast.client.util.RandomLB", clientConfig.getLoadBalancer().getClass().getName()); final List<ListenerConfig> listenerConfigs = clientConfig.getListenerConfigs(); assertEquals(3, listenerConfigs.size()); assertTrue( listenerConfigs.contains(new ListenerConfig("com.hazelcast.examples.MembershipListener"))); assertTrue( listenerConfigs.contains(new ListenerConfig("com.hazelcast.examples.InstanceListener"))); assertTrue( listenerConfigs.contains(new ListenerConfig("com.hazelcast.examples.MigrationListener"))); }
public static List<ImageDTO> getImageDrillDown(List<Integer> criteria, String userToken) { Form form = new Form(); int i = 0; // List of selected series for (Integer dcriteria : criteria) { form.add("list", dcriteria.toString()); } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getImageDrillDown"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + userToken) .type(MediaType.APPLICATION_FORM_URLENCODED) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<ImageDTO> myObjects; try { // Object json = mapper.readValue(output, Object.class); // String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<ImageDTO>>() {}); } catch (Exception e) { e.printStackTrace(); return null; } return myObjects; }
public static String getJNLP( List<BasketSeriesItemBean> seriesItems, String password, boolean annotation, String userToken) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); if ((seriesItems == null) || (seriesItems.size() == 0)) { return ""; } // Step through all data in series items for display in download manager for (BasketSeriesItemBean item : seriesItems) { form.add("list", item.getSeriesId()); } form.add("password", password); String annotationString = "false"; if (annotation) { annotationString = "true"; } form.add("includeAnnotation", annotationString); ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getJNLPText"); ClientResponse response = resource .accept(MediaType.TEXT_PLAIN) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer " + userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); return output; }
public static List<PatientSearchResult> getTextSearch(String textValue, String userToken) { Form form = new Form(); form.add("textValue", textValue); ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getTextSearch"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer " + userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientTextSearchResult> myObjects; try { // Object json = mapper.readValue(output, Object.class); // String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientTextSearchResultImpl>>() {}); } catch (Exception e) { e.printStackTrace(); return null; } List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>(); for (PatientTextSearchResult result : myObjects) { returnValue.add(result); } return returnValue; }
@Test public void loadingThroughSystemProperty_existingFile() throws IOException { String xml = HAZELCAST_CLIENT_START_TAG + " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>" + "</hazelcast-client>"; File file = File.createTempFile("foo", "bar"); file.deleteOnExit(); PrintWriter writer = new PrintWriter(file, "UTF-8"); writer.println(xml); writer.close(); System.setProperty("hazelcast.client.config", file.getAbsolutePath()); XmlClientConfigBuilder configBuilder = new XmlClientConfigBuilder(); ClientConfig config = configBuilder.build(); assertEquals("foobar", config.getGroupConfig().getName()); }
@Test public void testNearCacheConfigWithEvictionConfig() throws IOException { URL schemaResource = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-client-test.xml"); ClientConfig clientConfig = new XmlClientConfigBuilder(schemaResource).build(); assertEquals("MyName", clientConfig.getInstanceName()); NearCacheConfig nearCacheConfig = clientConfig.getNearCacheConfig("nearCacheWithEviction"); assertEquals(10000, nearCacheConfig.getTimeToLiveSeconds()); assertEquals(5000, nearCacheConfig.getMaxIdleSeconds()); assertFalse(nearCacheConfig.isInvalidateOnChange()); assertEquals(InMemoryFormat.OBJECT, nearCacheConfig.getInMemoryFormat()); assertTrue(nearCacheConfig.isCacheLocalEntries()); assertNotNull(nearCacheConfig.getEvictionConfig()); assertEquals(100, nearCacheConfig.getEvictionConfig().getSize()); assertEquals( EvictionConfig.MaxSizePolicy.ENTRY_COUNT, nearCacheConfig.getEvictionConfig().getMaximumSizePolicy()); assertEquals(EvictionPolicy.LFU, nearCacheConfig.getEvictionConfig().getEvictionPolicy()); }
public static DefaultOAuth2AccessToken getToken(String userName, String password) { Form form = new Form(); form.add("username", userName); form.add("password", password); form.add("client_id", "nbiaRestAPIClient"); form.add("client_secret", "ItsBetweenUAndMe"); form.add("grant_type", "password"); ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/oauth/token"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); output = "[" + output + "]"; List<DefaultOAuth2AccessToken> myObjects; try { myObjects = mapper.readValue(output, new TypeReference<List<DefaultOAuth2AccessToken>>() {}); } catch (Exception e) { e.printStackTrace(); return null; } return myObjects.get(0); }
@Test public void testNearCacheConfigWildcardMatchingPointStartsWith() { NearCacheConfig nearCacheConfig1 = new NearCacheConfig().setName("hazelcast.*"); NearCacheConfig nearCacheConfig2 = new NearCacheConfig().setName("hazelcast.test.*"); NearCacheConfig nearCacheConfig3 = new NearCacheConfig().setName("hazelcast.test.sub.*"); ClientConfig config = new ClientConfig(); config.setConfigPatternMatcher(new LegacyMatchingPointConfigPatternMatcher()); config.addNearCacheConfig(nearCacheConfig1); config.addNearCacheConfig(nearCacheConfig2); config.addNearCacheConfig(nearCacheConfig3); // we should match this (contains) assertEquals(nearCacheConfig1, config.getNearCacheConfig("com.hazelcast.myNearCache")); assertEquals(nearCacheConfig2, config.getNearCacheConfig("com.hazelcast.test.myNearCache")); assertEquals(nearCacheConfig3, config.getNearCacheConfig("com.hazelcast.test.sub.myNearCache")); }
@SuppressWarnings("unchecked") public static <T> T createClient(final Class<T> clazz, ClientConfig config) { // create the server URI URI uri = null; try { uri = new URI(config.getServer()); } catch (Exception ex) { throw new RuntimeException( "Error creating the URI form the server string: " + config.getServer(), ex); } T service = null; if (clientCache.containsKey(clazz)) { service = (T) clientCache.get(clazz); } else { // create the rest-easy provider factory ClientBuilder builder = ClientBuilder.newBuilder(); if (config.isAllowAllHttps()) { builder.hostnameVerifier(new AllowAllHostnameVerifier()); } // add the default interceptors. if (config.isDefaultLogInterceptor()) { builder.register(ClientServiceLogFilter.class); } // add the advanced interceptors List<Class> cpc = config.getComponentClasses(); if (cpc != null) { for (Class filter : cpc) { builder.register(filter); } } List<Object> filters = config.getComponents(); if (filters != null) { for (Object filter : filters) { builder.register(filter); } } Client client = builder.build(); WebTarget target = client.target(uri); service = ClientServiceProxyFactory.newResource(clazz, target); clientCache.put(clazz, service); } return service; }
@Test public void loadingThroughSystemProperty_existingClasspathResource() throws IOException { System.setProperty("hazelcast.client.config", "classpath:test-hazelcast-client.xml"); XmlClientConfigBuilder configBuilder = new XmlClientConfigBuilder(); ClientConfig config = configBuilder.build(); assertEquals("foobar", config.getGroupConfig().getName()); assertEquals( "com.hazelcast.nio.ssl.BasicSSLContextFactory", config.getNetworkConfig().getSSLConfig().getFactoryClassName()); assertEquals(32, config.getNetworkConfig().getSocketOptions().getBufferSize()); assertFalse(config.getNetworkConfig().getSocketOptions().isKeepAlive()); assertFalse(config.getNetworkConfig().getSocketOptions().isTcpNoDelay()); assertEquals(3, config.getNetworkConfig().getSocketOptions().getLingerSeconds()); }
protected void setupHttpClient() { LOG.info("setting up http client"); BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParams, 70 * 1000); HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000); ConnManagerParams.setMaxTotalConnections(httpParams, 200); ConnPerRoute connPerRoute = new ConnPerRouteBean(400); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); // ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, // HttpClientWithKeystore.getSchemeRegistry()); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "utf-8"); mHttpClient = new HttpClientWithKeystore(cm, httpParams); mHttpClient.getParams().setParameter("http.useragent", mConfig.getApplicationName()); mHttpClient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); mHttpClient.setReuseStrategy(new NoConnectionReuseStrategy()); }
@Test public void testProperties() { assertEquals(6, clientConfig.getProperties().size()); assertEquals("60000", clientConfig.getProperty("hazelcast.client.heartbeat.timeout")); }
private MongoClientOptions createMongoClientOptions(ClientConfig config) { MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder(); optionsBuilder.alwaysUseMBeans(config.alwaysUseMBeans()); optionsBuilder.connectionsPerHost(config.connectionsPerHost()); optionsBuilder.connectTimeout(config.connectTimeout()); optionsBuilder.cursorFinalizerEnabled(config.cursorFinalizerEnabled()); optionsBuilder.description(config.description()); optionsBuilder.heartbeatConnectTimeout(config.heartbeatConnectTimeout()); optionsBuilder.heartbeatFrequency(config.heartbeatFrequency()); optionsBuilder.heartbeatSocketTimeout(config.heartbeatSocketTimeout()); optionsBuilder.localThreshold(config.localThreshold()); optionsBuilder.maxConnectionIdleTime(config.maxConnectionIdleTime()); optionsBuilder.maxConnectionLifeTime(config.maxConnectionLifeTime()); optionsBuilder.maxWaitTime(config.maxWaitTime()); optionsBuilder.minConnectionsPerHost(config.minConnectionsPerHost()); optionsBuilder.minHeartbeatFrequency(config.minHeartbeatFrequency()); optionsBuilder.serverSelectionTimeout(config.serverSelectionTimeout()); optionsBuilder.socketKeepAlive(config.socketKeepAlive()); optionsBuilder.socketTimeout(config.socketTimeout()); optionsBuilder.sslEnabled(config.sslEnabled()); optionsBuilder.sslInvalidHostNameAllowed(config.sslInvalidHostNameAllowed()); optionsBuilder.threadsAllowedToBlockForConnectionMultiplier( config.threadsAllowedToBlockForConnectionMultiplier()); WriteConcern writeConcern = new WriteConcern( config.writeConcernW(), config.writeConcernWtimeout(), config.writeConcernFsync(), config.writeConcernJ()); optionsBuilder.writeConcern(writeConcern); if (!config.requiredReplicaSetName().isEmpty()) optionsBuilder.requiredReplicaSetName(config.requiredReplicaSetName()); List<Tag> tags = new ArrayList<>(); if (config.readPreferenceTags() != null) { for (String tag : config.readPreferenceTags()) { String[] elements = tag.split("="); tags.add(new Tag(elements[0], elements[1])); } } TagSet tagSet = new TagSet(tags); switch (config.readPreferenceType()) { case 1: optionsBuilder.readPreference(ReadPreference.nearest(tagSet)); break; case 2: optionsBuilder.readPreference(ReadPreference.primary()); break; case 3: optionsBuilder.readPreference(ReadPreference.primaryPreferred(tagSet)); break; case 4: optionsBuilder.readPreference(ReadPreference.secondary(tagSet)); break; case 5: optionsBuilder.readPreference(ReadPreference.secondaryPreferred(tagSet)); break; } return optionsBuilder.build(); }
protected String sign(String url) { return ApiSigningTools.sign(url, mConfig.getApiKey(), mConfig.getSharedSecret()); }
@Test public void testGroupConfig() { final GroupConfig groupConfig = clientConfig.getGroupConfig(); assertEquals("dev", groupConfig.getName()); assertEquals("dev-pass", groupConfig.getPassword()); }
@Override public void runValidation() { ioHelper.validatePath(clientConfig.getBrokerDir(), "broker must be configured"); }
public static void getSimpleSearch(List<Criteria> criteria, String userToken) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); int i = 0; // Step through all criteria given, the form fields are appended with an integer // to maintain grouping in REST call (dataGroup0, dataGroup1...) for (Criteria scriteria : criteria) { if (scriteria instanceof CollectionCriteria) { CollectionCriteria cri = (CollectionCriteria) scriteria; for (String collection : ((CollectionCriteria) scriteria).getCollectionObjects()) { form.add("criteriaType" + i, "CollectionCriteria"); form.add("value" + i, collection); } } if (scriteria instanceof ImageModalityCriteria) { ImageModalityCriteria cri = (ImageModalityCriteria) scriteria; for (String value : ((ImageModalityCriteria) scriteria).getImageModalityObjects()) { form.add("criteriaType" + i, "ImageModalityCriteria"); form.add("value" + i, value); } } if (scriteria instanceof AnatomicalSiteCriteria) { AnatomicalSiteCriteria cri = (AnatomicalSiteCriteria) scriteria; for (String value : ((AnatomicalSiteCriteria) scriteria).getAnatomicalSiteValueObjects()) { form.add("criteriaType" + i, "AnatomicalSiteCriteria"); form.add("value" + i, value); } } if (scriteria instanceof ManufacturerCriteria) { ManufacturerCriteria cri = (ManufacturerCriteria) scriteria; for (String value : ((ManufacturerCriteria) scriteria).getManufacturerObjects()) { form.add("criteriaType" + i, "ManufacturerCriteria"); form.add("value" + i, value); } } if (scriteria instanceof DateRangeCriteria) { DateRangeCriteria cri = (DateRangeCriteria) scriteria; form.add("criteriaType" + i, "DateRangeCriteria"); SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy"); form.add("fromDate" + i, formatter.format(cri.getFromDate())); form.add("toDate" + i, formatter.format(cri.getToDate())); } if (scriteria instanceof PatientCriteria) { PatientCriteria cri = (PatientCriteria) scriteria; for (String value : ((PatientCriteria) scriteria).getPatientIdObjects()) { form.add("criteriaType" + i, "PatientCriteria"); form.add("value" + i, value); } } if (scriteria instanceof MinNumberOfStudiesCriteria) { MinNumberOfStudiesCriteria cri = (MinNumberOfStudiesCriteria) scriteria; form.add("criteriaType" + i, "MinNumberOfStudiesCriteria"); form.add("value" + i, cri.getMinNumberOfStudiesValue().toString()); } i++; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getSimpleSearch"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer " + userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientSearchResultImpl> myObjects; try { // Object json = mapper.readValue(output, Object.class); // String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>() {}); } catch (Exception e) { e.printStackTrace(); return; } List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>(); for (PatientSearchResultImpl result : myObjects) { returnValue.add(result); } return; }