Example usage for android.provider OpenableColumns SIZE

List of usage examples for android.provider OpenableColumns SIZE

Introduction

In this page you can find the example usage for android.provider OpenableColumns SIZE.

Prototype

String SIZE

To view the source code for android.provider OpenableColumns SIZE.

Click Source Link

Document

The number of bytes in the file identified by the openable URI.

Usage

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }/*  w  w w.ja  v  a 2s .  c o m*/

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

From source file:com.remobile.file.ContentFilesystem.java

private Long resourceSizeForCursor(Cursor cursor) {
    int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
    if (columnIndex != -1) {
        String sizeStr = cursor.getString(columnIndex);
        if (sizeStr != null) {
            return Long.parseLong(sizeStr);
        }/*from w  w w .ja  va2s  .  c  o  m*/
    }
    return null;
}

From source file:net.sf.fdshare.BaseProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final String filePath = uri.getPath();
    if (TextUtils.isEmpty(filePath))
        throw new IllegalArgumentException("Empty path!");

    if (projection == null) {
        projection = new String[] { MediaStore.MediaColumns.MIME_TYPE, OpenableColumns.DISPLAY_NAME,
                OpenableColumns.SIZE };
    }/*  www  .j av  a2  s . c  o m*/

    final MatrixCursor result = new MatrixCursor(projection);

    final TimestampedMime info = guessTypeInternal(filePath);

    final Object[] row = new Object[projection.length];
    for (int i = 0; i < projection.length; i++) {
        String projColumn = projection[i];

        if (TextUtils.isEmpty(projColumn))
            continue;

        switch (projColumn.toLowerCase()) {
        case OpenableColumns.DISPLAY_NAME:

            row[i] = uri.getLastPathSegment();

            break;
        case OpenableColumns.SIZE:

            row[i] = info.size >= 0 ? info.size : null;

            break;
        case MediaStore.MediaColumns.MIME_TYPE:

            final String forcedType = uri.getQueryParameter("type");

            if (!TextUtils.isEmpty(forcedType))
                row[i] = "null".equals(forcedType) ? null : forcedType;
            else
                row[i] = info.mime[0];

            break;
        case MediaStore.MediaColumns.DATA:
            Log.w("BaseProvider", "Relying on MediaColumns.DATA is unreliable and must be avoided!");
            row[i] = uri.getPath();
            break;
        }
    }

    result.addRow(row);
    return result;
}

From source file:org.sufficientlysecure.keychain.util.FileHelper.java

public static long getFileSize(Context context, Uri uri, long def) {
    if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
        long size = new File(uri.getPath()).length();
        if (size == 0) {
            size = def;/*from  ww  w. j a v  a 2s .com*/
        }
        return size;
    }

    long size = def;
    try {
        Cursor cursor = context.getContentResolver().query(uri, new String[] { OpenableColumns.SIZE }, null,
                null, null);

        if (cursor != null) {
            if (cursor.moveToNext()) {
                size = cursor.getLong(0);
            }
            cursor.close();
        }
    } catch (Exception ignored) {
        // This happens in rare cases (eg: document deleted since selection) and should not cause a failure
    }
    return size;
}

From source file:com.amytech.android.library.views.imagechooser.api.BChooser.java

/**
 * Utility method which quickly looks up the file size. Use this, if you want to set a limit to
 * the media chosen, and which your application can safely handle.
 * <p/>/*w  ww .j a v  a2  s  .c o m*/
 * For example, you might not want a video of 1 GB to be imported into your app.
 *
 * @param uri
 * @param context
 * @return
 */
public long queryProbableFileSize(Uri uri, Context context) {
    try {
        if (uri.toString().startsWith("file")) {
            File file = new File(uri.getPath());
            return file.length();
        } else if (uri.toString().startsWith("content")) {
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            long length = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
            cursor.close();
            return length;
        }
        return 0;
    } catch (Exception e) {
        return 0;
    }
}

From source file:com.Jsu.framework.image.imageChooser.BChooser.java

/**
 * Utility method which quickly looks up the file size. Use this, if you want to set a limit to
 * the media chosen, and which your application can safely handle.
 * <p/>/*from  w w  w. ja v  a  2 s.c  om*/
 * For example, you might not want a video of 1 GB to be imported into your app.
 *
 * @param uri
 * @param context
 * @return
 */
public long queryProbableFileSize(Uri uri, Context context) {

    if (uri.toString().startsWith("file")) {
        File file = new File(uri.getPath());
        return file.length();
    } else if (uri.toString().startsWith("content")) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            StreamHelper.verifyCursor(uri, cursor);
            if (cursor.moveToFirst()) {
                return cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
            }
            return 0;
        } catch (ChooserException e) {
            return 0;
        } finally {
            StreamHelper.closeSilent(cursor);
        }
    }

    return 0;
}

From source file:com.kbeanie.imagechooser.api.BChooser.java

/**
 * Utility method which quickly looks up the file size. Use this, if you want to set a limit to
 * the media chosen, and which your application can safely handle.
 * <p/>//from   www .j ava2  s  .c  o  m
 * For example, you might not want a video of 1 GB to be imported into your app.
 *
 * @param uri
 * @param context
 * @return
 */
public long queryProbableFileSize(Uri uri, Context context) {

    if (uri.toString().startsWith("file")) {
        File file = new File(uri.getPath());
        return file.length();
    } else if (uri.toString().startsWith("content")) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            verifyCursor(uri, cursor);
            if (cursor.moveToFirst()) {
                return cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
            }
            return 0;
        } catch (ChooserException e) {
            return 0;
        } finally {
            closeSilent(cursor);
        }
    }

    return 0;
}

From source file:de.j4velin.encrypter.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == REQUEST_INPUT && resultCode == RESULT_OK && data != null) {
        Uri uri = data.getData();//from w w w.ja  v a 2 s  .  c om
        String inputName = null;
        int inputSize = -1;
        String inputType = getContentResolver().getType(uri);
        try (Cursor cursor = getContentResolver().query(uri, null, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                inputName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                if (!cursor.isNull(sizeIndex)) {
                    inputSize = cursor.getInt(sizeIndex);
                }
            }
        }
        File input = new File(-1, inputName, inputType, uri, inputSize, false);
        try {
            CryptoUtil.encrypt(MainActivity.this, input);
        } catch (GeneralSecurityException e) {
            Snackbar.make(coordinatorLayout, getString(R.string.error_security, e.getMessage()),
                    Snackbar.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Snackbar.make(coordinatorLayout, R.string.error_file_not_found, Snackbar.LENGTH_LONG).show();
        } catch (IOException e) {
            Snackbar.make(coordinatorLayout, getString(R.string.error_io, e.getMessage()), Snackbar.LENGTH_LONG)
                    .show();
        }
    } else

    {
        super.onActivityResult(requestCode, resultCode, data);
    }

}

From source file:org.rm3l.ddwrt.mgmt.AbstractRouterMgmtDialogFragment.java

/**
 * Receive the result from a previous call to
 * {@link #startActivityForResult(android.content.Intent, int)}.  This follows the
 * related Activity API as described there in
 * {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}.
 *
 * @param requestCode The integer request code originally supplied to
 *                    startActivityForResult(), allowing you to identify who this
 *                    result came from.//from   w w  w  .  ja va 2 s  .c o  m
 * @param resultCode  The integer result code returned by the child activity
 *                    through its setResult().
 * @param resultData  An Intent, which can return result data to the caller
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    // The ACTION_OPEN_DOCUMENT intent was sent with the request code
    // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
    // response to some other intent, and the code below shouldn't run at all.

    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        // The document selected by the user won't be returned in the intent.
        // Instead, a URI to that document will be contained in the return intent
        // provided to this method as a parameter.
        // Pull that URI using resultData.getData().
        Uri uri;
        if (resultData != null) {
            uri = resultData.getData();
            Log.i(LOG_TAG, "Uri: " + uri.toString());
            final AlertDialog d = (AlertDialog) getDialog();
            if (d != null) {

                final ContentResolver contentResolver = this.getSherlockActivity().getContentResolver();

                final Cursor uriCursor = contentResolver.query(uri, null, null, null, null);

                /*
                 * Get the column indexes of the data in the Cursor,
                 * move to the first row in the Cursor, get the data,
                 * and display it.
                 */
                final int nameIndex = uriCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                final int sizeIndex = uriCursor.getColumnIndex(OpenableColumns.SIZE);

                uriCursor.moveToFirst();

                //File size in bytes
                final long fileSize = uriCursor.getLong(sizeIndex);
                final String filename = uriCursor.getString(nameIndex);

                //Check file size
                if (fileSize > MAX_PRIVKEY_SIZE_BYTES) {
                    displayMessage(String.format("File '%s' too big (%s). Limit is %s", filename,
                            toHumanReadableByteCount(fileSize),
                            toHumanReadableByteCount(MAX_PRIVKEY_SIZE_BYTES)), ALERT);
                    return;
                }

                //Replace button hint message with file name
                final Button fileSelectorButton = (Button) d.findViewById(R.id.router_add_privkey);
                final CharSequence fileSelectorOriginalHint = fileSelectorButton.getHint();
                if (!Strings.isNullOrEmpty(filename)) {
                    fileSelectorButton.setHint(filename);
                }

                //Set file actual content in hidden field
                final TextView privKeyPath = (TextView) d.findViewById(R.id.router_add_privkey_path);
                try {
                    privKeyPath.setText(IOUtils.toString(contentResolver.openInputStream(uri)));
                } catch (IOException e) {
                    displayMessage("Error: " + e.getMessage(), ALERT);
                    e.printStackTrace();
                    fileSelectorButton.setHint(fileSelectorOriginalHint);
                }
            }
        }
    }
}

From source file:com.github.chenxiaolong.dualbootpatcher.FileUtils.java

public static UriMetadata[] queryUriMetadata(ContentResolver cr, Uri... uris) {
    ThreadUtils.enforceExecutionOnNonMainThread();

    UriMetadata[] metadatas = new UriMetadata[uris.length];
    for (int i = 0; i < metadatas.length; i++) {
        UriMetadata metadata = new UriMetadata();
        metadatas[i] = metadata;//from   w  ww.jav  a2 s  .  c o  m
        metadata.uri = uris[i];
        metadata.mimeType = cr.getType(metadata.uri);

        if (SAF_SCHEME.equals(metadata.uri.getScheme())) {
            Cursor cursor = cr.query(metadata.uri, null, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);

                    metadata.displayName = cursor.getString(nameIndex);
                    if (cursor.isNull(sizeIndex)) {
                        metadata.size = -1;
                    } else {
                        metadata.size = cursor.getLong(sizeIndex);
                    }
                }
            } finally {
                IOUtils.closeQuietly(cursor);
            }
        } else if (FILE_SCHEME.equals(metadata.uri.getScheme())) {
            metadata.displayName = metadata.uri.getLastPathSegment();
            metadata.size = new File(metadata.uri.getPath()).length();
        } else {
            throw new IllegalArgumentException("Cannot handle URI: " + metadata.uri);
        }
    }

    return metadatas;
}