Example usage for android.webkit MimeTypeMap getMimeTypeFromExtension

List of usage examples for android.webkit MimeTypeMap getMimeTypeFromExtension

Introduction

In this page you can find the example usage for android.webkit MimeTypeMap getMimeTypeFromExtension.

Prototype

@Nullable
public String getMimeTypeFromExtension(String extension) 

Source Link

Document

Return the MIME type for the given extension.

Usage

From source file:com.todoroo.astrid.activity.TaskEditFragment.java

private void attachFile(String file) {
    File src = new File(file);
    if (!src.exists()) {
        Toast.makeText(getActivity(), R.string.file_err_copy, Toast.LENGTH_LONG).show();
        return;/*  w  ww  . j a  v a 2s .  c o m*/
    }

    File dst = new File(FileUtilities.getAttachmentsDirectory(getActivity()) + File.separator + src.getName());
    try {
        AndroidUtilities.copyFile(src, dst);
    } catch (Exception e) {
        Toast.makeText(getActivity(), R.string.file_err_copy, Toast.LENGTH_LONG).show();
        return;
    }

    String path = dst.getAbsolutePath();
    String name = dst.getName();
    String extension = AndroidUtilities.getFileExtension(name);

    String type = TaskAttachment.FILE_TYPE_OTHER;
    if (!TextUtils.isEmpty(extension)) {
        MimeTypeMap map = MimeTypeMap.getSingleton();
        String guessedType = map.getMimeTypeFromExtension(extension);
        if (!TextUtils.isEmpty(guessedType))
            type = guessedType;
    }

    createNewFileAttachment(path, name, type);
}

From source file:org.odk.collect.android.http.HttpClientConnection.java

@Override
public @NonNull HttpPostResult uploadSubmissionFile(@NonNull List<File> fileList, @NonNull File submissionFile,
        @NonNull URI uri, @Nullable HttpCredentialsInterface credentials, @NonNull long contentLength)
        throws IOException {
    addCredentialsForHost(uri, credentials);
    clearCookieStore();/*from   w w w.  j  a va  2 s  .  c om*/

    HttpClient httpclient = createHttpClient(UPLOAD_CONNECTION_TIMEOUT);

    // if https then enable preemptive basic auth...
    if (uri.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(uri.getHost());
    }

    HttpPostResult postResult = null;

    boolean first = true;
    int fileIndex = 0;
    int lastFileIndex;
    while (fileIndex < fileList.size() || first) {
        lastFileIndex = fileIndex;
        first = false;

        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        long byteCount = 0L;

        // mime post
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        // add the submission file first...
        FileBody fb = new FileBody(submissionFile, ContentType.TEXT_XML);
        builder.addPart("xml_submission_file", fb);
        Timber.i("added xml_submission_file: %s", submissionFile.getName());
        byteCount += submissionFile.length();

        for (; fileIndex < fileList.size(); fileIndex++) {
            File file = fileList.get(fileIndex);

            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            ContentType contentType = ContentTypeMapping.of(file.getName());
            if (contentType == null) {
                String mime = mimeTypeMap.getMimeTypeFromExtension(FileUtils.getFileExtension(file.getName()));
                if (mime != null) {
                    contentType = ContentType.create(mime);
                } else {
                    Timber.w("No specific MIME type found for file: %s", file.getName());
                    contentType = ContentType.APPLICATION_OCTET_STREAM;
                }
            }
            fb = new FileBody(file, contentType);
            builder.addPart(file.getName(), fb);
            byteCount += file.length();
            Timber.i("added file of type '%s' %s", contentType, file.getName());

            // we've added at least one attachment to the request...
            if (fileIndex + 1 < fileList.size()) {
                if ((fileIndex - lastFileIndex + 1 > 100)
                        || (byteCount + fileList.get(fileIndex + 1).length() > contentLength)) {
                    // the next file would exceed the 10MB threshold...
                    Timber.i("Extremely long post is being split into multiple posts");
                    try {
                        StringBody sb = new StringBody("yes",
                                ContentType.TEXT_PLAIN.withCharset(Charset.forName("UTF-8")));
                        builder.addPart("*isIncomplete*", sb);
                    } catch (Exception e) {
                        Timber.e(e);
                    }
                    ++fileIndex; // advance over the last attachment added...
                    break;
                }
            }
        }

        HttpPost httppost = createOpenRosaHttpPost(uri);
        httppost.setEntity(builder.build());

        // prepare response and return uploaded
        HttpResponse response;

        try {
            Timber.i("Issuing POST request to: %s", uri.toString());
            response = httpclient.execute(httppost, httpContext);
            int responseCode = response.getStatusLine().getStatusCode();
            HttpEntity httpEntity = response.getEntity();
            Timber.i("Response code:%d", responseCode);

            postResult = new HttpPostResult(EntityUtils.toString(httpEntity), responseCode,
                    response.getStatusLine().getReasonPhrase());

            discardEntityBytes(response);

            if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
                clearCookieStore();
            }

            if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
                return postResult;
            }

        } catch (IOException e) {
            if (e instanceof UnknownHostException || e instanceof HttpHostConnectException
                    || e instanceof SocketException || e instanceof NoHttpResponseException
                    || e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException) {
                Timber.i(e);
            } else {
                Timber.e(e);
            }
            String msg = e.getMessage();
            if (msg == null) {
                msg = e.toString();
            }

            throw new IOException(msg);
        }
    }

    return postResult;
}

From source file:com.jp.miaulavirtual.DisplayMessageActivity.java

public int downloadFile(String request) {
    URL url2;/*  w  w w.j a  v a  2  s.  com*/
    URLConnection conn;
    int lastSlash;
    Long fileSize = null;
    BufferedInputStream inStream;
    BufferedOutputStream outStream;
    FileOutputStream fileStream;
    String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty
    final int BUFFER_SIZE = 23 * 1024;
    int id = 1;

    File file = null;

    Log.d("Document", "2 respueesta");
    try {
        // Just resources
        lastSlash = url.toString().lastIndexOf('/');

        // Directory creation
        String root = Environment.getExternalStorageDirectory().toString();
        Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        // check if is there external storage
        if (!isSDPresent) {
            task_status = false;
            id = 9;
        } else {
            String folder;
            if (comunidades) {
                folder = onData.get(2)[1];
            } else {
                folder = onData.get(1)[1];
            }
            folder = folder.replaceAll(
                    "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", "");
            folder = folder.toString().trim();
            Log.d("Folder", folder);
            File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder);
            myDir.mkdirs();

            // Document creation
            String name = url.toString().substring(lastSlash + 1);
            file = new File(myDir, name);
            Log.d("Document", name);
            fileSize = (long) file.length();

            // Check if we have already downloaded the whole file
            if (file.exists()) {
                dialog.setProgress(100); // full progress if file already donwloaded
            } else {
                // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them)
                url2 = new URL(request);
                conn = url2.openConnection();
                conn.setUseCaches(false);
                conn.setRequestProperty("Cookie", cookies);
                conn.setConnectTimeout(10 * 1000);
                conn.setReadTimeout(20 * 1000);
                fileSize = (long) conn.getContentLength();

                // Check if we have necesary space
                if (fileSize >= myDir.getUsableSpace()) {
                    task_status = false;
                    id = 2;
                } else {

                    // Start downloading
                    inStream = new BufferedInputStream(conn.getInputStream());
                    fileStream = new FileOutputStream(file);
                    outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);
                    byte[] data = new byte[BUFFER_SIZE];
                    int bytesRead = 0;
                    int setMax = (conn.getContentLength() / 1024);
                    dialog.setMax(setMax);

                    while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
                        outStream.write(data, 0, bytesRead);
                        // update progress bar
                        dialog.incrementProgressBy((int) (bytesRead / 1024));
                    }

                    // Close stream
                    outStream.close();
                    fileStream.close();
                    inStream.close();

                    // Delete file if Cancel button
                    if (!task_status) {
                        file.delete();
                        if (myDir.listFiles().length <= 0)
                            myDir.delete();
                        id = 0;
                    }
                }
            }
            Log.d("Status", String.valueOf(task_status));
            // Open file
            if (task_status) {
                Log.d("Type", "Hola2");
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);

                MimeTypeMap mime = MimeTypeMap.getSingleton();
                // Get extension file
                String file_s = file.toString();
                String extension = "";

                int i = file_s.lastIndexOf('.');
                int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\'));

                if (i > p) {
                    extension = file_s.substring(i + 1);
                }

                // Get extension reference
                String doc_type = mime.getMimeTypeFromExtension(extension);

                Log.d("Type", extension);

                intent.setDataAndType(Uri.fromFile(file), doc_type);
                startActivity(intent);
            }
        }
    } catch (MalformedURLException e) // Invalid URL
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 3;
    } catch (FileNotFoundException e) // FIle not found
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 4;
    } catch (SocketTimeoutException e) // time out
    {
        Log.d("Timeout", "Timeout");
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 7;
    } catch (Exception e) // General error
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 8;
    }
    Log.d("Type", String.valueOf(id));
    Log.d("StartOk3", "Como he llegado hasta aqu?");
    // notify completion
    Log.d("ID", String.valueOf(id));
    return id;

}

From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;/*www.  j  a va  2  s  .c om*/
    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();
    }

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

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

    Cursor c = MIntel.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));
            if (urlString == null) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            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());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                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());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                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. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    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);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    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.
            //
            // get instance file
            File instanceFile = new File(instance);

            if (!instanceFile.exists()) {
                mResults.put(id, fail + "instance XML file does not exist!");
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                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 if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

            postResponse = "";
            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();
                    // }

                    HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (IOException 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 {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

        }
        if (c != null) {
            c.close();
        }

    } // end while

    return mResults;
}

From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(final Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;// w  w w . j  a  v a 2s .  c o m
    String selection = BaseColumns._ID + "=?";
    final String[] selectionArgs = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != values.length - 1) {
            selection += " or " + BaseColumns._ID + "=?";
        }
        selectionArgs[i] = values[i].toString();
    }

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

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

    final Cursor c = MIntel.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());
            final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
            final String id = c.getString(c.getColumnIndex(BaseColumns._ID));
            final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);

            String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
            if (urlString == null) {
                final SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            final ContentValues cv = new ContentValues();
            URI u = null;
            try {
                final URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
                u = url.toURI();
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                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
                final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

                // prepare response
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpHead, localContext);
                    final 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) {
                        final Header[] locations = response.getHeaders("Location");
                        if (locations != null && locations.length == 1) {
                            try {
                                final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                                final 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());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (final Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                continue;
                            }
                        }
                    } else {
                        // may be a server that does not handle
                        try {
                            // have to read the stream in order to reuse the
                            // connection
                            final InputStream is = response.getEntity().getContent();
                            // read to end of stream...
                            final long count = 1024L;
                            while (is.skip(count) == count) {
                                ;
                            }
                            is.close();
                        } catch (final IOException e) {
                            e.printStackTrace();
                        } catch (final 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. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (final ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + "Generic Exception");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    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.
            //
            // get instance file
            final File instanceFile = new File(instance);

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

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

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

                final 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 if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

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

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

                final MimeTypeMap m = MimeTypeMap.getSingleton();

                long byteCount = 0L;

                // mime post
                final 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++) {
                    final File f = files.get(j);
                    final String fileName = f.getName();
                    final 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 {
                                final StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                                entity.addPart("*isIncomplete*", sb);
                            } catch (final 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);
                    final 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();
                    // }

                    final HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (final IOException 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 {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

        }
        if (c != null) {
            c.close();
        }

    } // end while

    return mResults;
}

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

@Override
// BEGIN custom//from   w  w w.  j a  v a2 s.  c o  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:net.bluehack.ui.MediaActivity.java

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;//from  w  ww.  j  ava2s .co  m
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            MimeTypeMap myMime = MimeTypeMap.getSingleton();
                            int idx = fileName.lastIndexOf('.');
                            if (idx != -1) {
                                String ext = fileName.substring(idx + 1);
                                realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
                                if (realMimeType == null) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                BuildConfig.APPLICATION_ID + ".provider", f),
                                        realMimeType != null ? realMimeType : "text/plain");
                            } else {
                                intent.setDataAndType(Uri.fromFile(f),
                                        realMimeType != null ? realMimeType : "text/plain");
                            }
                            if (realMimeType != null) {
                                try {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    R.string.NoHandleAppInstalled, message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

From source file:kr.wdream.ui.MediaActivity.java

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;/*  w ww .j  a v a  2  s . c  o  m*/
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            MimeTypeMap myMime = MimeTypeMap.getSingleton();
                            int idx = fileName.lastIndexOf('.');
                            if (idx != -1) {
                                String ext = fileName.substring(idx + 1);
                                realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
                                if (realMimeType == null) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                BuildConfig.APPLICATION_ID + ".provider", f),
                                        realMimeType != null ? realMimeType : "text/plain");
                            } else {
                                intent.setDataAndType(Uri.fromFile(f),
                                        realMimeType != null ? realMimeType : "text/plain");
                            }
                            if (realMimeType != null) {
                                try {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName",
                                    kr.wdream.storyshop.R.string.AppName));
                            builder.setPositiveButton(
                                    LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    kr.wdream.storyshop.R.string.NoHandleAppInstalled,
                                    message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

From source file:com.android.mms.ui.MessageUtils.java

public static String getContentType(Uri uri) {
    String path = uri.getPath();//from   w ww .  j a v a 2 s.co m

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = MimeTypeMap.getFileExtensionFromUrl(path).toLowerCase();
    if (TextUtils.isEmpty(extension)) {
        int dotPos = path.lastIndexOf('.');
        if (0 <= dotPos) {
            extension = path.substring(dotPos + 1);
            extension = extension.toLowerCase();
        }
    }

    String type = mimeTypeMap.getMimeTypeFromExtension(extension);
    return type;
}

From source file:org.telegram.ui.ChatActivity.java

@Override
public void didSelectFile(DocumentSelectActivity activity, String path, String name, String ext, long size) {
    activity.finishFragment();/*  w ww  . j  a va2  s.c  om*/
    TLRPC.TL_document document = new TLRPC.TL_document();
    document.thumb = new TLRPC.TL_photoSizeEmpty();
    document.thumb.type = "s";
    document.id = 0;
    document.user_id = UserConfig.clientUserId;
    document.date = ConnectionsManager.Instance.getCurrentTime();
    document.file_name = name;
    document.size = (int) size;
    document.dc_id = 0;
    document.path = path;
    if (ext.length() != 0) {
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
        if (mimeType != null) {
            document.mime_type = mimeType;
        } else {
            document.mime_type = "application/octet-stream";
        }
    } else {
        document.mime_type = "application/octet-stream";
    }
    MessagesController.Instance.sendMessage(document, dialog_id);
}