Java Code Examples for org.eclipse.jetty.client.api.ContentResponse#getStatus()
The following examples show how to use
org.eclipse.jetty.client.api.ContentResponse#getStatus() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CloudStore.java From athenz with Apache License 2.0 | 6 votes |
String getMetaData(String path) { final String baseUri = "http://169.254.169.254/latest"; ContentResponse response; try { response = httpClient.GET(baseUri + path); } catch (InterruptedException | ExecutionException | TimeoutException ex) { LOGGER.error("CloudStore: unable to fetch requested uri '{}':{}", path, ex.getMessage()); return null; } if (response.getStatus() != 200) { LOGGER.error("CloudStore: unable to fetch requested uri '{}' status:{}", path, response.getStatus()); return null; } String data = response.getContentAsString(); if (data == null || data.isEmpty()) { LOGGER.error("CloudStore: received empty response from uri '{}' status:{}", path, response.getStatus()); return null; } return data; }
Example 2
Source File: WebClientFactoryImplTest.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
@Test @Ignore("connecting to the outside world makes this test flaky") public void testCommonClientUsesExtensibleTrustManager() throws Exception { ArgumentCaptor<X509Certificate[]> certificateChainCaptor = ArgumentCaptor.forClass(X509Certificate[].class); ArgumentCaptor<SSLEngine> sslEngineCaptor = ArgumentCaptor.forClass(SSLEngine.class); HttpClient httpClient = webClientFactory.getCommonHttpClient(); ContentResponse response = httpClient.GET(TEST_URL); if (response.getStatus() != 200) { fail("Statuscode != 200"); } verify(extensibleTrustManager).checkServerTrusted(certificateChainCaptor.capture(), anyString(), sslEngineCaptor.capture()); verifyNoMoreInteractions(extensibleTrustManager); assertThat(sslEngineCaptor.getValue().getPeerHost(), is("www.eclipse.org")); assertThat(sslEngineCaptor.getValue().getPeerPort(), is(443)); assertThat(certificateChainCaptor.getValue()[0].getSubjectX500Principal().getName(), containsString("eclipse.org")); }
Example 3
Source File: CommonStarter.java From nem.deploy with MIT License | 6 votes |
private void stopOtherInstance(final URL stopURL) throws Exception { final HttpClient httpClient = new HttpClient(); try { httpClient.start(); LOGGER.info("Send shutdown to other instance..."); final ContentResponse response = httpClient.GET(stopURL.toURI()); if (response.getStatus() != HttpStatus.OK.value()) { LOGGER.info(String.format("Other instance returned %d: %s", response.getStatus(), response.getContentAsString())); } else { LOGGER.info("Pause 2 seconds"); Thread.sleep(2000); } } finally { httpClient.stop(); } }
Example 4
Source File: WebClientFactoryTest.java From smarthome with Eclipse Public License 2.0 | 6 votes |
@Test @Ignore("connecting to the outside world makes this test flaky") public void testCommonClientUsesExtensibleTrustManager() throws Exception { ArgumentCaptor<X509Certificate[]> certificateChainCaptor = ArgumentCaptor.forClass(X509Certificate[].class); ArgumentCaptor<SSLEngine> sslEngineCaptor = ArgumentCaptor.forClass(SSLEngine.class); HttpClient httpClient = webClientFactory.getCommonHttpClient(); ContentResponse response = httpClient.GET(TEST_URL); if (response.getStatus() != 200) { fail("Statuscode != 200"); } verify(extensibleTrustManager).checkServerTrusted(certificateChainCaptor.capture(), anyString(), sslEngineCaptor.capture()); verifyNoMoreInteractions(extensibleTrustManager); assertThat(sslEngineCaptor.getValue().getPeerHost(), is("www.eclipse.org")); assertThat(sslEngineCaptor.getValue().getPeerPort(), is(443)); assertThat(certificateChainCaptor.getValue()[0].getSubjectX500Principal().getName(), containsString("eclipse.org")); }
Example 5
Source File: HealthCheckManager.java From ja-micro with Apache License 2.0 | 5 votes |
public void updateHealthStatus(HealthCheck.Status status) throws Exception { logger.trace("Updating health of {}", serviceProps.getServiceName()); ContentResponse httpResponse = httpClient.newRequest(getHealthCheckUri(status)).method(HttpMethod.PUT).send(); if (httpResponse.getStatus() != 200) { logger.warn("Received {} trying to update health", httpResponse.getStatus()); } }
Example 6
Source File: RegistrationManager.java From ja-micro with Apache License 2.0 | 5 votes |
private boolean verifyRegistrationInConsul() { String registryServer = serviceProps.getRegistryServer(); if (StringUtils.isBlank(registryServer)) { return false; } String url = "http://" + registryServer + "/v1/catalog/service/" + serviceProps.getServiceName(); try { ContentResponse httpResponse = httpClient.newRequest(url). method(HttpMethod.GET).header(HttpHeader.CONTENT_TYPE, "application/json").send(); if (httpResponse.getStatus() != 200) { return false; } JsonArray pods = new JsonParser().parse(httpResponse.getContentAsString()).getAsJsonArray(); Iterator<JsonElement> iter = pods.iterator(); while (iter.hasNext()) { JsonElement pod = iter.next(); String serviceId = pod.getAsJsonObject().get("ServiceID").getAsString(); if (serviceProps.getServiceInstanceId().equals(serviceId)) { return true; } } } catch (Exception ex) { logger.warn("Caught exception verifying registration", ex); } return false; }
Example 7
Source File: RegistrationManager.java From ja-micro with Apache License 2.0 | 5 votes |
private boolean sendRegistration(JsonObject request) { try { ContentResponse httpResponse = httpClient.newRequest(getRegistrationUri()). content(new StringContentProvider(request.toString())). method(HttpMethod.PUT).header(HttpHeader.CONTENT_TYPE, "application/json").send(); if (httpResponse.getStatus() == 200) { return true; } } catch (Exception ex) { logger.warn("Caught exception sending registration {}", request.toString(), ex); } return false; }
Example 8
Source File: HttpCertSigner.java From athenz with Apache License 2.0 | 5 votes |
@Override public String generateX509Certificate(String csr, String keyUsage, int expireMins) { // Key Usage value used in Go - https://golang.org/src/crypto/x509/x509.go?s=18153:18173#L558 // we're only interested in ExtKeyUsageClientAuth - with value of 2 List<Integer> extKeyUsage = null; if (InstanceProvider.ZTS_CERT_USAGE_CLIENT.equals(keyUsage)) { extKeyUsage = new ArrayList<>(); extKeyUsage.add(2); } ContentResponse response = null; for (int i = 0; i < requestRetryCount; i++) { response = processX509CertRequest(csr, extKeyUsage, expireMins, i + 1); if (response != null) { break; } } if (response == null) { return null; } if (response.getStatus() != HttpStatus.CREATED_201) { LOGGER.error("unable to fetch requested uri '" + x509CertUri + "' status: " + response.getStatus()); return null; } String data = response.getContentAsString(); if (data == null || data.isEmpty()) { LOGGER.error("received empty response from uri '" + x509CertUri + "' status: " + response.getStatus()); return null; } X509CertSignObject pemCert = JSON.fromString(data, X509CertSignObject.class); return (pemCert != null) ? pemCert.getPem() : null; }
Example 9
Source File: HttpCertSigner.java From athenz with Apache License 2.0 | 5 votes |
@Override public String getCACertificate() { ContentResponse response; try { response = httpClient.GET(x509CertUri); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOGGER.error("getCACertificate: unable to fetch requested uri '" + x509CertUri + "': " + e.getMessage()); return null; } if (response.getStatus() != HttpStatus.OK_200) { LOGGER.error("getCACertificate: unable to fetch requested uri '" + x509CertUri + "' status: " + response.getStatus()); return null; } String data = response.getContentAsString(); if (data == null || data.isEmpty()) { LOGGER.error("getCACertificate: received empty response from uri '" + x509CertUri + "' status: " + response.getStatus()); return null; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("getCACertificate: CA Certificate" + data); } X509CertSignObject pemCert = JSON.fromString(data, X509CertSignObject.class); return (pemCert != null) ? pemCert.getPem() : null; }
Example 10
Source File: JettyReactiveHttpClientService.java From mutual-tls-ssl with Apache License 2.0 | 5 votes |
@Override public ClientResponse executeRequest(String url) throws Exception { httpClient.start(); ContentResponse contentResponse = httpClient.newRequest(url) .method(HttpMethod.GET) .header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue()) .send(); httpClient.stop(); return new ClientResponse(contentResponse.getContentAsString(), contentResponse.getStatus()); }
Example 11
Source File: WaveAnalyticsTarget.java From datacollector with Apache License 2.0 | 5 votes |
private void runDataflow(String dataflowId) throws StageException { try { ContentResponse response = httpClient.newRequest(restEndpoint + String.format(startDataflow, dataflowId)) .method(HttpMethod.PUT) .header("Authorization", "OAuth " + connection.getConfig().getSessionId()) .send(); int statusCode = response.getStatus(); String content = response.getContentAsString(); LOG.info("PUT dataflow with result {} content {}", statusCode, content); } catch (InterruptedException | TimeoutException | ExecutionException e) { LOG.error("PUT dataflow with result {}", e.getMessage()); throw new StageException(Errors.WAVE_03, e.getMessage(), e); } }
Example 12
Source File: AudioServletTest.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
@Test public void requestToMultitimeStreamCannotBeDoneAfterTheTimeoutOfTheStreamHasExipred() throws Exception { final int streamTimeout = 1; AudioStream audioStream = getByteArrayAudioStream(testByteArray, AudioFormat.CONTAINER_NONE, AudioFormat.CODEC_MP3); final long beg = System.currentTimeMillis(); String url = serveStream(audioStream, streamTimeout); Request request = getHttpRequest(url); ContentResponse response = request.send(); final long end = System.currentTimeMillis(); if (response.getStatus() == HttpStatus.NOT_FOUND_404) { assertThat("Response status 404 is only allowed if streamTimeout is exceeded.", TimeUnit.MILLISECONDS.toSeconds(end - beg), greaterThan((long) streamTimeout)); } else { assertThat("The response status was not as expected", response.getStatus(), is(HttpStatus.OK_200)); assertThat("The response content was not as expected", response.getContent(), is(testByteArray)); assertThat("The response media type was not as expected", response.getMediaType(), is(MEDIA_TYPE_AUDIO_MPEG)); assertThat("The audio stream was not added to the multitime streams", audioServlet.getMultiTimeStreams().containsValue(audioStream), is(true)); } waitForAssert(() -> { try { request.send(); } catch (Exception e) { throw new IllegalStateException(e); } assertThat("The audio stream was not removed from multitime streams", audioServlet.getMultiTimeStreams().containsValue(audioStream), is(false)); }); response = request.send(); assertThat("The response status was not as expected", response.getStatus(), is(HttpStatus.NOT_FOUND_404)); }
Example 13
Source File: FrontierSiliconRadioConnection.java From smarthome with Eclipse Public License 2.0 | 4 votes |
/** * Performs a request to the radio with addition parameters. * * Typically used for changing parameters. * * @param REST * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result * @throws IOException if the request failed. */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException { // 3 retries upon failure for (int i = 0; i < 3; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH + "/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '{}'", url); Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); try { ContentResponse response = request.send(); final int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { /*- * Issue: https://github.com/eclipse/smarthome/issues/2548 * If the session expired, we might get a 404 here. That's ok, remember that we are not logged-in * and try again. Print warning only if this happens in the last iteration. */ if (i >= 2) { String reason = response.getReason(); logger.warn("Method failed: {} {}", statusCode, reason); } isLoggedIn = false; continue; } final String responseBody = response.getContentAsString(); if (!responseBody.isEmpty()) { logger.trace("got result: {}", responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { return result; } isLoggedIn = false; continue; // try again } catch (Exception e) { logger.error("Fatal transport error: {}", e.toString()); throw new IOException(e); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
Example 14
Source File: FrontierSiliconRadioConnection.java From smarthome with Eclipse Public License 2.0 | 4 votes |
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests. * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH + "/CREATE_SESSION?pin=" + pin; logger.trace("opening URL: {}", url); Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); try { ContentResponse response = request.send(); int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { String reason = response.getReason(); logger.debug("Communication with radio failed: {} {}", statusCode, reason); if (statusCode == HttpStatus.FORBIDDEN_403) { throw new IllegalStateException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = response.getContentAsString(); if (!responseBody.isEmpty()) { logger.trace("login response: {}", responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (Exception e) { logger.debug("Fatal transport error: {}", e.toString()); throw new IOException(e); } return false; // login not successful }
Example 15
Source File: HttpUtil.java From smarthome with Eclipse Public License 2.0 | 4 votes |
/** * Download the data from an URL. * * @param url the URL of the data to be downloaded * @param contentTypeRegex the REGEX the content type must match; null to ignore the content type * @param scanTypeInContent true to allow the scan of data to determine the content type if not found in the headers * @param maxContentLength the maximum data size in bytes to trigger the download; any negative value to ignore the * data size * @param timeout the socket timeout in milliseconds to wait for data * @return a RawType object containing the downloaded data, null if the content type does not match the expected * type or the data size is too big */ public static RawType downloadData(String url, String contentTypeRegex, boolean scanTypeInContent, long maxContentLength, int timeout) { final ProxyParams proxyParams = prepareProxyParams(); RawType rawData = null; try { ContentResponse response = executeUrlAndGetReponse("GET", url, null, null, null, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); byte[] data = response.getContent(); if (data == null) { data = new byte[0]; } long length = data.length; String mediaType = response.getMediaType(); LOGGER.debug("Media download response: status {} content length {} media type {} (URL {})", response.getStatus(), length, mediaType, url); if (response.getStatus() != HttpStatus.OK_200 || length == 0) { LOGGER.debug("Media download failed: unexpected return code {} (URL {})", response.getStatus(), url); return null; } if (maxContentLength >= 0 && length > maxContentLength) { LOGGER.debug("Media download aborted: content length {} too big (URL {})", length, url); return null; } String contentType = mediaType; if (contentTypeRegex != null) { if ((contentType == null || contentType.isEmpty()) && scanTypeInContent) { // We try to get the type from the data contentType = guessContentTypeFromData(data); LOGGER.debug("Media download: content type from data: {} (URL {})", contentType, url); } if (contentType != null && contentType.isEmpty()) { contentType = null; } if (contentType == null) { LOGGER.debug("Media download aborted: unknown content type (URL {})", url); return null; } else if (!contentType.matches(contentTypeRegex)) { LOGGER.debug("Media download aborted: unexpected content type \"{}\" (URL {})", contentType, url); return null; } } else if (contentType == null || contentType.isEmpty()) { contentType = RawType.DEFAULT_MIME_TYPE; } rawData = new RawType(data, contentType); LOGGER.debug("Media downloaded: size {} type {} (URL {})", rawData.getBytes().length, rawData.getMimeType(), url); } catch (IOException e) { LOGGER.debug("Media download failed (URL {}) : {}", url, e.getMessage()); } return rawData; }
Example 16
Source File: OAuthConnector.java From smarthome with Eclipse Public License 2.0 | 4 votes |
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request, Fields fields) throws OAuthResponseException, OAuthException, IOException { int statusCode = 0; String content = ""; try { final FormContentProvider entity = new FormContentProvider(fields); final ContentResponse response = AccessController .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> { Request requestWithContent = request.content(entity); return requestWithContent.send(); }); statusCode = response.getStatus(); content = response.getContentAsString(); if (statusCode == HttpStatus.OK_200) { AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class); jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response logger.info("grant type {} to URL {} success", grantType, request.getURI()); return jsonResponse; } else if (statusCode == HttpStatus.BAD_REQUEST_400) { OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class); logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType, request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription()); throw errorResponse; } else { logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(), statusCode); throw new OAuthException("Bad http response, http code " + statusCode); } } catch (PrivilegedActionException pae) { Exception underlyingException = pae.getException(); if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException || underlyingException instanceof ExecutionException) { throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException); } // Dont know what exception it is, wrap it up and throw it out throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException); } catch (JsonSyntaxException e) { throw new OAuthException(String.format( "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s", statusCode, content), e); } }
Example 17
Source File: SolrFulltextSearchImpl.java From database with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("deprecation") private FulltextSearchHit[] queryIndex( FulltextSearchQuery query, HttpClient httpClient) throws Exception { if (httpClient.isStopped()) { throw new FulltextSearchException("The client has been stopped"); } Request request = httpClient.newRequest(query.getEndpoint()); // Limit response content buffer to 512 KiB FutureResponseListener listener = new FutureResponseListener(request, 10 * 1024 * 1024); // 100 MB size request.param("q", query.getQuery()); request.param("wt", "json"); final String searchParams = query.getParams(); if (searchParams!=null && !searchParams.isEmpty()) { final String[] params = searchParams.split("&"); for (int i=0; i<params.length; i++) { if (params[i]!=null) { String kv[] = params[i].split("="); if (kv.length==2 && kv[0]!=null && !(kv[0].isEmpty())) { if (!(kv[0].equals("wt"))) { try { final String val = kv[1]==null ? "" : URLDecoder.decode(kv[1], "UTF-8"); request.param(kv[0], val); } catch (Exception e) { if (log.isInfoEnabled()) { log.info("Solr search param: '" + params[i] + "'" + "' can't be URL decoded. Will be ignored..."); } } } } else { if (log.isInfoEnabled()) { log.info("Invalid Solr search param: '" + params[i] + "'"); log.info("Will be ignored..."); } } } } } final Integer queryTimeoutSpecified = query.getSearchTimeout(); final Integer queryTimeoutUsed = queryTimeoutSpecified==null ? FTS.Options.DEFAULT_TIMEOUT : queryTimeoutSpecified; request.send(listener); ContentResponse resp = listener.get(queryTimeoutUsed, TimeUnit.MILLISECONDS); final int statusCode = resp.getStatus(); if (statusCode != 200) { throw new FulltextSearchException("Status code != 200 received from " + "external fulltext service: " + statusCode); } final String jsonStr = resp.getContentAsString(); final JSONObject json = new JSONObject(jsonStr); return constructFulltextSearchList(json, query); }
Example 18
Source File: OAuthConnector.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request, Fields fields) throws OAuthResponseException, OAuthException, IOException { int statusCode = 0; String content = ""; try { final FormContentProvider entity = new FormContentProvider(fields); final ContentResponse response = AccessController .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> { Request requestWithContent = request.content(entity); return requestWithContent.send(); }); statusCode = response.getStatus(); content = response.getContentAsString(); if (statusCode == HttpStatus.OK_200) { AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class); jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response logger.debug("grant type {} to URL {} success", grantType, request.getURI()); return jsonResponse; } else if (statusCode == HttpStatus.BAD_REQUEST_400) { OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class); logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType, request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription()); throw errorResponse; } else { logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(), statusCode); throw new OAuthException("Bad http response, http code " + statusCode); } } catch (PrivilegedActionException pae) { Exception underlyingException = pae.getException(); if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException || underlyingException instanceof ExecutionException) { throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException); } // Dont know what exception it is, wrap it up and throw it out throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException); } catch (JsonSyntaxException e) { throw new OAuthException(String.format( "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s", statusCode, content), e); } }
Example 19
Source File: HttpUtil.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
/** * Download the data from an URL. * * @param url the URL of the data to be downloaded * @param contentTypeRegex the REGEX the content type must match; null to ignore the content type * @param scanTypeInContent true to allow the scan of data to determine the content type if not found in the headers * @param maxContentLength the maximum data size in bytes to trigger the download; any negative value to ignore the * data size * @param timeout the socket timeout in milliseconds to wait for data * @return a RawType object containing the downloaded data, null if the content type does not match the expected * type or the data size is too big */ public static RawType downloadData(String url, String contentTypeRegex, boolean scanTypeInContent, long maxContentLength, int timeout) { final ProxyParams proxyParams = prepareProxyParams(); RawType rawData = null; try { ContentResponse response = executeUrlAndGetReponse("GET", url, null, null, null, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); byte[] data = response.getContent(); if (data == null) { data = new byte[0]; } long length = data.length; String mediaType = response.getMediaType(); LOGGER.debug("Media download response: status {} content length {} media type {} (URL {})", response.getStatus(), length, mediaType, url); if (response.getStatus() != HttpStatus.OK_200 || length == 0) { LOGGER.debug("Media download failed: unexpected return code {} (URL {})", response.getStatus(), url); return null; } if (maxContentLength >= 0 && length > maxContentLength) { LOGGER.debug("Media download aborted: content length {} too big (URL {})", length, url); return null; } String contentType = mediaType; if (contentTypeRegex != null) { if ((contentType == null || contentType.isEmpty()) && scanTypeInContent) { // We try to get the type from the data contentType = guessContentTypeFromData(data); LOGGER.debug("Media download: content type from data: {} (URL {})", contentType, url); } if (contentType != null && contentType.isEmpty()) { contentType = null; } if (contentType == null) { LOGGER.debug("Media download aborted: unknown content type (URL {})", url); return null; } else if (!contentType.matches(contentTypeRegex)) { LOGGER.debug("Media download aborted: unexpected content type \"{}\" (URL {})", contentType, url); return null; } } else if (contentType == null || contentType.isEmpty()) { contentType = RawType.DEFAULT_MIME_TYPE; } rawData = new RawType(data, contentType); LOGGER.debug("Media downloaded: size {} type {} (URL {})", rawData.getBytes().length, rawData.getMimeType(), url); } catch (IOException e) { LOGGER.debug("Media download failed (URL {}) : {}", url, e.getMessage()); } return rawData; }
Example 20
Source File: JerseyUnixSocketConnector.java From tessera with Apache License 2.0 | 4 votes |
private ClientResponse doApply(ClientRequest request) throws Exception { HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod()); final URI originalUri = request.getUri(); final URI uri; Path basePath = Paths.get(unixfile); if (originalUri.getScheme().startsWith("unix")) { String path = originalUri.getRawPath() .replaceFirst(basePath.toString(), ""); LOGGER.trace("Extracted path {} from {}",path, originalUri.getRawPath()); uri = UriBuilder.fromUri(originalUri) .replacePath(path) .scheme("http") .port(99) .host("localhost") .build(); LOGGER.trace("Created psuedo uri {} for originalUri {}", uri, originalUri); } else { uri = originalUri; } Request clientRequest = httpClient.newRequest(uri) .method(httpMethod); MultivaluedMap<String, Object> headers = request.getHeaders(); headers.keySet().stream().forEach(name -> { headers.get(name).forEach(value -> { clientRequest.header(name, Objects.toString(value)); }); }); if (request.hasEntity()) { final long length = request.getLengthLong(); try (ByteArrayOutputStream bout = new ByteArrayOutputStream()){ request.setStreamProvider((int contentLength) -> bout); request.writeEntity(); ContentProvider content = new BytesContentProvider(bout.toByteArray()); clientRequest.content(content); } } final ContentResponse contentResponse = clientRequest.send(); int statusCode = contentResponse.getStatus(); String reason = contentResponse.getReason(); LOGGER.trace("uri {}, method: {},statusCode:{},reason: {} ", uri, httpMethod, statusCode, reason); final Response.StatusType status = Statuses.from(statusCode, reason); ClientResponse response = new ClientResponse(status, request); contentResponse.getHeaders().stream() .forEach(header -> { response.headers(header.getName(), (Object[]) header.getValues()); }); response.setEntityStream(new ByteArrayInputStream(contentResponse.getContent())); return response; }