Refine search
public static void main(String[] args) { try { System.out.println("\"Hello World\" Jersey OpenTracing Example App"); prepare(); final ResourceConfig resourceConfig = new ResourceConfig(TracedResource.class, OpenTracingFeature.class, ReqFilterA.class, ReqFilterB.class, RespFilterA.class, RespFilterB.class); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig, false); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow)); server.start(); System.out.println(String.format("Application started.\nTry out %s/application.wadl\n" + "Stop the application using CTRL+C", BASE_URI)); // do the first "example" request with tracing-enabled client to show something in Jaegger UI, // include some weird headers and accepted types, that will be visible in the span's tags Client client = ClientBuilder.newBuilder().register(OpenTracingFeature.class).build(); client.target(BASE_URI).path("resource/managedClient").request() .accept("text/plain", "application/json", "*/*") .header("foo", "bar") .header("foo", "baz") .header("Hello", "World").get(); Thread.currentThread().join(); } catch (IOException | InterruptedException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }
.keyPassword("asdfgh"); final Client client = ClientBuilder.newBuilder().sslContext(sslConfig.createSSLContext()).build(); client.property(ClientProperties.CONNECT_TIMEOUT, 2000) .register(new MoxyJsonFeature()) .register(HttpAuthenticationFeature.basic(App.getTwitterUserName(), App.getTwitterUserPassword())) .register(GZipEncoder.class); final Response response = client.target("https://stream.twitter.com/1.1/statuses/filter.json") .queryParam("track", keywords) .request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.HOST, "stream.twitter.com") .header(HttpHeaders.USER_AGENT, "Jersey/2.0") .header(HttpHeaders.ACCEPT_ENCODING, "gzip") .get(); if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { LOGGER.log(Level.WARNING, "Error connecting to Twitter Streaming API: " + response.getStatus()); msgListener.onError(); return; final ChunkedInput<Message> chunks = response.readEntity(new GenericType<ChunkedInput<Message>>() { }); try {
private void addSSLConfiguration(ClientBuilder clientBuilder) { try { if (systemSSL) { clientBuilder.sslContext(SSLContext.getDefault()); } else if (trustStoreFileName != null) { KeyStore trustStore = KeyStore.getInstance(KEY_STORE_TYPE); FileInputStream fin = new FileInputStream(trustStoreFileName); trustStore.load(fin, trustStorePassword.toCharArray()); clientBuilder.trustStore(trustStore); } else if (sslContext != null) { clientBuilder.sslContext(sslContext); } } catch (Exception ex) { throw new IllegalArgumentException("Cannot setup SSL for Jersey2 client", ex); } }
/** * A helper method for creating clients. The client will be created using * the given configuration and security context. Additionally, the client * will be automatically configured for JSON serialization/deserialization. * * @param config client configuration * @param ctx security context, which may be null for non-secure client * creation * @return a Client instance */ private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) { ClientBuilder clientBuilder = ClientBuilder.newBuilder(); if (config != null) { clientBuilder = clientBuilder.withConfig(config); } if (ctx != null) { // Apache http DefaultHostnameVerifier that checks subject alternative names against the hostname of the URI clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(new DefaultHostnameVerifier()); } clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class); return clientBuilder.build(); }
private static Client buildClient() { final ObjectMapper objectMapper = JsonMapper.INSTANCE.mapper; objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); objectMapper.registerModule(new Jdk8Module()); final JacksonMessageBodyProvider jsonProvider = new JacksonMessageBodyProvider(objectMapper); return ClientBuilder.newBuilder().register(jsonProvider).build(); } }
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 60000) .property(ClientProperties.READ_TIMEOUT, 60000); final Client client = ClientBuilder.newClient(clientConfig); final Response response = client.target(path.urlPost()) .request(APPLICATION_JSON_TYPE) .post(Entity.json(inputOrder)); System.out.printf("Response: %s %n", response.getStatus()); returnedOrder = client.target(path.urlGet(i)) .queryParam("timeout", MIN / 2) .request(APPLICATION_JSON_TYPE) .get(newBean());
private void authenticate() { Token token = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build() .target(this.baseUrl + "/login").request(MediaType.APPLICATION_JSON_TYPE).post( javax.ws.rs.client.Entity.entity(this.credential, MediaType.APPLICATION_JSON_TYPE)) .readEntity(Token.class); checkState(!checkNotNull(token).isExpired()); this.token = token; }
/** * Send message to webapp to refresh SearcherManagers for given projects. * This is used for partial reindex. * * @param subFiles list of directories to refresh corresponding SearcherManagers * @param host the host address to receive the configuration */ public void signalTorefreshSearcherManagers(List<String> subFiles, String host) { // subFile entries start with path separator so get basename // to convert them to project names. subFiles.stream().map(proj -> new File(proj).getName()).forEach(project -> { Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("system") .path("refresh") .request() .put(Entity.text(project)); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { LOGGER.log(Level.WARNING, "Could not refresh search manager for {0}", project); } }); }
@Override public void run() { final Client resourceClient = ClientBuilder.newClient(); resourceClient.register(new MoxyJsonFeature()); final WebTarget messageStreamResource = resourceClient.target(App.getApiUri()).path("message/stream"); Message message = null; try { while (!cancelled && (message = messages.take()) != null) { msgListener.onMessage(message); final Response r = messageStreamResource.request().put(Entity.json(message)); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { LOGGER.warning("Unexpected PUT message response status code: " + r.getStatus()); } } if (message == null) { LOGGER.info("Timed out while waiting for a message."); } } catch (InterruptedException ex) { LOGGER.log(Level.WARNING, "Waiting for a message has been interrupted.", ex); } finally { readerHandle.cancel(true); msgListener.onComplete(); } } });
final Client client = ClientBuilder.newBuilder() .register(filterFeature) .register(JacksonFeature.class) .build(); final Response response = client.target(FRIENDS_TIMELINE_URI).request().get(); if (response.getStatus() != 200) { String errorEntity = null; if (response.hasEntity()) { errorEntity = response.readEntity(String.class);
public void get(final GetStatusConfig config) { final SSLContext sslContext = config.getSslContext(); final ClientBuilder clientBuilder = ClientBuilder.newBuilder(); if (sslContext != null) { clientBuilder.sslContext(sslContext); } final ClientConfig clientConfig = new ClientConfig(); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 10000); clientConfig.property(ClientProperties.READ_TIMEOUT, 10000); clientBuilder.withConfig(clientConfig); final Client client = clientBuilder.build(); final WebTarget target = client.target(config.getUrl()); final Response response = target.request().get(); System.out.println("Response Code - " + response.getStatus()); }
/** * Google should always have a valid SSL. Test this. */ @Test public void testHttpsConnectionToGoogle() throws Exception { final Client client = ClientBuilder .newBuilder() .hostnameVerifier( DisableSslCertificateCheckUtil.NULL_HOSTNAME_VERIFIER) .sslContext( DisableSslCertificateCheckUtil .buildUnsecureSslContext()).build(); client.target( "https://accounts.google.com/.well-known/openid-configuration") .request().get(); }
/** * Write the current configuration to a socket * * @param host the host address to receive the configuration * @throws IOException if an error occurs */ public void writeConfiguration(String host) throws IOException { String configXML; try { configLock.readLock().lock(); configXML = configuration.getXMLRepresentationAsString(); } finally { configLock.readLock().unlock(); } Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("configuration") .queryParam("reindex", true) .request() .put(Entity.xml(configXML)); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException(r.toString()); } }
private static Response sendHttpRequest(String url, Map<String, String> params) throws Exception { Form formData = new Form(); params.forEach(formData::param); ClientBuilder clientBuilder = ClientBuilder.newBuilder(); if (!isDevMode()){ clientBuilder.sslContext(SslManager.getSSLContext()); } javax.ws.rs.client.Client client = clientBuilder.build(); Entity<Form> payload = Entity.form(formData); return client.target(url) .request(MediaType.APPLICATION_FORM_URLENCODED) .header("Accept", "application/json") .post(payload); } }
@Test public void testGetSetEntityStreamLambda() { String address = "http://localhost:" + PORT + "/bookstore/entityecho"; String entity = "BOOKSTORE"; Client client = ClientBuilder.newClient(); client.register((ClientRequestFilter) context -> { context.setEntityStream(new ReplacingOutputStream(context.getEntityStream(), 'X', 'O')); }); WebTarget target = client.target(address); Response response = target.request().post( Entity.entity(entity.replace('O', 'X'), "text/plain")); assertEquals(entity, response.readEntity(String.class)); }
@Test public void runAppAndBasicTest() throws InterruptedException, ExecutionException{ Client client = ClientBuilder.newClient(); WebTarget resource = client.target("http://localhost:8080/simple-app/single/ping"); Builder request = resource.request(); request.accept(MediaType.TEXT_PLAIN); assertTrue(request.get().getHeaders().containsKey("Access-Control-Allow-Origin")); }
public HttpsClient(String host, String project) { SslConfigurator sslConfig = SslConfigurator.newInstance(); SSLContext ssl = sslConfig.createSSLContext(); this.target = ClientBuilder.newBuilder().sslContext(ssl).build().target(UriBuilder.fromUri("https://" + host).build()); if (project != null) { this.target = this.target.path(project); } }
private void init() { final ApacheConnectorProvider apacheConnectorProvider = new ApacheConnectorProvider(); final ClientConfig clientConfig = new ClientConfig().connectorProvider(apacheConnectorProvider); // transfer encoding should be set as jersey sets it on by default. clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, enableChunkedEncoding ? RequestEntityProcessing.CHUNKED : RequestEntityProcessing.BUFFERED); client = ClientBuilder.newClient(clientConfig); target = client.target(urlString).path(PUT_PATH); if(sync) { // need to add an empty string else it is nto added as query param. target = target.queryParam("sync", "").queryParam("sync_timeout", syncTimeout); } if(responseType != ResponseType.None) { // need to add an empty string else it is nto added as query param. target = target.queryParam(responseType.value, ""); } LOG.info("target uri [{}]", target.getUri()); }