/** * Format of response - status code, status family, reason phrase and info about entity. * * @param response response to be formatted * @param textSB Formatted info will be appended to {@code StringBuilder} */ private static void formatResponse(final Response response, final StringBuilder textSB) { textSB.append(" <").append(formatStatusInfo(response.getStatusInfo())).append('|'); if (response.hasEntity()) { formatInstance(response.getEntity(), textSB); } else { textSB.append("-no-entity-"); } textSB.append('>'); }
/** * Format of response - status code, status family, reason phrase and info about entity. * * @param response response to be formatted * @param textSB Formatted info will be appended to {@code StringBuilder} */ private static void formatResponse(final Response response, final StringBuilder textSB) { textSB.append(" <").append(formatStatusInfo(response.getStatusInfo())).append('|'); if (response.hasEntity()) { formatInstance(response.getEntity(), textSB); } else { textSB.append("-no-entity-"); } textSB.append('>'); }
Form form = new Form(); form.add("x", "foo"); form.add("y", "bar"); Client client = ClientBuilder.newClient(); WebTarget resource = client.target("http://localhost:8080/someresource"); Builder request = resource.request(); request.accept(MediaType.APPLICATION_JSON); Response response = request.get(); if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { System.out.println("Success! " + response.getStatus()); System.out.println(response.getEntity()); } else { System.out.println("ERROR! " + response.getStatus()); System.out.println(response.getEntity()); }
/** * 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); } }); }
if (enabled == null || !Boolean.valueOf(enabled)) { final Response r = request.put(Entity.text(Boolean.TRUE.toString())); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new WebApplicationException(String.format("Unable to enable projects: %s", r.getStatusInfo().getReasonPhrase()), r.getStatus());
/** * 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 Response _follow3Redirects(Response currentResponse) { Response.StatusType statusType = currentResponse.getStatusInfo(); if (statusType.getFamily() != Response.Status.Family.REDIRECTION) { return currentResponse; } AtomicInteger counter = new AtomicInteger(); Response response = currentResponse; while ((statusType.getFamily() == Response.Status.Family.REDIRECTION) && (counter.incrementAndGet() <= 3)) { String location = response.getHeaderString(HttpHeaders.LOCATION); if (StringUtils.isEmpty(location)) { return response; } if (_log.isDebugEnabled()) { _log.debug( "Redirect location {}#: {}", counter.get(), location); } response.close(); WebTarget webTarget = _client.target(location); Invocation.Builder builder = webTarget.request(APPLICATION_JSON_LD); response = builder.get(); } return response; }
@Override public Response toResponse(E exception) { // If we're dealing with a web exception, we can service certain types of request (like // redirection or server errors) better and also propagate properties of the inner response. if (exception instanceof WebApplicationException) { final Response response = ((WebApplicationException) exception).getResponse(); Response.Status.Family family = response.getStatusInfo().getFamily(); if (family.equals(Response.Status.Family.REDIRECTION)) { return response; } if (family.equals(Response.Status.Family.SERVER_ERROR)) { logException(exception); } return Response.fromResponse(response) .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorMessage(response.getStatus(), exception.getLocalizedMessage())) .build(); } // Else the thrown exception is a not a web exception, so the exception is most likely // unexpected. We'll create a unique id in the server error response that is also logged for // correlation final long id = logException(exception); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorMessage(formatErrorMessage(id, exception))) .build(); }
@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(); } } });
private Optional<SignedJwt> getAndCacheAppTokenFromServer() { MultivaluedMap<String, String> formData = new MultivaluedHashMap<>(); formData.putSingle("grant_type", "client_credentials"); formData.putSingle("scope", "urn:opc:idm:__myscopes__"); Response tokenResponse = tokenEndpoint .request() .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.form(formData)); if (tokenResponse.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { JsonObject response = tokenResponse.readEntity(JsonObject.class); String accessToken = response.getString(ACCESS_TOKEN_KEY); LOGGER.finest(() -> "Access token: " + accessToken); SignedJwt signedJwt = SignedJwt.parseToken(accessToken); this.appToken = signedJwt; this.appJwt = signedJwt.getJwt(); return Optional.of(signedJwt); } else { LOGGER.severe("Failed to obtain access token for application to read groups" + " from IDCS. Response code: " + tokenResponse.getStatus() + ", entity: " + tokenResponse.readEntity(String.class)); return Optional.empty(); } }
public class Slimclient { private static final String TARGET_URL = "http://localhost:49158/rest/service/upload"; public Slimclient() { Client client = ClientBuilder.newBuilder() .register(MultiPartFeature.class).build(); WebTarget webTarget = client.target(TARGET_URL); MultiPart multiPart = new MultiPart(); multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", new File("C:/Users/Nicklas/Desktop/aab.txt"), MediaType.APPLICATION_OCTET_STREAM_TYPE); multiPart.bodyPart(fileDataBodyPart); Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(multiPart, multiPart.getMediaType())); System.out.println(response.getStatus() + " " + response.getStatusInfo() + " " + response); } public static void main(String[] args) { new Slimclient(); } }
@Override public Response toResponse(final Exception ex) { final String errorTrackingId = UUID.randomUUID().toString(); Tuple2<String, Status> error = new Tuple2<>(MapOfExceptionsToErrorCodes.INTERNAL_SERVER_ERROR, Status.INTERNAL_SERVER_ERROR); Optional<Tuple2<String, Status>> errorFromLookup = find(ex.getClass()); if (errorFromLookup.isPresent()) { error = errorFromLookup.get(); } else { if(ex instanceof javax.ws.rs.WebApplicationException){ javax.ws.rs.WebApplicationException rsEx = ((javax.ws.rs.WebApplicationException)ex); error = tuple(rsEx.getResponse().getStatusInfo().getReasonPhrase(),Status.fromStatusCode(rsEx.getResponse().getStatus())); } } logger.error(String.format("%s Error id: %s, %s", error._1(), errorTrackingId, ex.getMessage()), ex); Response.ResponseBuilder responseBuilder = Response.status(error._2()).type(MediaType.APPLICATION_JSON_TYPE); if (showDetails) { responseBuilder.entity(new ExceptionWrapper(error._1(), String.format("Error id: %s %s", errorTrackingId, ex.getMessage()))); } else { responseBuilder.entity(new ExceptionWrapper(MapOfExceptionsToErrorCodes.INTERNAL_SERVER_ERROR, errorTrackingId)); } return responseBuilder.build(); } }
private ApioResult _invokeBuilder( String httpMethod, Invocation.Builder builder, Entity<String> entity) throws ApioException { Response response = _handleResponse(httpMethod, builder, entity); String messageEntity = response.readEntity(String.class); int statusCode = response.getStatus(); Response.StatusType statusType = response.getStatusInfo(); if (statusType.getFamily() == Response.Status.Family.SUCCESSFUL) { return new ApioResult(statusCode, messageEntity); } if (_log.isDebugEnabled()) { _log.debug( "{} request failed: {}. \n{}", httpMethod, statusCode, messageEntity); } throw new ApioException( statusCode, "Request failed: \n" + messageEntity); }
private void markProjectIndexed(Project project) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); // Successfully indexed the project. The message is sent even if // the project's isIndexed() is true because it triggers RepositoryInfo // refresh. if (project != null) { // Also need to store the correct value in configuration // when indexer writes it to a file. project.setIndexed(true); if (env.getConfigURI() != null) { Response r = ClientBuilder.newClient() .target(env.getConfigURI()) .path("api") .path("v1") .path("projects") .path(Util.URIEncode(project.getName())) .path("indexed") .request() .put(Entity.text("")); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { LOGGER.log(Level.WARNING, "Couldn''t notify the webapp that project {0} was indexed: {1}", new Object[] {project, r}); } } } }
@Override public void start(final String keywords, final DataListener msgListener) { msgListener.onStart(); running = true; final Random rnd = new Random(); final String aggregatorPrefix = getPrefix(); Executors.newSingleThreadExecutor().submit(() -> { final Client resourceClient = ClientBuilder.newClient(); resourceClient.register(new MoxyJsonFeature()); final WebTarget messageStreamResource = resourceClient.target(App.getApiUri()).path(getPath()); try { while (running) { final Message message = new Message( aggregatorPrefix + " " + MESSAGES[rnd.nextInt(MESSAGES.length)], rgbColor, IMG_URI); 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()); } Thread.sleep(rnd.nextInt(1000) + 750); } msgListener.onComplete(); } catch (Throwable t) { LOGGER.log(Level.WARNING, "Waiting for a message has been interrupted.", t); msgListener.onError(); } }); }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { if (!responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) { return; } Response resp = requestContext.getClient().target(responseContext.getLocation()).request() .method(requestContext.getMethod()); responseContext.setEntityStream((InputStream) resp.getEntity()); responseContext.setStatusInfo(resp.getStatusInfo()); responseContext.setStatus(resp.getStatus()); } }
private void requestAndTail(final String method, final ProgressHandler handler, final WebTarget resource, final Invocation.Builder request) throws DockerException, InterruptedException { Response response = request(method, Response.class, resource, request); if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new DockerRequestException(method, resource.getUri(), response.getStatus(), message(response), null); } tailResponse(method, response, handler, resource); }
/** * Get an OutboundJaxrsResponse instance for a given JAX-RS response. * * @param response response instance to from. * @return corresponding {@code OutboundJaxrsResponse} instance. */ public static OutboundJaxrsResponse from(javax.ws.rs.core.Response response) { if (response instanceof OutboundJaxrsResponse) { return (OutboundJaxrsResponse) response; } else { final StatusType status = response.getStatusInfo(); final OutboundMessageContext context = new OutboundMessageContext(); context.getHeaders().putAll(response.getMetadata()); context.setEntity(response.getEntity()); return new OutboundJaxrsResponse(status, context); } }
/** * Get an OutboundJaxrsResponse instance for a given JAX-RS response. * * @param response response instance to from. * @return corresponding {@code OutboundJaxrsResponse} instance. */ public static OutboundJaxrsResponse from(javax.ws.rs.core.Response response) { if (response instanceof OutboundJaxrsResponse) { return (OutboundJaxrsResponse) response; } else { final StatusType status = response.getStatusInfo(); final OutboundMessageContext context = new OutboundMessageContext(); context.getHeaders().putAll(response.getMetadata()); context.setEntity(response.getEntity()); return new OutboundJaxrsResponse(status, context); } }
this(response.getStatusInfo(), requestContext); this.headers(OutboundJaxrsResponse.from(response).getContext().getStringHeaders());