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:org.seasr.meandre.components.nlp.calais.OpenCalaisClient.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    String text = DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))[0];

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.useragent", "SEASR " + getClass().getSimpleName());
    try {/*from w ww .j  av a2s .c o  m*/
        HttpPost post = new HttpPost(CALAIS_URL);
        post.setEntity(new StringEntity(text, _charset));
        for (Entry<String, String> entry : _headers.entrySet())
            post.setHeader(entry.getKey(), entry.getValue());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpClient.execute(post, responseHandler);

        cc.pushDataComponentToOutput(OUT_RESPONSE, BasicDataTypesTools.stringToStrings(response));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:io.werval.gradle.ApplicationPluginIntegTest.java

@Test
public void startTaskIntegrationTest() throws InterruptedException, IOException {
    final Holder<Exception> errorHolder = new Holder<>();
    Thread runThread = new Thread(newRunnable(errorHolder, "start"), "gradle-werval-start-thread");
    try {//from   w w  w  .  j  ava  2s  .co  m
        runThread.start();

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

        await().atMost(60, SECONDS).pollInterval(5, SECONDS).until(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    return client.execute(get, handler);
                } catch (Exception ex) {
                    return null;
                }
            }
        }, allOf(containsString("I ran!"), containsString("custom")));

        client.getConnectionManager().shutdown();

        if (errorHolder.isSet()) {
            throw new RuntimeException(
                    "Error during werval:start invocation: " + errorHolder.get().getMessage(),
                    errorHolder.get());
        }
    } finally {
        runThread.interrupt();
    }
}

From source file:org.sociotech.communitymashup.framework.java.apiwrapper.CommunityMashupApi.java

/**
 * Processes a post request against the given url.
 * //w w  w .ja v  a  2s . com
 * @param url
 *            Url for the get request.
 * @param parameterMap
 * @return The response as string
 * @throws MashupConnectionException
 *             If connection was not successful
 */
@SuppressWarnings("unused")
private String doPost(String url, Map<String, String> parameterMap) throws MashupConnectionException {
    String result = null;

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    // add all post parameter
    for (String key : parameterMap.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key)));
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        throw new MashupConnectionException(e, url);
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Checks if is ready.//from  ww  w  .  j a v  a2s .  c om
 *
 * @param endPoint the end point
 * @param testId the test id
 * @param client the client (optional)
 * @return true, if is ready
 * @throws Exception
 */
public static boolean isReady(String endPoint, String testId, CloseableHttpClient client) throws Exception {

    if (testId == null) {
        return false;
    }

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId + "/progress");

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);
        HttpResponse response;

        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);

            JSONObject jsonRoot = new JSONObject(body);

            // Completed when estimated number of Test Steps is equal to completed Test Steps
            // Somehow this condition is necessary but not sufficient
            // so another check on real value of test is evaluated
            return jsonRoot.getInt("val") == jsonRoot.getInt("max")
                    & InspireValidatorUtils.isPassed(endPoint, testId, client) != null;

        } else if (response.getStatusLine().getStatusCode() == 404) {

            throw new NotFoundException("Test not found");

        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress");
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        throw e;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }

    return false;
}

From source file:com.mobiperf_library.Checkin.java

private String serviceRequest(String url, String jsonString) throws IOException {

    if (this.accountSelector == null) {
        accountSelector = new AccountSelector(context);
    }/*from  ww w  . j  a  v  a 2  s . c o  m*/
    if (!accountSelector.isAnonymous()) {
        synchronized (this) {
            if (authCookie == null) {
                if (!checkGetCookie()) {
                    throw new IOException("No authCookie yet");
                }
            }
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = (accountSelector.isAnonymous() ? phoneUtils.getAnonymousServerUrl()
            : phoneUtils.getServerUrl()) + "/" + url;
    Logger.i("Checking in to " + fullurl);
    HttpPost postMethod = new HttpPost(fullurl);

    StringEntity se;
    try {
        se = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }
    postMethod.setEntity(se);
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");
    if (!accountSelector.isAnonymous()) {
        // TODO(mdw): This should not be needed
        postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue());
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    Logger.i("Sending request: " + fullurl);
    String result = client.execute(postMethod, responseHandler);
    return result;
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public WebResponse uploadFile(String path, String fname, InputStream in, String stoken)
        throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(path);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);

    builder.addPart("fname", fn);
    builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);

    BasicCookieStore cookieStore = new BasicCookieStore();

    if (stoken != null) {
        BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken);
        cookie.setDomain(TestConstants.JETTY_HOST);
        cookie.setPath("/");
        cookieStore.addCookie(cookie);//from   w  w w  .j  a  va  2  s.c  o  m
    }

    TestConstants.LOG.debug("stoken=" + stoken);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpEntity entity = builder.build();

    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    String body;
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        body = handler.handleResponse(response);
    } catch (HttpResponseException e) {
        return new WebResponse(e.getStatusCode(), e.getMessage());
    }

    return new WebResponse(response.getStatusLine().getStatusCode(), body);
}

From source file:com.pk.wallpapermanager.PkWallpaperManager.java

/**
 * Loads wallpapers stored on your cloud repository.
 * May throw an exception so watch out and handle it carefully.
 * // w  ww.j  a va 2  s.  c  o m
 * Note: Do NOT call this from the main UI thread of it will force close!
 *        Call this from a separate thread instead.
 * 
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public void fetchCloudWallpapers() throws ClientProtocolException, IOException, JSONException {
    // Cancel if not enabled
    if (!mSettings.getWebEnabled()) {
        if (debugEnabled)
            Log.d(LOG_TAG, "Cloud wallpapers aren't enabled in settings! Canceling task...");

        return;
    }

    // Retrieve Metadata URL or build default (if null)
    String metadataURL = mSettings.getMetadataURL();
    if (metadataURL == null) {
        metadataURL = mSettings.getStorageURL() + "/" + mSettings.getWallpaperPath() + "/"
                + DEFAULT_METADATA_FILE_NAME;
    }

    // Make a request to the Metadata URL and wait for the JSON response
    HttpGet get = new HttpGet(metadataURL);

    if (debugEnabled)
        Log.d(LOG_TAG, "Sending wallpaper info data request to " + metadataURL + "...");

    String response = "";
    try {
        response = httpClient.execute(get, new BasicResponseHandler());

        if (debugEnabled)
            Log.d(LOG_TAG, "Response: " + response);
    } catch (Exception e) {
        if (debugEnabled) {
            Log.d(LOG_TAG,
                    "Unable to make a request to metadata URL! Are you sure you specified your metadata URL in settings correctly?");
        }
    }

    // Loop through all listeners notifying them
    for (CloudWallpaperListener mListener : mCloudWallpaperListeners) {
        mListener.onCloudWallpapersLoading();
    }

    // Convert response into JSONArray and loop through it
    JSONArray jsonResponse = new JSONArray(response);
    int responseLength = jsonResponse.length();
    mCloudWallpapers.clear();
    Wallpaper mWall = null;

    for (int index = 0; index < responseLength; index++) {
        JSONObject jsonWallpaper = jsonResponse.getJSONObject(index);

        mWall = new Wallpaper();
        mWall.setPathURL(mSettings.getStorageURL() + "/" + mSettings.getWallpaperPath() + "/");
        mWall.setRelativeFullURL(jsonWallpaper.getString(FULL_SRC));
        mWall.setRelativeThumbURL(jsonWallpaper.getString(THUMB_SRC));
        mWall.setFullUri(Uri.parse(mWall.getFullURL()));
        mWall.setThumbUri(Uri.parse(mWall.getThumbURL()));
        mWall.setTitle(jsonWallpaper.getString(TITLE));
        mWall.setByLine(jsonWallpaper.getString(BYLINE));
        mWall.setFileSize(jsonWallpaper.getLong(FILE_SIZE));
        mWall.setLocal(false);
        mCloudWallpapers.add(mWall);

        if (debugEnabled)
            Log.d(LOG_TAG, mWall.toString());

        mWall = null;
    }

    if (debugEnabled)
        Log.d(LOG_TAG, "Finished loading " + mCloudWallpapers.size() + " cloud wallpapers!");

    // Loop through all listeners notifying them
    for (CloudWallpaperListener mListener : mCloudWallpaperListeners) {
        mListener.onCloudWallpapersLoaded();
    }
}

From source file:com.josephblough.sbt.transport.SbaTransport.java

private static List<LoanAndGrantData> getLoansAndGrantsData(final String url) {
    try {//w w  w. j a v  a2 s  .c  om
        HttpClient client = new DefaultHttpClient();
        Log.d(TAG, "url: " + url);
        HttpGet httpMethod = new HttpGet(url);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = client.execute(httpMethod, handler);

        JSONArray array = new JSONArray(response);

        return processLoansAndGrantsData(array);
    } catch (OutOfMemoryError e) {
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    }
    return null;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

/**
 * Login to Bungeni via the OAuth route//w w w.j  av a2 s .c o  m
 * @param oauthForwardURL
 * @param oauthCameFromURL
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL)
        throws UnsupportedEncodingException, IOException {

    final HttpPost post = new HttpPost(oauthForwardURL);
    final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>();
    nameValuePairs.put("login", new StringBody(this.getUser()));
    nameValuePairs.put("password", new StringBody(this.getPassword()));
    nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL));
    nameValuePairs.put("actions.login", new StringBody("login"));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    HttpContext context = new BasicHttpContext();
    post.setEntity(entity);
    HttpResponse oauthResponse = client.execute(post, context);
    // if the OAuth page retrieval failed throw an exception
    if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(oauthResponse.getStatusLine().toString());
    }
    String currentUrl = getRequestEndContextURL(context);
    // consume the response
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(oauthResponse);
    consumeContent(oauthResponse.getEntity());
    return currentUrl;
}