List of usage examples for org.apache.http.client HttpResponseException getStatusCode
public int getStatusCode()
From source file:com.streamsets.stage.destination.waveanalytics.WaveAnalyticsTarget.java
private void putDataflowJson(String dataflowId, String payload) throws IOException { try {/*from w ww . jav a 2 s . co m*/ HttpResponse res = Request.Patch(restEndpoint + String.format(dataflowJson, dataflowId)) .addHeader("Authorization", "OAuth " + connection.getConfig().getSessionId()) .bodyString(payload, ContentType.APPLICATION_JSON).execute().returnResponse(); int statusCode = res.getStatusLine().getStatusCode(); String content = EntityUtils.toString(res.getEntity()); LOG.info("PATCH dataflow with result {} content {}", statusCode, content); } catch (HttpResponseException e) { LOG.error("PATCH dataflow with result {} {}", e.getStatusCode(), e.getMessage()); throw e; } }
From source file:io.logspace.agent.hq.HqAgentController.java
@Override public void update(Date nextFireTime) { try {// www . j ava 2 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.offbytwo.jenkins.model.JobWithDetails.java
/** * * <ul>//w ww. j a v a 2 s.c o m * <li>{M,N}: From the M-th element (inclusive) to the N-th element * (exclusive).</li> * <li>{M,}: From the M-th element (inclusive) to the end.</li> * <li>{,N}: From the first element (inclusive) to the N-th element * (exclusive). The same as {0,N}.</li> * <li>{N}: Just retrieve the N-th element. The same as {N,N+1}.</li> * </ul> * * <b>Note: At the moment there seemed to be no option to get the number of * existing builds for a job. The only option is to get all builds via * {@link #getAllBuilds()}.</b> * * @param range {@link Range} * @return the list of {@link Build}. In case of no builds have been * executed yet return {@link Collections#emptyList()}. * @throws IOException in case of an error. */ public List<Build> getAllBuilds(Range range) throws IOException { String path = "/" + "job/" + EncodingUtils.encode(this.getName()) + "?tree=allBuilds[number[*],url[*],queueId[*]]"; try { List<Build> builds = client.get(path + range.getRangeString(), AllBuilds.class).getAllBuilds(); if (builds == null) { return Collections.emptyList(); } else { return transform(builds, new Function<Build, Build>() { @Override public Build apply(Build from) { return buildWithClient(from); } }); } } catch (HttpResponseException e) { // TODO: Thinks about a better handline if the job does not exist? if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { // TODO: Check this if this is necessary or a good idea? return null; } throw e; } }
From source file:com.offbytwo.jenkins.model.JobWithDetails.java
/** * This method will give you back all builds which exists independent of the * number. You should be aware that this can be much in some cases if you * have more than 100 builds which is by default limited by Jenkins * {@link #getBuilds()}. This method limits it to particular information * which can be later used to get supplemental information about a * particular build {@link Build#details()} to reduce the amount of data * which needed to be transfered./*ww w. ja v a2 s .c o m*/ * * @return the list of {@link Build}. In case of no builds have been * executed yet return {@link Collections#emptyList()}. * @throws IOException * In case of failure. * @see <a href="https://issues.jenkins-ci.org/browse/JENKINS-30238">Jenkins * Issue</a> */ public List<Build> getAllBuilds() throws IOException { String path = "/"; try { List<Build> builds = client.get(path + "job/" + EncodingUtils.encode(this.getName()) + "?tree=allBuilds[number[*],url[*],queueId[*]]", AllBuilds.class).getAllBuilds(); if (builds == null) { return Collections.emptyList(); } else { return transform(builds, new Function<Build, Build>() { @Override public Build apply(Build from) { return buildWithClient(from); } }); } } catch (HttpResponseException e) { // TODO: Thinks about a better handline if the job does not exist? if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { // TODO: Check this if this is necessary or a good idea? return null; } throw e; } }
From source file:com.binaryelysium.mp3tunes.api.Locker.java
public boolean testSession() { String text;/*from ww w.j ava 2 s . co m*/ try { text = HttpClientCaller.getInstance() .callNoFixSession(new RemoteMethod.Builder(RemoteMethod.METHODS.LAST_UPDATE) .addParam("type", UpdateType.locker.toString()).create()); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) { return false; } e.printStackTrace(); return true; } catch (IOException e) { e.printStackTrace(); return true; } catch (InvalidSessionException e) { e.printStackTrace(); return false; } catch (LockerException e) { e.printStackTrace(); return false; } catch (LoginException e) { e.printStackTrace(); return false; } try { JSONObject json = new JSONObject(text); if (json.getInt("status") == 1) return true; else { int error = json.getInt("errorCode"); if (error == 401001) return false; String errorStr = Integer.toString(error); Log.e("Mp3Tunes", "Got error " + errorStr + " testing for valid session"); } } catch (JSONException e) { e.printStackTrace(); return true; } return false; }
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
private String getEntityJSON(UriInfo uriInfo) { try {/*from w w w. ja va 2s.co 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:org.sakaiproject.hybrid.util.NakamuraAuthenticationHelper.java
/** * Calls Nakamura to determine the identity of the current user. * //from w w w.j a v a 2s . com * @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:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
private String getEntityXML(UriInfo uriInfo) { try {/*w ww .j av a2 s.co 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(), "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:org.tellervo.desktop.wsi.WebJaxbAccessor.java
private INTYPE doRequest() throws IOException { HttpClient client = new ContentEncodingHttpClient(); HttpUriRequest req;/* w ww .j ava 2 s .co m*/ JAXBContext context; Document outDocument = null; try { context = getJAXBContext(); } catch (JAXBException jaxb) { throw new IOException("Unable to acquire JAXB context: " + jaxb.getMessage()); } try { if (requestMethod == RequestMethod.POST) { if (this.sendingObject == null) throw new NullPointerException("requestDocument is null yet required for this type of query"); // Create a new POST request HttpPost post = new HttpPost(url); // Make it a multipart post MultipartEntity postEntity = new MultipartEntity(); req = post; // create an XML document from the given objects outDocument = marshallToDocument(context, sendingObject, getNamespacePrefixMapper()); // add it to the http post request XMLBody xmlb = new XMLBody(outDocument, "application/tellervo+xml", null); postEntity.addPart("xmlrequest", xmlb); postEntity.addPart("traceback", new StringBody(getStackTrace())); post.setEntity(postEntity); } else { // well, that's nice and easy req = new HttpGet(url); } // debug this transaction... TransactionDebug.sent(outDocument, noun); // load cookies ((AbstractHttpClient) client).setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); req.setHeader("User-Agent", "Tellervo WSI " + Build.getUTF8Version() + " (" + clientModuleVersion + "; ts " + Build.getCompleteVersionNumber() + ")"); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } // create a responsehandler JaxbResponseHandler<INTYPE> responseHandler = new JaxbResponseHandler<INTYPE>(context, receivingObjectClass); // set the schema we validate against responseHandler.setValidateSchema(getValidationSchema()); // execute the actual http query INTYPE inObject = null; try { inObject = client.execute(req, responseHandler); } catch (EOFException e4) { log.debug("Caught EOFException"); } TransactionDebug.received(inObject, noun, context); // save our cookies? WSCookieStoreHandler.getCookieStore().fromCookieStore(((AbstractHttpClient) client).getCookieStore()); // ok, now inspect the document we got back //TellervoDocumentInspector inspector = new TellervoDocumentInspector(inDocument); // Verify our document based on schema validity //inspector.validate(); // Verify our document structure, throw any exceptions! //inspector.verifyDocument(); return inObject; } catch (UnknownHostException e) { throw new IOException("The URL of the server you have specified is unknown"); } catch (HttpResponseException hre) { if (hre.getStatusCode() == 404) { throw new IOException("The URL of the server you have specified is unknown"); } BugReport bugs = new BugReport(hre); bugs.addDocument("sent.xml", outDocument); new BugDialog(bugs); throw new IOException("The server returned a protocol error " + hre.getStatusCode() + ": " + hre.getLocalizedMessage()); } catch (IllegalStateException ex) { throw new IOException("Webservice URL must be a full URL qualified with a communications protocol.\n" + "Tellervo currently supports http:// and https://."); } catch (ResponseProcessingException rspe) { Throwable cause = rspe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = rspe.getNonvalidatingDocument(); File invalidFile = rspe.getInvalidFile(); if (outDocument != null) bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw rspe; } catch (XMLParsingException xmlpe) { Throwable cause = xmlpe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = xmlpe.getNonvalidatingDocument(); File invalidFile = xmlpe.getInvalidFile(); bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw xmlpe; } catch (IOException ioe) { throw ioe; } catch (Exception uhe) { BugReport bugs = new BugReport(uhe); bugs.addDocument("sent.xml", outDocument); /* // MalformedDocs are handled automatically by BugReport class if(!(uhe instanceof MalformedDocumentException) && inDocument != null) bugs.addDocument("received.xml", inDocument); */ new BugDialog(bugs); throw new IOException("Exception " + uhe.getClass().getName() + ": " + uhe.getLocalizedMessage()); } finally { //? } }