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.appcelerator.titanium.analytics.TiAnalyticsService.java

@Override
public void onStart(Intent intent, final int startId) {
    super.onStart(intent, startId);

    if (!sending.compareAndSet(false, true)) {
        Log.i(TAG, "Send already in progress, skipping intent");
    }/*  ww  w.jav  a  2  s  .  c  o m*/

    final TiAnalyticsService self = this;

    Thread t = new Thread(new Runnable() {

        public void run() {
            Log.i(TAG, "Analytics Service Started");
            try {

                if (connectivityManager == null) {
                    Log.w(TAG, "Connectivity manager not available.");
                    stopSelf(startId);
                    return;
                }
                TiAnalyticsModel model = new TiAnalyticsModel(self);
                if (!model.hasEvents()) {
                    Log.d(TAG, "No events to send.", Log.DEBUG_MODE);
                    stopSelf(startId);
                    return;
                }

                while (model.hasEvents()) {
                    if (canSend()) {
                        LinkedHashMap<Integer, JSONObject> events = model
                                .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK);

                        int len = events.size();
                        int[] eventIds = new int[len];
                        Iterator<Integer> keys = events.keySet().iterator();

                        JSONArray records = new JSONArray();
                        // build up data to send and records to delete on success
                        for (int i = 0; i < len; i++) {
                            int id = keys.next();
                            // ids are kept even on error JSON to prevent unrestrained growth
                            // and a queue blocked by bad records.
                            eventIds[i] = id;
                            records.put(events.get(id));

                            if (Log.isDebugModeEnabled()) {
                                JSONObject obj = events.get(id);
                                Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = "
                                        + obj.getString("ts"));
                            }
                        }
                        boolean deleteEvents = true;
                        if (records.length() > 0) {
                            if (Log.isDebugModeEnabled()) {
                                Log.d(TAG, "Sending " + records.length() + " analytics events.");
                            }
                            try {
                                String jsonData = records.toString() + "\n";
                                String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL
                                        : ANALYTICS_URL + TiApplication.getInstance().getAppGUID();

                                HttpPost httpPost = new HttpPost(postUrl);
                                StringEntity entity = new StringEntity(jsonData);
                                entity.setContentType("text/json");
                                httpPost.setEntity(entity);

                                HttpParams httpParams = new BasicHttpParams();
                                HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property
                                //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property
                                HttpClient client = new DefaultHttpClient(httpParams);

                                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                                client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

                                @SuppressWarnings("unused")
                                String response = client.execute(httpPost, responseHandler);
                            } catch (Throwable t) {
                                Log.e(TAG, "Error posting events: " + t.getMessage(), t);
                                deleteEvents = false;
                                records = null;
                                break;
                            }
                        }

                        records = null;

                        if (deleteEvents) {
                            model.deleteEvents(eventIds);
                        }

                        events.clear();
                    } else {
                        Log.w(TAG, "Network unavailable, can't send analytics");
                        //TODO reset alarm?
                        break;
                    }
                }

                Log.i(TAG, "Stopping Analytics Service");
                stopSelf(startId);
            } catch (Throwable t) {
                Log.e(TAG, "Unhandled exception in analytics thread: ", t);
                stopSelf(startId);
            } finally {
                if (!sending.compareAndSet(true, false)) {
                    Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE);
                }
            }
        }
    });
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:ch.ethz.inf.vs.android.g54.a4.net.RequestHandler.java

/**
 * Execute an HTTP post on a given resource on the configured server
 * /*from ww  w  . j  a  v  a  2 s  .c  om*/
 * @param res
 *            The resource URL without host
 * @param data
 *            The data to post
 * @return a JSONObject / JSONArray
 * @throws ServerException
 * @throws ConnectionException
 * @throws UnrecognizedResponseException
 */
public Object post(String res, String data)
        throws ServerException, ConnectionException, UnrecognizedResponseException {
    U.logInPieces(TAG, String.format("Sending request for resource %s with data %s.", res, data));

    HttpClient client = new DefaultHttpClient();
    String responseBody = null;

    try {
        HttpPost post = new HttpPost(HOST + ":" + PORT + res);
        post.addHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(data);
        post.setEntity(se);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(post, responseHandler);

    } catch (ClientProtocolException e) {
        throw new ServerException("Server returned an error.", e);
    } catch (IOException e) {
        throw new ConnectionException("Could not connect to server.", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return parseResponse(responseBody);
}

From source file:gov.nih.nci.cagrid.portal.portlet.workflow.service.impl.MyExperimentWorkflowRegistry.java

private WorkflowDescription downloadWorkflow(String uri) throws WorkflowException {
    log.debug("Downloading workflow #" + uri);
    ResponseHandler<String> rh = new BasicResponseHandler();
    HttpGet get = new HttpGet(uri);
    try {/*  w w w.j  a v a  2 s .  c o  m*/
        String body = getHTTPClient().execute(get, rh);
        WorkflowDescription wd = unmarshalWorkflowDescription(new ByteArrayInputStream(body.getBytes()));
        log.debug("Workflow components: " + wd.getComponents());
        if (wd.getComponents() != null && wd.getComponents().getDataflow() != null) {
            log.debug("Getting workflow inputs.  Found " + wd.getComponents().getDataflow().size()
                    + " dataflows");
            for (WorkflowDescription.Dataflow df : wd.getComponents().getDataflow()) {
                if (df.getRole().equals("top") && df.getSource() != null && df.getSource().size() > 0) {
                    log.debug("Found root dataflow with " + df.getSource().size() + " sources");
                    wd.setInputs(df.getSource());
                    return wd;
                }
            }
        }
        return wd;
    } catch (Throwable e) {
        get.abort();
        throw new WorkflowException(e);
    }
}

From source file:eu.lod2.ConfigurationTab.java

public static List<String> request_graphs(LOD2DemoState state) throws Exception {

    List<String> result = null;

    HttpClient httpclient = new DefaultHttpClient();
    try {//from  w  w w .  j a  v a2 s. com

        String prefixurl = state.getLod2WebApiService();

        HttpGet httpget = new HttpGet(prefixurl + "/graphs");
        httpget.addHeader("accept", "application/json");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);

        result = parse_graph_api_result(responseBody);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:org.apache.tomcat.maven.it.AbstractWarProjectIT.java

private String getResponseBody() throws IOException {
    HttpGet httpGet = new HttpGet(getWebappUrl());
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return httpClient.execute(httpGet, responseHandler);
}

From source file:org.jenkinsci.plugins.appio.service.AppioService.java

/**
 * @param appName/*from ww  w .  j  a v a2 s  . co  m*/
 * @return
 * @throws Exception
 */
public AppioAppObject findApp(String appName) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ResponseHandler<String> handler = new BasicResponseHandler();
    AppioAppObject theApp = new AppioAppObject();

    try {
        // App.io Authorization and Content-Type headers
        String appioAuth = "Basic " + apiKey;
        httpGet.addHeader("Authorization", appioAuth);
        httpGet.addHeader("Accept", appio_v1);

        LOGGER.fine("AppioService.findApp() Request");
        HttpResponse response = httpClient.execute(httpHost, httpGet);
        String jsonAppioApps = handler.handleResponse(response);
        LOGGER.fine("AppioService.findApp() Response: " + jsonAppioApps);

        AppioApps appioApps = new Gson().fromJson(jsonAppioApps, AppioApps.class);
        List<AppioAppObject> list = Arrays.asList(appioApps.getApps());
        Iterator<AppioAppObject> iterator = list.iterator();

        boolean foundAppName = false;
        while ((iterator.hasNext()) && (!foundAppName)) {
            AppioAppObject thisApp = iterator.next();

            if (thisApp.getName().equals(appName)) {
                theApp = thisApp;
                foundAppName = true;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            httpClient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
    return theApp;
}

From source file:br.ufsc.das.gtscted.shibbauth.Connection.java

public String httpGet(String url) throws ClientProtocolException, IOException {
    HttpGet httpGet = new HttpGet(url);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpGet, responseHandler);
    return responseBody;
}

From source file:org.openremote.controller.protocol.http.HttpGetCommand.java

private String requestURL() {
    DefaultHttpClient client = new DefaultHttpClient();

    if (getUsername() != null) {
        CredentialsProvider cred = new BasicCredentialsProvider();

        cred.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(getUsername(), new String(password)));

        client.setCredentialsProvider(cred);
    }// w w  w . ja  v a2 s .c  o  m

    HttpGet httpget = new HttpGet(url.toExternalForm());

    String resp = "";

    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        resp = client.execute(httpget, responseHandler);
        logger.info("received message: " + resp);
    }

    catch (Exception e) {
        logger.error("HttpGetCommand could not execute", e);
    }

    return resp;
}

From source file:com.adam.aslfms.service.Scrobbler.java

/**
 * /*  w w  w. j a va2 s .com*/
 * @return a {@link ScrobbleResult} struct with some info
 * @throws BadSessionException
 * @throws TemporaryFailureException
 */
public void scrobbleCommit(HandshakeResult hInfo, Track[] tracks)
        throws BadSessionException, TemporaryFailureException {

    DefaultHttpClient http = new DefaultHttpClient();
    HttpPost request = new HttpPost(hInfo.scrobbleUri);

    List<BasicNameValuePair> data = new LinkedList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("s", hInfo.sessionId));

    for (int i = 0; i < tracks.length; i++) {
        Track track = tracks[i];
        String is = "[" + i + "]";
        data.add(new BasicNameValuePair("a" + is, track.getArtist()));
        data.add(new BasicNameValuePair("b" + is, track.getAlbum()));
        data.add(new BasicNameValuePair("t" + is, track.getTrack()));
        data.add(new BasicNameValuePair("i" + is, Long.toString(track.getWhen())));
        data.add(new BasicNameValuePair("o" + is, track.getSource()));
        data.add(new BasicNameValuePair("l" + is, Integer.toString(track.getDuration())));
        data.add(new BasicNameValuePair("n" + is, track.getTrackNr()));
        data.add(new BasicNameValuePair("m" + is, track.getMbid()));
        data.add(new BasicNameValuePair("r" + is, track.getRating()));
    }

    try {
        request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = http.execute(request, handler);
        String[] lines = response.split("\n");
        if (response.startsWith("OK")) {
            Log.i(TAG, "Scrobble success: " + getNetApp().getName());
        } else if (response.startsWith("BADSESSION")) {
            throw new BadSessionException("Scrobble failed because of badsession");
        } else if (response.startsWith("FAILED")) {
            String reason = lines[0].substring(7);
            throw new TemporaryFailureException("Scrobble failed: " + reason);
        } else {
            throw new TemporaryFailureException("Scrobble failed weirdly: " + response);
        }

    } catch (ClientProtocolException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } catch (IOException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } finally {
        http.getConnectionManager().shutdown();
    }
}

From source file:seava.j4e.web.controller.ui.extjs.DependencyLoader.java

private void writeContentByUrl(String url, Writer writer) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Loading content from URL: {}", url);
    }//from  ww w.  j a v a2 s . co  m
    HttpGet get = new HttpGet(url);
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = getHttpClient().execute(get, responseHandler);
        writer.write(responseBody);
    } catch (Exception e) {
        logger.error("Cannot find content at url " + url);
    } finally {
        get.releaseConnection();
    }

}