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:org.alfresco.mobile.android.application.fragments.config.MenuConfigFragment.java

private JSONObject saveConfiguration() {
    JSONObject configuration = new JSONObject();
    boolean hasItems = false;
    try {/*from   w  w  w  . j  av  a  2s  .c  o m*/
        // INFO
        JSONObject info = new JSONObject();
        info.put(ConfigConstants.SCHEMA_VERSION_VALUE, 0.1);
        info.putOpt(ConfigConstants.CONFIG_VERSION_VALUE, 0.1);
        configuration.put(ConfigTypeIds.INFO.value(), info);

        // PROFILES
        JSONObject profiles = new JSONObject();
        JSONObject defaultProfile = new JSONObject();
        defaultProfile.put(ConfigConstants.DEFAULT_VALUE, true);
        defaultProfile.putOpt(ConfigConstants.LABEL_ID_VALUE, "Custom Default");
        defaultProfile.putOpt(ConfigConstants.ROOTVIEW_ID_VALUE, "views-menu-default");
        profiles.put("default", defaultProfile);
        configuration.put(ConfigTypeIds.PROFILES.value(), profiles);

        // VIEW GROUPS
        JSONArray viewGroupsArray = new JSONArray();
        JSONObject defaultMenu = new JSONObject();
        defaultMenu.putOpt(ConfigConstants.ID_VALUE, "views-menu-default");
        defaultMenu.putOpt(ConfigConstants.LABEL_ID_VALUE, getString(R.string.menu_view));

        // Items
        JSONArray items = new JSONArray();
        JSONObject item = null;
        MenuItemConfig itemConfig = null;
        for (int i = 0; i < adapter.getCount(); i++) {
            itemConfig = menuConfigItems.get(i);
            if (itemConfig.isEnable()) {
                items.put(((ViewConfigImpl) itemConfig.config).toJson());
                hasItems = true;
            }
        }

        defaultMenu.putOpt(ConfigConstants.ITEMS_VALUE, items);
        viewGroupsArray.put(defaultMenu);

        configuration.put(ConfigTypeIds.VIEW_GROUPS.value(), viewGroupsArray);

        // SAVE TO DEVICE
        OutputStream sourceFile = null;
        try {
            File configFolder = AlfrescoStorageManager.getInstance(getActivity()).getCustomFolder(account);
            File configFile = new File(configFolder, ConfigConstants.CONFIG_FILENAME);

            sourceFile = new FileOutputStream(configFile);
            sourceFile.write(configuration.toString().getBytes("UTF-8"));
            sourceFile.close();

            // Send Event
            ConfigManager.getInstance(getActivity()).loadAndUseCustom(account);
            EventBusManager.getInstance().post(new ConfigManager.ConfigurationMenuEvent(accountId));
        } catch (Exception e) {
            Log.w(TAG, Log.getStackTraceString(e));
        } finally {
            org.alfresco.mobile.android.api.utils.IOUtils.closeStream(sourceFile);
        }
    } catch (JSONException e) {
        Log.w(TAG, Log.getStackTraceString(e));
    }
    return configuration;
}

From source file:org.alfresco.mobile.android.api.services.impl.onpremise.OnPremiseWorkflowServiceImpl.java

/** {@inheritDoc} */
public Process startProcess(ProcessDefinition processDefinition, List<Person> assignees,
        Map<String, Serializable> variables, List<Document> items) {
    if (isObjectNull(processDefinition)) {
        throw new IllegalArgumentException(String.format(
                Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "processDefinition"));
    }/*from w  ww  .  jav a 2 s.  com*/

    Process process = null;
    try {
        String link = OnPremiseUrlRegistry.getFormProcessUrl(session, processDefinition.getKey());
        UrlBuilder url = new UrlBuilder(link);

        // prepare json data
        JSONObject jo = new JSONObject();

        // ASSIGNEES
        // We need to retrieve the noderef associated to the person
        if (assignees != null && !assignees.isEmpty()) {
            if (assignees.size() == 1 && WorkflowModel.FAMILY_PROCESS_ADHOC.contains(processDefinition.getKey())
                    || WorkflowModel.FAMILY_PROCESS_REVIEW.contains(processDefinition.getKey())) {
                jo.put(OnPremiseConstant.ASSOC_BPM_ASSIGNEE_ADDED_VALUE, getPersonGUID(assignees.get(0)));
            } else if (WorkflowModel.FAMILY_PROCESS_PARALLEL_REVIEW.contains(processDefinition.getKey())) {
                List<String> guids = new ArrayList<String>(assignees.size());
                for (Person p : assignees) {
                    guids.add(getPersonGUID(p));
                }
                jo.put(OnPremiseConstant.ASSOC_BPM_ASSIGNEES_ADDED_VALUE, TextUtils.join(",", guids));
            }
        }

        // VARIABLES
        if (variables != null && !variables.isEmpty()) {
            for (Entry<String, Serializable> entry : variables.entrySet()) {
                if (ALFRESCO_TO_WORKFLOW.containsKey(entry.getKey())) {
                    jo.put(ALFRESCO_TO_WORKFLOW.get(entry.getKey()), entry.getValue());
                } else {
                    jo.put(entry.getKey(), entry.getValue());
                }
            }
        }

        // ITEMS
        if (items != null && !items.isEmpty()) {
            List<String> variablesItems = new ArrayList<String>(items.size());
            for (Node node : items) {
                variablesItems.add(NodeRefUtils.getCleanIdentifier(node.getIdentifier()));
            }
            jo.put(OnPremiseConstant.ASSOC_PACKAGEITEMS_ADDED_VALUE,
                    TextUtils.join(",", variablesItems.toArray(new String[0])));
        }
        final JsonDataWriter dataWriter = new JsonDataWriter(jo);

        // send
        Response resp = post(url, dataWriter.getContentType(), new Output() {
            public void write(OutputStream out) throws IOException {
                dataWriter.write(out);
            }
        }, ErrorCodeRegistry.WORKFLOW_GENERIC);

        Map<String, Object> json = JsonUtils.parseObject(resp.getStream(), resp.getCharset());
        String data = JSONConverter.getString(json, OnPremiseConstant.PERSISTEDOBJECT_VALUE);

        // WorkflowInstance[id=activiti$18328,active=true,def=WorkflowDefinition[
        String processId = data.split("\\[")[1].split(",")[0].split("=")[1];

        process = getProcess(processId);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
        convertException(e);
    }

    return process;
}

From source file:android_network.hetnet.vpn_service.AdapterLog.java

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long id = cursor.getLong(colID);
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDAddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views/* ww w  .j  av  a2 s  .  co  m*/
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    final TextView tvOrganization = (TextView) view.findViewById(R.id.tvOrganization);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Show time
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    // Show connection type
    if (connection <= 0)
        ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked);
    else {
        if (allowed > 0)
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
        else
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }

    // Show if screen on
    if (interactive <= 0)
        ivInteractive.setImageDrawable(null);
    else {
        ivInteractive.setImageResource(R.drawable.screen_on);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
            DrawableCompat.setTint(wrap, colorOn);
        }
    }

    // Show protocol name
    tvProtocol.setText(Util.getProtocolName(protocol, version, false));

    // SHow TCP flags
    tvFlags.setText(flags);
    tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE);

    // Show source and destination port
    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null)
        ivIcon.setImageDrawable(null);
    else if (info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // Show source address
    tvSAddr.setText(getKnownAddress(saddr));

    // Show destination address
    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            tvDaddr.setText(daddr);
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvDaddr, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return InetAddress.getByName(args[0]).getHostName();
                    } catch (UnknownHostException ignored) {
                        return args[0];
                    }
                }

                @Override
                protected void onPostExecute(String name) {
                    tvDaddr.setText(">" + name);
                    ViewCompat.setHasTransientState(tvDaddr, false);
                }
            }.execute(daddr);
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    // Show organization
    tvOrganization.setVisibility(View.GONE);
    if (organization) {
        if (!isKnownAddress(daddr))
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvOrganization, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return Util.getOrganization(args[0]);
                    } catch (Throwable ex) {
                        Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String organization) {
                    if (organization != null) {
                        tvOrganization.setText(organization);
                        tvOrganization.setVisibility(View.VISIBLE);
                    }
                    ViewCompat.setHasTransientState(tvOrganization, false);
                }
            }.execute(daddr);
    }

    // Show extra data
    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}

From source file:org.apache.cordova.plugins.Actionable.java

private void updateMenu(final JSONArray menu) {
    for (int i = 0; i < menu.length(); i++) {
        try {//from  w  w  w  .  java  2s . c o  m
            JSONObject mi = menu.getJSONObject(i);
            Actionable action = Actionable.fromJSON(mi);

            action.setOrder(i);

            mMenuItems.put(action.getTitle(), action);
        } catch (Exception e) {
            Log.v("Cambie", Log.getStackTraceString(e));
        }
    }
}

From source file:com.dm.material.dashboard.candybar.fragments.SettingsFragment.java

public void rebuildPremiumRequest() {
    new AsyncTask<Void, Void, Boolean>() {

        MaterialDialog dialog;//from ww  w .  j ava  2  s. c o m
        StringBuilder sb;
        List<Request> requests;
        String zipFile;

        String log = "";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            sb = new StringBuilder();

            MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
            builder.content(R.string.premium_request_rebuilding);
            builder.cancelable(false);
            builder.canceledOnTouchOutside(false);
            builder.progress(true, 0);
            builder.progressIndeterminateStyle(true);
            dialog = builder.build();
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    Database database = new Database(getActivity());
                    File directory = getActivity().getCacheDir();
                    File appFilter = new File(directory.toString() + "/" + "appfilter.xml");

                    requests = database.getPremiumRequest(null);

                    if (requests.size() == 0)
                        return true;

                    sb.append(DeviceHelper.getDeviceInfo(getActivity()));

                    List<String> files = new ArrayList<>();
                    Writer out = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(appFilter), "UTF8"));

                    for (int i = 0; i < requests.size(); i++) {
                        String activity = requests.get(i).getActivity();
                        String packageName = activity.substring(0, activity.lastIndexOf("/"));
                        Request request = new Request(requests.get(i).getName(), packageName, activity, true);

                        String string = RequestHelper.writeRequest(request);
                        sb.append(string);
                        sb.append("\n").append("Order Id : ").append(requests.get(i).getOrderId());
                        sb.append("\n").append("Product Id : ").append(requests.get(i).getProductId());

                        String string1 = RequestHelper.writeAppFilter(request);
                        out.append(string1);

                        Bitmap bitmap = DrawableHelper.getHighQualityIcon(getActivity(),
                                request.getPackageName());

                        String icon = FileHelper.saveIcon(directory, bitmap, request.getName());
                        if (icon != null)
                            files.add(icon);
                    }

                    out.flush();
                    out.close();
                    files.add(appFilter.toString());

                    zipFile = directory.toString() + "/" + "icon_request.zip";
                    FileHelper.createZip(files, zipFile);
                    return true;
                } catch (Exception e) {
                    log = e.toString();
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            dialog.dismiss();
            if (aBoolean) {
                if (requests.size() == 0) {
                    Toast.makeText(getActivity(), R.string.premium_request_rebuilding_empty, Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                String subject = "Rebuild Premium Icon Request "
                        + getActivity().getResources().getString(R.string.app_name);

                Request request = new Request(subject, sb.toString(), zipFile);
                IntentChooserFragment.showIntentChooserDialog(getActivity().getSupportFragmentManager(),
                        request);
            } else {
                Toast.makeText(getActivity(), "Failed " + log, Toast.LENGTH_LONG).show();
            }
            dialog = null;
            sb.setLength(0);
        }

    }.execute();
}

From source file:org.alfresco.mobile.android.test.api.services.ActivityStreamServiceTest.java

/**
 * All Tests forActivityStreamService public methods which don't create an
 * error./* ww  w.ja v a  2 s . c o m*/
 * 
 * @Requirement 1S3, 1S4, 2F1,2F2, 2F3, 2F4, 2S1, 2S6, 2S7, 2S8, 2S9, 3S3,
 *              3S4, 4F1, 4F2, 4F3, 4F4, 4S6, 4S7, 4S8, 4S9, 5S3, 6F4, 6F6,
 *              6F7, 6S6, 6S7, 6S8, 6S9
 */
public void testActivityStreamService() {
    try {
        prepareScriptData();

        // ///////////////////////////////////////////////////////////////////////////
        // Method getActivityStream()
        // ///////////////////////////////////////////////////////////////////////////
        List<ActivityEntry> feed = activityStreamService.getActivityStream();
        if (feed == null || feed.isEmpty()) {
            // Log.d("ActivityStreamService",
            // "No stream activities available. Test aborted.");
            return;
        }
        int totalItems = feed.size();
        Assert.assertNotNull(feed);
        Assert.assertFalse(feed.isEmpty());

        // Sorting with listinContext and sort property : Sort is not
        // supported
        // by ActivityStreamService
        wait(10000);
        ListingContext lc = new ListingContext();
        lc.setSortProperty(DocumentFolderService.SORT_PROPERTY_DESCRIPTION);
        PagingResult<ActivityEntry> feedUnSorted = activityStreamService.getActivityStream(lc);
        Assert.assertEquals(lc.getMaxItems(), feedUnSorted.getList().size());
        Assert.assertEquals(feed.get(0).getIdentifier(), feed.get(0).getIdentifier());
        // ///////////////////////////////////////////////////////////////////////////
        // Paging ALL Activity Entry
        // ///////////////////////////////////////////////////////////////////////////
        lc = new ListingContext();
        lc.setMaxItems(5);
        lc.setSkipCount(0);

        // Check 1 activity
        PagingResult<ActivityEntry> pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(5, pagingFeed.getList().size());
        Assert.assertEquals(getTotalItems(feed.size()), pagingFeed.getTotalItems());
        Assert.assertTrue(pagingFeed.hasMoreItems());

        // Check 0 activity if outside of total item
        lc.setMaxItems(10);
        lc.setSkipCount(feed.size());
        pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(getTotalItems(feed.size()), pagingFeed.getTotalItems());
        Assert.assertEquals(hasMoreItem(), pagingFeed.hasMoreItems());

        // OnPremise max is 100 and not the case for cloud.
        if (isOnPremise()) {
            Assert.assertEquals(0, pagingFeed.getList().size());
        } else {
            Assert.assertEquals(10, pagingFeed.getList().size());
        }

        // Check feed.size() activity
        lc.setMaxItems(feed.size());
        lc.setSkipCount(0);
        pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(feed.size(), pagingFeed.getList().size());
        Assert.assertEquals(getTotalItems(feed.size()), pagingFeed.getTotalItems());
        Assert.assertEquals(hasMoreItem(), pagingFeed.hasMoreItems());

        // ////////////////////////////////////////////////////
        // Incorrect Listing Context Value
        // ////////////////////////////////////////////////////
        // Incorrect settings in listingContext: Such as inappropriate
        // maxItems
        // (0)
        lc.setSkipCount(0);
        lc.setMaxItems(-1);
        pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(getTotalItems(totalItems), pagingFeed.getTotalItems());
        Assert.assertEquals(
                (totalItems > ListingContext.DEFAULT_MAX_ITEMS) ? ListingContext.DEFAULT_MAX_ITEMS : totalItems,
                pagingFeed.getList().size());
        Assert.assertEquals(Boolean.TRUE, pagingFeed.hasMoreItems());

        // Incorrect settings in listingContext: Such as inappropriate
        // maxItems
        // (-1)
        lc.setSkipCount(0);
        lc.setMaxItems(-1);
        pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(getTotalItems(totalItems), pagingFeed.getTotalItems());
        Assert.assertEquals(
                (totalItems > ListingContext.DEFAULT_MAX_ITEMS) ? ListingContext.DEFAULT_MAX_ITEMS : totalItems,
                pagingFeed.getList().size());
        Assert.assertEquals(Boolean.TRUE, pagingFeed.hasMoreItems());

        // Incorrect settings in listingContext: Such as inappropriate
        // skipcount
        // (-12)
        lc.setSkipCount(-12);
        lc.setMaxItems(5);
        pagingFeed = activityStreamService.getActivityStream(lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(getTotalItems(totalItems), pagingFeed.getTotalItems());
        Assert.assertEquals(5, pagingFeed.getList().size());
        Assert.assertTrue(pagingFeed.hasMoreItems());

        // List by User
        List<ActivityEntry> feed2 = activityStreamService.getActivityStream(alfsession.getPersonIdentifier());
        Assert.assertNotNull(feed2);

        // List with fake user
        Assert.assertNotNull(activityStreamService.getActivityStream(FAKE_USERNAME));
        Assert.assertEquals(0, activityStreamService.getActivityStream(FAKE_USERNAME).size());

        // List by site
        List<ActivityEntry> feed3 = activityStreamService.getSiteActivityStream(getSiteName(alfsession));
        Assert.assertNotNull(feed3);

        // ///////////////////////////////////////////////////////////////////////////
        // Activity Entry
        // ///////////////////////////////////////////////////////////////////////////
        ActivityEntry entry = feed.get(0);
        Assert.assertNotNull(entry.getIdentifier());
        Assert.assertNotNull(entry.getType());
        Assert.assertNotNull(entry.getCreatedBy());
        Assert.assertNotNull(entry.getCreatedAt());
        Assert.assertNotNull(entry.getSiteShortName());
        Assert.assertNotNull(entry.getData());

        // ///////////////////////////////////////////////////////////////////////////
        // Paging User Activity Entry
        // ///////////////////////////////////////////////////////////////////////////
        wait(10000);

        // Check consistency between Cloud and OnPremise
        if (!isOnPremise()) {
            // Check 1 activity
            lc.setMaxItems(1);
            lc.setSkipCount(0);
            pagingFeed = activityStreamService.getActivityStream(alfsession.getPersonIdentifier(), lc);
            Assert.assertNotNull(pagingFeed);
            Assert.assertEquals(1, pagingFeed.getList().size());
            // Assert.assertTrue(feed2.size() == pagingFeed.getTotalItems()
            // ||
            // feed2.size() - 1 == pagingFeed.getTotalItems());
            Assert.assertTrue(pagingFeed.hasMoreItems());
        }

        // ///////////////////////////////////////////////////////////////////////////
        // Paging Site Activity Entry
        // ///////////////////////////////////////////////////////////////////////////
        // Check 1 activity
        lc.setMaxItems(1);
        lc.setSkipCount(0);
        pagingFeed = activityStreamService.getSiteActivityStream(getSiteName(alfsession), lc);
        Assert.assertNotNull(pagingFeed);
        Assert.assertEquals(1, pagingFeed.getList().size());
        // Assert.assertTrue(feed3.size() == pagingFeed.getTotalItems() ||
        // feed3.size() - 1 == pagingFeed.getTotalItems());
        if (feed3.size() > 1) {
            Assert.assertTrue(pagingFeed.hasMoreItems());
        } else {
            Assert.assertFalse(pagingFeed.hasMoreItems());
        }
    } catch (Exception e) {
        Log.e(TAG, "Error during Activity Tests");
        Log.e("TAG", Log.getStackTraceString(e));
    }
}

From source file:org.proninyaroslav.libretorrent.core.TorrentEngine.java

@Override
public void loadSettings() {
    if (session == null) {
        return;//from  w w w  . j av  a2s  .  co m
    }

    try {
        String sessionPath = TorrentUtils.findSessionFile(context);

        if (sessionPath == null) {
            return;
        }

        File sessionFile = new File(sessionPath);

        if (sessionFile.exists()) {
            byte[] data = FileUtils.readFileToByteArray(sessionFile);
            session.loadState(data);
        } else {
            revertToDefaultConfiguration();
        }

    } catch (Exception e) {
        Log.e(TAG, "Error loading session state: ");
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:org.alfresco.mobile.android.application.managers.ActionUtils.java

public static boolean actionSendMailWithAttachment(Fragment fr, String subject, String content, Uri attachment,
        int requestCode) {
    try {//from   ww  w  .j  a v a2  s  .  c o m
        Intent i = new Intent(Intent.ACTION_SEND);
        i.putExtra(Intent.EXTRA_SUBJECT, subject);
        i.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(content));
        i.putExtra(Intent.EXTRA_STREAM, attachment);
        i.setType("text/plain");

        if (i.resolveActivity(fr.getActivity().getPackageManager()) == null) {
            AlfrescoNotificationManager.getInstance(fr.getActivity()).showAlertCrouton(fr.getActivity(),
                    fr.getString(R.string.feature_disable));
            return false;
        }

        fr.startActivityForResult(Intent.createChooser(i, fr.getString(R.string.send_email)), requestCode);

        return true;
    } catch (Exception e) {
        AlfrescoNotificationManager.getInstance(fr.getActivity()).showAlertCrouton(fr.getActivity(),
                R.string.decryption_failed);
        Log.d(TAG, Log.getStackTraceString(e));
    }

    return false;
}

From source file:io.teak.sdk.DeviceConfiguration.java

private void registerForGCM(@NonNull final AppConfiguration appConfiguration) {
    try {/*from  w w w.  jav a 2s  .  c  o m*/
        if (appConfiguration.pushSenderId != null) {
            final DeviceConfiguration _this = this;

            final FutureTask<String> gcmRegistration = new FutureTask<>(
                    new RetriableTask<>(100, 7000L, new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                            GoogleCloudMessaging gcm = _this.gcm.get();

                            if (Teak.isDebug) {
                                Log.d(LOG_TAG,
                                        "Registering for GCM with sender id: " + appConfiguration.pushSenderId);
                            }
                            return gcm.register(appConfiguration.pushSenderId);
                        }
                    }));
            new Thread(gcmRegistration).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        String registration = gcmRegistration.get();

                        if (registration == null) {
                            Log.e(LOG_TAG, "Got null token during GCM registration.");
                            return;
                        }

                        if (_this.preferences != null) {
                            SharedPreferences.Editor editor = _this.preferences.edit();
                            editor.putInt(PREFERENCE_APP_VERSION, appConfiguration.appVersion);
                            editor.putString(PREFERENCE_GCM_ID, registration);
                            editor.apply();
                        }

                        // Inform event listeners GCM is here
                        if (!registration.equals(gcmId)) {
                            _this.gcmId = registration;
                            synchronized (eventListenersMutex) {
                                for (EventListener e : eventListeners) {
                                    e.onGCMIdChanged(_this);
                                }
                            }
                        }

                        displayGCMDebugMessage();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, Log.getStackTraceString(e));
                    }
                }
            }).start();
        }
    } catch (Exception ignored) {
    }
}

From source file:org.alfresco.mobile.android.api.session.authentication.impl.OAuthHelper.java

/**
 * Request a new accestoken & refreshtoken based on OAuthData information. <br/>
 * Note that you can refresh the access token at any time before the timeout
 * expires. The old access token becomes invalid when the new one is
 * granted. The new refresh token supplied in the response body can be used
 * in the same way./*from   w w w .  ja v a  2s . c om*/
 * 
 * @param data : OAuthData object available from your cloud session object :
 *            {@link CloudSession#getOAuthData()}
 * @return OAuthData object that can be used to make authenticated calls
 *         using the Alfresco API.
 * @exception AlfrescoSessionException
 *                {@link ErrorCodeRegistry#SESSION_API_KEYS_INVALID
 *                SESSION_API_KEYS_INVALID} : API key or secret were not
 *                recognized.
 * @exception AlfrescoSessionException
 *                {@link ErrorCodeRegistry#SESSION_REFRESH_TOKEN_EXPIRED
 *                SESSION_AUTH_CODE_INVALID} : Refresh token is invalid or
 *                expired.
 */
public OAuthData refreshToken(OAuthData data) {

    if (data == null) {
        throw new IllegalArgumentException(String
                .format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "OAuthData"));
    }

    try {
        UrlBuilder builder = new UrlBuilder(baseUrl + PUBLIC_API_OAUTH_TOKEN_PATH);

        Map<String, String> params = new HashMap<String, String>();
        params.put(PARAM_REFRESH_TOKEN, data.getRefreshToken());
        params.put(PARAM_CLIENT_ID, data.getApiKey());
        params.put(PARAM_CLIENT_SECRET, data.getApiSecret());
        params.put(PARAM_GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN);

        Response resp = NetworkHttpInvoker.invokePOST(builder, FORMAT, params);
        if (resp.getResponseCode() != HttpStatus.SC_OK) {
            ExceptionHelper.convertStatusCode(null, resp, ErrorCodeRegistry.SESSION_REFRESH_TOKEN_EXPIRED);
        }

        Map<String, Object> json = JsonUtils.parseObject(resp.getStream(), resp.getCharset());
        OAuth2DataImpl token = new OAuth2DataImpl(data.getApiKey(), data.getApiSecret());
        token.parseTokenResponse(json);
        return token;
    } catch (CmisConnectionException e) {
        if (e.getCause() instanceof IOException
                && e.getCause().getMessage().contains("Received authentication challenge is null")) {
            throw new AlfrescoSessionException(ErrorCodeRegistry.SESSION_API_KEYS_INVALID, e);
        }
    } catch (AlfrescoSessionException e) {
        throw (AlfrescoSessionException) e;

    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return null;
}