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/restoreOpportunity", method = RequestMethod.POST)
@ResponseBody//  ww w .ja va2  s  .  c o m
@Secured({ "ROLE_Opportunity Modify" })
public ProcedureResult restoreTestOpportunity(HttpServletResponse response,
        @RequestParam(value = "oppkey", required = false) UUID v_oppKey,
        @RequestParam(value = "requester", required = false) String v_requester,
        @RequestParam(value = "reason", required = false) String v_reason) throws HttpResponseException {
    ProcedureResult result = null;
    if (v_oppKey == null || StringUtils.isEmpty(v_requester)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST,
                "oppkey, requester are required parameters. reason is accepted as an optional parameter.");
    }
    try {
        result = getDao().restoreTestOpportunity(v_oppKey, v_requester, v_reason);
        if (result != null && "success".equalsIgnoreCase(result.getStatus()))
            logger.info(String.format("Appeals: Restore successful for Oppkey=%s, requester=%s, Reason=%s",
                    v_oppKey, v_requester, v_reason));
        else
            logger.error(String.format("Appeals: Restore failed for Oppkey=%s, requester=%s, Reason=%s",
                    v_oppKey, v_requester, (result != null) ? result.getReason() : null));
    } catch (ReturnStatusException e) {
        logger.error("Appeals: " + e.getMessage());
    }
    return result;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

private static String readData(Executor exec, Request req, IProgressMonitor monitor) throws IOException {
    String obj = null;/*from  w ww  .  j  av  a 2  s . c  om*/
    ConnectionManager.register(monitor, req);
    try {
        obj = exec.execute(req).handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                InputStream in = null;
                String res = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    // System.out
                    // .println("---------------------------------------------------------------------------");
                    // System.out.println(response.toString());
                    // for (Header h : response.getAllHeaders()) {
                    // System.out.println(h.toString());
                    // }

                    switch (statusLine.getStatusCode()) {
                    case 200:
                        in = getContent(entity);
                        res = IOUtils.toString(in);
                        break;
                    default:
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return res;
            }

            protected InputStream getContent(HttpEntity entity) throws ClientProtocolException, IOException {
                if (entity == null)
                    throw new ClientProtocolException("Response contains no content");
                return entity.getContent();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        ConnectionManager.unregister(req);
    }
    return obj;
}

From source file:com.helger.peppol.smpclient.SMPHttpResponseHandlerSigned.java

@Nonnull
public T handleResponse(@Nonnull final HttpResponse aHttpResponse) throws IOException {
    final StatusLine aStatusLine = aHttpResponse.getStatusLine();
    final HttpEntity aEntity = aHttpResponse.getEntity();
    if (aStatusLine.getStatusCode() >= 300)
        throw new HttpResponseException(aStatusLine.getStatusCode(), aStatusLine.getReasonPhrase());
    if (aEntity == null)
        throw new ClientProtocolException("Response from SMP server contains no content");

    // Get complete response as one big byte buffer
    final byte[] aResponseBytes = StreamHelper.getAllBytes(aEntity.getContent());
    if (ArrayHelper.isEmpty(aResponseBytes))
        throw new ClientProtocolException("Could not read SMP server response content");

    try {//  w  w  w .jav a 2s  .  co m
        // Check the signature
        if (!_checkSignature(new NonBlockingByteArrayInputStream(aResponseBytes)))
            throw new ClientProtocolException("Signature returned from SMP server was not valid");
    } catch (final Exception ex) {
        throw new ClientProtocolException("Error in validating signature returned from SMP server", ex);
    }

    // Finally convert to domain object
    final T ret = m_aMarshaller.read(aResponseBytes);
    if (ret == null)
        throw new ClientProtocolException("Malformed XML document returned from SMP server");
    return ret;
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

public ESearchResult esearch(final String database, final String query, final int retstart, final int retmax)
        throws Exception {
    return httpClient.request(ESEARCH_BASE_URI).post()
            .bodyForm(esearchForm(database, query, retstart, retmax).build())
            .handleResponse(new ResponseHandler<ESearchResult>() {
                @Override/* w w w . ja  v a  2 s .c om*/
                public ESearchResult handleResponse(final HttpResponse response) throws IOException {
                    final StatusLine statusLine = response.getStatusLine();
                    final HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    final ContentType contentType = getOrDefault(entity);
                    final String mimeType = contentType.getMimeType();
                    if (!mimeType.equals(APPLICATION_XML.getMimeType())
                            && !mimeType.equals(TEXT_XML.getMimeType())) {
                        throw new ClientProtocolException("Unexpected content type:" + contentType);
                    }
                    Charset charset = contentType.getCharset();
                    if (charset == null) {
                        charset = HTTP.DEF_CONTENT_CHARSET;
                    }
                    return ESEARCH_XMLB.typeFromInputStream(entity.getContent());
                }
            }, false);
}

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

@RequestMapping(value = "/rest/reopenOpportunity", method = RequestMethod.POST)
@ResponseBody//from   ww  w . ja  v  a 2 s.  c om
@Secured({ "ROLE_Opportunity Modify" })
public ProcedureResult reopenOpportunity(HttpServletResponse response,
        @RequestParam(value = "oppkey", required = false) UUID v_oppKey,
        @RequestParam(value = "requester", required = false) String v_requester,
        @RequestParam(value = "reason", required = false) String v_reason) throws HttpResponseException {
    ProcedureResult result = null;
    if (v_oppKey == null || StringUtils.isEmpty(v_requester)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST,
                "oppkey, requester are required parameters. reason is accepted as an optional parameter.");
    }
    try {
        result = getDao().reopenOpportunity(v_oppKey, v_requester, v_reason);
        if (result != null && "success".equalsIgnoreCase(result.getStatus()))
            logger.info(String.format("Appeals: Reopen successful for Oppkey=%s, requester=%s, Reason=%s",
                    v_oppKey, v_requester, v_reason));
        else
            logger.error(String.format("Appeals: Reopen failed for Oppkey=%s, requester=%s, Reason=%s",
                    v_oppKey, v_requester, (result != null) ? result.getReason() : null));
    } catch (ReturnStatusException e) {
        logger.error("Appeals: " + e.getMessage());
    }
    return result;
}

From source file:com.esri.geoportal.commons.gpt.client.Client.java

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

    try (CloseableHttpResponse httpResponse = execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }/* w  w  w.ja  v a  2  s.c o 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:org.opentestsystem.shared.permissions.dao.db.dll.DbPermissionsDll.java

public void editRole(SQLConnection connection, String roleId, String newRole)
        throws ReturnStatusException, HttpResponseException {
    // Check if role exists or not.
    Role r = this.getRoleByRoleName(connection, newRole);
    if (r != null)
        throw new HttpResponseException(409, "Already exists.");

    final String SQL = "UPDATE role set role.name = ${newName} where role.name = ${roleName};";

    SqlParametersMaps parameters = new SqlParametersMaps();
    parameters.put("roleName", roleId).put("newName", newRole);

    executeStatement(connection, SQL, parameters, false);
}

From source file:com.baidu.asynchttpclient.AsyncHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();

    String responseBody = null;//from  w  w w. j  a  va2  s  . c  o  m
    try {
        HttpEntity entity = response.getEntity();
        if (statusCode >= 300) {
            responseBody = EntityUtils.toString(entity);
        } else {
            if (entity == null) {
                throw new IllegalArgumentException("HTTP entity may not be null");
            }
            // 
            InputStream instream = entity.getContent();
            if (instream == null) {
                sendReceiveStartMessage(0, null/* , headers */);
                sendReceiveUpdateMessage(new byte[0], 0);
                sendReceiveEndMessage();
                return;
            }
            // ///////////////phase 1////////////////////////////
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }

            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            String charset = null;
            if (entity.getContentType() != null) {
                HeaderElement values[] = entity.getContentType().getElements();
                if (values.length > 0) {
                    NameValuePair param = values[0].getParameterByName("charset");
                    if (param != null) {
                        charset = param.getValue();
                    }
                }
            }
            sendReceiveStartMessage(i, charset/* , headers */);
            // ////////////////////////phase 2//////////////////////////

            final int _1KSize = 1024;
            // final int _100KSize = _1KSize * 100;
            int tmpSize = _1KSize;
            // if (i > _100KSize) {
            // tmpSize = _1KSize * 2;
            // }

            boolean readDone = false;
            byte[] tmp = null;
            int remain = 0;
            do {
                if (Thread.currentThread().isInterrupted()) {
                    sendFailureMessage(new InterruptedException("request interupted!"), null);
                    return;
                }
                if (tmp == null) {
                    tmp = new byte[tmpSize];
                }
                int offset = 0;
                remain = tmpSize;
                do {
                    if (Thread.currentThread().isInterrupted()) {
                        sendFailureMessage(new InterruptedException("request interupted!"), null);
                        return;
                    }
                    int length = instream.read(tmp, offset, remain);
                    if (length != -1) {
                        offset += length;
                        remain -= length;
                    } else {
                        readDone = true;
                        break;
                    }
                } while (remain > 0);

                if (offset >= 0) {
                    sendReceiveUpdateMessage(tmp, offset);
                }
                tmp = null;
            } while (!readDone);
            // ////////////////////////phase 3//////////////////////////
            sendReceiveEndMessage();
        }

    } catch (IOException e) {
        sendFailureMessage(e, null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    }
}

From source file:org.opentestsystem.shared.permissions.dao.db.dll.DbPermissionsDll.java

public void addRole(SQLConnection connection, String roleId)
        throws ReturnStatusException, HttpResponseException {
    // Check if role exists or not.
    Role r = this.getRoleByRoleName(connection, roleId);
    if (r != null)
        throw new HttpResponseException(409, "Role already exists.");

    final String SQL = "insert into role (name) values(${roleName});";
    SqlParametersMaps parameters = new SqlParametersMaps();
    parameters.put("roleName", roleId);

    executeStatement(connection, SQL, parameters, false);
}