Example usage for android.util Log isLoggable

List of usage examples for android.util Log isLoggable

Introduction

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

Prototype

public static native boolean isLoggable(String tag, int level);

Source Link

Document

Checks to see whether or not a log for the specified tag is loggable at the specified level.

Usage

From source file:com.ntsync.android.sync.client.MySSLSocketFactory.java

private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException {
    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0) {
        throw new SSLPeerUnverifiedException("No server certificates found!");
    }//from  w  ww . j  a  v a  2  s .  c  om

    // get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    // might be useful to print out all certificates we receive from the
    // server, in case one has to debug a problem with the installed certs.
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            Log.d(TAG, "X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    // get the common name from the first cert
    String cn = getCN(dn);
    if (hostname != null && hostname.equalsIgnoreCase(cn)) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Target hostname valid: " + cn);
        }
    } else {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            return;
        }
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:com.senechaux.rutino.utils.NetworkUtilities.java

/**
 * Connects to the Voiper server, authenticates the provided username and password.
 * /*from  w w w . ja va 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 boolean The boolean result indicating whether the user was successfully authenticated.
 */
public static boolean authenticate(String username, String password, Handler handler, final Context context) {
    final HttpResponse resp;
    String response = "";
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }

    final HttpPost post = new HttpPost(Constants.AUTH_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    try {
        resp = mHttpClient.execute(post);
        response = EntityUtils.toString(resp.getEntity());
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Resp: " + resp.toString());
        }
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication, resp: " + resp.toString());
            }
            sendResult(true, handler, context, response);
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            sendResult(false, handler, context, response);
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        sendResult(false, handler, context, response);
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:com.ibm.commerce.worklight.android.search.SearchSuggestionsProvider.java

/**
 * Performs the search by projections and selection arguments
 * @param uri The URI to be used//from  w ww. ja v  a 2  s .  c  om
 * @param projection The string array for the search
 * @param selection The selection string
 * @param selectionArgs The selection arguments
 * @param sortOrder The sort order
 * @return The cursor containing the suggestions
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final String METHOD_NAME = CLASS_NAME + ".query()";
    boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG);
    if (loggingEnabled) {
        Log.d(METHOD_NAME, "ENTRY");
    }

    int id = 1;
    MatrixCursor suggestionCursor = new MatrixCursor(COLUMNS);
    Cursor recentSearchCursor = null;

    try {
        recentSearchCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
        // get search history
        if (recentSearchCursor != null) {
            int searchTermIndex = recentSearchCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
            while (recentSearchCursor.moveToNext() && id <= MAX_RECENT_TERM) {
                suggestionCursor.addRow(createRecentRow(id, recentSearchCursor.getString(searchTermIndex)));
                id++;
            }
        }
    } finally {
        if (recentSearchCursor != null) {
            recentSearchCursor.close();
            recentSearchCursor = null;
        }
    }

    // get search suggestion
    if (selectionArgs[0] != null && !selectionArgs[0].equals("")) {
        List<String> suggestionList = getSearchTermSuggestions(selectionArgs[0]);
        if (suggestionList != null) {
            for (String aSuggestion : suggestionList) {
                suggestionCursor.addRow(createSuggestionRow(id, aSuggestion));
                id++;
            }
        }
    }

    if (loggingEnabled) {
        Log.d(METHOD_NAME, "EXIT");
    }

    return suggestionCursor;
}

From source file:com.emorym.android_pusher.Pusher.java

public void unsubscribe(String channelName) {
    if (channels.containsKey(channelName)) {
        if (mWebSocket != null && mWebSocket.isConnected()) {
            try {
                sendUnsubscribeMessage(channels.get(channelName));
            } catch (Exception e) {
                if (Log.isLoggable(TAG, DEBUG))
                    Log.d(TAG, "Exception sending unsubscribe message", e);
            }//from   ww w .  j  a v a2  s .  co m
        }

        channels.remove(channelName);
    }
}

From source file:com.android.car.trust.CarBleTrustAgent.java

@Override
public void onCreate() {
    super.onCreate();

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Bluetooth trust agent starting up");
    }//from w w  w .j  a  v a  2s  . com
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_REVOKE_TRUST);
    filter.addAction(ACTION_ADD_TOKEN);
    filter.addAction(ACTION_IS_TOKEN_ACTIVE);
    filter.addAction(ACTION_REMOVE_TOKEN);

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this /* context */);
    mLocalBroadcastManager.registerReceiver(mTrustEventReceiver, filter);

    // If the user is already unlocked, don't bother starting the BLE service.
    UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
    if (!um.isUserUnlocked()) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "User locked, will now bind CarUnlockService");
        }
        Intent intent = new Intent(this, CarUnlockService.class);

        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    } else {
        setManagingTrust(true);
    }
}

From source file:org.tritsch.android.chargefinder.CFService.java

/**
 * <code>getString</code> extract a/the string from the input stream.
 *
 * @param is an <code>InputStream</code> value
 * @return a <code>String</code> value
 *//* www . j  a  v a 2s  . com*/
private static String getString(final InputStream is) {
    if (Log.isLoggable(TAG, Log.DEBUG))
        Log.d(TAG, "Enter: getString()");
    Assert.assertNotNull(is);

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    Assert.assertNotNull(reader);
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail();
        }
    }

    if (Log.isLoggable(TAG, Log.DEBUG))
        Log.d(TAG, "Leave: getString()");
    return sb.toString();
}

From source file:com.phonemetra.turbo.lockclock.weather.OpenWeatherMapProvider.java

private WeatherInfo handleWeatherRequest(String selection, String localizedCityName, boolean metric) {
    String units = metric ? "metric" : "imperial";
    String locale = getLanguageCode();
    String conditionUrl = String.format(Locale.US, URL_WEATHER, selection, units, locale);
    String conditionResponse = HttpRetriever.retrieve(conditionUrl);
    if (conditionResponse == null) {
        return null;
    }//from  ww  w  .  j  a va2s . c  om

    String forecastUrl = String.format(Locale.US, URL_FORECAST, selection, units, locale);
    String forecastResponse = HttpRetriever.retrieve(forecastUrl);
    if (forecastResponse == null) {
        return null;
    }

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "URL = " + conditionUrl + " returning a response of " + conditionResponse);
    }

    try {
        JSONObject conditions = new JSONObject(conditionResponse);
        JSONObject weather = conditions.getJSONArray("weather").getJSONObject(0);
        JSONObject conditionData = conditions.getJSONObject("main");
        JSONObject windData = conditions.getJSONObject("wind");
        ArrayList<DayForecast> forecasts = parseForecasts(new JSONObject(forecastResponse).getJSONArray("list"),
                metric);
        int speedUnitResId = metric ? R.string.weather_kph : R.string.weather_mph;
        if (localizedCityName == null) {
            localizedCityName = conditions.getString("name");
        }

        WeatherInfo w = new WeatherInfo(mContext, conditions.getString("id"), localizedCityName,
                /* condition */ weather.getString("main"),
                /* conditionCode */ mapConditionIconToCode(weather.getString("icon"), weather.getInt("id")),
                /* temperature */ sanitizeTemperature(conditionData.getDouble("temp"), metric),
                /* tempUnit */ metric ? "C" : "F", /* humidity */ (float) conditionData.getDouble("humidity"),
                /* wind */ (float) windData.getDouble("speed"), /* windDir */ windData.getInt("deg"),
                /* speedUnit */ mContext.getString(speedUnitResId), forecasts, System.currentTimeMillis());

        Log.d(TAG, "Weather updated: " + w);
        return w;
    } catch (JSONException e) {
        Log.w(TAG, "Received malformed weather data (selection = " + selection + ", lang = " + locale + ")", e);
    }

    return null;
}

From source file:com.bearstech.android.myownsync.client.NetworkUtilities.java

/**
 * Connects to the Voiper server, authenticates the provided username and
 * password./*from w w w .ja  v  a 2s.  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 boolean The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean authenticate(String username, String password, String serveraddr, Handler handler,
        final Context context) {
    final HttpResponse resp;

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }
    if (!serveraddr.startsWith("http://"))
        serveraddr = "http://" + serveraddr;
    final HttpPost post = new HttpPost(serveraddr + AUTH_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

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

From source file:com.streamdataio.android.stockmarket.StockMarketList.java

/**
 * Closes the event source connection and dereference the EventSource object
 *///from   ww w .j ava 2s  .c o  m
private void disconnect() {
    // Disconnect the eventSource Handler
    if (eventSource != null && eventSource.isConnected()) {
        try {
            eventSource.close();
        } catch (Exception e) {
            if (Log.isLoggable(TAG, Log.ERROR)) {
                Log.e(TAG, "Error on closing SSE", e);
            }
        }
    }

    // Dereferencing variable
    eventSource = null;
}

From source file:com.google.android.gcm.GCMRegistrar.java

/**
 * Checks that the application manifest is properly configured.
 * <p>//from w w w  . j  ava 2  s.  c o m
 * A proper configuration means:
 * <ol>
 *    <li>It creates a custom permission called
 *      {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
 *    <li>It defines at least one {@link BroadcastReceiver} with category
 *      {@code PACKAGE_NAME}.
 *    <li>The {@link BroadcastReceiver}(s) uses the
 *      {@value GCMConstants#PERMISSION_GCM_INTENTS} permission.
 *    <li>The {@link BroadcastReceiver}(s) handles the 3 GCM intents
 *      ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE},
 *      {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK},
 *      and {@value GCMConstants#INTENT_FROM_GCM_LIBRARY_RETRY}).
 * </ol>
 * ...where {@code PACKAGE_NAME} is the application package.
 * <p>
 * This method should be used during development time to verify that the
 * manifest is properly set up, but it doesn't need to be called once the
 * application is deployed to the users' devices.
 *
 * @param context application context.
 * @throws IllegalStateException if any of the conditions above is not met.
 */
public static void checkManifest(Context context) {
    PackageManager packageManager = context.getPackageManager();
    String packageName = context.getPackageName();
    String permissionName = packageName + ".permission.C2D_MESSAGE";
    // check permission
    try {
        packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS);
    } catch (NameNotFoundException e) {
        throw new IllegalStateException("Application does not define permission " + permissionName);
    }
    // check receivers
    PackageInfo receiversInfo;
    try {
        receiversInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        throw new IllegalStateException("Could not get receivers for package " + packageName);
    }
    ActivityInfo[] receivers = receiversInfo.receivers;
    if (receivers == null || receivers.length == 0) {
        throw new IllegalStateException("No receiver for package " + packageName);
    }
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length);
    }
    Set<String> allowedReceivers = new HashSet<String>();
    for (ActivityInfo receiver : receivers) {
        if (GCMConstants.PERMISSION_GCM_INTENTS.equals(receiver.permission)) {
            allowedReceivers.add(receiver.name);
        }
    }
    if (allowedReceivers.isEmpty()) {
        throw new IllegalStateException(
                "No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS);
    }
    checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
    checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE);
}