Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

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

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

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

/**
 * ERROR  ?./*w  w w.  ja v a2  s  .  c o m*/
 * 
 * @param clazz  ??  Class.
 * @param tr Throwable.
 */
public static void e(final Class<?> clazz, final Throwable tr) {
    if (LogUtil.isErrorEnabled()) {
        Log.println(Log.ERROR, TAG, LogUtil.getClassLineNumber(clazz) + " - " + Log.getStackTraceString(tr));

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

From source file:net.olejon.mdapp.DiseasesAndTreatmentsSearchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*w  w w  . j a  v a2  s.c  o  m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    mSearchLanguage = intent.getStringExtra("language");

    final String searchString = intent.getStringExtra("string");

    // Layout
    setContentView(R.layout.activity_diseases_and_treatments_search);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.diseases_and_treatments_search_toolbar);
    mToolbar.setTitle(getString(R.string.diseases_and_treatments_search_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.diseases_and_treatments_search_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Spinner
    mSpinner = (Spinner) findViewById(R.id.diseases_and_treatments_search_spinner);

    ArrayAdapter<CharSequence> arrayAdapter;

    if (mSearchLanguage.equals("")) {
        arrayAdapter = ArrayAdapter.createFromResource(mContext,
                R.array.diseases_and_treatments_search_spinner_items_english,
                R.layout.activity_diseases_and_treatments_search_spinner_header);
    } else {
        arrayAdapter = ArrayAdapter.createFromResource(mContext,
                R.array.diseases_and_treatments_search_spinner_items_norwegian,
                R.layout.activity_diseases_and_treatments_search_spinner_header);
    }

    arrayAdapter.setDropDownViewResource(R.layout.activity_diseases_and_treatments_search_spinner_item);

    mSpinner.setAdapter(arrayAdapter);
    mSpinner.setOnItemSelectedListener(this);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(
            R.id.diseases_and_treatments_search_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(mSearchLanguage, searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.diseases_and_treatments_search_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new DiseasesAndTreatmentsSearchAdapter(mContext, new JSONArray(), ""));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // Search
    search(mSearchLanguage, searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(
                                                        DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

                                                SQLiteDatabase sqLiteDatabase = new DiseasesAndTreatmentsSQLiteHelper(
                                                        mContext).getWritableDatabase();

                                                sqLiteDatabase.delete(DiseasesAndTreatmentsSQLiteHelper.TABLE,
                                                        DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(DiseasesAndTreatmentsSQLiteHelper.TABLE,
                                                        null, contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(
                                                        R.string.diseases_and_treatments_search_search) + ": \""
                                                        + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                search(mSearchLanguage, correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("DiseasesAndTreatments", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("DiseasesAndTreatments", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("DiseasesAndTreatments", Log.getStackTraceString(e));
    }
}

From source file:com.android.mms.transaction.NotificationTransaction.java

public void run() {
    MmsLog.d(MmsApp.TXN_TAG, "NotificationTransaction: run");
    DownloadManager downloadManager = DownloadManager.getInstance();
    boolean autoDownload = allowAutoDownload(mContext, mSubId);
    try {/*from  www.j a va2  s . com*/
        if (LOCAL_LOGV) {
            Log.v(TAG, "Notification transaction launched: " + this);
        }

        // By default, we set status to STATUS_DEFERRED because we
        // should response MMSC with STATUS_DEFERRED when we cannot
        // download a MM immediately.
        int status = STATUS_DEFERRED;
        // Don't try to download when data is suspended, as it will fail, so defer download
        if (!autoDownload) {
            // M: change API for ALPS01889178, use sub id.
            downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED, mSubId);
            sendNotifyRespInd(status);
            getState().setState(SUCCESS);
            getState().setContentUri(mUri);
            notifyObservers();
            return;
        }

        // M: change API for ALPS01889178, use sub id.
        downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING, mSubId);

        if (mOpNotificationTransactionExt.run(mIsCancelling, mUri, mContext, getUri(), mContentLocation)) {
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            mIsCancelling = false;
            return;
        }

        if (LOCAL_LOGV) {
            Log.v(TAG, "Content-Location: " + mContentLocation);
        }
        mPduFile = createPduFile(null, RETRIEVE_RESULT_NAME + mUri.getLastPathSegment());
        mPduFile.setWritable(true, false);

        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());

        Log.d(MmsApp.TXN_TAG, "NotificationTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent downloadedIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId);
        Log.d(MmsApp.TXN_TAG, "download MMS with param, mContentLocation = " + mContentLocation + ", mUri = "
                + mUri + ", subId" + mSubId);

        /// M: Add MmsService configure param @{
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        manager.downloadMultimediaMessage(mContext, mContentLocation, pduFileUri,
                MmsConfig.getMmsServiceConfig(), downloadedIntent);
        /// @}

        // sendNotifyRespInd(status);

        // Make sure this thread isn't over the limits in message count.
        Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);
        MmsWidgetProvider.notifyDatasetChanged(mContext);
    } catch (Throwable t) {
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
        Log.e(TAG, Log.getStackTraceString(t));
    }
}

From source file:org.droidparts.persist.json.JSONSerializer.java

private void readFromModelAndPutToJSON(ModelType item, FieldSpec<KeyAnn> spec, JSONObject obj, String key)
        throws JSONException {
    Pair<String, String> keyParts = getNestedKeyParts(key);
    if (keyParts != null) {
        String subKey = keyParts.first;
        JSONObject subObj;//  ww w  .  ja v a  2 s  . co  m
        if (hasNonNull(obj, subKey)) {
            subObj = obj.getJSONObject(subKey);
        } else {
            subObj = new JSONObject();
            obj.put(subKey, subObj);
        }
        readFromModelAndPutToJSON(item, spec, subObj, keyParts.second);
    } else {
        Object columnVal = getFieldVal(item, spec.field);
        try {
            putToJSONObject(obj, key, spec.field.getType(), spec.arrCollItemType, columnVal);
        } catch (Exception e) {
            if (spec.ann.optional) {
                L.w("Failded to serialize " + cls.getSimpleName() + "." + spec.field.getName() + ": "
                        + e.getMessage());
            } else {
                throw new JSONException(Log.getStackTraceString(e));
            }
        }
    }
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {/*from  ww w.j av  a2  s.c om*/
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.g_node.gca.map.MapActivity.java

public void locationMarkers() {
    /*/*from  ww  w . j av  a  2 s  . com*/
     * Implement Location Markers
     */
    BufferedReader jsonReader = new BufferedReader(
            new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
    StringBuilder jsonBuilder = new StringBuilder();
    try {
        for (String line = null; (line = jsonReader.readLine()) != null;) {
            jsonBuilder.append(line).append("\n");
        }

        JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
        JSONArray jsonArray = new JSONArray(tokener);

        for (int index = 0; index < jsonArray.length(); index++) {

            JSONObject jsonObject = jsonArray.getJSONObject(index);
            /*
             * getting Latitude
             */
            double getLat = jsonObject.getJSONObject("point").getDouble("lat");
            /*
             * getting Longitude
             */
            double getLng = jsonObject.getJSONObject("point").getDouble("long");
            /*
             * getting Location Type
             */
            int gettype = jsonObject.getInt("type");
            /*
             * getting zoomto value
             */
            int getZoomto = 1;
            if (jsonObject.has("zoomto")) {
                getZoomto = jsonObject.getInt("zoomto");
            }
            /*
             * Venue name
             */
            String name = jsonObject.getString("name");
            LatLng myLoc = new LatLng(getLat, getLng);
            if (getZoomto == 1) {
                /*
                 * Adding only food and venue coordinates for automatic zoom
                 * level
                 */
                allCoordinates.add(myLoc);
            }
            FragmentManager fmanager = getSupportFragmentManager();
            Fragment fragment = fmanager.findFragmentById(R.id.map);
            SupportMapFragment supportmapfragment = (SupportMapFragment) fragment;
            supportMap = supportmapfragment.getMap();
            if (supportMap != null) {
                /*
                 * implementing different colors markers for different
                 * location's
                 */
                switch (gettype) {
                case 0:
                    /*
                     * Conference Venue Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.conference)));
                    break;
                case 1:
                    /*
                     * University Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.university)));
                    break;
                case 2:
                    /*
                     * Hotel -1 Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.hotel_1)));
                    break;
                case 3:
                    /*
                     * Hotel -2 Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.hotel_2)));
                    break;
                case 4:
                    /*
                     * Transport Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.transport)));
                    break;
                case 5:
                    /*
                     * Food Marker
                     */
                    supportMap.addMarker(new MarkerOptions().position(myLoc).title(name)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.food)));
                    break;

                default:
                    break;
                }
            }

        }

        /*
         * Automatic zoom level
         */
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng m : allCoordinates) {
            builder = builder.include(m);
        }
        LatLngBounds bounds = builder.build();
        CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                this.getResources().getDisplayMetrics().widthPixels
                        - (int) (this.getResources().getDisplayMetrics().widthPixels * 0.1),
                this.getResources().getDisplayMetrics().heightPixels
                        - (int) (this.getResources().getDisplayMetrics().heightPixels * 0.1),
                50);
        /*
         * Move Camera
         */
        supportMap.moveCamera(cu);
        /*
         * Set My Current Location Enable
         */
        supportMap.setMyLocationEnabled(true);
        supportMap.getUiSettings().setMyLocationButtonEnabled(true);
        /*
         * Set Compass Enable
         */
        supportMap.getUiSettings().setCompassEnabled(true);
        /*
         * Set Manual ZoomControl Enable
         */
        supportMap.getUiSettings().setZoomControlsEnabled(false);
    } catch (FileNotFoundException e) {
        Log.e("jsonFile", "file not found");
    } catch (IOException e) {
        Log.e("jsonFile", "ioerror");
    } catch (JSONException e) {
        Log.e("jsonFile", Log.getStackTraceString(e));
    }

}

From source file:org.catrobat.catroid.ui.fragment.LookFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    listView = getListView();//from   w  w  w . ja v  a2s.c  o m

    if (listView != null) {
        registerForContextMenu(listView);
    }

    if (savedInstanceState != null) {
        selectedLookData = (LookData) savedInstanceState
                .getSerializable(LookController.BUNDLE_ARGUMENTS_SELECTED_LOOK);

        boolean uriIsSet = savedInstanceState.getBoolean(LookController.BUNDLE_ARGUMENTS_URI_IS_SET);
        if (uriIsSet) {
            String defLookName = getString(R.string.default_look_name);
            lookFromCameraUri = UtilCamera.getDefaultLookFromCameraUri(defLookName);
        }
    }

    try {
        lookDataList = ProjectManager.getInstance().getCurrentSprite().getLookDataList();
    } catch (NullPointerException nullPointerException) {
        Log.e(TAG, Log.getStackTraceString(nullPointerException));
        lookDataList = new ArrayList<LookData>();
    }

    if (ProjectManager.getInstance().getCurrentSpritePosition() == 0) {
        TextView emptyViewHeading = (TextView) getActivity().findViewById(R.id.fragment_look_text_heading);
        emptyViewHeading.setTextSize(TypedValue.COMPLEX_UNIT_SP, 60.0f);
        emptyViewHeading.setText(R.string.backgrounds);
        TextView emptyViewDescription = (TextView) getActivity()
                .findViewById(R.id.fragment_look_text_description);
        emptyViewDescription.setText(R.string.fragment_background_text_description);
    }

    adapter = new LookAdapter(getActivity(), R.layout.fragment_look_looklist_item,
            R.id.fragment_look_item_name_text_view, lookDataList, false);
    adapter.setOnLookEditListener(this);
    setListAdapter(adapter);
    ((LookAdapter) adapter).setLookFragment(this);

    Utils.loadProjectIfNeeded(getActivity());
}

From source file:com.android.mms.transaction.RetrieveTransaction.java

public void run() {
    MmsLog.i(MmsApp.TXN_TAG, "RetrieveTransaction: run()");
    try {/*from w w  w . ja va  2 s. c  o  m*/
        NotificationInd nInd = (NotificationInd) PduPersister.getPduPersister(mContext).load(mUri);
        if (nInd.getExpiry() < System.currentTimeMillis() / 1000L) {
            MmsLog.d(MmsApp.TXN_TAG, "The message is expired!");
            sendExpiredRes();
            // Change the downloading state of the M-Notification.ind.
            DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            notifyObservers();
            return;
        }

        // Change the downloading state of the M-Notification.ind.
        DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);

        /// M: For OP009, check if cancel download requested. @{
        /*            if (MmsConfig.isCancelDownloadEnable() && mIsCancelling) {
        mTransactionState.setState(TransactionState.SUCCESS);
        mTransactionState.setContentUri(mUri);
                
        if (MmsConfig.isCancelDownloadEnable()) {
            sMmsFailedNotifyPlugin.popupToast(mContext,
                IMmsFailedNotifyExt.CANCEL_DOWNLOAD, null);
        }
        mIsCancelling = false;
        final Uri trxnUri = getUri();
        sCancelDownloadPlugin.markStateExt(trxnUri, sCancelDownloadPlugin.STATE_COMPLETE);
        DownloadManager.getInstance().markState(trxnUri, DownloadManager.STATE_UNSTARTED);
                
        return;
                    }*/
        /// @}

        if (mOpRetrieveTransactionExt.run(mIsCancelling, mUri, mContext, getUri(), mContentLocation)) {
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            mIsCancelling = false;
            return;
        }

        mPduFile = createPduFile(null, RETRIEVE_RESULT_NAME + mUri.getLastPathSegment());
        mPduFile.setWritable(true, false);
        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());
        Log.d(MmsApp.TXN_TAG, "RetrieveTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent downloadedIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId);
        Log.d(MmsApp.TXN_TAG, "download MMS with param, mContentLocation = " + mContentLocation + ", mUri = "
                + mUri + ", subId" + mSubId);
        /// M: Add MmsService configure param @{
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        manager.downloadMultimediaMessage(mContext, mContentLocation, pduFileUri,
                MmsConfig.getMmsServiceConfig(), downloadedIntent);
        /// @}

        // Make sure this thread isn't over the limits in message count.
        Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);

        /// OP009 MMS Feature: cancel download Mms @{
        /*            if (MmsConfig.isCancelDownloadEnable()) {
        sCancelDownloadPlugin.addHttpClient(mContentLocation, mUri);
                    }*/
        /// @}

        // Send ACK to the Proxy-Relay to indicate we have fetched the
        // MM successfully.
        // Don't mark the transaction as failed if we failed to send it.
        // sendAcknowledgeInd(retrieveConf);
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        mTransactionState.setState(TransactionState.FAILED);
        mTransactionState.setContentUri(mUri);
        notifyObservers();
    }
}

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

/**
 * ERROR  ?.//from w  w w  .  j a va 2 s . com
 * 
 * @param clazz  ??  Class.
 * @param msg .
 * @param tr Throwable.
 */
public static void e(final Class<?> clazz, final String msg, final Throwable tr) {
    if (LogUtil.isErrorEnabled()) {
        Log.println(Log.ERROR, TAG,
                LogUtil.getClassLineNumber(clazz) + " - " + msg + '\n' + Log.getStackTraceString(tr));

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

From source file:com.listomate.activities.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * /*from  w  ww  .j  a  va  2 s.com*/
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.putString(Util.AUTH_COOKIE, null);
    editor.commit();

    // Obtain an auth token and register
    AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        if (acct.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the account name
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle authTokenBundle = future.getResult();
                            String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
                            String authCookie = getAuthCookie(authToken);
                            prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        } catch (AuthenticatorException e) {
                            Log.w(TAG, "Got AuthenticatorException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (IOException e) {
                            Log.w(TAG, "Got IOException " + Log.getStackTraceString(e));
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (OperationCanceledException e) {
                            Log.w(TAG, "Got OperationCanceledException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        }
                    }
                }, null);
            }
            break;
        }
    }
}