List of usage examples for org.apache.http.client HttpResponseException getMessage
public String getMessage()
From source file:org.sakaiproject.hybrid.util.NakamuraAuthenticationHelper.java
/** * Calls Nakamura to determine the identity of the current user. * //w w w . j a v a 2 s . c o m * @param request * @return null if user cannot be authenticated. * @throws IllegalArgumentException * @throws IllegalStateException * For all unexpected cause Exceptions. */ public AuthInfo getPrincipalLoggedIntoNakamura(final HttpServletRequest request) { LOG.debug("getPrincipalLoggedIntoNakamura(HttpServletRequest request)"); if (request == null) { throw new IllegalArgumentException("HttpServletRequest == null"); } final Object cache = threadLocalManager.get(THREAD_LOCAL_CACHE_KEY); if (cache instanceof AuthInfo) { LOG.debug("cache hit!"); return (AuthInfo) cache; } @SuppressWarnings("PMD.DataflowAnomalyAnalysis") AuthInfo authInfo = null; final String secret = getSecret(request); if (secret != null) { final HttpClient httpClient = httpClientProvider.getHttpClient(); try { final URI uri = new URI(validateUrl + secret); final HttpGet httpget = new HttpGet(uri); // authenticate to Nakamura using x-sakai-token mechanism final String token = xSakaiToken.createToken(hostname, principal); httpget.addHeader(XSakaiToken.X_SAKAI_TOKEN_HEADER, token); // final ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String responseBody = httpClient.execute(httpget, responseHandler); authInfo = new AuthInfo(responseBody); } catch (HttpResponseException e) { // usually a 404 error - could not find cookie / not valid if (LOG.isDebugEnabled()) { LOG.debug("HttpResponseException: " + e.getMessage() + ": " + e.getStatusCode() + ": " + validateUrl + secret); } } catch (Exception e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } finally { httpClient.getConnectionManager().shutdown(); } } // cache results in thread local threadLocalManager.set(THREAD_LOCAL_CACHE_KEY, authInfo); return authInfo; }
From source file:edu.vt.vbi.patric.common.DataApiHandler.java
public String get(Map<String, String> headers, String url) { String responseBody = null;/*from w w w. j av a 2s . com*/ try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(baseUrl + url); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } if (headers == null || !headers.containsKey("accept")) { request.addHeader("Accept", "application/json"); } if (token != null) { request.setHeader("Authorization", token); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseBody = client.execute(request, responseHandler); } catch (HttpResponseException e) { if (e.getMessage().equals("Unauthorized")) { // handle unauthorized case LOGGER.debug(e.getMessage()); } else if (e.getMessage().equals("Not Found")) { LOGGER.debug("{} - request url: {}", e.getMessage(), url); } else { LOGGER.error(e.getMessage(), e); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return responseBody; }
From source file:com.postmark.PostmarkMailSender.java
@Override public void send(SimpleMailMessage message) throws MailException { HttpClient httpClient = new DefaultHttpClient(); PostmarkResponse theResponse = new PostmarkResponse(); try {//from ww w.jav a 2s . c o m // Create post request to Postmark API endpoint HttpPost method = new HttpPost("http://api.postmarkapp.com/email"); // Add standard headers required by Postmark method.addHeader("Accept", "application/json"); method.addHeader("Content-Type", "application/json; charset=utf-8"); method.addHeader("X-Postmark-Server-Token", serverToken); method.addHeader("User-Agent", "Postmark-Java"); // Convert the message into JSON content String messageContents = UnicodeEscapeFilterWriter.escape(gson.toJson(message)); logger.log(Level.FINER, "Message contents: " + messageContents); // Add JSON as payload to post request StringEntity payload = new StringEntity(messageContents); payload.setContentEncoding(HTTP.UTF_8); method.setEntity(payload); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { String response = httpClient.execute(method, responseHandler); logger.log(Level.FINER, "Message response: " + response); theResponse = gson.fromJson(response, PostmarkResponse.class); theResponse.status = PostmarkResponseStatus.SUCCESS; } catch (HttpResponseException hre) { switch (hre.getStatusCode()) { case 401: case 422: logger.log(Level.SEVERE, "There was a problem with the email: " + hre.getMessage()); theResponse.setMessage(hre.getMessage()); theResponse.status = PostmarkResponseStatus.USERERROR; throw new MailSendException("Postmark returned: " + theResponse); case 500: logger.log(Level.SEVERE, "There has been an error sending your email: " + hre.getMessage()); theResponse.setMessage(hre.getMessage()); theResponse.status = PostmarkResponseStatus.SERVERERROR; throw new MailSendException("Postmark returned: " + theResponse); default: logger.log(Level.SEVERE, "There has been an unknow error sending your email: " + hre.getMessage()); theResponse.status = PostmarkResponseStatus.UNKNOWN; theResponse.setMessage(hre.getMessage()); throw new MailSendException("Postmark returned: " + theResponse); } } } catch (Exception e) { logger.log(Level.SEVERE, "There has been an error sending email: " + e.getMessage()); throw new MailSendException("There has been an error sending email", e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.osbitools.ws.shared.web.BasicWebUtils.java
public WebResponse uploadFile(String path, String fname, InputStream in, String stoken) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA); builder.addPart("fname", fn); builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname); BasicCookieStore cookieStore = new BasicCookieStore(); if (stoken != null) { BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken); cookie.setDomain(TestConstants.JETTY_HOST); cookie.setPath("/"); cookieStore.addCookie(cookie);/* www . j av a 2s .c o m*/ } TestConstants.LOG.debug("stoken=" + stoken); HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); String body; ResponseHandler<String> handler = new BasicResponseHandler(); try { body = handler.handleResponse(response); } catch (HttpResponseException e) { return new WebResponse(e.getStatusCode(), e.getMessage()); } return new WebResponse(response.getStatusLine().getStatusCode(), body); }
From source file:io.logspace.agent.hq.HqAgentController.java
@Override public void update(Date nextFireTime) { try {/*from www.j ava2 s . c o m*/ this.uploadCapabilities(); } catch (UnknownHostException uhex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", uhex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (NoRouteToHostException nrthex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", nrthex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (ConnectException cex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", cex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (IOException ioex) { this.logger.error("Failed to upload capabilities. Will retry at " + nextFireTime, ioex); } try { this.downloadOrder(); } catch (ConnectException cex) { this.logger.error("Could not download orders because the HQ was not available: {} - Will retry at {}", cex.getMessage(), nextFireTime); } catch (HttpResponseException hrex) { if (hrex.getStatusCode() == HTTP_NOT_FOUND) { this.logger.error("There was no order available: {} - Will retry at {}", hrex.getMessage(), nextFireTime); } else if (hrex.getStatusCode() == HTTP_FORBIDDEN) { this.logger.error("Not allowed to download order: {} - Will retry at {}", hrex.getMessage(), nextFireTime); } else { this.logger.error("Failed to download order. Will retry at {}", nextFireTime, hrex); } } catch (IOException ioex) { this.logger.error("Failed to download order. Will retry at {}", nextFireTime, ioex); } }
From source file:com.jaspersoft.studio.server.protocol.ProxyConnection.java
@Override public ResourceDescriptor get(IProgressMonitor monitor, ResourceDescriptor rd, File f) throws Exception { if (useSoap(monitor, rd) && soap != null) rd = soap.get(monitor, rd, f);/*from w w w . ja v a 2 s . c o m*/ else try { rd = c.get(monitor, rd, f); } catch (Exception e) { if (e instanceof HttpResponseException) { HttpResponseException he = (HttpResponseException) e; if (he.getStatusCode() == 500 && he.getMessage().contains("Unexpected error")) { if (soap == null) throw e; rd = soap.get(monitor, rd, f); rd.setChildrenDirty(false); return rd; } else if (he.getStatusCode() == 403) { try { if (soap == null) throw e; rd = soap.get(monitor, rd, f); rd.setChildrenDirty(false); } catch (Exception e1) { // let's keep original exception , we tried, but it // not works on soap e1.printStackTrace(); throw he; } return rd; } else if (he.getStatusCode() == 401 && !error401) { c.connect(monitor, getServerProfile()); error401 = true; return get(monitor, rd, f); } } error401 = false; throw e; } if (rd != null) rd.setChildrenDirty(false); error401 = false; return rd; }
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
private String getEntityJSON(UriInfo uriInfo) { try {// w w w. jav a 2 s.c o m MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); StringBuilder builder = new StringBuilder(); Set<String> keys = queryParameters.keySet(); for (String k : keys) { for (String v : queryParameters.get(k)) { if (k.equals("fl")) { checkFieldSettings(v); } String value = URLEncoder.encode(v, "UTF-8"); value = checkHighlightValues(k, value); builder.append(k + "=" + value); builder.append("&"); } } InputStream istream = this.solrAccess.request(builder.toString(), "json"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copyStreams(istream, bos); String rawString = new String(bos.toByteArray(), "UTF-8"); String uri = UriBuilder.fromResource(SearchResource.class).path("").build().toString(); JSONObject jsonObject = changeJSONResult(rawString, uri, this.jsonDecoratorAggregates.getDecorators()); return jsonObject.toString(); } catch (HttpResponseException e) { if (e.getStatusCode() == SC_BAD_REQUEST) { LOGGER.log(Level.INFO, "SOLR Bad Request: " + uriInfo.getRequestUri()); throw new BadRequestException(e.getMessage()); } else { LOGGER.log(Level.INFO, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } catch (JSONException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } }
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
private String getEntityXML(UriInfo uriInfo) { try {// w w w .j a va2 s.c om MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); StringBuilder builder = new StringBuilder(); Set<String> keys = queryParameters.keySet(); for (String k : keys) { for (String v : queryParameters.get(k)) { if (k.equals("fl")) { checkFieldSettings(v); } String value = URLEncoder.encode(v, "UTF-8"); value = checkHighlightValues(k, value); builder.append(k + "=" + value); builder.append("&"); } } InputStream istream = this.solrAccess.request(builder.toString(), "xml"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copyStreams(istream, bos); String rawString = new String(bos.toByteArray(), "UTF-8"); String uri = UriBuilder.fromResource(SearchResource.class).path("").build().toString(); Document domObject = changeXMLResult(rawString, uri); StringWriter strWriter = new StringWriter(); XMLUtils.print(domObject, strWriter); return strWriter.toString(); } catch (HttpResponseException e) { if (e.getStatusCode() == SC_BAD_REQUEST) { LOGGER.log(Level.INFO, "SOLR Bad Request: " + uriInfo.getRequestUri()); throw new BadRequestException(e.getMessage()); } else { LOGGER.log(Level.INFO, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } catch (TransformerException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } catch (ParserConfigurationException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } catch (SAXException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new GenericApplicationException(e.getMessage()); } }
From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java
protected <R> R doHttpGet(URI requestUri, ResponseHandler<R> responseHandler) throws DataAdapterException { try (Profiler p = Profiler.start("Executing HTTP request: [" + requestUri.toString() + "]", logger::trace)) {/* ww w.j av a2 s .c o m*/ logger.debug(() -> "requestUri = " + requestUri); HttpGet httpget = new HttpGet(requestUri); // Set user-agent pattern to workaround CAS server not proposing SPNEGO authentication unless it thinks agent can handle it. httpget.setHeader("User-Agent", "binjr/" + AppEnvironment.getInstance().getVersion() + " (Authenticates like: Firefox/Safari/Internet Explorer)"); R result = httpClient.execute(httpget, responseHandler); if (result == null) { throw new FetchingDataFromAdapterException( "Response entity to \"" + requestUri.toString() + "\" is null."); } return result; } catch (HttpResponseException e) { String msg; switch (e.getStatusCode()) { case 401: msg = "Authentication failed while trying to access \"" + requestUri.toString() + "\""; break; case 403: msg = "Access to the resource at \"" + requestUri.toString() + "\" is denied."; break; case 404: msg = "The resource at \"" + requestUri.toString() + "\" could not be found."; break; case 500: msg = "A server-side error has occurred while trying to access the resource at \"" + requestUri.toString() + "\": " + e.getMessage(); break; default: msg = "Error executing HTTP request \"" + requestUri.toString() + "\": " + e.getMessage(); break; } throw new SourceCommunicationException(msg, e); } catch (ConnectException e) { throw new SourceCommunicationException(e.getMessage(), e); } catch (UnknownHostException e) { throw new SourceCommunicationException("Host \"" + baseAddress.getHost() + (baseAddress.getPort() > 0 ? ":" + baseAddress.getPort() : "") + "\" could not be found.", e); } catch (IOException e) { throw new SourceCommunicationException("IO error while communicating with host \"" + baseAddress.getHost() + (baseAddress.getPort() > 0 ? ":" + baseAddress.getPort() : "") + "\"", e); } catch (Exception e) { throw new SourceCommunicationException("Unexpected error in HTTP GET", e); } }