Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

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

Prototype

BasicResponseHandler

Source Link

Usage

From source file:dk.i2m.drupal.resource.NodeResource.java

public NodeMessage create(UrlEncodedFormEntity uefe) throws HttpResponseException, IOException {
    URLBuilder builder = new URLBuilder(getDc().getHostname());
    builder.add(getDc().getEndpoint());//from   w  w  w . ja v  a  2 s  . c  om
    builder.add(getAlias());

    HttpPost method = new HttpPost(builder.toURI());
    method.setEntity(uefe);

    ResponseHandler<String> handler = new BasicResponseHandler();
    String response = getDc().getHttpClient().execute(method, handler);

    return new Gson().fromJson(response, NodeMessage.class);
}

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.RequestExecutor.java

public String execute(CloseableHttpClient client, HttpUriRequest method) {
    try (CloseableHttpResponse resp = client.execute(method)) {
        checkResponseCode(resp.getStatusLine());

        ResponseHandler<String> handler = new BasicResponseHandler();

        return handler.handleResponse(resp);
    } catch (AccessDenied ex) {
        throw new AccessDenied(
                "Test automation - jenkins : operation rejected the operation because of wrong credentials"); // NOSONAR no need for actual call stack
    } catch (IOException ex) {
        throw new ServerConnectionFailed(
                "Test automation - jenkins : could not connect to server due to technical error : ", ex);
    }/*from w  ww .j  a  v  a  2  s.  c  o m*/
}

From source file:org.labkey.freezerpro.export.GetFreezersCommand.java

public FreezerProCommandResonse execute(HttpClient client, PipelineJob job) {
    HttpPost post = new HttpPost(_url);

    try {/* w w w  .  j  a  v  a 2  s. c  o  m*/
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "freezers"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));

        post.setEntity(new UrlEncodedFormEntity(params));

        ResponseHandler<String> handler = new BasicResponseHandler();

        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            return new GetFreezersResponse(_export, handler.handleResponse(response), status.getStatusCode(),
                    job);
        else
            return new GetFreezersResponse(_export, status.getReasonPhrase(), status.getStatusCode(), job);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.solr.handler.CheckBackupStatus.java

public void fetchStatus() throws IOException {
    String masterUrl = client.getBaseURL() + "/" + coreName + ReplicationHandler.PATH + "?command="
            + ReplicationHandler.CMD_DETAILS;
    response = client.getHttpClient().execute(new HttpGet(masterUrl), new BasicResponseHandler());
    if (pException.matcher(response).find()) {
        fail("Failed to create backup");
    }//from   w w  w. ja v  a2 s  . c o m
    if (response.contains("<str name=\"status\">success</str>")) {
        Matcher m = p.matcher(response);
        if (!m.find()) {
            fail("could not find the completed timestamp in response.");
        }
        if (lastBackupTimestamp != null) {
            backupTimestamp = m.group(1);
            if (backupTimestamp.equals(lastBackupTimestamp)) {
                success = true;
            }
        } else {
            success = true;
        }
    }
}

From source file:org.openengsb.openengsbplugin.tools.OpenEngSBVersionResolver.java

public String resolveUri() throws NoVersionFoundException {
    try {//from  w ww. jav  a  2 s  . c  o m

        HttpClient client = new DefaultHttpClient();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        HttpGet httpget = new HttpGet(defaultUri);
        return client.execute(httpget, responseHandler);
    } catch (MalformedURLException e) {
        throw new NoVersionFoundException("Unknown URI", e);
    } catch (IOException e) {
        throw new NoVersionFoundException("IOException caught", e);
    }
}

From source file:com.oauth.servlet.AuthorizationCallbackServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*ww  w  .  j  a  v a  2  s.  c  om*/
        System.err.println(req.getQueryString());
        System.err.println(req.getRequestURI());
        String token = null;
        String responseBody = null;
        if (req.getParameter("code") != null) {
            HttpClient httpclient = new DefaultHttpClient();
            String authCode = req.getParameter("code");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try {
                if (req.getRequestURI().indexOf("git") > 0) {
                    HttpGet httpget = new HttpGet(client.getAccessTokenUrl(authCode));

                    responseBody = httpclient.execute(httpget, responseHandler);
                    int accessTokenStartIndex = responseBody.indexOf("access_token=")
                            + "access_token=".length();
                    token = responseBody.substring(accessTokenStartIndex,
                            responseBody.indexOf("&", accessTokenStartIndex));

                } else if (req.getRequestURI().indexOf("isam") > 0) {
                    System.err.println(iSAMClient.getAccessTokenUrl());
                    HttpPost httpPost = new HttpPost(iSAMClient.getAccessTokenUrl());
                    httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

                    System.err.println("Post Params--------");
                    for (Iterator<NameValuePair> postParamIter = iSAMClient.getPostParams(authCode)
                            .iterator(); postParamIter.hasNext();) {
                        NameValuePair postParam = postParamIter.next();
                        System.err.println(postParam.getName() + "=" + postParam.getValue());
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(iSAMClient.getPostParams(authCode)));
                    System.err.println("Post Params--------");
                    responseBody = httpclient.execute(httpPost, responseHandler);
                    token = parseJsonString(responseBody);
                } else {
                    resp.sendError(HttpStatus.SC_FORBIDDEN);
                }
                System.err.println(responseBody);
                req.setAttribute("Response", responseBody);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            resp.sendRedirect("userDetails.jsp?token=" + token);
        } /*else if(req.getParameter("access_token") != null) {
           Writer w = resp.getWriter();
                    
            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("User Code [" + req.getParameter("access_token") + "] has successfully logged in!");
            w.write("</h3>");
            w.write("</center></body></html>");
                    
            w.flush();
            w.close();   
          } */else {
            Writer w = resp.getWriter();

            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("UNAUTHORIZED Access!");
            w.write("</h3>");
            w.write("</center></body></html>");

            w.flush();
            w.close();
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.qi4j.library.staticlet.StaticletServiceTest.java

@Before
public void before() {
    httpClient = new DefaultHttpClient();
    strResponseHandler = new BasicResponseHandler() {

        @Override//  w  w w.ja  va  2  s.co m
        public String handleResponse(HttpResponse response) throws HttpResponseException, IOException {
            String strResponse = super.handleResponse(response);
            LOGGER.debug("BasicResponseHandler got: {}", strResponse);
            return strResponse;
        }

    };
    host = new HttpHost("localhost", DEFAULT_PORT);
}

From source file:io.werval.maven.DevShellMojoIT.java

@Test
public void devshellMojoIntegrationTest() throws InterruptedException, IOException {
    final Holder<Exception> errorHolder = new Holder<>();
    Thread devshellThread = new Thread(newRunnable(errorHolder, "werval:devshell"),
            "maven-werval-devshell-thread");
    try {//from  ww w .  jav a  2  s  . c  o m
        devshellThread.start();

        await().atMost(60, SECONDS).until(() -> lock.exists());

        if (errorHolder.isSet()) {
            throw new RuntimeException("Error during devhell invocation: " + errorHolder.get().getMessage(),
                    errorHolder.get());
        }

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://localhost:23023/");
        ResponseHandler<String> handler = new BasicResponseHandler();

        assertThat(client.execute(get, handler), containsString("I ran!"));

        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER_CHANGED.getBytes(UTF_8));

        // Wait for source code change to be detected
        Thread.sleep(2000);

        assertThat(client.execute(get, handler), containsString("I ran changed!"));

        assertThat(client.execute(new HttpGet("http://localhost:23023/@doc"), handler),
                containsString("Werval Documentation"));

        client.getConnectionManager().shutdown();
    } finally {
        devshellThread.interrupt();
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.HttpClientIT.java

@Test
public void test() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*w  w  w.  j a va2 s.  com*/
        HttpPost post = new HttpPost("http://www.naver.com");
        post.addHeader("Content-Type", "application/json;charset=UTF-8");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        httpClient.execute(post, responseHandler);
    } catch (Exception ignored) {
    } finally {
        if (null != httpClient && null != httpClient.getConnectionManager()) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Class<?> connectorClass;

    try {
        connectorClass = Class.forName("org.apache.http.impl.conn.ManagedClientConnectionImpl");
    } catch (ClassNotFoundException e) {
        connectorClass = Class.forName("org.apache.http.impl.conn.AbstractPooledConnAdapter");
    }

    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            AbstractHttpClient.class.getMethod("execute", HttpUriRequest.class, ResponseHandler.class)));
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            connectorClass.getMethod("open", HttpRoute.class, HttpContext.class, HttpParams.class),
            annotation("http.internal.display", "www.naver.com")));
    verifier.verifyTrace(event("HTTP_CLIENT_4",
            HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class,
                    HttpContext.class),
            null, null, "www.naver.com", annotation("http.url", "/"), annotation("http.status.code", 200),
            annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}

From source file:srdes.menupp.EntreeDbAdapter.java

/**
 * @brief   Create a new review using the title and body provided. If the review is
 *          successfully created return the new rowId for that review, otherwise return
 *          a -1 to indicate failure.//from   w  w w .  ja v a  2 s . c o  m
 * 
 * @param    title the title of the note
 * 
 * @param    body the body of the note
 * 
 * @param    entree the name of the entree the review is for
 * 
 * @param    rating the rating given to the entree in the review
 * 
 * @throws    JSONException if cannot get rowID
 * 
 * @return    rowId or -1 if failed
 */
public static Long createReview(String title, String body, String entree, float rating) throws JSONException {

    //add column information to pass to database
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair(KEY_TITLE, title));
    nameValuePairs.add(new BasicNameValuePair(KEY_BODY, body));
    nameValuePairs.add(new BasicNameValuePair(KEY_ENTREE, entree));
    nameValuePairs.add(new BasicNameValuePair(KEY_RATING, new Float(rating).toString()));

    //http post
    JSONObject response = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(INSERT_REVIEW_SCRIPT);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = new JSONObject(responseBody);

    } catch (ClientProtocolException e) {
        DebugLog.LOGD("Protocol error in http connection " + e.toString());
    } catch (UnsupportedEncodingException e) {
        DebugLog.LOGD("Encoding error in http connection " + e.toString());
    } catch (IOException e) {
        DebugLog.LOGD("IO error in http connection " + e.toString());
    }
    //rowID encoded in response
    return (Long) response.get(KEY_ROWID);
}