Example usage for org.apache.http.client HttpResponseException HttpResponseException

List of usage examples for org.apache.http.client HttpResponseException HttpResponseException

Introduction

In this page you can find the example usage for org.apache.http.client HttpResponseException HttpResponseException.

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:tds.tdsadmin.rest.TDSAdminController.java

@RequestMapping(value = "/rest/setOpportunitySegmentPerm", method = RequestMethod.POST)
@ResponseBody/*w ww.j a  va  2s  .c  o m*/
@Secured({ "ROLE_Opportunity Modify" })
public ProcedureResult setOpportunitySegmentPerm(HttpServletResponse response,
        @RequestParam(value = "oppkey", required = false) UUID v_oppKey,
        @RequestParam(value = "requester", required = false) String v_requester,
        @RequestParam(value = "segmentid", required = false) String v_segmentid,
        @RequestParam(value = "segmentposition", required = false) Integer v_segmentposition,
        @RequestParam(value = "restoreon", required = false) String v_restoreon,
        @RequestParam(value = "ispermeable", required = false) Integer v_ispermeable,
        @RequestParam(value = "reason", required = false) String v_reason) throws HttpResponseException {

    ProcedureResult result = null;
    if (v_oppKey == null || StringUtils.isEmpty(v_requester) || StringUtils.isEmpty(v_segmentid)
            || StringUtils.isEmpty(v_restoreon) || v_segmentposition == null || v_segmentposition <= 0
            || v_ispermeable == null) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST,
                "oppkey, segmentid, restoreon, ispermeable, segmentposition, and requester are required parameters. reason is accepted as an optional parameter.");
    }
    if (!restoreOnValues.contains(v_restoreon)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST,
                v_restoreon + " is not a valid value for restoreon");
    }
    // ispermeable stores only -1 and 1 in the database
    if (v_ispermeable != -1 && v_ispermeable != 1) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST,
                v_ispermeable + " is not a valid value for ispermeable");
    }
    try {
        result = getDao().setOpportunitySegmentPerm(v_oppKey, v_requester, v_segmentid, v_segmentposition,
                v_restoreon, v_ispermeable, v_reason);
        if (result != null && "success".equalsIgnoreCase(result.getStatus()))
            logger.info(String.format(
                    "Appeals: Set opportunity segment permeability successful for Oppkey=%s, requester=%s, SegmentId=%s, SegmentPosition=%s, RestoreOn=%s, Ispermeable=%s, Reason=%s",
                    v_oppKey, v_requester, v_segmentid, v_segmentposition, v_restoreon, v_ispermeable,
                    v_reason));
        else
            logger.error(String.format(
                    "Appeals: Set opportunity segment permeability failed for Oppkey=%s, requester=%s, SegmentId=%s, SegmentPosition=%s, RestoreOn=%s, Ispermeable=%s, Reason=%s",
                    v_oppKey, v_requester, v_segmentid, v_segmentposition, v_restoreon, v_ispermeable,
                    (result != null) ? result.getReason() : null));
    } catch (ReturnStatusException e) {
        logger.error("Appeals: " + e.getMessage());
    }
    return result;
}

From source file:org.sakaiproject.hybrid.util.NakamuraAuthenticationHelperTest.java

/**
 * @see NakamuraAuthenticationHelper#getPrincipalLoggedIntoNakamura(HttpServletRequest)
 *///from  w w  w .  j  a v a2s.c o m
@Test
public void testHttpResponseExceptionLogDebugDisabled() throws Exception {
    disableLog4jDebug();
    // HttpResponseException
    when(httpClient.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class)))
            .thenThrow(new HttpResponseException(404, "could not find cookie / not valid"));
    AuthInfo authInfo = nakamuraAuthenticationHelper.getPrincipalLoggedIntoNakamura(request);
    assertNull(authInfo);
    enableLog4jDebug();
}

From source file:com.flipzu.flipzu.FlipInterface.java

public FlipUser getUser(String username, String token) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url = WSServer + "/api/get_user.xml";

    debug.logV(TAG, "getUser for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }/*from   w ww . ja v  a2  s.  c om*/

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException {

    try (CloseableHttpResponse httpResponse = httpClient.execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }//from  www .  ja va2s .  co  m
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(responseContent, clazz);
    }
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Verifies that the HttpResponse has a good status code. Throws exceptions if they are not.
 *
 * @param res/*from  w w  w  .jav  a  2 s.c  om*/
 * @param createdOk
 *            true if a 201 (CREATED) code is ok. Otherwise, only 200 (OK) is allowed.
 * @throws HttpResponseException
 *             if the status code is 400 series.
 * @throws NetworkProtocolException
 *             for all status codes errors.
 * @throws IOException
 * @return returns true upon success or throws an exception explaining what went wrong.
 */
public boolean checkStatusCode(HttpResponse res, boolean createdOk)
        throws HttpResponseException, NetworkProtocolException, IOException {
    final int statusCode = res.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK || (createdOk && statusCode == HttpStatus.SC_CREATED)) {
        return true;
    } else if (statusCode >= HttpStatus.SC_BAD_REQUEST && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        final HttpEntity e = res.getEntity();
        if (e.getContentType().getValue().equals("text/html") || e.getContentLength() > 40) {
            logDebug("Got long response body. Not showing.");
        } else {
            logDebug(StreamUtils.inputStreamToString(e.getContent()));
        }
        e.consumeContent();
        throw new HttpResponseException(statusCode, res.getStatusLine().getReasonPhrase());
    } else {
        final HttpEntity e = res.getEntity();
        if (e.getContentType().getValue().equals("text/html") || e.getContentLength() > 40) {
            logDebug("Got long response body. Not showing.");
        } else {
            logDebug(StreamUtils.inputStreamToString(e.getContent()));
        }
        e.consumeContent();
        throw new NetworkProtocolException(
                "HTTP " + res.getStatusLine().getStatusCode() + " " + res.getStatusLine().getReasonPhrase(),
                res);
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

private List<BroadcastDataSet> sendRequest(String url, String data) throws IOException {
    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }//from ww  w . j  ava2 s  . c o m

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "sendRequest ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        TimelineHandler myTimelineHandler = new TimelineHandler();
        xr.setContentHandler(myTimelineHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        List<BroadcastDataSet> parsedDataSet = myTimelineHandler.getParsedData();

        return parsedDataSet;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.swater.meimeng.activity.oomimg.ImageCache.java

/**
 * Blocking call to download an image. The image is placed directly into the disk cache at the
 * given key.//from w  ww .j  a va  2 s.c  om
 *
 * @param uri
 *            the location of the image
 * @return a decoded bitmap
 * @throws org.apache.http.client.ClientProtocolException
 *             if the HTTP response code wasn't 200 or any other HTTP errors
 * @throws java.io.IOException
 */
protected void downloadImage(String key, Uri uri) throws ClientProtocolException, IOException {
    if (DEBUG) {
        Log.d(TAG, "downloadImage(" + key + ", " + uri + ")");
    }
    if (USE_APACHE_NC) {
        final HttpGet get = new HttpGet(uri.toString());
        final HttpParams params = get.getParams();
        params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);

        final HttpResponse hr = hc.execute(get);
        final StatusLine hs = hr.getStatusLine();
        if (hs.getStatusCode() != 200) {
            throw new HttpResponseException(hs.getStatusCode(), hs.getReasonPhrase());
        }

        final HttpEntity ent = hr.getEntity();

        // TODO I think this means that the source file must be a jpeg. fix this.
        try {

            putRaw(key, ent.getContent());
            if (DEBUG) {
                Log.d(TAG, "source file of " + uri + " saved to disk cache at location "
                        + getFile(key).getAbsolutePath());
            }
        } finally {
            ent.consumeContent();
        }
    } else {
        final URLConnection con = new URL(uri.toString()).openConnection();
        putRaw(key, con.getInputStream());
        if (DEBUG) {
            Log.d(TAG, "source file of " + uri + " saved to disk cache at location "
                    + getFile(key).getAbsolutePath());
        }
    }

}