List of usage examples for org.apache.http.client HttpResponseException HttpResponseException
public HttpResponseException(final int statusCode, final String s)
From source file:me.ixfan.wechatkit.token.AccessTokenResponseHandler.java
/** * Response handler of WeChat access_token request. * * @param response//from w w w .ja v a 2 s. c o m * @return * @throws IOException */ @Override public AccessToken handleResponse(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (status.getStatusCode() >= 300) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } if (null == entity) { logger.error("Exception occurred while obtaining access_token, there's no data in the response."); throw new ClientProtocolException("Empty HTTP response"); } ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); if (null == charset) { charset = StandardCharsets.UTF_8; } Reader reader = new InputStreamReader(entity.getContent(), charset); JsonObject jsonObject = new JsonParser().parse(reader).getAsJsonObject(); logger.debug("obtained access_token: " + jsonObject.toString()); Map<String, String> keyValues = new HashMap<>(); for (Map.Entry<String, JsonElement> element : jsonObject.entrySet()) { keyValues.put(element.getKey(), element.getValue().getAsString()); } AccessToken accessToken = new AccessToken(); if (null != keyValues.get("access_token")) { accessToken.setAccessToken(keyValues.get("access_token")); accessToken.setExpiresIn(Long.parseLong(keyValues.get("expires_in"))); } else { logger.error("Obtaining access_token failed, errcode:{}, errmsg:{}", keyValues.get("errcode"), keyValues.get("errmsg")); } return accessToken; }
From source file:cn.com.lowe.android.tools.net.response.HtmlHttpResponseHandler.java
@Override public void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); String responseBody = null;//from ww w.j ava2 s . com try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, ENCODING); } } catch (IOException e) { sendFailureMessage(e, (String) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } }
From source file:de.mpg.imeji.logic.export.format.ZIPExport.java
/** * @param type/* w w w . j a v a2 s .c om*/ * @return * @throws HttpResponseException */ public ZIPExport(String type) throws HttpResponseException { boolean supported = false; if ("image".equalsIgnoreCase(type)) { modelURI = Imeji.imageModel; supported = true; } if (!supported) { throw new HttpResponseException(400, "Type " + type + " is not supported."); } }
From source file:com.esri.geoportal.harvester.waf.HtmlUrlScrapper.java
/** * Scrap HTML page for URL's// w ww.ja va 2 s. c o m * @param root root of the page * @return list of found URL's * @throws IOException if error reading data * @throws URISyntaxException if invalid URL */ public List<URL> scrap(URL root) throws IOException, URISyntaxException { ContentAnalyzer analyzer = new ContentAnalyzer(root); HttpGet method = new HttpGet(root.toExternalForm()); method.setConfig(DEFAULT_REQUEST_CONFIG); HttpClientContext context = creds != null && !creds.isEmpty() ? createHttpClientContext(root, creds) : null; try (CloseableHttpResponse httpResponse = httpClient.execute(method, context); InputStream input = httpResponse.getEntity().getContent();) { if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } String content = IOUtils.toString(input, "UTF-8"); return analyzer.analyze(content); } }
From source file:net.oneandone.shared.artifactory.SearchLatestVersionTest.java
/** * Test of search method, of class SearchLatestVersion. *//*ww w . j a va 2 s . com*/ @Test public void testSearchOtherHttpResponseException() throws NotFoundException, IOException { final HttpResponseException badRequest = new HttpResponseException(HttpStatus.SC_BAD_REQUEST, "Bad Request"); setupSearchWithException(badRequest); thrown.expect(RuntimeException.class); thrown.expectCause(is(badRequest)); sut.search("repo1", "commons-logging", "commons-logging"); }
From source file:com.rackspacecloud.blueflood.cache.TtlCacheTest.java
@Before public void setupCache() { loadCount = new AtomicLong(0); buildCount = new AtomicLong(0); twoSecondCache = new TtlCache("Test", new TimeValue(2, TimeUnit.SECONDS), 5, new InternalAPI() { public Account fetchAccount(String tenantId) throws IOException { loadCount.incrementAndGet(); if (IOException.class.getName().equals(tenantId)) throw new IOException("Error retrieving account from internal API"); else if (HttpResponseException.class.getName().equals(tenantId)) throw new HttpResponseException(404, "That account does not exist"); else/* w w w.j av a 2 s. com*/ return Account.fromJSON(AccountTest.JSON_ACCOUNTS.get(tenantId)); } @Override public List<AccountMapEntry> listAccountMapEntries() throws IOException { throw new RuntimeException("Not implemented for this test"); } }) { @Override protected Map<ColumnFamily<Locator, Long>, TimeValue> buildTtlMap(Account acct) { buildCount.incrementAndGet(); return super.buildTtlMap(acct); } }; }
From source file:com.github.horrorho.inflatabledonkey.cloud.auth.Authenticator.java
public static Auth authenticate(HttpClient httpClient, String id, String password) throws IOException { logger.trace("<< authenticate() < id: {} password: {}", id, password); AuthenticationRequestFactory authenticationRequestFactory = AuthenticationRequestFactory.instance(); PropertyListResponseHandler<NSDictionary> nsDictionaryResponseHandler = PropertyListResponseHandler .nsDictionaryResponseHandler(); try {/*from w w w. j a v a 2 s . c o m*/ HttpUriRequest request = authenticationRequestFactory.apply(id, password); NSDictionary authentication = httpClient.execute(request, nsDictionaryResponseHandler); logger.debug("-- authenticate() - authentication: {}", authentication.toASCIIPropertyList()); NSDictionary appleAccountInfo = PLists.getAs(authentication, "appleAccountInfo", NSDictionary.class); String dsPrsID = PLists.getAs(appleAccountInfo, "dsPrsID", NSNumber.class).toString(); NSDictionary tokens = PLists.getAs(authentication, "tokens", NSDictionary.class); String mmeAuthToken = PLists.getAs(tokens, "mmeAuthToken", NSString.class).getContent(); logger.debug("-- authenticate() - dsPrsID: {}", dsPrsID); logger.debug("-- authenticate() - mmeAuthToken: {}", mmeAuthToken); Auth auth = new Auth(dsPrsID, mmeAuthToken); logger.trace(">> authenticate() > auth: {}", auth); return auth; } catch (HttpResponseException ex) { int statusCode = ex.getStatusCode(); if (statusCode == 401) { throw new HttpResponseException(statusCode, "Bad appleId/ password or not an iCloud account?"); } if (statusCode == 409) { throw new HttpResponseException(statusCode, "Two-step enabled or partial iCloud account activation?"); } throw ex; } }
From source file:com.github.horrorho.inflatabledonkey.responsehandler.DonkeyResponseHandler.java
@Override public T handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String message = statusLine.getReasonPhrase(); if (entity != null) { message += ": " + EntityUtils.toString(entity); }/*from w w w . j a v a 2 s . co m*/ throw new HttpResponseException(statusLine.getStatusCode(), message); } if (entity == null) { return null; } long timestampSystem = System.currentTimeMillis(); logger.debug("-- handleResponse() - timestamp system: {}", timestampSystem); Optional<Long> timestampOffset = timestamp(response).map(t -> t - timestampSystem); logger.debug("-- handleResponse() - timestamp offset: {}", timestampOffset); return handleEntityTimestampOffset(entity, timestampOffset); }
From source file:org.opentestsystem.shared.permissions.rest.APIHandler.java
@RequestMapping(value = "role", method = RequestMethod.GET) @ResponseBody/*ww w. j a v a2 s .com*/ //@Secured({ "ROLE_Administrator Read" }) public ReturnStatus<List<Role>> getRoles(@RequestParam(value = "role", required = false) String roleName, @RequestParam(value = "component", required = false) String componentName, @RequestParam(value = "permission", required = false) String permissionName) throws PermissionsRetrievalException, HttpResponseException { List<Role> roles; if (!StringUtils.isEmpty(componentName)) { //if the component does not exist if (getPersister().getComponentByComponentName(componentName) == null) { throw (new HttpResponseException(404, String.format("Role by component:'%s' is not found.", componentName))); } if (!StringUtils.isEmpty(permissionName)) { // We are going to return roles by component name and // permission. roles = getPersister().getRoleByComponentandPermission(componentName, permissionName); } else { // just by component name roles = getPersister().getRoleByComponent(componentName); } } else if (!StringUtils.isEmpty(roleName)) { // we have been passed a role name. roles = new ArrayList<Role>(); Role role = getPersister().getRoleByRoleName(roleName); if (role == null) { throw (new HttpResponseException(404, String.format("Role:'%s' is not found.", roleName))); } roles.add(role); } else { // no parameters have been passed. return all roles. roles = new ArrayList<Role>(); roles.addAll(getPersister().getAllRoles()); } ReturnStatus<List<Role>> status = new ReturnStatus<List<Role>>(StatusEnum.SUCCESS, null); status.setValue(roles); return status; }
From source file:org.apache.abdera2.protocol.client.AbderaResponseHandler.java
public Document<? extends Element> handleResponse(HttpResponse response) throws ClientProtocolException, IOException { ResponseType type = ResponseType.select(response.getStatusLine().getStatusCode()); switch (type) { case SUCCESSFUL: return options == null ? abdera.getParser().parse(getInputStream(response)) : abdera.getParser().parse(getInputStream(response), options); default:/* www .ja va 2 s .c o m*/ EntityUtils.consume(response.getEntity()); StatusLine status = response.getStatusLine(); throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } }