Example usage for java.lang OutOfMemoryError printStackTrace

List of usage examples for java.lang OutOfMemoryError printStackTrace

Introduction

In this page you can find the example usage for java.lang OutOfMemoryError printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.klinker.android.twitter.ui.drawer_activities.discover.trends.SearchedTrendsActivity.java

public void doSearch(final String mQuery) {
    spinner.setVisibility(View.VISIBLE);

    new Thread(new Runnable() {
        @Override/* w  w  w.  j  a  va 2s .  com*/
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                query = new Query();

                if (mQuery.contains(" TOP")) {
                    query.setResultType(Query.ResultType.popular);
                }

                query.setQuery(mQuery.replace(" TOP", ""));
                QueryResult result;
                try {
                    result = twitter.search(query);
                } catch (OutOfMemoryError e) {
                    return;
                }

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, tweets);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });

            }
        }
    }).start();
}

From source file:com.klinker.android.twitter.activities.drawer_activities.discover.trends.SearchedTrendsActivity.java

public void doSearch(final String mQuery) {
    spinner.setVisibility(View.VISIBLE);

    new Thread(new Runnable() {
        @Override// w w  w. j av a2s. co m
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                Log.v("talon_search", "search query: " + mQuery);
                query = new Query();

                if (mQuery.contains(" TOP")) {
                    query.setResultType(Query.ResultType.popular);
                }

                query.setQuery(mQuery.replace(" TOP", ""));
                QueryResult result;
                try {
                    result = twitter.search(query);
                } catch (OutOfMemoryError e) {
                    return;
                }

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, tweets);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });

            }
        }
    }).start();
}

From source file:org.akaza.openclinica.control.core.SecureController.java

License:asdf

private void process(HttpServletRequest request, HttpServletResponse response)
        throws OpenClinicaException, UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    session = request.getSession();/*  www.  java  2 s .  c  o  m*/
    // BWP >> 1/8/2008
    try {
        // YW 10-03-2007 <<
        session.setMaxInactiveInterval(Integer.parseInt(SQLInitServlet.getField("max_inactive_interval")));
        String smURL = CoreResources.getField("smURL");
        if (StringUtils.isNotEmpty(smURL)) {

            int index = smURL.indexOf("//");
            String protocol = smURL.substring(0, index) + "//";
            String subDomain = smURL.substring(smURL.indexOf("//") + 2, smURL.indexOf("/", protocol.length()));
            String crossStorageURL = protocol + subDomain + "/hub/hub.html";
            session.setAttribute("crossStorageURL", crossStorageURL);
        }
        // YW >>
    } catch (NumberFormatException nfe) {
        // BWP>>3600 is the datainfo.properties maxInactiveInterval on
        // 1/8/2008
        session.setMaxInactiveInterval(3600);
    }

    // If the session already has a value with key SUPPORT_URL don't reset
    if (session.getAttribute(SUPPORT_URL) == null) {
        session.setAttribute(SUPPORT_URL, SQLInitServlet.getSupportURL());
    }

    // If the session already has a value with key WALKME_URL don't reset
    if (session.getAttribute(WALKME_URL) == null) {
        session.setAttribute(WALKME_URL, CoreResources.getField("walkme.url"));
    }

    // If the session already has a value with key PIWIK_URL don't reset
    if (session.getAttribute(PIWIK_URL) == null) {
        session.setAttribute(PIWIK_URL, CoreResources.getField("piwik.url"));
    }

    ub = (UserAccountBean) session.getAttribute(USER_BEAN_NAME);
    currentStudy = (StudyBean) session.getAttribute("study");
    currentPublicStudy = (StudyBean) session.getAttribute("publicStudy");
    currentRole = (StudyUserRoleBean) session.getAttribute("userRole");

    // Set current language preferences
    Locale locale = LocaleResolver.getLocale(request);
    ResourceBundleProvider.updateLocale(locale);
    resadmin = ResourceBundleProvider.getAdminBundle(locale);
    resaudit = ResourceBundleProvider.getAuditEventsBundle(locale);
    resexception = ResourceBundleProvider.getExceptionsBundle(locale);
    resformat = ResourceBundleProvider.getFormatBundle(locale);
    restext = ResourceBundleProvider.getTextsBundle(locale);
    resterm = ResourceBundleProvider.getTermsBundle(locale);
    resword = ResourceBundleProvider.getWordsBundle(locale);
    respage = ResourceBundleProvider.getPageMessagesBundle(locale);
    resworkflow = ResourceBundleProvider.getWorkflowBundle(locale);

    local_df = I18nFormatUtil.getDateFormat(locale);

    try {
        String userName = request.getRemoteUser();
        // BWP 1/8/08<< the sm variable may already be set with a mock
        // object,
        // from the perspective of
        // JUnit servlets tests
        /*
         * if(sm==null && (!StringUtil.isBlank(userName))) {//check if user logged in, then create a new
         * sessionmanger to
         * get ub //create a new sm in order to get a new ub object sm = new SessionManager(ub, userName); }
         */
        // BWP 01/08 >>
        // sm = new SessionManager(ub, userName);
        sm = new SessionManager(ub, userName, SpringServletAccess.getApplicationContext(context));
        if (ub == null || StringUtils.isEmpty(ub.getName())) {
            UserAccountDAO uDAO = new UserAccountDAO(sm.getDataSource());
            ub = (UserAccountBean) uDAO.findByEmail(userName);
            session.setAttribute("userBean", ub);
        }
        request.setAttribute("userBean", ub);
        StudyDAO sdao = new StudyDAO(sm.getDataSource());
        if (currentPublicStudy == null || currentPublicStudy.getId() <= 0) {
            UserAccountDAO uDAO = new UserAccountDAO(sm.getDataSource());
            ub = (UserAccountBean) uDAO.findByUserName(ub.getName());
            session.setAttribute(USER_BEAN_NAME, ub);
            if (ub.getId() > 0 && ub.getActiveStudyId() > 0) {
                CoreResources.setRequestSchema(request, "public");
                StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
                currentPublicStudy = (StudyBean) sdao.findByPK(ub.getActiveStudyId());

                ArrayList studyParameters = spvdao.findParamConfigByStudy(currentPublicStudy);

                currentPublicStudy.setStudyParameters(studyParameters);

                // set up the panel here, tbh
                panel.reset();
                /*
                 * panel.setData("Study", currentPublicStudy.getName()); panel.setData("Summary",
                 * currentPublicStudy.getSummary());
                 * panel.setData("Start Date", sdf.format(currentPublicStudy.getDatePlannedStart()));
                 * panel.setData("End Date",
                 * sdf.format(currentPublicStudy.getDatePlannedEnd())); panel.setData("Principal Investigator",
                 * currentPublicStudy.getPrincipalInvestigator());
                 */
                session.setAttribute(STUDY_INFO_PANEL, panel);
            } else {
                currentPublicStudy = new StudyBean();
            }
            session.setAttribute("publicStudy", currentPublicStudy);
            request.setAttribute("requestSchema", currentPublicStudy.getSchemaName());
            currentStudy = (StudyBean) sdao.findByUniqueIdentifier(currentPublicStudy.getIdentifier());
            if (currentStudy != null) {
                currentStudy.setParentStudyName(currentPublicStudy.getParentStudyName());
                StudyConfigService scs = new StudyConfigService(sm.getDataSource());
                if (currentStudy.getParentStudyId() <= 0) {// top study
                    scs.setParametersForStudy(currentStudy);

                } else {
                    // YW <<
                    currentStudy.setParentStudyName(
                            ((StudyBean) sdao.findByPK(currentStudy.getParentStudyId())).getName());
                    // YW >>
                    scs.setParametersForSite(currentStudy);
                }
            }
            request.setAttribute("requestSchema", "public");
            session.setAttribute("study", currentStudy);
        } else if (currentPublicStudy.getId() > 0) {
            // YW 06-20-2007<< set site's parentstudy name when site is
            // restored
            if (currentPublicStudy.getParentStudyId() > 0) {
                currentPublicStudy.setParentStudyName(
                        ((StudyBean) sdao.findByPK(currentPublicStudy.getParentStudyId())).getName());
                request.setAttribute("requestSchema", currentPublicStudy.getSchemaName());
                currentStudy.setParentStudyName(
                        ((StudyBean) sdao.findByPK(currentStudy.getParentStudyId())).getName());
                request.setAttribute("requestSchema", "public");
            }
            // YW >>
        }

        if (currentPublicStudy.getParentStudyId() > 0) {
            /*
             * The Role decription will be set depending on whether the user logged in at study lever or site level.
             * issue-2422
             */
            List roles = Role.toArrayList();
            for (Iterator it = roles.iterator(); it.hasNext();) {
                Role role = (Role) it.next();
                switch (role.getId()) {
                case 2:
                    role.setDescription("site_Study_Coordinator");
                    break;
                case 3:
                    role.setDescription("site_Study_Director");
                    break;
                case 4:
                    role.setDescription("site_investigator");
                    break;
                case 5:
                    role.setDescription("site_Data_Entry_Person");
                    break;
                case 6:
                    role.setDescription("site_monitor");
                    break;
                case 7:
                    role.setDescription("site_Data_Entry_Person2");
                    break;
                default:
                    // logger.info("No role matched when setting role description");
                }
            }
        } else {
            /*
             * If the current study is a site, we will change the role description. issue-2422
             */
            List roles = Role.toArrayList();
            for (Iterator it = roles.iterator(); it.hasNext();) {
                Role role = (Role) it.next();
                switch (role.getId()) {
                case 2:
                    role.setDescription("Study_Coordinator");
                    break;
                case 3:
                    role.setDescription("Study_Director");
                    break;
                case 4:
                    role.setDescription("Investigator");
                    break;
                case 5:
                    role.setDescription("Data_Entry_Person");
                    break;
                case 6:
                    role.setDescription("Monitor");
                    break;
                default:
                    // logger.info("No role matched when setting role description");
                }
            }
        }

        if (currentRole == null || currentRole.getId() <= 0) {
            // if (ub.getId() > 0 && currentPublicStudy.getId() > 0) {
            // if current study has been "removed", current role will be
            // kept as "invalid" -- YW 06-21-2007
            if (ub.getId() > 0 && currentPublicStudy.getId() > 0
                    && !currentPublicStudy.getStatus().getName().equals("removed")) {
                currentRole = ub.getRoleByStudy(currentPublicStudy.getId());
                if (currentPublicStudy.getParentStudyId() > 0) {
                    // Checking if currentPublicStudy has been removed or not will
                    // ge good enough -- YW 10-17-2007
                    StudyUserRoleBean roleInParent = ub.getRoleByStudy(currentPublicStudy.getParentStudyId());
                    // inherited role from parent study, pick the higher
                    // role
                    currentRole.setRole(Role.max(currentRole.getRole(), roleInParent.getRole()));
                }
                // logger.info("currentRole:" + currentRole.getRoleName());
            } else {
                currentRole = new StudyUserRoleBean();
            }
            session.setAttribute("userRole", currentRole);
        }
        // YW << For the case that current role is not "invalid" but current
        // active study has been removed.
        else if (currentRole.getId() > 0 && (currentPublicStudy.getStatus().equals(Status.DELETED)
                || currentPublicStudy.getStatus().equals(Status.AUTO_DELETED))) {
            currentRole.setRole(Role.INVALID);
            currentRole.setStatus(Status.DELETED);
            session.setAttribute("userRole", currentRole);
        }
        // YW 06-19-2007 >>

        request.setAttribute("isAdminServlet", getAdminServlet());

        this.request = request;
        this.response = response;

        // java.util.Enumeration en_session = session.getAttributeNames();
        // java.util.Enumeration en_request = request.getAttributeNames();
        //
        // // logging added to find problems with adding subjects, tbh
        // 102007
        // String ss_names = "session names: ";
        // while (en_session.hasMoreElements()) {
        // ss_names += " - " + en_session.nextElement();
        // }
        // logger.info(ss_names);
        //
        // // also added tbh, 102007
        // String rq_names = "request names: ";
        // while (en_request.hasMoreElements()) {
        // rq_names += " - " + en_request.nextElement();
        // }
        // logger.info(rq_names);
        if (!request.getRequestURI().endsWith("ResetPassword")) {
            passwdTimeOut();
        }
        request.setAttribute("requestSchema", getRequestSchema(request));
        mayProceed();
        // pingJobServer(request);
        processRequest();
    } catch (InconsistentStateException ise) {
        ise.printStackTrace();
        logger.warn("InconsistentStateException: org.akaza.openclinica.control.SecureController: "
                + ise.getMessage());

        addPageMessage(ise.getOpenClinicaMessage());
        forwardPage(ise.getGoTo());
    } catch (InsufficientPermissionException ipe) {
        ipe.printStackTrace();
        logger.warn("InsufficientPermissionException: org.akaza.openclinica.control.SecureController: "
                + ipe.getMessage());

        // addPageMessage(ipe.getOpenClinicaMessage());
        forwardPage(ipe.getGoTo());
    } catch (OutOfMemoryError ome) {
        ome.printStackTrace();
        long heapSize = Runtime.getRuntime().totalMemory();
        session.setAttribute("ome", "yes");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(SecureController.getStackTrace(e));

        forwardPage(Page.ERROR);
    }
}

From source file:com.akop.bach.ImageCache.java

public Bitmap getBitmap(String imageUrl, boolean bypassCache, int resizeH, int resizeV) {
    File file = getCacheFile(imageUrl, null);

    // See if it's in the local cache 
    // (but only if not being forced to refresh)
    if (!bypassCache && file.canRead()) {
        if (App.getConfig().logToConsole())
            App.logv("Cache hit: " + file.getAbsolutePath());

        file.lastModified();//from ww  w  . j  a  v a2 s  .  c  o m

        try {
            return BitmapFactory.decodeFile(file.getAbsolutePath());
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    // Fetch the image
    byte[] blob;
    int length;

    try {
        HttpClient client = new IgnorantHttpClient();
        HttpResponse resp = client.execute(new HttpGet(imageUrl));
        HttpEntity entity = resp.getEntity();

        if (entity == null)
            return null;

        InputStream stream = entity.getContent();
        if (stream == null)
            return null;

        try {
            if ((length = (int) entity.getContentLength()) <= 0)
                return null;

            blob = new byte[length];

            // Read the stream until nothing more to read
            for (int r = 0; r < length; r += stream.read(blob, r, length - r))
                ;
        } finally {
            stream.close();
            entity.consumeContent();
        }
    } catch (IOException e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();

        return null;
    }

    // if (file.canWrite())
    {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file);

            if (resizeH > -1 || resizeV > -1) {
                Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, length);
                float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight();

                int newWidth = (resizeH < 0) ? (int) ((float) resizeV * aspectRatio) : resizeH;
                int newHeight = (resizeV < 0) ? (int) ((float) resizeH / aspectRatio) : resizeV;

                Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                resized.compress(Bitmap.CompressFormat.PNG, 100, fos);

                return resized;
            } else {
                fos.write(blob);
            }

            if (App.getConfig().logToConsole())
                App.logv("Wrote to cache: " + file.getAbsolutePath());
        } catch (IOException e) {
            if (App.getConfig().logToConsole())
                e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    Bitmap bmp = null;

    try {
        bmp = BitmapFactory.decodeByteArray(blob, 0, length);
    } catch (Exception e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();
    }

    return bmp;
}

From source file:com.zld.ui.ZldNewActivity.java

@Override
public void onDataReceive(int handle, PlateResult plateResult, int uNumPlates, int eResultType, byte[] pImgFull,
        int nFullSize, byte[] pImgPlateClip, int nClipSize) {
    try {//from   w w w  . ja v a 2  s .c o  m
        DeviceSet ds = this.getDeviceSetFromHandle(handle);

        if (ds == null) {
            Toast.makeText(ZldNewActivity.this, "?:", Toast.LENGTH_SHORT)
                    .show();
        }

        DeviceInfo di = ds.getDeviceInfo();

        String dateText = "";

        dateText += plateResult.struBDTime.bdt_year;
        dateText += "/";

        dateText += plateResult.struBDTime.bdt_mon;
        dateText += "/";

        dateText += plateResult.struBDTime.bdt_mday;
        dateText += " ";

        dateText += plateResult.struBDTime.bdt_hour;
        dateText += ":";

        dateText += plateResult.struBDTime.bdt_min;
        dateText += ":";

        dateText += plateResult.struBDTime.bdt_sec;

        String plateText = new String(plateResult.license, "GBK");

        if (!m_gb.getplateCallbackInfoTable().addCallbackInfo(di.DeviceName, plateText, dateText, pImgFull,
                pImgPlateClip)) {
            Toast.makeText(ZldNewActivity.this, "?", Toast.LENGTH_SHORT).show();
        }

        Log.i("visizion", "decodeByteArray begin");

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;//??? 
        options.inInputShareable = true;
        Bitmap bmp;
        try {

            bmp = BitmapFactory.decodeByteArray(pImgFull, 0, pImgFull.length, options);
            if (bmp != null) {
                Message msg = new Message();

                msg.what = PlateImage;

                msg.arg1 = ds.getDeviceInfo().id;
                msg.obj = bmp;
                Bundle data = new Bundle();
                data.putString("plate", plateText);
                msg.setData(data);

                handler.sendMessage(msg);
            }
        } catch (OutOfMemoryError e) {
            Log.e("Map", "Tile Loader (241) Out Of Memory Error " + e.getLocalizedMessage());
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Log.i("visizion", "decodeByteArray end");
        }

    } catch (UnsupportedEncodingException e) {

        Toast.makeText(ZldNewActivity.this, "???", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.akop.bach.ImageCache.java

public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) {
    if (imageUrl == null || imageUrl.length() < 1)
        return null;

    File file = getCacheFile(imageUrl, cachePol);

    // See if it's in the local cache 
    // (but only if not being forced to refresh)
    if (!cachePol.bypassCache && file.canRead()) {
        if (App.getConfig().logToConsole())
            App.logv("Cache hit: " + file.getName());

        try {/* ww  w  .  j  av  a  2  s. co  m*/
            if (!cachePol.expired(System.currentTimeMillis(), file.lastModified()))
                return BitmapFactory.decodeFile(file.getAbsolutePath());
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    // Fetch the image
    byte[] blob;
    int length;

    try {
        HttpClient client = new IgnorantHttpClient();

        HttpParams params = client.getParams();
        params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)");

        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS);

        HttpResponse resp = client.execute(new HttpGet(imageUrl));
        HttpEntity entity = resp.getEntity();

        if (entity == null)
            return null;

        InputStream stream = entity.getContent();
        if (stream == null)
            return null;

        try {
            if ((length = (int) entity.getContentLength()) <= 0) {
                // Length is negative, perhaps content length is not set
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

                int chunkSize = 5000;
                byte[] chunk = new byte[chunkSize];

                for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize))
                    byteStream.write(chunk, 0, r);

                blob = byteStream.toByteArray();
            } else {
                // We know the length
                blob = new byte[length];

                // Read the stream until nothing more to read
                for (int r = 0; r < length; r += stream.read(blob, r, length - r))
                    ;
            }
        } finally {
            stream.close();
            entity.consumeContent();
        }
    } catch (IOException e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();

        return null;
    }

    // if (file.canWrite())
    {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file);

            if (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) {
                Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
                float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight();

                int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio)
                        : cachePol.resizeWidth;
                int newHeight = (cachePol.resizeHeight <= 0)
                        ? (int) ((float) cachePol.resizeWidth / aspectRatio)
                        : cachePol.resizeHeight;

                Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                resized.compress(Bitmap.CompressFormat.PNG, 100, fos);

                return resized;
            } else {
                fos.write(blob);
            }

            if (App.getConfig().logToConsole())
                App.logv("Wrote to cache: " + file.getName());
        } catch (IOException e) {
            if (App.getConfig().logToConsole())
                e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    Bitmap bmp = null;

    try {
        bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
    } catch (Exception e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();
    }

    return bmp;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToFacebook(final Activity activity, final Handler handler, final Facebook mFacebook,
        final String path, final String title, final String description, final String emailAddress,
        final long sdrecord_id) {

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // Track errors
            boolean failed = false;

            Log.i(TAG, "Upload starting");
            // Initialising REST API video.upload parameters
            Bundle params = new Bundle();

            params.putString("method", "facebook.video.upload");
            params.putString("format", "json");
            params.putString("title", title);
            params.putString("description", description);
            params.putString("call_id", String.valueOf(System.currentTimeMillis()));
            params.putString("v", "1.0");
            params.putString("oauth_token", mFacebook.getAccessToken());

            // Reading input file
            try {
                File videoFile = new File(path);
                byte[] data = null;
                try {

                    // XXX
                    // SPLIT THIS INTO 5K chunks!!
                    // XXX

                    data = new byte[(int) videoFile.length()];
                } catch (OutOfMemoryError e) {
                    failed = true;//from  w  w  w .j a  v  a 2  s . co m
                }
                if (data != null) {
                    InputStream is = new FileInputStream(videoFile);
                    is.read(data);
                    params.putByteArray(videoFile.getName(), data);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Cannot read video file :", ex);
            }

            // Sending POST request to Facebook
            String response = null;
            String url = "https://api-video.facebook.com/restserver.php";

            try {
                if (!failed) {
                    response = Util.openUrl(url, "POST", params);
                }
                // SessionEvents.onUploadComplete(response);
            } catch (FileNotFoundException e) {
                // SessionEvents.onFileNotFoundException(e);
                failed = true;
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // SessionEvents.onMalformedURLException(e);
                failed = true;
                e.printStackTrace();
            } catch (IOException e) {
                // SessionEvents.onIOException(e);
                failed = true;
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                failed = true;
                e.printStackTrace();
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

                return;
            }

            Log.i(TAG, "Uploading to facebook complete. Response is " + response);

            // response is JSON
            JSONObject fb_response = null;
            // decode, and grab URL
            try {
                fb_response = (JSONObject) new JSONTokener(response).nextValue();
            } catch (JSONException e) {
                //
                e.printStackTrace();
                fb_response = null;
            }
            String hosted_url = "facebook.com";

            if (fb_response != null) {

                try {
                    hosted_url = fb_response.getString("link");
                    Log.i(TAG, "Facebook hosted url is : " + hosted_url);
                } catch (JSONException e) {
                    //
                    e.printStackTrace();
                    hosted_url = null;
                }

                if (hosted_url != null) {
                    // Log record of this URL in POSTs table
                    dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, url, hosted_url, "");

                    mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                    // Use the handler to execute a Runnable on the
                    // main thread in order to have access to the
                    // UI elements.
                    handler.postDelayed(new Runnable() {

                        public void run() {
                            // Update UI

                            // Indicate back to calling activity the result!
                            // update uploadInProgress state also.

                            ((VidiomActivity) activity).finishedUploading(true);
                            ((VidiomActivity) activity)
                                    .createNotification(res.getString(R.string.upload_to_facebook_succeeded_));

                        }
                    }, 0);
                }

            } else {

                // an error -- fb_response is NULL.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

            }

            if (emailAddress != null && fb_response != null && hosted_url != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + hosted_url, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

        }
    });

    t.start();

    return t;

}

From source file:com.androzic.Androzic.java

public void drawMap(Viewport viewport, boolean bestmap, Canvas c) {
    BaseMap cm = currentMap;//  w  w  w  .  ja va2 s.  c  o  m

    if (cm != null) {
        if (adjacentMaps) {
            int l = -(viewport.width / 2 + viewport.lookAheadXY[0]);
            int t = -(viewport.height / 2 + viewport.lookAheadXY[1]);
            int r = l + viewport.width;
            int b = t + viewport.height;

            if (coveringMaps == null || invalidCoveringMaps || viewport.mapCenter[0] != coveringLoc[0]
                    || viewport.mapCenter[1] != coveringLoc[1] || coveringBestMap != bestmap
                    || l != coveringScreen.left || t != coveringScreen.top || r != coveringScreen.right
                    || b != coveringScreen.bottom) {
                coveringScreen.left = l;
                coveringScreen.top = t;
                coveringScreen.right = r;
                coveringScreen.bottom = b;
                coveringLoc[0] = viewport.mapCenter[0];
                coveringLoc[1] = viewport.mapCenter[1];
                coveringBestMap = bestmap;
                updateCoveringMaps();
            }
        }
        try {
            if (coveringMaps != null && !coveringMaps.isEmpty()) {
                boolean drawn = false;
                for (BaseMap map : coveringMaps) {
                    if (!drawn && coveringBestMap && map.getMPP() < cm.getMPP()) {
                        coveredAll = cm.drawMap(viewport, cropMapBorder, drawMapBorder, c);
                        drawn = true;
                    }
                    map.drawMap(viewport, cropMapBorder, drawMapBorder, c);
                }
                if (!drawn) {
                    coveredAll = cm.drawMap(viewport, cropMapBorder, drawMapBorder, c);
                }
            } else {
                coveredAll = cm.drawMap(viewport, cropMapBorder, drawMapBorder, c);
            }
        } catch (OutOfMemoryError err) {
            if (!memmsg && mapHolder != null)
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Androzic.this, R.string.err_nomemory, Toast.LENGTH_LONG).show();
                    }
                });
            memmsg = true;
            err.printStackTrace();
        }
    }
}

From source file:website.openeng.async.Connection.java

private Payload doInBackgroundSync(Payload data) {
    // for for doInBackgroundLoadDeckCounts if any
    Timber.d("doInBackgroundSync()");
    // Block execution until any previous background task finishes, or timeout after 5s
    boolean ok = DeckTask.waitToFinish(5);

    String hkey = (String) data.data[0];
    boolean media = (Boolean) data.data[1];
    String conflictResolution = (String) data.data[2];
    Collection col = data.col;// w w  w .j  a va  2 s.c om

    boolean colCorruptFullSync = false;
    if (!CollectionHelper.getInstance().colIsOpen() || !ok) {
        if (conflictResolution != null && conflictResolution.equals("download")) {
            colCorruptFullSync = true;
        } else {
            data.success = false;
            data.result = new Object[] { "genericError" };
            return data;
        }
    }
    try {
        CollectionHelper.getInstance().lockCollection();
        HttpSyncer server = new RemoteServer(this, hkey);
        Syncer client = new Syncer(col, server);

        // run sync and check state
        boolean noChanges = false;
        if (conflictResolution == null) {
            Timber.i("Sync - starting sync");
            publishProgress(R.string.sync_prepare_syncing);
            Object[] ret = client.sync(this);
            data.message = client.getSyncMsg();
            if (ret == null) {
                data.success = false;
                data.result = new Object[] { "genericError" };
                return data;
            }
            String retCode = (String) ret[0];
            if (!retCode.equals("noChanges") && !retCode.equals("success")) {
                data.success = false;
                data.result = ret;
                // Check if there was a sanity check error
                if (retCode.equals("sanityCheckError")) {
                    // Force full sync next time
                    col.modSchemaNoCheck();
                    col.save();
                }
                return data;
            }
            // save and note success state
            if (retCode.equals("noChanges")) {
                // publishProgress(R.string.sync_no_changes_message);
                noChanges = true;
            } else {
                // publishProgress(R.string.sync_database_acknowledge);
            }
        } else {
            try {
                server = new FullSyncer(col, hkey, this);
                if (conflictResolution.equals("upload")) {
                    Timber.i("Sync - fullsync - upload collection");
                    publishProgress(R.string.sync_preparing_full_sync_message);
                    Object[] ret = server.upload();
                    if (ret == null) {
                        data.success = false;
                        data.result = new Object[] { "genericError" };
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                    if (!ret[0].equals(HttpSyncer.ANKIWEB_STATUS_OK)) {
                        data.success = false;
                        data.result = ret;
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                } else if (conflictResolution.equals("download")) {
                    Timber.i("Sync - fullsync - download collection");
                    publishProgress(R.string.sync_downloading_message);
                    Object[] ret = server.download();
                    if (ret == null) {
                        data.success = false;
                        data.result = new Object[] { "genericError" };
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                    if (!ret[0].equals("success")) {
                        data.success = false;
                        data.result = ret;
                        if (!colCorruptFullSync) {
                            CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        }
                        return data;
                    }
                }
                col = CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
            } catch (OutOfMemoryError e) {
                KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
                data.success = false;
                data.result = new Object[] { "OutOfMemoryError" };
                return data;
            } catch (RuntimeException e) {
                if (timeoutOccured(e)) {
                    data.result = new Object[] { "connectionError" };
                } else {
                    KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
                    data.result = new Object[] { "IOException" };
                }
                data.success = false;
                return data;
            }
        }

        // clear undo to avoid non syncing orphans (because undo resets usn too
        if (!noChanges) {
            col.clearUndo();
        }
        // then move on to media sync
        boolean noMediaChanges = false;
        String mediaError = null;
        if (media) {
            server = new RemoteMediaServer(col, hkey, this);
            MediaSyncer mediaClient = new MediaSyncer(col, (RemoteMediaServer) server, this);
            String ret;
            try {
                ret = mediaClient.sync();
                if (ret == null) {
                    mediaError = KanjiDroidApp.getAppResources().getString(R.string.sync_media_error);
                } else {
                    if (ret.equals("noChanges")) {
                        publishProgress(R.string.sync_media_no_changes);
                        noMediaChanges = true;
                    }
                    if (ret.equals("sanityFailed")) {
                        mediaError = KanjiDroidApp.getAppResources()
                                .getString(R.string.sync_media_sanity_failed);
                    } else {
                        publishProgress(R.string.sync_media_success);
                    }
                }
            } catch (UnsupportedSyncException e) {
                mediaError = KanjiDroidApp.getAppResources().getString(R.string.sync_media_unsupported);
                KanjiDroidApp.getSharedPrefs(KanjiDroidApp.getInstance().getApplicationContext()).edit()
                        .putBoolean("syncFetchesMedia", false).commit();
                KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync");
            } catch (RuntimeException e) {
                if (timeoutOccured(e)) {
                    data.result = new Object[] { "connectionError" };
                } else {
                    KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync");
                }
                mediaError = e.getLocalizedMessage();
            }
        }
        if (noChanges && noMediaChanges) {
            data.success = false;
            data.result = new Object[] { "noChanges" };
            return data;
        } else {
            data.success = true;
            data.data = new Object[] { conflictResolution, col, mediaError };
            return data;
        }
    } catch (UnknownHttpResponseException e) {
        Timber.e("doInBackgroundSync -- unknown response code error");
        e.printStackTrace();
        data.success = false;
        Integer code = e.getResponseCode();
        String msg = e.getLocalizedMessage();
        data.result = new Object[] { "error", code, msg };
        return data;
    } catch (Exception e) {
        // Global error catcher.
        // Try to give a human readable error, otherwise print the raw error message
        Timber.e("doInBackgroundSync error");
        e.printStackTrace();
        data.success = false;
        if (timeoutOccured(e)) {
            data.result = new Object[] { "connectionError" };
        } else {
            KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync");
            data.result = new Object[] { e.getLocalizedMessage() };
        }
        return data;
    } finally {
        // Close collection to roll back any sync failures and
        Timber.d("doInBackgroundSync -- closing collection on outer finally statement");
        col.close(false);
        CollectionHelper.getInstance().unlockCollection();
        Timber.d("doInBackgroundSync -- reopening collection on outer finally statement");
        CollectionHelper.getInstance().reopenCollection();
    }

}