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

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

Introduction

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

Prototype

public ClientProtocolException() 

Source Link

Usage

From source file:org.adblockplus.android.CrashReportDialog.java

public void onOk(View v) {
    String comment = ((EditText) findViewById(R.id.comments)).getText().toString();

    try {/*from ww  w .j  a va 2  s. co  m*/
        String[] reportLines = report.split(System.getProperty("line.separator"));
        int api = Integer.parseInt(reportLines[0]);
        int build = Integer.parseInt(reportLines[1]);

        XmlSerializer xmlSerializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();

        xmlSerializer.setOutput(writer);
        xmlSerializer.startDocument("UTF-8", true);
        xmlSerializer.startTag("", "crashreport");
        xmlSerializer.attribute("", "version", "1");
        xmlSerializer.attribute("", "api", String.valueOf(api));
        xmlSerializer.attribute("", "build", String.valueOf(build));
        xmlSerializer.startTag("", "error");
        xmlSerializer.attribute("", "type", reportLines[2]);
        xmlSerializer.startTag("", "message");
        xmlSerializer.text(reportLines[3]);
        xmlSerializer.endTag("", "message");
        xmlSerializer.startTag("", "stacktrace");
        Pattern p = Pattern.compile("\\|");
        boolean hasCause = false;
        int i = 4;
        while (i < reportLines.length) {
            if ("cause".equals(reportLines[i])) {
                xmlSerializer.endTag("", "stacktrace");
                xmlSerializer.startTag("", "cause");
                hasCause = true;
                i++;
                xmlSerializer.attribute("", "type", reportLines[i]);
                i++;
                xmlSerializer.startTag("", "message");
                xmlSerializer.text(reportLines[i]);
                i++;
                xmlSerializer.endTag("", "message");
                xmlSerializer.startTag("", "stacktrace");
                continue;
            }
            Log.e(TAG, "Line: " + reportLines[i]);
            String[] element = TextUtils.split(reportLines[i], p);
            xmlSerializer.startTag("", "frame");
            xmlSerializer.attribute("", "class", element[0]);
            xmlSerializer.attribute("", "method", element[1]);
            xmlSerializer.attribute("", "isnative", element[2]);
            xmlSerializer.attribute("", "file", element[3]);
            xmlSerializer.attribute("", "line", element[4]);
            xmlSerializer.endTag("", "frame");
            i++;
        }
        xmlSerializer.endTag("", "stacktrace");
        if (hasCause)
            xmlSerializer.endTag("", "cause");
        xmlSerializer.endTag("", "error");
        xmlSerializer.startTag("", "comment");
        xmlSerializer.text(comment);
        xmlSerializer.endTag("", "comment");
        xmlSerializer.endTag("", "crashreport");
        xmlSerializer.endDocument();

        String xml = writer.toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(getString(R.string.crash_report_url));
        httppost.setHeader("Content-Type", "text/xml; charset=UTF-8");
        httppost.addHeader("X-Adblock-Plus", "yes");
        httppost.setEntity(new StringEntity(xml));
        HttpResponse httpresponse = httpclient.execute(httppost);
        StatusLine statusLine = httpresponse.getStatusLine();
        Log.e(TAG, statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        Log.e(TAG, EntityUtils.toString(httpresponse.getEntity()));
        if (statusLine.getStatusCode() != 200)
            throw new ClientProtocolException();
        String response = EntityUtils.toString(httpresponse.getEntity());
        if (!"saved".equals(response))
            throw new ClientProtocolException();
        deleteFile(CrashHandler.REPORT_FILE);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "Failed to submit a crash", e);
        Toast.makeText(this, R.string.msg_crash_submission_failure, Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        Log.e(TAG, "Failed to submit a crash", e);
        Toast.makeText(this, R.string.msg_crash_submission_failure, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Log.e(TAG, "Failed to create report", e);
        // Assuming corrupted report file, just silently deleting it
        deleteFile(CrashHandler.REPORT_FILE);
    }
    finish();
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportPollTest.java

@Test
public void testPollWrapsClientExceptionInLaunchKeyException() throws Exception {
    ClientProtocolException expectedCause = new ClientProtocolException();
    expectedException.expect(LaunchKeyException.class);
    expectedException.expectMessage("Exception caught processing poll request");
    expectedException.expectCause(is(expectedCause));

    when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(expectedCause);
    transport.poll(new PollRequest(null, 0L, null, null));
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportUsersTest.java

@Test
public void testWrapsClientExceptionInLaunchKeyException() throws Exception {
    ClientProtocolException expectedCause = new ClientProtocolException();
    expectedException.expect(LaunchKeyException.class);
    expectedException.expectMessage("Exception processing users request");
    expectedException.expectCause(is(expectedCause));

    when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(expectedCause);
    transport.users(new UsersRequest(null, 0L, null));
}

From source file:org.robertburrelldonkin.template4couchdb.rest.HttpClientRestClientTest.java

@Test(expected = HttpClientRestClientException.class)
public void testPostClientProcotolExceptionRethrow() throws Exception {
    when(client.execute((HttpPost) anyObject(), eq(handler))).thenThrow(new ClientProtocolException());
    this.subject.post(URL, documentMarshaller, document, responseUnmarshaller);
}

From source file:com.comcast.drivethru.client.ClientExecuteTest.java

@DataProvider(name = "exceptionTests")
public Iterator<Object[]> getExceptionTests() {
    List<Object[]> tests = new ArrayList<>();

    tests.add(new Object[] { new RuntimeException("example"), RuntimeException.class, "example" });
    tests.add(new Object[] { new HttpResponseException(500, "Internal Server Error"), HttpStatusException.class,
            "500" });
    tests.add(new Object[] { new ClientProtocolException(), HttpException.class, "HTTP Protocol" });
    tests.add(new Object[] { new IOException(), HttpException.class, "Error establishing connection" });

    return tests.iterator();
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportLogsTest.java

@Test
public void testWrapsClientExceptionInLaunchKeyException() throws Exception {
    ClientProtocolException expectedCause = new ClientProtocolException();
    expectedException.expect(CommunicationErrorException.class);
    expectedException.expectMessage("Exception caught processing logs request");
    expectedException.expectCause(is(expectedCause));

    when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(expectedCause);
    transport.logs(new LogsRequest("Authenticate", true, null, 0L, null, null));
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportAuthsTest.java

@Test
public void testAuthsWrapsClientExceptionInLaunchKeyException() throws Exception {
    ClientProtocolException expectedCause = new ClientProtocolException();
    expectedException.expect(LaunchKeyException.class);
    expectedException.expectMessage("Exception caught processing auths request");
    expectedException.expectCause(is(expectedCause));

    when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(expectedCause);
    transport.auths(new AuthsRequest(null, 0L, null, null, 0, 0));
}

From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModuleTest.java

@Test
public void noActionWithHttpExceptions() throws Exception {
    setupNeededComponents();// w ww  .  ja  v a2 s . co  m
    when(this.client.execute(any(HttpPost.class))).thenThrow(new ClientProtocolException(), new IOException());
    Assert.assertNull(this.mocker.getComponentUnderTest().hasAccess(this.user, this.access, this.document));
    Assert.assertNull(this.mocker.getComponentUnderTest().hasAccess(this.user, this.access, this.document));
    verify(this.cache, never()).set(Matchers.anyString(), Matchers.anyBoolean());
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryWithExceptions(String dms_endpoint, String body, String method)
        throws SocketTimeoutException, ConnectException, IOException, InterruptedException {
    Cookie ck;/*from  w w  w . jav  a  2s.com*/
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;

    httpclient = HttpClients.createDefault();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(dms_URL + "/" + dms_endpoint);
    } catch (URISyntaxException e1) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(5000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);

    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);

    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        throw new ClientProtocolException();
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                throw new InterruptedException();
                // e1.printStackTrace();
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea);
            throw new ClientProtocolException();
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                    throw new InterruptedException();
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ClientProtocolException();
            } catch (SocketTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new SocketTimeoutException();
            } catch (ConnectException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectException();
            } catch (ConnectTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectTimeoutException();
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 503");
            throw new ServiceUnavailableException();
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 502");
            throw new ServerErrorException(502);
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "could't Athorize the DMS");
            throw new NotAuthorizedException("could't Athorize the DMS");
        } else {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 500");
            throw new ServiceUnavailableException();
        }
    }

    HttpEntity entity;
    entity = response.getEntity();
    String respString = "";

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return respString;

}