/** * Gets a client web resource builder. * * @param localUrl the URL to access remote resource * @return web resource builder */ public Invocation.Builder getClientBuilder(String localUrl) { log.info("URL: {}", localUrl); Client client = ClientBuilder.newClient(); WebTarget wt = client.target(localUrl); return wt.request(UTF_8); }
private static void registerUser(String url, MediaType mediaType) { System.out.println("Registering user via " + url); User user = new User(1L, "larrypage"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().post(Entity.entity(user, mediaType)); try { if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); } System.out.println("Successfully got result: " + response.readEntity(String.class)); } finally { response.close(); client.close(); } }
private Result executeAction(Action action, Object lraInfo, String lraUri) { log.infof("executing action - %s", action); Client client = ClientBuilder.newClient(); URI build = UriBuilder .fromUri(servicesLocator.getServiceUri(action.getService())) .path(API_PREFIX) .path(action.getType().getPath()) .build(); log.info("action request url - " + build); WebTarget target = client.target(build); Response response = target.request().header(LRAClient.LRA_HTTP_HEADER, lraUri).post(Entity.json(lraInfo)); log.info("Result of action - " + response.readEntity(String.class)); Result result = response.getStatus() == Response.Status.OK.getStatusCode() ? Result.COMPLETED : Result.NEED_COMPENSATION; response.close(); return result; }
public TestServiceRunner start() { ServiceConfig serviceConfigwithProps = serviceConfig.addPropertiesAndApplyToBindings(propertyMap); ServiceConfig serviceConfigWithContext = ServiceConfigInitializer.finalize(serviceConfigwithProps); JerseyConfig jerseyConfig = new JerseyConfig(serviceConfigWithContext.serviceDefinition) .addRegistrators(serviceConfigWithContext.registrators) .addBinders(serviceConfigWithContext.binders); serviceConfigWithContext.addons.forEach(it -> it.addToJerseyConfig(jerseyConfig)); DeploymentContext context = DeploymentContext.builder(jerseyConfig.getResourceConfig()).build(); URI uri = UriBuilder.fromUri("http://localhost/").port(0).build(); TestContainer testContainer = new InMemoryTestContainerFactory().create(uri, context); testContainer.start(); ClientConfig clientConfig = testContainer.getClientConfig(); ClientGenerator clientGenerator = clientConfigurator.apply( ClientGenerator.defaults(serviceConfigWithContext.serviceDefinition) .clientConfigBase(clientConfig) ); Client client = clientGenerator.generate(); Runtime runtime = new Runtime(serviceConfigWithContext, jerseyConfig, testContainer, clientConfig, uri, client, stubConfigurator, targetConfigurator); return withServiceConfig(serviceConfigWithContext).withRuntime(runtime); }
public static Response processRequest( String url, String method, String payload, String authHeader) { Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Builder builder = target.request(); builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); if (authHeader != null) { builder.header(HttpHeaders.AUTHORIZATION, authHeader); } return (payload != null) ? builder.build(method, Entity.json(payload)).invoke() : builder.build(method).invoke(); }
public boolean removeServer(String url) { for (int i = 0; i < serverTargetsList.size(); i++) { try { if (serverTargetsList.get(i).getUri().getHost().equals(new URI(url).getHost()) ) { serverTargetsList.remove(i); Client client = serverList.get(i); if (client != null) { client.close(); } serverList.remove(i); return true; } } catch (URISyntaxException ex) { Logger.getLogger(ConnectorMThreatModuleRest.class.getName()).log(Level.SEVERE, null, ex); return false; } } return false; }
@Test public void testCommit() throws SQLException, ClassNotFoundException, NamingException { Client client = ClientBuilder.newClient(); client.target("http://127.0.0.1:8090/rest/test").request().get(); Class.forName("org.h2.Driver"); int resultCount = 0; try (Connection conn = DriverManager.getConnection("jdbc:h2:~/data/testdb;AUTO_SERVER=TRUE", "SA", "SA")) { ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASK"); while (rs.next()) { resultCount++; } } Assert.assertEquals(1, resultCount); }
public void testMPToken() { MPJWTToken mpjwtToken = tokenBuilder.setAudience("Octopus Rest MP"). setSubject("Octopus Test").build(); JWTParameters parameters = JWTParametersBuilder.newBuilderFor(JWTEncoding.JWS) .withSecretKeyForSigning(jwkManager.getJWKSigningKey()) .build(); String bearerHeader = jwtEncoder.encode(mpjwtToken, parameters); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://localhost:8080/rest-mp/data/hello"); Response response = target.request(MediaType.APPLICATION_JSON) .header(AUTHORIZATION_HEADER, BEARER + " " + bearerHeader) .get(); System.out.println("status : " + response.getStatus()); System.out.println(response.readEntity(String.class)); }
private Greeting getGreeting(String endpoint, String name) { String endpointURL = endpoints.get(endpoint); Client client = ClientBuilder.newClient(); try { WebTarget target = client.target(endpointURL); // Provide the authorization information target.register((ClientRequestFilter) requestContext -> { requestContext.getHeaders().add("Authorization", "Bearer "+token); }); if(cmdArgs.debugLevel > 0) target.register(new LoggingFilter()); IGreeting greetingClient = ((ResteasyWebTarget)target).proxy(IGreeting.class); Greeting greeting = greetingClient.greeting(name); return greeting; } finally { client.close(); } }
@Test public void shouldFailHealthcheckWhenMsaMetadataUnavailable() { wireMockServer.stubFor( get(urlEqualTo("/matching-service/metadata")) .willReturn(aResponse() .withStatus(500) ) ); applicationTestSupport.before(); Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client"); Response response = client .target(URI.create(String.format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort()))) .request() .buildGet() .invoke(); String expectedResult = "\"msaMetadata\":{\"healthy\":false"; wireMockServer.verify(getRequestedFor(urlEqualTo("/matching-service/metadata"))); assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(response.readEntity(String.class)).contains(expectedResult); }
private boolean trafficIsOk(boolean expectedResult) throws Throwable { if (isTrafficTestsEnabled()) { System.out.println("=====> Send traffic"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/checkflowtraffic") .queryParam("srcswitch", "s1") .queryParam("dstswitch", "s8") .queryParam("srcport", "1") .queryParam("dstport", "1") .queryParam("srcvlan", "1000") .queryParam("dstvlan", "1000") .request() .get(); System.out.println(String.format("======> Response = %s", result.toString())); System.out.println(String.format("======> Send traffic Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; } else { return expectedResult; } }
private boolean disconnectSwitch(String switchName) throws Exception { System.out.println("\n==> Disconnect Switch"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/knockoutswitch") .queryParam("switch", switchName) .request() .post(Entity.json("")); System.out.println(String.format("===> Response = %s", result.toString())); System.out.println(String.format("===> Disconnect Switch Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; }
private boolean islDiscovered(String switchName, String portNo) throws Throwable { System.out.println("\n==> Set ISL Discovered"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/restorelink") .queryParam("switch", switchName) .queryParam("port", portNo) .request() .post(Entity.json("")); System.out.println(String.format("===> Response = %s", result.toString())); System.out.println(String.format("===> Set ISL Discovered Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; }
private boolean portUp(String switchName, String portNo) throws Throwable { System.out.println("\n==> Set Port Up"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/port/up") .queryParam("switch", switchName) .queryParam("port", portNo) .request() .post(Entity.json("")); System.out.println(String.format("===> Response = %s", result.toString())); System.out.println(String.format("===> Set Port Up Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; }
@Test public void testSwaggerYaml() { Client client = JerseyClientBuilder.createClient(); WebTarget target = client.target("http://localhost:" + port + "/docs1").queryParam("type", "yaml"); Response response = target.request().get(); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertEquals("application/yaml", response.getMediaType().toString()); target = client.target("http://localhost:" + port + "/docs2").queryParam("type", "yaml"); response = target.request().get(); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertEquals("application/yaml", response.getMediaType().toString()); }
/** * Returns Switches through Topology-Engine-Rest service. * * @return The JSON document of all flows */ public static List<SwitchInfoData> dumpSwitches() throws Exception { System.out.println("\n==> Topology-Engine Dump Switches"); Client client = ClientBuilder.newClient(new ClientConfig()); Response response = client .target(topologyEndpoint) .path("/api/v1/topology/switches") .request() .header(HttpHeaders.AUTHORIZATION, authHeaderValue) .get(); System.out.println(String.format("===> Response = %s", response.toString())); List<SwitchInfoData> switches = new ObjectMapper().readValue( response.readEntity(String.class), new TypeReference<List<SwitchInfoData>>() {}); System.out.println(String.format("====> Data = %s", switches)); return switches; }
/** * Returns links through Topology-Engine-Rest service. * * @return The JSON document of all flows */ public static List<IslInfoData> dumpLinks() throws Exception { System.out.println("\n==> Topology-Engine Dump Links"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response response = client .target(topologyEndpoint) .path("/api/v1/topology/links") .request() .header(HttpHeaders.AUTHORIZATION, authHeaderValue) .get(); System.out.println(String.format("===> Response = %s", response.toString())); System.out.println(String.format("===> Topology-Engine Dump Links Time: %,.3f", getTimeDuration(current))); List<IslInfoData> links = new ObjectMapper().readValue( response.readEntity(String.class), new TypeReference<List<IslInfoData>>() {}); System.out.println(String.format("====> Data = %s", links)); return links; }
public static boolean islFail(String switchName, String portNo) { System.out.println("\n==> Set ISL Discovery Failed"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/cutlink") .queryParam("switch", switchName) .queryParam("port", portNo) .request() .post(Entity.json("")); System.out.println(String.format("===> Response = %s", result.toString())); System.out.println(String.format("===> Set ISL Discovery Failed Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; }
/** * NB: This method calls TE, not Mininet * * @return The JSON document of the Topology from the Topology Engine */ public static String GetTopology() { System.out.println("\n==> Get Topology-Engine Topology"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response response = client .target(topologyEndpoint) .path("/api/v1/topology/network") .request() .get(); System.out.println(String.format("===> Response = %s", response.toString())); System.out.println(String.format("===> Get Topology-Engine Topology Time: %,.3f", getTimeDuration(current))); String result = response.readEntity(String.class); System.out.println(String.format("====> Topology-Engine Topology = %s", result)); return result; }
private RegistryEndpoints getRegistryClient(ImageRef imageRef) { if (!proxyClients.containsKey(imageRef.getRegistryUrl())) { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); Client client = ClientBuilder.newClient() .register(new JacksonJaxbJsonProvider(mapper, new Annotations[] {Annotations.JACKSON})) .register(JacksonFeature.class); String auth = config.getAuthFor(imageRef.getRegistryName()); if (auth != null) { String[] credentials = new String(Base64.getDecoder().decode(auth), StandardCharsets.UTF_8).split(":"); client.register(HttpAuthenticationFeature.basicBuilder().credentials(credentials[0], credentials[1])); } WebTarget webTarget = client.target(imageRef.getRegistryUrl()); proxyClients.put(imageRef.getRegistryUrl(), WebResourceFactory.newResource(RegistryEndpoints.class, webTarget)); } return proxyClients.get(imageRef.getRegistryUrl()); }
@Test public void testSwaggerJson() { Client client = JerseyClientBuilder.createClient(); WebTarget target = client.target("http://localhost:" + port + "/docs1"); Response response = target.request().get(); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertEquals("application/json", response.getMediaType().toString()); target = client.target("http://localhost:" + port + "/docs2"); response = target.request().get(); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertEquals("application/json", response.getMediaType().toString()); }
private void provisionFabric(VlanId vlanId, ConnectPoint point, ConnectPoint fromPoint) { long vlan = vlanId.toShort(); JsonObject node = new JsonObject(); node.add("vlan", vlan); if (vlan == 201) { node.add("iptv", true); } else { node.add("iptv", false); } JsonArray array = new JsonArray(); JsonObject cp1 = new JsonObject(); JsonObject cp2 = new JsonObject(); cp1.add("device", point.deviceId().toString()); cp1.add("port", point.port().toLong()); cp2.add("device", fromPoint.deviceId().toString()); cp2.add("port", fromPoint.port().toLong()); array.add(cp1); array.add(cp2); node.add("ports", array); String baseUrl = "http://" + FABRIC_CONTROLLER_ADDRESS + ":" + Integer.toString(FABRIC_SERVER_PORT); Client client = ClientBuilder.newClient(); WebTarget wt = client.target(baseUrl + FABRIC_BASE_URI); Invocation.Builder builder = wt.request(JSON_UTF_8.toString()); builder.post(Entity.json(node.toString())); }
@Test public void testEndpoint() { Client client = JerseyClientBuilder.createClient(); WebTarget target = client.target("http://localhost:" + port + "/test2").path("ping"); String response = target.request().get(String.class); Assert.assertEquals("pong", response); }
private static Bucket createBucket(Client client, int num) { final Bucket bucket = new Bucket(); bucket.setName("Bucket #" + num); bucket.setDescription("This is bucket #" + num); final Bucket createdBucket = client.target(REGISTRY_API_BUCKETS_URL) .request() .post( Entity.entity(bucket, MediaType.APPLICATION_JSON), Bucket.class ); return createdBucket; }
/** * Invoke the token web service with specified parameters. */ @Nullable private AccessTokenResponse callTokenService( @Nonnull final MultivaluedMap<String, String> parameters ) { final ClientBuilder builder = ClientBuilder.newBuilder().register( JacksonFeature.class ); final String clientSecret = _config.getClientSecret(); if ( null != clientSecret ) { builder.register( new BasicAuthFilter( _config.getClientID(), clientSecret ) ); } final Client client = builder.build(); try { final WebTarget target = client. target( _config.getServerUrl() ). path( "/realms/" ).path( _config.getRealm() ).path( "/protocol/openid-connect/token" ); final Response response = target. request( MediaType.APPLICATION_FORM_URLENCODED ). accept( MediaType.APPLICATION_JSON ). post( Entity.form( parameters ) ); if ( Response.Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily() ) { return response.readEntity( AccessTokenResponse.class ); } else { return null; } } finally { client.close(); } }
@Test public void testEndpoint() { Client client = JerseyClientBuilder.createClient(); WebTarget target = client.target("http://localhost:" + port + "/test").path("ping"); String response = target.request().get(String.class); Assert.assertEquals("pong", response); }
@Test public void testSslEndpoint() { Client client = clientBuilder.build(); Assert.assertEquals("test", client.getConfiguration().getProperty("test.customizers")); WebTarget target = client.target("https://localhost:8443/test").path("ping"); String response = target.request().get(String.class); Assert.assertEquals("pong", response); }
/** * Execute a nested web service call. * @param requestUrl The request URL. */ private void executeNested(String requestUrl) { Client restClient = ClientBuilder.newBuilder().build(); WebTarget target = restClient.target(requestUrl); Response nestedResponse = target.request().get(); nestedResponse.close(); }
private static void getUser(String url) { System.out.println("Getting user via " + url); Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().get(); try { if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); } System.out.println("Successfully got result: " + response.readEntity(String.class)); } finally { response.close(); client.close(); } }
private String getResponseBody(KeycloakEndpoint endpoint, String authHeader) { try { Client client = WebClientHelpers.createClientWihtoutHostVerification(); return client.target(endpoint.toString()) .request(MediaType.APPLICATION_JSON) .header("Authorization", authHeader) .get(String.class); } catch (Exception e) { throw new KeyCloakFailureException(endpoint, e); } }
/** * Execute a remote web service and return the content. * @param service Web service path * @param relativePath Web service endpoint * @param queryParameters Query parameters. * @param expectedStatus Expected HTTP status. * @return Response */ private Response executeRemoteWebServiceRaw(final String service, final String relativePath, Map<String, Object> queryParameters, Status expectedStatus) { Client client = ClientBuilder.newClient(); String url = getWebServiceURL(service, relativePath, queryParameters); debug("Executing " + url); WebTarget target = client.target(url); Response response = target.request().get(); if (response.getStatus() != expectedStatus.getStatusCode()) { String unexpectedResponse = response.readEntity(String.class); Assert.fail("Expected HTTP response code " + expectedStatus.getStatusCode() + " but received " + response.getStatus() + "; Response: " + unexpectedResponse); } return response; }
@Test public void testConfiguration() throws Exception { logger.info("start REST Configuration test"); Client client = newClient(); Configuration configuration = client.getConfiguration(); Set<Class<?>> classes = configuration.getClasses(); for (Class<?> clazz : classes) { assertTrue("verify if the class is a rest component or provider", MessageBodyReader.class.isAssignableFrom(clazz) || MessageBodyWriter.class.isAssignableFrom(clazz) || clazz.isAnnotationPresent(Provider.class) || DynamicFeature.class.isAssignableFrom(clazz)); Map<Class<?>, Integer> contracts = configuration.getContracts(clazz); assertFalse("each class has different contracts", contracts.isEmpty()); for (Class<?> contract : contracts.keySet()) { int value = contracts.get(contract); assertTrue("verify if the contract is a rest component or provider", value == 5000 || value == 4000 || value == 3000 || value == 0); } } Set<Object> instances = configuration.getInstances(); assertTrue("by default there are not instances", instances.isEmpty()); Map<String, Object> properties = configuration.getProperties(); assertTrue("by default there are not properties", properties.isEmpty()); MyComponent myComponent = new MyComponent(); client.register(myComponent); instances = configuration.getInstances(); assertFalse("Added instance", instances.isEmpty()); for (Object instance : instances) { if (instance instanceof MyComponent) assertTrue("MyComponent is registered and active", configuration.isEnabled((Feature) instance)); } assertEquals("Added property through MyComponent", 1, properties.size()); boolean property = (Boolean) properties.get("configured_myComponent"); assertEquals("configured_myComponent ok!", true, property); assertEquals("type CLIENT by default", CLIENT, configuration.getRuntimeType()); }
@Test public void testEndpoints() { Client client = JerseyClientBuilder.createClient(); WebTarget target = client.target("http://localhost:" + port + "/v1").path("ping"); String response = target.request().get(String.class); Assert.assertEquals("pong", response); target = client.target("http://localhost:" + port + "/v2").path("ping"); response = target.request().get(String.class); Assert.assertEquals("pong", response); }
@Test @RunAsClient public void testJaxRSOptionsDeleteTypes() throws Exception { logger.info("start JaxRS options delete test"); Client client = newClient(); WebTarget target = client.target(url + "services/receiver/options"); Response response = target.request().options(); String calledMethod = response.getHeaderString("calledMethod"); double value = response.readEntity(Double.class); assertEquals("options implemented: ", 88.99, value, 0.0); client.close(); assertEquals("The filter registerCall is called only for @Logged services", OPTIONS, calledMethod); client = newClient(); target = client.target(url + "services/receiver/delete"); response = target.request().delete(); calledMethod = response.getHeaderString("calledMethod"); value = response.readEntity(Double.class); assertEquals("delete implemented: ", 99.66, value, 0.0); client.close(); assertEquals("The filter registerCall is called only for @Logged services", DELETE, calledMethod); client = newClient(); target = client.target(url + "services/receiver/header"); Builder builder = target.request().header("my_new_header", "Hi all"); response = builder.get(); calledMethod = response.getHeaderString("calledMethod"); String valueStr = response.readEntity(String.class); assertEquals("head implemented: ", "Hi all", valueStr); client.close(); assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod); client = newClient(); target = client.target(url + "services/receiver/headerWithContext"); builder = target.request(TEXT_PLAIN).header("my_new_header", "Hi allll"); response = builder.get(); calledMethod = response.getHeaderString("calledMethod"); valueStr = response.readEntity(String.class); assertEquals("head implemented: ", "Hi allll", valueStr); client.close(); assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod); }
protected Builder getInvocationBuilder(String url, Map<String, String> queryParameters) { ClientConfig clientConfig = new ClientConfig(); if (getProxyAddress() != null) { clientConfig.connectorProvider(new ApacheConnectorProvider()); clientConfig.property(ClientProperties.PROXY_URI, getProxyAddress()); } Client client = ClientBuilder.newClient(clientConfig); client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); WebTarget webTarget = client.target(url); if (queryParameters != null) { for (Map.Entry<String, String> queryParameter: queryParameters.entrySet()) // webTarget = webTarget.queryParam(queryParameter.getKey(), queryParameter.getValue().replace("_", "_1").replace("%", "_0")); webTarget = webTarget.queryParam(queryParameter.getKey(), queryParameter.getValue()); } return webTarget.request(MediaType.APPLICATION_JSON).accept("application/ld+json").header("Authorization", getCloudTokenValue()); }
@Inject public ControllerConnectorAPI( Client forwardingClient, RequestDispatcher requestDispatcher) { super(forwardingClient, requestDispatcher); }
@Test public void testEndpoint() { Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://localhost:8889/test").path("ping"); String response = target.request().get(String.class); Assert.assertEquals("pang", response); }
@Inject public NexMoServiceImpl(Configuration configuration, Client client) { jwtAuthMethod = configuration.getJwtAuthMethod(); this.client = client; LOGGER.debug("jwtAuthMethod: {}", jwtAuthMethod); nexmoClient = new NexmoClient(jwtAuthMethod); LOGGER.debug("client created!"); }
@Inject public ControllerConfigAPI( Client forwardingClient, RequestDispatcher requestDispatcher) { super(forwardingClient, requestDispatcher); }