List of usage examples for org.apache.http.client HttpResponseException HttpResponseException
public HttpResponseException(final int statusCode, final String s)
From source file:org.opentestsystem.shared.permissions.dao.db.dll.DbPermissionsDll.java
public void addComponent(SQLConnection connection, String componentId) throws ReturnStatusException, HttpResponseException { // check if the component already exists or not Component c = getComponentByComponentName(connection, componentId); if (c != null) throw new HttpResponseException(409, "Component already exists."); final String SQL = "insert into component (name) values(${compID});"; SqlParametersMaps parameters = new SqlParametersMaps(); parameters.put("compID", componentId); executeStatement(connection, SQL, parameters, false); }
From source file:com.makotosan.vimeodroid.vimeo.Methods.java
private XmlPullParser makeRequest(String method, HashMap<String, String> parameters) { final StringBuilder urlStringBuilder = new StringBuilder(); try {/* w w w. ja va 2 s . c o m*/ urlStringBuilder.append(VimeoUrls.STANDARD_API + "?method=vimeo." + method); final ConsumerInfo info = getConsumerInfo(); if (parameters != null && !parameters.isEmpty()) { for (String key : parameters.keySet()) { urlStringBuilder.append("&" + key + "=" + parameters.get(key)); } if (!parameters.containsKey("user_id")) { urlStringBuilder.append("&user_id=" + info.getConsumerToken()); } } final HttpGet request = new HttpGet(urlStringBuilder.toString()); request.addHeader("Accept-Encoding", "gzip"); final HttpClient client = this.app.getHttpClient(); Authentication.signRequest(info, request); final org.apache.http.HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); // Log.d("HTTP method : " + method, "return statusCode : " + // statusCode); if (statusCode != 200) { throw new HttpResponseException(statusCode, "HTTP Error"); } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); final Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); final XmlPullParser xpp = factory.newPullParser(); final String rawXml = IOUtils.toString(inputStream); xpp.setInput(new StringReader(rawXml)); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: if ("rsp".equals(xpp.getName())) { String status = xpp.getAttributeValue(XmlPullParser.NO_NAMESPACE, "stat"); if ("fail".equals(status)) { ErrorInfo error = VimeoXmlParser.parse(ErrorInfo.class, xpp); Log.e(TAG, error.getExplanation()); Toast.makeText(context, error.getExplanation(), Toast.LENGTH_LONG).show(); return null; // throw new // Exception(error.getExplanation()); } return xpp; } break; } eventType = xpp.next(); } return xpp; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); // Toast.makeText(context, e.getMessage(), // Toast.LENGTH_SHORT).show(); } return null; }
From source file:tds.tdsadmin.rest.TDSAdminController.java
@RequestMapping(value = "/rest/extendOppGracePeriod", method = RequestMethod.POST) @ResponseBody// www. j a v a 2s . co m @Secured({ "ROLE_Opportunity Modify" }) public ProcedureResult extendingOppGracePeriod(HttpServletResponse response, @RequestParam(value = "oppkey", required = false) UUID v_oppKey, @RequestParam(value = "requester", required = false) String v_requester, @RequestParam(value = "selectedsitting", required = false) Integer v_selectedsitting, @RequestParam(value = "doupdate", required = false) Boolean v_doupdate, @RequestParam(value = "reason", required = false) String v_reason) throws HttpResponseException { ProcedureResult result = null; // selected sitting is number of sitting for an opportunity, which can't // be negative, upper limit for this is 99, taken arbitrarily if (v_oppKey == null || StringUtils.isEmpty(v_requester) || v_selectedsitting == null || v_selectedsitting < 0 || v_selectedsitting > 99 || v_doupdate == null || v_doupdate == false) { response.setStatus(HttpStatus.SC_BAD_REQUEST); throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST, "oppkey, requester, selectedsitting, and doupdate are required parameters. reason is accepted as an optional parameter. selectedsitting has range:<0,99> and doupdate accepts only true or 1"); } try { result = getDao().extendingOppGracePeriod(v_oppKey, v_requester, v_selectedsitting, v_doupdate, v_reason); if (result != null && "success".equalsIgnoreCase(result.getStatus())) logger.info(String.format( "Appeals: Extend grace period successful for Oppkey=%s, requester=%s, SelectedSitting=%s, Doupdate=%s, Reason=%s", v_oppKey, v_requester, v_selectedsitting, v_doupdate, v_reason)); else logger.error(String.format( "Appeals: Extend grace period failed for Oppkey=%s, requester=%s, SelectedSitting=%s, Doupdate=%s, Reason=%s", v_oppKey, v_requester, v_selectedsitting, v_doupdate, (result != null) ? result.getReason() : null)); } catch (ReturnStatusException e) { logger.error("Appeals: " + e.getMessage()); } return result; }
From source file:cn.edu.zzu.wemall.http.AsyncHttpResponseHandler.java
void sendResponseMessage(HttpResponse response) throws IOException { // do not process if request has been cancelled if (!Thread.currentThread().isInterrupted()) { StatusLine status = response.getStatusLine(); byte[] responseBody; responseBody = getResponseData(response.getEntity()); // additional cancellation check as getResponseData() can take non-zero time to process if (!Thread.currentThread().isInterrupted()) { if (status.getStatusCode() >= 300) { sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); }/*from w w w . j a v a 2s .com*/ } } }
From source file:org.modelio.vbasic.net.ApacheUriConnection.java
/** * Builds and throws a {@link FileSystemException} from {@link #res}. * <p>/*from www . j a va 2 s . c o m*/ * Adds as cause another exception whose message is the entity content. This may be the HTML message sent by the server. * @throws java.nio.file.FileSystemException the built exception */ @objid("4e25ec1d-3711-45cc-b742-0c77edf5e414") private void handleConnectionFailure() throws FileSystemException { StatusLine statusLine = this.res.getStatusLine(); String reason = statusLine.getReasonPhrase(); Exception base = null; try { String s = EntityUtils.toString(this.res.getEntity()); if (s != null) base = new HttpResponseException(statusLine.getStatusCode(), s); } catch (IOException e) { base = e; } FileSystemException error; int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_FORBIDDEN) { error = new AccessDeniedException(this.uri.toString(), null, reason); } else if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { error = new UriAuthenticationException(this.uri.toString(), reason); } else if (statusCode == HttpStatus.SC_NOT_FOUND) { error = new NoSuchFileException(this.uri.toString(), null, reason); } else { error = new FileSystemException(this.uri.toString(), null, reason); } if (base != null) error.initCause(base); throw error; }
From source file:org.opentestsystem.shared.permissions.dao.db.dll.DbPermissionsDll.java
public void addPermission(SQLConnection connection, String componentId, String permissionId) throws ReturnStatusException, HttpResponseException { // check component already has permission or not if (this.getComponentByComponentName(connection, componentId).containsPermission(permissionId)) { throw new HttpResponseException(409, componentId + " already has Permission [" + permissionId + "]."); }// w ww .j a v a2 s .c om SqlParametersMaps parameters = new SqlParametersMaps(); parameters.put("permName", permissionId).put("compName", componentId); // Check if new permission. If new permission, we need to add new permission // to DB, then add to role-component-permission mapping // If not new, we add component and permission combination to DB // Check if new permission Permission p = new Permission(); p.setName(permissionId); if (!(getAllPermissions(connection).contains(p))) { // Insert new permission into database final String SQL = "insert into permission (name) values(${permName});"; executeStatement(connection, SQL, parameters, false); } // Now Add Component-Permission combination // Check if there are associations between this pair already final String SQL2 = "SELECT DISTINCT permission._id from permission_role, component, permission where component.name = ${compName} and permission_role._fk_cid=component._id and permission_role._fk_pid = permission._id and permission.name = ${permName};"; SingleDataResultSet results = executeStatement(connection, SQL2, parameters, false).getResultSets().next(); Integer id = null; Iterator<DbResultRecord> records = results.getRecords(); if (records.hasNext()) { DbResultRecord record = records.next(); id = (record.<Integer>get("_id")); } // TODO: Ayo: separate methods for following SQL scripts ? String SQL3 = ""; if (id == null) { // No instance of this component with an empty permission reference // field. SQL3 = "insert into permission_role ( _fk_rid, _fk_cid, _fk_pid) values (null, (select _id from component where name = ${compName}), (select _id from permission where name = ${permName}));"; executeStatement(connection, SQL3, parameters, false); } }
From source file:org.jets3t.service.utils.oauth.OAuthUtils.java
/** * Performs an HTTP/S POST request to a given URL with the given POST parameters * and parses the response document, which must be JSON, into a Map of name/value objects. * * @param endpointUri Authorization or token endpoint * @param postParams Name value pairs//from w ww . j a v a 2 s.c om * @return JSON mapped response * @throws ClientProtocolException No HTTP 200 response * @throws IOException */ protected Map<String, Object> performPostRequestAndParseJSONResponse(String endpointUri, List<NameValuePair> postParams) throws IOException { log.debug("Performing POST request to " + endpointUri + " and expecting JSON response. POST parameters: " + postParams); HttpPost post = new HttpPost(endpointUri); post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); String responseDataString = httpClient.execute(post, new ResponseHandler<String>() { public String handleResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } else { return null; } } throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } }); return jsonMapper.readValue(responseDataString, Map.class); }
From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java
private Graphdesc getGraphDescriptor(String id) throws DataAdapterException { URI requestUri = craftRequestUri("/graphdesc", new BasicNameValuePair("id", id)); return doHttpGet(requestUri, response -> { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 404) { // This is probably an older version of JRDS that doesn't provide the graphdesc service, // so we're falling back to recovering the datastore name from the csv file provided by // the download service. logger.warn("Cannot found graphdesc service; falling back to legacy mode."); try { return getGraphDescriptorLegacy(id); } catch (Exception e) { throw new IOException("", e); }/*from w w w . j a v a2 s . c om*/ } HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity != null) { try { return JAXB.unmarshal(XmlUtils.toNonValidatingSAXSource(entity.getContent()), Graphdesc.class); } catch (Exception e) { throw new IOException("Failed to unmarshall graphdesc response", e); } } return null; }); }
From source file:com.yunmall.ymsdk.net.http.AsyncHttpResponseHandler.java
@Override public void sendResponseMessage(HttpResponse response) throws IOException { // do not process if request has been cancelled if (!Thread.currentThread().isInterrupted()) { StatusLine status = response.getStatusLine(); byte[] responseBody; responseBody = getResponseData(response.getEntity()); //save responseBody in cache file // additional cancellation check as getResponseData() can take non-zero time to process if (!Thread.currentThread().isInterrupted()) { if (status.getStatusCode() >= 300) { sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); } else { String cacheName = getCacheFileName(); if (cacheName != null && !TextUtils.isEmpty(cacheName)) { saveResponse(cacheName, responseBody); }/* ww w .ja v a2 s .co m*/ sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } } } }
From source file:com.loopj.android.AsyncHttpResponseHandler.java
@Override public void sendResponseMessage(HttpResponse response) throws IOException { // do not process if request has been cancelled if (!Thread.currentThread().isInterrupted()) { StatusLine status = response.getStatusLine(); byte[] responseBody; responseBody = getResponseData(response.getEntity()); // additional cancellation check as getResponseData() can take non-zero // time to process if (!Thread.currentThread().isInterrupted()) { if (status.getStatusCode() >= 300) { sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); }/* w w w. j a v a2s . c o m*/ } } }