Example usage for android.util Log VERBOSE

List of usage examples for android.util Log VERBOSE

Introduction

In this page you can find the example usage for android.util Log VERBOSE.

Prototype

int VERBOSE

To view the source code for android.util Log VERBOSE.

Click Source Link

Document

Priority constant for the println method; use Log.v.

Usage

From source file:nl.frankkie.bronylivewallpaper.CLog.java

public static void v(String tag, String msg) {
    if (shouldLog && errorLevel <= Log.VERBOSE) {
        Log.v(tag, msg);
    }
}

From source file:com.goliathonline.android.kegbot.io.RemoteTapHandler.java

/** {@inheritDoc} */
@Override/* ww  w.j  a  v  a2 s  .  c o m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    if (parser.has("result")) {
        JSONObject events = parser.getJSONObject("result");
        JSONArray resultArray = events.getJSONArray("taps");
        int numKegs = resultArray.length();

        JSONObject taps;
        for (int i = 0; i < numKegs; i++) {
            taps = resultArray.getJSONObject(i);

            JSONObject keg = taps.getJSONObject("keg");
            JSONObject tap = taps.getJSONObject("tap");
            JSONObject beer = taps.getJSONObject("beer_type");
            JSONObject image = beer.getJSONObject("image");

            final String tapId = sanitizeId(tap.getString("id"));
            final Uri tapUri = Taps.buildTapUri(tapId);

            // Check for existing details, only update when changed
            final ContentValues values = queryTapDetails(tapUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found tap " + tapId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(tapUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Taps.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Taps.TAP_ID, tapId);

            if (tap.has("name"))
                builder.withValue(Taps.TAP_NAME, tap.getString("name"));

            if (tap.has("current_keg_id"))
                builder.withValue(Taps.KEG_ID, tap.getDouble("current_keg_id"));

            if (keg.has("status"))
                builder.withValue(Taps.STATUS, keg.getString("status"));

            if (keg.has("percent_full"))
                builder.withValue(Taps.PERCENT_FULL, keg.getString("percent_full"));

            if (keg.has("size_name"))
                builder.withValue(Taps.SIZE_NAME, keg.getString("size_name"));

            if (keg.has("volume_ml_remain"))
                builder.withValue(Taps.VOL_REMAIN, keg.getDouble("volume_ml_remain"));

            if (keg.has("size_volume_ml"))
                builder.withValue(Taps.VOL_SIZE, keg.getDouble("size_volume_ml"));

            if (beer.has("name"))
                builder.withValue(Taps.BEER_NAME, beer.getString("name"));

            if (keg.has("description"))
                builder.withValue(Taps.DESCRIPTION, keg.getString("description"));

            JSONObject last_temp = tap.getJSONObject("last_temperature");

            if (last_temp.has("temperature_c"))
                builder.withValue(Taps.LAST_TEMP, last_temp.getString("temperature_c"));

            if (last_temp.has("record_time"))
                builder.withValue(Taps.LAST_TEMP_TIME, last_temp.getString("record_time"));

            if (image.has("url"))
                builder.withValue(Taps.IMAGE_URL, image.getString("url"));

            // Normal tap details ready, write to provider
            batch.add(builder.build());
        }
    }

    return batch;
}

From source file:com.facebook.stetho.inspector.ChromeDevtoolsServer.java

@Override
public void onMessage(SimpleSession session, String message) {
    if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
        LogRedirector.v(TAG, "onMessage: message=" + message);
    }/*from   www . j a  v  a2 s  .  c o  m*/
    try {
        JsonRpcPeer peer = mPeers.get(session);
        Util.throwIfNull(peer);

        handleRemoteMessage(peer, message);
    } catch (IOException e) {
        if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
            LogRedirector.v(TAG, "Unexpected I/O exception processing message: " + e);
        }
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (MessageHandlingException e) {
        LogRedirector.i(TAG, "Message could not be processed by implementation: " + e);
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (JSONException e) {
        LogRedirector.v(TAG, "Unexpected JSON exception processing message", e);
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    }
}

From source file:com.geocine.mms.com.android.mms.transaction.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.//ww w.j  a v  a 2  s .  c  o  m
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
                    Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.v(TAG, "httpConnection: transfer encoding is chunked");
                    int bytesTobeRead = MmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset)
                                    + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.deliciousdroid.client.NetworkUtilities.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * /*from w ww.ja  v a  2 s .c  o m*/
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:carbon.internal.PercentLayoutHelper.java

/**
 * Constructs a PercentLayoutInfo from attributes associated with a View. Call this method from
 * {@code LayoutParams(Context c, AttributeSet attrs)} constructor.
 *//*from   w  w  w  .j ava  2  s .  co m*/
public static PercentLayoutInfo getPercentLayoutInfo(Context context, AttributeSet attrs) {
    PercentLayoutInfo info = null;
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Carbon);
    float value = array.getFraction(R.styleable.Carbon_carbon_widthPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent width: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.widthPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_heightPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent height: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.heightPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.leftMarginPercent = value;
        info.topMarginPercent = value;
        info.rightMarginPercent = value;
        info.bottomMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginLeftPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent left margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.leftMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginTopPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent top margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.topMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginRightPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent right margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.rightMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginBottomPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent bottom margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.bottomMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginStartPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent start margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.startMarginPercent = value;
    }
    value = array.getFraction(R.styleable.Carbon_carbon_marginEndPercent, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent end margin: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.endMarginPercent = value;
    }

    value = array.getFraction(R.styleable.Carbon_carbon_aspectRatio, 1, 1, -1f);
    if (value != -1f) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "aspect ratio: " + value);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.aspectRatio = value;
    }

    array.recycle();
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "constructed: " + info);
    }
    return info;
}

From source file:com.kth.common.utils.etc.LogUtil.java

/**
 * VERBOSE  ?.//from  www .j a v a  2  s  .  co  m
 * 
 * @param clazz  ??  Class.
 * @param msg .
 * @param tr Throwable.
 */
public static void v(final Class<?> clazz, final String msg, final Throwable tr) {
    if (LogUtil.isVerboseEnabled()) {
        Log.println(Log.VERBOSE, TAG,
                LogUtil.getClassLineNumber(clazz) + " - " + msg + '\n' + Log.getStackTraceString(tr));

        //  ?? ?   ?.
        if (LogUtil.isFileLogEnabled()) {
            write(Log.VERBOSE, LogUtil.getClassLineNumber(clazz), msg, tr);
        }
    }
}

From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java

/** {@inheritDoc} */
@Override//  w w w  .jav  a 2  s  .  c om
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(drinkUri).build());
            batch.add(ContentProviderOperation.newDelete(drinkKegUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Drinks.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

            // Inherit starred value from previous row
            if (values.containsKey(Drinks.DRINK_STARRED)) {
                builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED));
            }

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

            // Normal session details ready, write to provider
            batch.add(builder.build());

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build());
            }
        }
    }

    return batch;
}

From source file:com.example.jumpnote.android.jsonrpc.JsonRpcJavaClient.java

public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) {
    HttpPost httpPost = new HttpPost(mRpcUrl);
    JSONObject requestJson = new JSONObject();
    JSONArray callsJson = new JSONArray();
    try {//from ww  w  . j a  v a  2s  . c om
        for (int i = 0; i < calls.size(); i++) {
            JsonRpcClient.Call call = calls.get(i);

            JSONObject callJson = new JSONObject();

            callJson.put("method", call.getMethodName());

            if (call.getParams() != null) {
                JSONObject callParams = (JSONObject) call.getParams();
                @SuppressWarnings("unchecked")
                Iterator<String> keysIterator = callParams.keys();
                String key;
                while (keysIterator.hasNext()) {
                    key = keysIterator.next();
                    callJson.put(key, callParams.get(key));
                }
            }

            callsJson.put(i, callJson);
        }

        requestJson.put("calls", callsJson);
        httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8"));
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "POST request: " + requestJson.toString());
        }
    } catch (JSONException e) {
        // throw e;
    } catch (UnsupportedEncodingException e) {
        // throw e;
    }

    try {
        HttpResponse httpResponse = mHttpClient.execute(httpPost);
        final int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
        if (200 <= responseStatusCode && responseStatusCode < 300) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "POST response: " + sb.toString());
            }
            JSONTokener tokener = new JSONTokener(sb.toString());
            JSONObject responseJson = new JSONObject(tokener);
            JSONArray resultsJson = responseJson.getJSONArray("results");
            Object[] resultData = new Object[calls.size()];

            for (int i = 0; i < calls.size(); i++) {
                JSONObject result = resultsJson.getJSONObject(i);
                if (result.has("error")) {
                    callback.onError(i, new JsonRpcException((int) result.getInt("error"),
                            calls.get(i).getMethodName(), result.getString("message"), null));
                    resultData[i] = null;
                } else {
                    resultData[i] = result.get("data");
                }
            }

            callback.onData(resultData);
        } else {
            callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: "
                    + httpResponse.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException e) {
        Log.e("JsonRpcJavaClient", e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:ir.keloud.android.lib.common.SingleSessionManager.java

@Override
public KeloudClient getClientFor(KeloudAccount account, Context context)
        throws AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log_OC.d(TAG, "getClientFor starting ");
    }/*from   ww w .  j ava  2  s . co  m*/
    if (account == null) {
        throw new IllegalArgumentException("Cannot get an KeloudClient for a null account");
    }

    KeloudClient client = null;
    String accountName = account.getName();
    String sessionName = account.getCredentials() == null ? ""
            : AccountUtils.buildAccountName(account.getBaseUri(), account.getCredentials().getAuthToken());

    if (accountName != null) {
        client = mClientsWithKnownUsername.get(accountName);
    }
    boolean reusingKnown = false; // just for logs
    if (client == null) {
        if (accountName != null) {
            client = mClientsWithUnknownUsername.remove(sessionName);
            if (client != null) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log_OC.v(TAG, "reusing client for session " + sessionName);
                }
                mClientsWithKnownUsername.put(accountName, client);
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log_OC.v(TAG, "moved client to account " + accountName);
                }
            }
        } else {
            client = mClientsWithUnknownUsername.get(sessionName);
        }
    } else {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log_OC.v(TAG, "reusing client for account " + accountName);
        }
        reusingKnown = true;
    }

    if (client == null) {
        // no client to reuse - create a new one
        client = KeloudClientFactory.createKeloudClient(account.getBaseUri(), context.getApplicationContext(),
                true); // TODO remove dependency on KeloudClientFactory
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // enable cookie tracking

        AccountUtils.restoreCookies(accountName, client, context);

        account.loadCredentials(context);
        client.setCredentials(account.getCredentials());
        if (accountName != null) {
            mClientsWithKnownUsername.put(accountName, client);
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log_OC.v(TAG, "new client for account " + accountName);
            }

        } else {
            mClientsWithUnknownUsername.put(sessionName, client);
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log_OC.v(TAG, "new client for session " + sessionName);
            }
        }
    } else {
        if (!reusingKnown && Log.isLoggable(TAG, Log.VERBOSE)) {
            Log_OC.v(TAG, "reusing client for session " + sessionName);
        }
        keepCredentialsUpdated(account, client);
        keepUriUpdated(account, client);
    }

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log_OC.d(TAG, "getClientFor finishing ");
    }
    return client;
}