final ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); throw new ProcessingException(ex); } finally { try { in.close(); } catch (IOException ex) { throw new ProcessingException(ex); context.setEntity(new ByteArrayInputStream(out.toByteArray())); buffered = true; return true;
private static boolean shouldRetry( final Optional<Integer> readTimeoutMs, final ProcessingException e ) { return readTimeoutMs.map(timeout -> timeout < MAX_TIMEOUT).orElse(false) && e.getCause() instanceof SocketTimeoutException; }
try { if (!wadlContext.isWadlGenerationEnabled()) { return Response.status(Response.Status.NOT_FOUND).build(); final Marshaller marshaller = wadlContext.getJAXBContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); final ByteArrayOutputStream os = new ByteArrayOutputStream(); marshaller.marshal(application, os); wadlXmlRepresentation = os.toByteArray(); os.close(); } catch (Exception e) { throw new ProcessingException("Could not marshal the wadl Application.", e); return Response.ok(new ByteArrayInputStream(wadlXmlRepresentation)).header("Last-modified", lastModified).build(); } catch (Exception e) { throw new ProcessingException("Error generating /application.wadl.", e);
private byte[] bufferEntity(final ClientRequest requestContext) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); requestContext.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return baos; } }); try { requestContext.writeEntity(); } catch (final IOException ioe) { throw new ProcessingException("Error buffering the entity.", ioe); } return baos.toByteArray(); }
clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate); containerRequest.getHeaders().putAll(clientRequest.getStringHeaders()); final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream(); if (clientRequest.getEntity() != null) { clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { final String msg = "Error while writing entity to the output stream."; LOGGER.log(Level.SEVERE, msg, e); throw new ProcessingException(msg, e); containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray())); boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(),
for (Map.Entry<String, List<Object>> entry : response.getMetadata().entrySet()) setStatus(response.getStatus()); setEntity(response.getEntity()); if (response instanceof BuiltResponse) { BuiltResponse built = (BuiltResponse) response; null, mediaType); if (writer == null) { throw new ProcessingException(Messages.MESSAGES.failedToBufferAbortedResponseNoWriter(mediaType, entityClass.getName())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { writer.writeTo(getEntity(), getEntityClass(), getGenericType(), getAnnotations(), mediaType, getHeaders(), baos); throw new ProcessingException(Messages.MESSAGES.failedToBufferAbortedResponse(), e); bufferedEntity = baos.toByteArray(); setInputStream(new ByteArrayInputStream(bufferedEntity));
/** * {@inheritDoc} */ @Override public ClientResponse apply(ClientRequest jerseyRequest) { try { final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest); final CloseableHttpResponse apacheResponse = client.execute(apacheRequest); final StatusLine statusLine = apacheResponse.getStatusLine(); final String reasonPhrase = Strings.nullToEmpty(statusLine.getReasonPhrase()); final Response.StatusType status = Statuses.from(statusLine.getStatusCode(), reasonPhrase); final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest); for (Header header : apacheResponse.getAllHeaders()) { jerseyResponse.getHeaders().computeIfAbsent(header.getName(), k -> new ArrayList<>()) .add(header.getValue()); } final HttpEntity httpEntity = apacheResponse.getEntity(); jerseyResponse.setEntityStream(httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0])); return jerseyResponse; } catch (Exception e) { throw new ProcessingException(e); } }
final String requestURIPath = requestURI.getPath(); final String schemaPath = rootURI != null ? requestURI.relativize(schemaURI).toString() : schemaURI.toString(); throw new ProcessingException(LocalizationMessages.ERROR_WADL_EXTERNAL_GRAMMAR(), e);
@Override public URI apply(String value) { try { return value == null ? null : URI.create(value); } catch (IllegalArgumentException ex) { throw new ProcessingException(ex); } } }, false);
final boolean start) { final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST : uri.getHost(); final int port = (uri.getPort() == -1) ? (secure ? Container.DEFAULT_HTTPS_PORT : Container.DEFAULT_HTTP_PORT) : uri.getPort(); } catch (final IOException ex) { server.shutdownNow(); throw new ProcessingException(LocalizationMessages.FAILED_TO_START_SERVER(ex.getMessage()), ex);
@Test public void shouldPrintErrorIfCantConnectToRestServer() throws Exception { givenRunInteractivelyWillExit(); final KsqlRestClient mockRestClient = EasyMock.mock(KsqlRestClient.class); EasyMock.expect(mockRestClient.makeRootRequest()).andThrow(new KsqlRestClientException("Boom", new ProcessingException(""))); EasyMock.expect(mockRestClient.getServerInfo()).andReturn( RestResponse.of(new ServerInfo("1.x", "testClusterId", "testServiceId"))); EasyMock.expect(mockRestClient.getServerAddress()).andReturn(new URI("http://someserver:8008")).anyTimes(); EasyMock.replay(mockRestClient); new Cli(1L, 1L, mockRestClient, console) .runInteractively(); assertThat(terminal.getOutputString(), containsString("Remote server address may not be valid")); }
final URI u = getProxyUri(proxyUri); final ProxyConfiguration proxyConfig = client.getProxyConfiguration(); proxyConfig.getProxies().add(new HttpProxy(u.getHost(), u.getPort())); client.start(); } catch (final Exception e) { throw new ProcessingException("Failed to start the client.", e);
@Produces({"application/xml"}) @GET @Path("{path}") public synchronized Response getExternalGrammar( @Context UriInfo uriInfo, @PathParam("path") String path) { try { // Fail if wadl generation is disabled if (!wadlContext.isWadlGenerationEnabled()) { return Response.status(Response.Status.NOT_FOUND).build(); } ApplicationDescription applicationDescription = wadlContext.getApplication(uriInfo, WadlUtils.isDetailedWadlRequested(uriInfo)); // Fail is we don't have any metadata for this path ApplicationDescription.ExternalGrammar externalMetadata = applicationDescription.getExternalGrammar(path); if (externalMetadata == null) { return Response.status(Response.Status.NOT_FOUND).build(); } // Return the data return Response.ok().type(externalMetadata.getType()) .entity(externalMetadata.getContent()) .build(); } catch (Exception e) { throw new ProcessingException(LocalizationMessages.ERROR_WADL_RESOURCE_EXTERNAL_GRAMMAR(), e); } }
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build(); } else { try { throw new ProcessingException(LocalizationMessages.ERROR_RESOURCE_JAVA_METHOD_INVOCATION(), ex); } catch (InvocationTargetException ex) { throw mapTargetToRuntimeEx(ex.getCause()); } catch (Throwable t) { throw new ProcessingException(t); } finally { tracingLogger.logDuration(ServerTraceEvent.METHOD_INVOKE, timestamp, resource, method);
} catch (ProcessingException e) { throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e); r.code = response.getStatus(); r.headers = response.getStringHeaders(); if (response.hasEntity()) { r.body = response.readEntity(String.class);
@Override public TokenResult refreshAccessToken(final String refreshToken) { refreshTokenProperties.put(OAuth2Parameters.REFRESH_TOKEN, refreshToken); final Form form = new Form(); for (final Map.Entry<String, String> entry : refreshTokenProperties.entrySet()) { form.param(entry.getKey(), entry.getValue()); } final Response response = client.target(refreshTokenUri) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != 200) { throw new ProcessingException(LocalizationMessages.ERROR_FLOW_REQUEST_REFRESH_TOKEN(response.getStatus())); } this.tokenResult = response.readEntity(TokenResult.class); return tokenResult; }
static void handleResponse(Response response) throws ScimException { try { if (!RestClientUtil.isSuccessful(response)) { Status status = Status.fromStatusCode(response.getStatus()); ErrorResponse errorResponse = response.readEntity(ErrorResponse.class); throw new ScimException(errorResponse, status); } } catch (ProcessingException e) { ErrorResponse er = new ErrorResponse(Status.INTERNAL_SERVER_ERROR, e.getMessage()); throw new ScimException(er, Status.INTERNAL_SERVER_ERROR); } finally { RestClientUtil.close(response); } }
/** * Invokes the given request * * @param <R> the return type * @param request the request to invoke * @return the response * @throws Exception the exception */ private <R> HttpResponse invoke(HttpRequest<R> request) throws Exception { HttpCommand<R> command = HttpCommand.create(request); try { return invokeRequest(command); } catch (ProcessingException pe) { throw new ConnectionException(pe.getMessage(), 0, pe); } catch (ClientErrorException e) { throw ResponseException.mapException(e.getResponse().getStatusInfo().toString(), e.getResponse().getStatus(), e); } }
private void awaitServerStartup() throws Exception { Instant started = Instant.now(); long elapsed = Duration.between(started, Instant.now()).toMillis(); WebClient client = WebClient.create(endPoint+"/tika").accept("text/plain"); while (elapsed < 30000) { try { Response response = client.get(); if (response.getStatus() == 200) { return; } LOG.info("tika test client failed to connect to server with status: {}", response.getStatus()); } catch (javax.ws.rs.ProcessingException e) { LOG.info("tika test client failed to connect to server: {}", e.getMessage()); LOG.debug("tika test client failed to connect to server", e); } Thread.sleep(100); elapsed = Duration.between(started, Instant.now()).toMillis(); } }
private T getResponse(Response response) { Family statusFamily = response.getStatusInfo().getFamily(); if (response.getMediaType().getSubtype().equals(MediaType.APPLICATION_JSON_TYPE.getSubtype())) { try { if (statusFamily == Family.INFORMATIONAL || statusFamily == Family.SUCCESSFUL) { T content = response.readEntity(respContentClass); return content; } else { JsonResponse jsonRes = response.readEntity(JsonResponse.class); throw new IllegalStateException(jsonRes.getErrorMsg()); } } catch (ProcessingException e) { throw new IllegalStateException(e.getMessage()); } } else { throw new IllegalStateException("Cannot Connect To Server."); } }