Search in sources :

Example 51 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project cerberus-source by cerberustesting.

the class ExecutionQueueWorkerThread method runExecution.

/**
 * Request execution of the inner {@link TestCaseExecutionQueue} to the
 * {@link RunTestCase} servlet
 *
 * @return the execution answer from the {@link RunTestCase} servlet
 * @throws RunProcessException if an error occurred during request execution
 * @see #run()
 */
private String runExecution(StringBuilder url) {
    try {
        LOG.debug("Trigger Execution to URL : " + url.toString());
        LOG.debug("Trigger Execution with TimeOut : " + toExecuteTimeout);
        CloseableHttpClient httpclient = HttpClientBuilder.create().disableAutomaticRetries().build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(toExecuteTimeout).setConnectionRequestTimeout(toExecuteTimeout).setSocketTimeout(toExecuteTimeout).build();
        HttpGet httpGet = new HttpGet(url.toString());
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity);
        return responseContent;
    } catch (Exception e) {
        final StringBuilder errorMessage = new StringBuilder("An unexpected error occurred during test case execution: ");
        if (e instanceof HttpResponseException) {
            errorMessage.append(String.format("%d (%s)", ((HttpResponseException) e).getStatusCode(), e.getMessage()));
        } else {
            errorMessage.append(e.getMessage());
            errorMessage.append(". Check server logs");
        }
        LOG.error(errorMessage.toString(), e);
        throw new RunQueueProcessException(errorMessage.toString(), e);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) HttpResponseException(org.apache.http.client.HttpResponseException) CerberusException(org.cerberus.exception.CerberusException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 52 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project eol-globi-data by jhpoelen.

the class EOLService method getResponse.

private String getResponse(URI uri) throws PropertyEnricherException {
    HttpGet get = new HttpGet(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    String response = null;
    try {
        response = HttpUtil.executeWithTimer(get, responseHandler);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() != 406 && e.getStatusCode() != 404) {
            throw new PropertyEnricherException("failed to lookup [" + uri.toString() + "]: http status [" + e.getStatusCode() + "]   ", e);
        }
    } catch (ClientProtocolException e) {
        throw new PropertyEnricherException("failed to lookup [" + uri.toString() + "]", e);
    } catch (IOException e) {
        throw new PropertyEnricherException("failed to lookup [" + uri.toString() + "]", e);
    }
    return response;
}
Also used : PropertyEnricherException(org.eol.globi.service.PropertyEnricherException) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 53 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project vcell by virtualcell.

the class ClientServerManager method connectToServer.

/**
 * Insert the method's description here.
 * Creation date: (5/12/2004 4:48:13 PM)
 */
private VCellConnection connectToServer(InteractiveContext requester, boolean bShowErrors) {
    BeanUtils.updateDynamicClientProperties();
    VCellThreadChecker.checkRemoteInvocation();
    VCellConnection newVCellConnection = null;
    VCellConnectionFactory vcConnFactory = null;
    String badConnStr = "";
    try {
        try {
            switch(getClientServerInfo().getServerType()) {
                case SERVER_REMOTE:
                    {
                        String apihost = getClientServerInfo().getApihost();
                        Integer apiport = getClientServerInfo().getApiport();
                        try {
                            badConnStr += apihost + ":" + apiport;
                            vcConnFactory = new RemoteProxyVCellConnectionFactory(apihost, apiport, getClientServerInfo().getUserLoginInfo());
                            setConnectionStatus(new ClientConnectionStatus(getClientServerInfo().getUsername(), apihost, apiport, ConnectionStatus.INITIALIZING));
                            newVCellConnection = vcConnFactory.createVCellConnection();
                        } catch (AuthenticationException ex) {
                            throw ex;
                        }
                        break;
                    }
                case SERVER_LOCAL:
                    {
                        new PropertyLoader();
                        LocalVCellConnectionService localVCellConnectionService = VCellServiceHelper.getInstance().loadService(LocalVCellConnectionService.class);
                        vcConnFactory = localVCellConnectionService.getLocalVCellConnectionFactory(getClientServerInfo().getUserLoginInfo());
                        setConnectionStatus(new ClientConnectionStatus(getClientServerInfo().getUsername(), null, null, ConnectionStatus.INITIALIZING));
                        newVCellConnection = vcConnFactory.createVCellConnection();
                        break;
                    }
            }
            requester.clearConnectWarning();
            reconnectStat = ReconnectStatus.NOT;
        } catch (Exception e) {
            e.printStackTrace();
            if (bShowErrors) {
                throw e;
            }
        }
    } catch (AuthenticationException aexc) {
        aexc.printStackTrace(System.out);
        requester.showErrorDialog(aexc.getMessage());
    } catch (ConnectionException cexc) {
        String msg = badConnectMessage(badConnStr) + "\n" + cexc.getMessage();
        cexc.printStackTrace(System.out);
        ErrorUtils.sendRemoteLogMessage(getClientServerInfo().getUserLoginInfo(), msg);
        if (reconnectStat != ReconnectStatus.SUBSEQUENT) {
            requester.showConnectWarning(msg);
        }
    } catch (HttpResponseException httpexc) {
        httpexc.printStackTrace(System.out);
        if (httpexc.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            requester.showErrorDialog("Invalid Userid or Password\n\n" + httpexc.getMessage());
        } else {
            String msg = "Exception: " + httpexc.getMessage() + "\n\n" + badConnectMessage(badConnStr);
            ErrorUtils.sendRemoteLogMessage(getClientServerInfo().getUserLoginInfo(), msg);
            requester.showErrorDialog(msg);
        }
    } catch (Exception exc) {
        exc.printStackTrace(System.out);
        String msg = "Exception: " + exc.getMessage() + "\n\n" + badConnectMessage(badConnStr);
        ErrorUtils.sendRemoteLogMessage(getClientServerInfo().getUserLoginInfo(), msg);
        requester.showErrorDialog(msg);
    }
    return newVCellConnection;
}
Also used : VCellConnection(cbit.vcell.server.VCellConnection) RemoteProxyVCellConnectionFactory(cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory) AuthenticationException(org.vcell.util.AuthenticationException) LocalVCellConnectionService(cbit.vcell.server.LocalVCellConnectionService) HttpResponseException(org.apache.http.client.HttpResponseException) PropertyLoader(cbit.vcell.resource.PropertyLoader) VCellConnectionFactory(cbit.vcell.server.VCellConnectionFactory) RemoteProxyVCellConnectionFactory(cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory) ConnectionException(cbit.vcell.server.ConnectionException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) AuthenticationException(org.vcell.util.AuthenticationException) RemoteProxyException(cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory.RemoteProxyException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) ConnectionException(cbit.vcell.server.ConnectionException)

Example 54 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project weixin-java-tools by chanjarster.

the class InputStreamResponseHandler method handleResponse.

public InputStream handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
    final StatusLine statusLine = response.getStatusLine();
    final HttpEntity entity = response.getEntity();
    if (statusLine.getStatusCode() >= 300) {
        EntityUtils.consume(entity);
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    return entity == null ? null : entity.getContent();
}
Also used : StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 55 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project blueocean-plugin by jenkinsci.

the class HttpRequest method executeInternal.

private Content executeInternal() throws IOException {
    String uriPath = urlParts.size() > 0 ? UriTemplate.fromTemplate(requestUrl).expand(urlParts) : requestUrl;
    URIBuilder uri;
    String fullUrl;
    try {
        uri = new URIBuilder(baseUrl + uriPath);
        fullUrl = uri.toString();
    } catch (URISyntaxException ex) {
        throw new RuntimeException("could not parse request URL: " + baseUrl + requestUrl, ex);
    }
    logger.info("request url: " + fullUrl);
    Request request;
    switch(method) {
        case GET:
            request = Request.Get(fullUrl);
            break;
        case POST:
            request = Request.Post(fullUrl);
            break;
        case PUT:
            request = Request.Put(fullUrl);
            break;
        case PATCH:
            request = Request.Patch(fullUrl);
            break;
        case DELETE:
            request = Request.Delete(fullUrl);
            break;
        default:
            throw new RuntimeException("Invalid method: " + method);
    }
    headers.forEach(request::setHeader);
    if (requestBody != null) {
        request.bodyString(requestBody, ContentType.parse(contentType));
    }
    Executor exec = Executor.newInstance();
    // use 'Authorization: Basic' for username/password
    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
        String authHost = uri.getPort() != -1 ? String.format("%s:%s", uri.getHost(), uri.getPort()) : uri.getHost();
        exec.authPreemptive(authHost).auth(username, password);
    }
    try {
        Response response = exec.execute(request);
        HttpResponse httpResponse = response.returnResponse();
        int returnedStatusCode = httpResponse.getStatusLine().getStatusCode();
        if (expectedStatus != returnedStatusCode) {
            throw new RuntimeException(String.format("Status code %s did not match expected %s", returnedStatusCode, expectedStatus));
        }
        // manually build content to avoid 'already consumed' exception from response.returnContent()
        return new ContentResponseHandler().handleEntity(httpResponse.getEntity());
    } catch (HttpResponseException ex) {
        throw new RuntimeException("Unexpected error during request", ex);
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) Response(org.apache.http.client.fluent.Response) ContentResponseHandler(org.apache.http.client.fluent.ContentResponseHandler) Executor(org.apache.http.client.fluent.Executor) Request(org.apache.http.client.fluent.Request) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

HttpResponseException (org.apache.http.client.HttpResponseException)82 IOException (java.io.IOException)32 StatusLine (org.apache.http.StatusLine)30 HttpEntity (org.apache.http.HttpEntity)25 HttpGet (org.apache.http.client.methods.HttpGet)14 HttpResponse (org.apache.http.HttpResponse)13 BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)11 Header (org.apache.http.Header)9 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 URISyntaxException (java.net.URISyntaxException)8 ArrayList (java.util.ArrayList)8 URI (java.net.URI)7 Document (org.jsoup.nodes.Document)7 Test (org.junit.Test)7 InputStream (java.io.InputStream)6 Expectations (mockit.Expectations)5 HttpClient (org.apache.http.client.HttpClient)5 Element (org.jsoup.nodes.Element)5 SubstitutionSchedule (me.vertretungsplan.objects.SubstitutionSchedule)4 HttpPost (org.apache.http.client.methods.HttpPost)4