Example usage for android.util Log ERROR

List of usage examples for android.util Log ERROR

Introduction

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

Prototype

int ERROR

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

Click Source Link

Document

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

Usage

From source file:com.digipom.manteresting.android.service.cache.CacheService.java

private int tryGetLargeMemoryClass(ActivityManager am) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        try {/*w w  w .j  a  v a2  s  . com*/
            final Method getLargeMemoryClass = ActivityManager.class.getMethod("getLargeMemoryClass",
                    (Class[]) null);
            final Integer largeMemoryClass = (Integer) getLargeMemoryClass.invoke(am, (Object[]) null);
            return largeMemoryClass;
        } catch (Exception e) {
            if (LoggerConfig.canLog(Log.ERROR)) {
                Log.e(TAG, "Reflection call failed.", e);
            }

            return am.getMemoryClass();
        }
    } else {
        return am.getMemoryClass();
    }
}

From source file:org.gnucash.android.export.ExportAsyncTask.java

/**
 * Generates the appropriate exported transactions file for the given parameters
 * @param params Export parameters/*from   w ww  .ja v  a 2 s  .c o  m*/
 * @return <code>true</code> if export was successful, <code>false</code> otherwise
 */
@Override
protected Boolean doInBackground(ExportParams... params) {
    mExportParams = params[0];
    mExporter = getExporter();

    try {
        mExportedFiles = mExporter.generateExport();
    } catch (final Exception e) {
        Log.e(TAG, "Error exporting: " + e.getMessage());
        Crashlytics.logException(e);
        e.printStackTrace();
        if (mContext instanceof Activity) {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext,
                            mContext.getString(R.string.toast_export_error,
                                    mExportParams.getExportFormat().name()) + "\n" + e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        return false;
    }

    if (mExportedFiles.isEmpty())
        return false;

    try {
        moveToTarget();
    } catch (Exporter.ExporterException e) {
        Crashlytics.log(Log.ERROR, TAG, "Error sending exported files to target: " + e.getMessage());
        return false;
    }

    return true;
}

From source file:biz.bokhorst.xprivacy.Util.java

public static String hasProLicense(Context context) {
    try {/*from  w w  w .  ja  va 2  s . c  o  m*/
        // Get license
        String[] license = getProLicenseUnchecked();
        if (license == null)
            return null;
        String name = license[0];
        String email = license[1];
        String signature = license[2];

        // Get bytes
        byte[] bEmail = email.getBytes("UTF-8");
        byte[] bSignature = hex2bytes(signature);
        if (bEmail.length == 0 || bSignature.length == 0) {
            Util.log(null, Log.ERROR, "Licensing: invalid file");
            return null;
        }

        // Verify license
        boolean licensed = verifyData(bEmail, bSignature, getPublicKey(context));
        if (licensed)
            Util.log(null, Log.INFO, "Licensing: ok");
        else
            Util.log(null, Log.ERROR, "Licensing: invalid");

        // Return result
        if (licensed)
            return name;
    } catch (Throwable ex) {
        Util.bug(null, ex);
    }
    return null;
}

From source file:com.android.talkback.labeling.CustomLabelMigrationManager.java

public void importLabels(Uri contentUri, boolean overrideExistingLabels, OnLabelMigrationCallback callback) {
    try {/*from  ww w .ja v  a2  s  .c  om*/
        String text = readText(contentUri);
        if (text == null) {
            return;
        }

        List<Label> labels = parseLabels(text);
        if (labels.size() == 0) {
            return;
        }

        mManager.importLabels(labels, overrideExistingLabels, callback);
    } catch (Exception e) {
        notifyFailure(callback);
        LogUtils.log(Log.ERROR, "failed to import labels");
    }
}

From source file:com.radicaldynamic.groupinform.activities.AccountDeviceList.java

static public void fetchDeviceList(boolean fetchAnyway) {
    if (Collect.getInstance().getIoService().isSignedIn() || fetchAnyway) {
        if (Collect.Log.INFO)
            Log.i(Collect.LOGTAG, t + "fetching list of devices");
    } else {/*w  ww .  j  a va2s  . c om*/
        if (Collect.Log.INFO)
            Log.i(Collect.LOGTAG, t + "not signed in, skipping device list fetch");
        return;
    }

    // Try to ping the service to see if it is "up"
    String deviceListUrl = Collect.getInstance().getInformOnlineState().getServerUrl() + "/device/list";
    String getResult = HttpUtils.getUrlData(deviceListUrl);
    JSONObject jsonDeviceList;

    try {
        jsonDeviceList = (JSONObject) new JSONTokener(getResult).nextValue();

        String result = jsonDeviceList.optString(InformOnlineState.RESULT, InformOnlineState.ERROR);

        if (result.equals(InformOnlineState.OK)) {
            // Write out list of jsonDevices for later retrieval by loadDevicesList() and InformOnlineService.loadDevicesHash()                
            JSONArray jsonDevices = jsonDeviceList.getJSONArray("devices");

            //                // Record the number of seats that this account is licenced for
            //                Collect
            //                    .getInstance()
            //                    .getInformOnlineState()
            //                    .setAccountLicencedSeats(jsonDeviceList.getInt("licencedSeats"));       

            //                // Record the plan type for this account (this is a weird place to do it in but it makes sense to piggyback)
            //                Collect
            //                    .getInstance()
            //                    .getInformOnlineState()
            //                    .setAccountPlan(jsonDeviceList.getString("planType"));
            try {
                // Write out a device list cache file
                FileOutputStream fos = new FileOutputStream(
                        new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.DEVICE_CACHE_FILE));
                fos.write(jsonDevices.toString().getBytes());
                fos.close();
            } catch (Exception e) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, t + "unable to write device cache: " + e.toString());
                e.printStackTrace();
            }
        } else {
            // There was a problem... handle it!
        }
    } catch (NullPointerException e) {
        // Communication error
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, t + "no getResult to parse.  Communication error with node.js server?");
        e.printStackTrace();
    } catch (JSONException e) {
        // Parse error (malformed result)
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, t + "failed to parse getResult " + getResult);
        e.printStackTrace();
    }
}

From source file:com.google.android.gcm.demo.logic.GcmServerSideSender.java

/**
 * Send a downstream message via HTTP JSON.
 *
 * @param destination the registration id of the recipient app.
 * @param message        the message to be sent
 * @throws IOException//from   w ww .j av  a2s  .co  m
 */
public String sendHttpJsonDownstreamMessage(String destination, Message message) throws IOException {

    JSONObject jsonBody = new JSONObject();
    try {
        jsonBody.put(PARAM_TO, destination);
        jsonBody.putOpt(PARAM_COLLAPSE_KEY, message.getCollapseKey());
        jsonBody.putOpt(PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
        jsonBody.putOpt(PARAM_TIME_TO_LIVE, message.getTimeToLive());
        jsonBody.putOpt(PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
        jsonBody.putOpt(PARAM_DRY_RUN, message.isDryRun());
        if (message.getData().size() > 0) {
            JSONObject jsonPayload = new JSONObject(message.getData());
            jsonBody.put(PARAM_JSON_PAYLOAD, jsonPayload);
        }
        if (message.getNotificationParams().size() > 0) {
            JSONObject jsonNotificationParams = new JSONObject(message.getNotificationParams());
            jsonBody.put(PARAM_JSON_NOTIFICATION_PARAMS, jsonNotificationParams);
        }
    } catch (JSONException e) {
        logger.log(Log.ERROR, "Failed to build JSON body");
        throw new IOException("Failed to build JSON body");
    }

    HttpRequest httpRequest = new HttpRequest();
    httpRequest.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
    httpRequest.setHeader(HEADER_AUTHORIZATION, "key=" + key);
    httpRequest.doPost(GCM_SEND_ENDPOINT, jsonBody.toString());

    if (httpRequest.getResponseCode() != 200) {
        throw new IOException("Invalid request." + " status: " + httpRequest.getResponseCode() + " response: "
                + httpRequest.getResponseBody());
    }

    JSONObject jsonResponse;
    try {
        jsonResponse = new JSONObject(httpRequest.getResponseBody());
        logger.log(Log.INFO, "Send message:\n" + jsonResponse.toString(2));
    } catch (JSONException e) {
        logger.log(Log.ERROR, "Failed to parse server response:\n" + httpRequest.getResponseBody());
    }
    return httpRequest.getResponseBody();
}

From source file:com.google.android.gcm.demo.ui.TopicsFragment.java

private void unsubscribe(View v) {
    String senderId = (String) v.getTag(R.id.tag_senderid);
    String topic = (String) v.getTag(R.id.tag_topic);
    Sender sender = mSenders.getSender(senderId);
    Token gcmToken = (sender != null) ? sender.getGcmDemoAppToken() : null;
    if (gcmToken == null) {
        mLogger.log(Log.ERROR, "gcmToken missing while un-subscribing from topic.");
        return;//from w  w w.  j  a  v  a  2  s  . co  m
    }
    Toast.makeText(getActivity(), getString(R.string.topics_unsubscribing, topic), Toast.LENGTH_SHORT).show();
    mPubSubHelper.unsubscribeTopic(senderId, gcmToken.token, topic);
}

From source file:com.radicaldynamic.groupinform.tasks.InstanceUploaderTask.java

@Override
// BEGIN custom//from w  w w  . j ava 2s .co  m
//    protected HashMap<String, String> doInBackground(Long... values) {
protected HashMap<String, String> doInBackground(String... values) {
    // END custom    
    mResults = new HashMap<String, String>();

    // BEGIN custom
    //        String selection = InstanceColumns._ID + "=?";
    //        String[] selectionArgs = new String[values.length];
    //        for (int i = 0; i < values.length; i++) {
    //            if (i != values.length - 1) {
    //                selection += " or " + InstanceColumns._ID + "=?";
    //            }
    //            selectionArgs[i] = values[i].toString();
    //        }        
    // END custom

    // get shared HttpContext so that authentication and cookies are retained.
    HttpContext localContext = Collect.getInstance().getHttpContext();
    HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    // BEGIN custom        
    //      Cursor c =
    //      Collect.getInstance().getContentResolver()
    //              .query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
    //
    //  if (c.getCount() > 0) {
    //      c.moveToPosition(-1);
    //      next_submission: while (c.moveToNext()) {
    //          if (isCancelled()) {
    //              return mResults;
    //          }        
    //          publishProgress(c.getPosition() + 1, c.getCount());
    //          String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
    //          String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
    //          Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
    //
    //          String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));

    next_submission: for (int i = 0; i < values.length; i++) {
        if (isCancelled()) {
            return mResults;
        }

        publishProgress(i + 1, values.length);

        FormInstance instanceDoc = null;
        String id = values[i];

        try {
            instanceDoc = Collect.getInstance().getDbService().getDb().get(FormInstance.class, id);
        } catch (DocumentNotFoundException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to retrieve instance: " + e.toString());
            mResults.put(id, fail + "warning: document not found :: details: " + e.getMessage());
            continue;
        } catch (DbAccessException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to access database: " + e.toString());
            mResults.put(id, fail + "error: could not acess database :: details: " + e.getMessage());
            continue;
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unexpected exception: " + e.toString());
            e.printStackTrace();
            mResults.put(id, fail + "unexpected error :: details: " + e.getMessage());
            continue;
        }

        String urlString = instanceDoc.getOdk().getUploadUri();
        // END custom

        if (urlString == null) {
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
            urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL,
                    Collect.getInstance().getString(R.string.default_server_url));
            String submissionUrl = settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
            urlString = urlString + submissionUrl;
        }

        @SuppressWarnings("unused")
        ContentValues cv = new ContentValues();
        URI u = null;
        try {
            URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
            u = url.toURI();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of MalformedURLException for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            continue;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of URISyntaxException for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            continue;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of UnsupportedEncodingException for "
                                    + id + ": " + e1.toString());
            }
            // END custom
            continue;
        }

        boolean openRosaServer = false;
        if (uriRemap.containsKey(u)) {
            // we already issued a head request and got a response,
            // so we know the proper URL to send the submission to
            // and the proper scheme. We also know that it was an
            // OpenRosa compliant server.
            openRosaServer = true;
            u = uriRemap.get(u);
        } else {
            // we need to issue a head request
            HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

            // prepare response
            HttpResponse response = null;
            try {
                response = httpclient.execute(httpHead, localContext);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 401) {
                    // we need authentication, so stop and return what we've
                    // done so far.
                    mAuthRequestingServer = u;
                    return null;
                } else if (statusCode == 204) {
                    Header[] locations = response.getHeaders("Location");
                    if (locations != null && locations.length == 1) {
                        try {
                            URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                            URI uNew = url.toURI();
                            if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                                openRosaServer = true;
                                // trust the server to tell us a new location
                                // ... and possibly to use https instead.
                                uriRemap.put(u, uNew);
                                u = uNew;
                            } else {
                                // Don't follow a redirection attempt to a different host.
                                // We can't tell if this is a spoof or not.
                                mResults.put(id, fail + "Unexpected redirection attempt to a different host: "
                                        + uNew.toString());
                                // BEGIN custom
                                //                                        cv.put(InstanceColumns.STATUS,
                                //                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                //                                        Collect.getInstance().getContentResolver()
                                //                                                .update(toUpdate, cv, null, null);

                                try {
                                    instanceDoc.getOdk()
                                            .setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                                } catch (Exception e1) {
                                    if (Collect.Log.ERROR)
                                        Log.e(Collect.LOGTAG, t
                                                + ": could not record upload failed because of redirection error for "
                                                + id + ": " + e1.toString());
                                }
                                // END custom
                                continue;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mResults.put(id, fail + urlString + " " + e.getMessage());
                            // BEGIN custom
                            //                                    cv.put(InstanceColumns.STATUS,
                            //                                        InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            //                                    Collect.getInstance().getContentResolver()
                            //                                            .update(toUpdate, cv, null, null);

                            try {
                                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                                Collect.getInstance().getDbService().getDb().update(instanceDoc);
                            } catch (Exception e1) {
                                if (Collect.Log.ERROR)
                                    Log.e(Collect.LOGTAG, t
                                            + ": could not record upload failed because of unexpected exception for "
                                            + id + ": " + e1.toString());
                            }
                            // END custom
                            continue;
                        }
                    }
                } else {
                    // may be a server that does not handle
                    try {
                        // have to read the stream in order to reuse the connection
                        InputStream is = response.getEntity().getContent();
                        // read to end of stream...
                        final long count = 1024L;
                        while (is.skip(count) == count)
                            ;
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Log.w(t, "Status code on Head request: " + statusCode);
                    if (statusCode >= 200 && statusCode <= 299) {
                        mResults.put(id, fail
                                + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                        // BEGIN custom
                        //                                cv.put(InstanceColumns.STATUS,
                        //                                    InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        //                                Collect.getInstance().getContentResolver()
                        //                                        .update(toUpdate, cv, null, null);

                        try {
                            instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                            Collect.getInstance().getDbService().getDb().update(instanceDoc);
                        } catch (Exception e1) {
                            if (Collect.Log.ERROR)
                                Log.e(Collect.LOGTAG, t
                                        + ": could not record upload failed because of network login error for "
                                        + id + ": " + e1.toString());
                        }
                        // END custom
                        continue;
                    }
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Log.e(t, e.getMessage());
                mResults.put(id, fail + "Client Protocol Exception");

                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of client protocol exception for "
                                        + id + ": " + e1.toString());
                }
                // END custom
                continue;
            } catch (ConnectTimeoutException e) {
                e.printStackTrace();
                Log.e(t, e.getMessage());
                mResults.put(id, fail + "Connection Timeout");
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG, t
                                + ": could not record upload failed because of connection timeout exception for "
                                + id + ": " + e1.toString());
                }
                // END custom
                continue;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                Log.e(t, e.getMessage());
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of unknown host exception for "
                                        + id + ": " + e1.toString());
                }
                // END custom
                continue;
            } catch (Exception e) {
                e.printStackTrace();
                mResults.put(id, fail + "Generic Exception");
                Log.e(t, e.getMessage());
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG, t
                                + ": could not record upload failed because of (generic) unexpected exception for "
                                + id + ": " + e1.toString());
                }
                // END custom
                continue;
            }
        }

        // At this point, we may have updated the uri to use https.
        // This occurs only if the Location header keeps the host name
        // the same. If it specifies a different host name, we error
        // out.
        //
        // And we may have set authentication cookies in our
        // cookiestore (referenced by localContext) that will enable
        // authenticated publication to the server.
        //
        // BEGIN custom                
        String uploadFolder = FileUtilsExtended.ODK_UPLOAD_PATH + File.separator + UUID.randomUUID();
        FileUtils.createFolder(uploadFolder);

        try {
            HashMap<String, Attachment> attachments = (HashMap<String, Attachment>) instanceDoc
                    .getAttachments();

            // Download files from database
            for (Entry<String, Attachment> entry : attachments.entrySet()) {
                String key = entry.getKey();

                AttachmentInputStream ais = Collect.getInstance().getDbService().getDb().getAttachment(id, key);

                // ODK code below expects the XML instance to have a .xml extension
                if (key.equals("xml"))
                    key = id + ".xml";

                FileOutputStream file = new FileOutputStream(new File(uploadFolder, key));
                byte[] buffer = new byte[8192];
                int bytesRead = 0;

                while ((bytesRead = ais.read(buffer)) != -1) {
                    file.write(buffer, 0, bytesRead);
                }

                ais.close();
                file.close();
            }
        } catch (DocumentNotFoundException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to retrieve attachment: " + e.toString());
            mResults.put(id, fail + "warning: attachment not found :: details: " + e.getMessage());
            continue;
        } catch (DbAccessException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to access database: " + e.toString());
            mResults.put(id, fail + "error: could not acess database :: details: " + e.getMessage());
            continue;
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unexpected exception: " + e.toString());
            e.printStackTrace();
            mResults.put(id, fail + "unexpected error :: details: " + e.getMessage());
            continue;
        }
        // END custom

        // get instance file
        // BEGIN custom
        //                File instanceFile = new File(instance);
        File instanceFile = new File(uploadFolder, id + ".xml");
        // END custom

        if (!instanceFile.exists()) {
            mResults.put(id, fail + "instance XML file does not exist!");
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of missing instance file for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            continue;
        }

        // find all files in parent directory
        File[] allFiles = instanceFile.getParentFile().listFiles();

        // add media files
        List<File> files = new ArrayList<File>();
        for (File f : allFiles) {
            String fileName = f.getName();

            int dotIndex = fileName.lastIndexOf(".");
            String extension = "";
            if (dotIndex != -1) {
                extension = fileName.substring(dotIndex + 1);
            }

            if (fileName.startsWith(".")) {
                // ignore invisible files
                continue;
            }
            if (fileName.equals(instanceFile.getName())) {
                continue; // the xml file has already been added
            } else if (openRosaServer) {
                files.add(f);
            } else if (extension.equals("jpg")) { // legacy 0.9x
                files.add(f);
            } else if (extension.equals("3gpp")) { // legacy 0.9x
                files.add(f);
            } else if (extension.equals("3gp")) { // legacy 0.9x
                files.add(f);
            } else if (extension.equals("mp4")) { // legacy 0.9x
                files.add(f);
            } else {
                Log.w(t, "unrecognized file type " + f.getName());
            }
        }

        boolean first = true;
        int j = 0;
        while (j < files.size() || first) {
            first = false;

            HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);

            MimeTypeMap m = MimeTypeMap.getSingleton();

            long byteCount = 0L;

            // mime post
            MultipartEntity entity = new MultipartEntity();

            // add the submission file first...
            FileBody fb = new FileBody(instanceFile, "text/xml");
            entity.addPart("xml_submission_file", fb);
            Log.i(t, "added xml_submission_file: " + instanceFile.getName());
            byteCount += instanceFile.length();

            for (; j < files.size(); j++) {
                File f = files.get(j);
                String fileName = f.getName();
                int idx = fileName.lastIndexOf(".");
                String extension = "";
                if (idx != -1) {
                    extension = fileName.substring(idx + 1);
                }
                String contentType = m.getMimeTypeFromExtension(extension);

                // we will be processing every one of these, so
                // we only need to deal with the content type determination...
                if (extension.equals("xml")) {
                    fb = new FileBody(f, "text/xml");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added xml file " + f.getName());
                } else if (extension.equals("jpg")) {
                    fb = new FileBody(f, "image/jpeg");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added image file " + f.getName());
                } else if (extension.equals("3gpp")) {
                    fb = new FileBody(f, "audio/3gpp");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added audio file " + f.getName());
                } else if (extension.equals("3gp")) {
                    fb = new FileBody(f, "video/3gpp");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added video file " + f.getName());
                } else if (extension.equals("mp4")) {
                    fb = new FileBody(f, "video/mp4");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added video file " + f.getName());
                } else if (extension.equals("csv")) {
                    fb = new FileBody(f, "text/csv");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added csv file " + f.getName());
                } else if (f.getName().endsWith(".amr")) {
                    fb = new FileBody(f, "audio/amr");
                    entity.addPart(f.getName(), fb);
                    Log.i(t, "added audio file " + f.getName());
                } else if (extension.equals("xls")) {
                    fb = new FileBody(f, "application/vnd.ms-excel");
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added xls file " + f.getName());
                } else if (contentType != null) {
                    fb = new FileBody(f, contentType);
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName());
                } else {
                    contentType = "application/octet-stream";
                    fb = new FileBody(f, contentType);
                    entity.addPart(f.getName(), fb);
                    byteCount += f.length();
                    Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
                }

                // we've added at least one attachment to the request...
                if (j + 1 < files.size()) {
                    if (byteCount + files.get(j + 1).length() > 10000000L) {
                        // the next file would exceed the 10MB threshold...
                        Log.i(t, "Extremely long post is being split into multiple posts");
                        try {
                            StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                            entity.addPart("*isIncomplete*", sb);
                        } catch (Exception e) {
                            e.printStackTrace(); // never happens...
                        }
                        ++j; // advance over the last attachment added...
                        break;
                    }
                }
            }

            httppost.setEntity(entity);

            // prepare response and return uploaded
            HttpResponse response = null;
            try {
                response = httpclient.execute(httppost, localContext);
                int responseCode = response.getStatusLine().getStatusCode();

                try {
                    // have to read the stream in order to reuse the connection
                    InputStream is = response.getEntity().getContent();
                    // read to end of stream...
                    final long count = 1024L;
                    while (is.skip(count) == count)
                        ;
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.i(t, "Response code:" + responseCode);
                // verify that the response was a 201 or 202.
                // If it wasn't, the submission has failed.
                if (responseCode != 201 && responseCode != 202) {
                    if (responseCode == 200) {
                        mResults.put(id, fail + "Network login failure? Again?");
                    } else {
                        mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode
                                + ") at " + urlString);
                    }
                    // BEGIN custom
                    //                            cv.put(InstanceColumns.STATUS,
                    //                                InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    //                            Collect.getInstance().getContentResolver()
                    //                                    .update(toUpdate, cv, null, null);

                    try {
                        instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                        Collect.getInstance().getDbService().getDb().update(instanceDoc);
                    } catch (Exception e1) {
                        if (Collect.Log.ERROR)
                            Log.e(Collect.LOGTAG,
                                    t + ": could not record upload failed because of network login error for "
                                            + id + ": " + e1.toString());
                    }
                    // END custom
                    continue next_submission;
                }
            } catch (Exception e) {
                e.printStackTrace();
                mResults.put(id, fail + "Generic Exception. " + e.getMessage());
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of generic exception for " + id
                                        + ": " + e1.toString());
                }
                // END custom
                continue next_submission;
            }
        }

        // if it got here, it must have worked
        mResults.put(id, Collect.getInstance().getString(R.string.success));
        // BEGIN custom
        //                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
        //                Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        // END custom

        // BEGIN custom
        instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.complete);
        instanceDoc.getOdk().setUploadDate(Generic.generateTimestamp());

        try {
            Collect.getInstance().getDbService().getDb().update(instanceDoc);
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unable to setUploadDate of successful upload: " + e.toString());
            e.printStackTrace();
        } finally {
            FileUtilsExtended.deleteFolder(uploadFolder);
        }
        // END custom
    }
    // BEGIN custom
    //            if (c != null) {
    //                c.close();
    //            }
    //
    //        } // end while
    // END custom

    return mResults;
}

From source file:com.irccloud.android.activity.PastebinViewerActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override//from  w  w  w . j av  a2  s . com
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(ColorScheme.getDialogWhenLargeTheme(ColorScheme.getUserTheme()));
    onMultiWindowModeChanged(isMultiWindow());
    if (savedInstanceState == null && (getWindowManager().getDefaultDisplay().getWidth() < TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 800, getResources().getDisplayMetrics())
            || isMultiWindow()))
        overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out);
    setContentView(R.layout.activity_pastebin);
    mSpinner = findViewById(R.id.spinner);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar.setNavigationIcon(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mWebView = findViewById(R.id.image);
    mWebView.setBackgroundColor(ColorScheme.getInstance().contentBackgroundColor);
    mWebView.getSettings().setBuiltInZoomControls(true);
    if (Integer.parseInt(Build.VERSION.SDK) >= 19)
        mWebView.getSettings()
                .setDisplayZoomControls(!getPackageManager().hasSystemFeature("android.hardware.touchscreen"));
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JSInterface(), "Android");
    mWebView.getSettings().setLoadWithOverviewMode(false);
    mWebView.getSettings().setUseWideViewPort(false);
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            fail();
        }

        @Override
        public void onLoadResource(WebView view, String url) {
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Crashlytics.log(
                    consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR ? Log.ERROR : Log.WARN,
                    "IRCCloud", "Javascript error - line: " + consoleMessage.lineNumber() + " message: "
                            + consoleMessage.message());
            return super.onConsoleMessage(consoleMessage);
        }
    });

    if (savedInstanceState != null && savedInstanceState.containsKey("url")) {
        url = savedInstanceState.getString("url");
        html = savedInstanceState.getString("html");
        mWebView.loadDataWithBaseURL(url, html, "text/html", "UTF-8", null);
    } else {
        if (getIntent() != null && getIntent().getDataString() != null) {
            url = getIntent().getDataString().replace(getResources().getString(R.string.PASTE_SCHEME), "https");
            if (!url.contains("?"))
                url += "?";
            try {
                url += "&mobile=android&version="
                        + getPackageManager().getPackageInfo(getPackageName(), 0).versionName + "&theme="
                        + ColorScheme.getUserTheme();
            } catch (PackageManager.NameNotFoundException e) {
            }
            new FetchPastebinTask().execute();
            Answers.getInstance().logContentView(new ContentViewEvent().putContentType("Pastebin"));
        } else {
            finish();
        }
    }
}

From source file:com.scvngr.levelup.core.util.LogManager.java

/**
 * Logs a message to the Android log./*from   ww w  .j a va 2 s .c o  m*/
 *
 * @param logLevel {@link Log#VERBOSE}, {@link Log#DEBUG}, {@link Log#INFO}, {@link Log#WARN},
 *        or {@link Log#ERROR}.
 * @param message the message to be logged. This message is expected to be a format string if
 *        messageFormatArgs is not null.
 * @param messageFormatArgs formatting arguments for the message, or null if the string is to be
 *        handled without formatting.
 * @param err an optional error to log with a stacktrace.
 */
private static void logMessage(final int logLevel, @NonNull final String message,
        @Nullable final Object[] messageFormatArgs, @Nullable final Throwable err) {
    final String preppedMessage = formatMessage(message, messageFormatArgs);

    final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    final String sourceClass = trace[STACKTRACE_SOURCE_FRAME_INDEX].getClassName();
    final String sourceMethod = trace[STACKTRACE_SOURCE_FRAME_INDEX].getMethodName();

    final String logcatLogLine = String.format(Locale.US, FORMAT, Thread.currentThread().getName(), sourceClass,
            sourceMethod, preppedMessage);

    switch (logLevel) {
    case Log.VERBOSE: {
        if (null == err) {
            Log.v(sLogTag, logcatLogLine);
        } else {
            Log.v(sLogTag, logcatLogLine, err);
        }
        break;
    }
    case Log.DEBUG: {
        if (null == err) {
            Log.d(sLogTag, logcatLogLine);
        } else {
            Log.d(sLogTag, logcatLogLine, err);
        }
        break;
    }
    case Log.INFO: {
        if (null == err) {
            Log.i(sLogTag, logcatLogLine);
        } else {
            Log.i(sLogTag, logcatLogLine, err);
        }
        break;
    }
    case Log.WARN: {
        if (null == err) {
            Log.w(sLogTag, logcatLogLine);
        } else {
            Log.w(sLogTag, logcatLogLine, err);
        }
        break;
    }
    case Log.ERROR: {
        if (null == err) {
            Log.e(sLogTag, logcatLogLine);
        } else {
            Log.e(sLogTag, logcatLogLine, err);
        }
        break;
    }
    case Log.ASSERT: {
        if (null == err) {
            Log.wtf(sLogTag, logcatLogLine);
        } else {
            Log.wtf(sLogTag, logcatLogLine, err);
        }
        break;
    }
    default: {
        throw new AssertionError();
    }
    }
}