Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody FileBody.

Prototype

public FileBody(final File file, final String mimeType) 

Source Link

Usage

From source file:ca.mcgill.hs.serv.LogFileUploaderService.java

/**
 * Uploads the specified file to the server.
 * /*ww  w .  j  a  va2  s  .  co  m*/
 * @param fileName
 *            The file to upload
 * @return A code indicating the result of the upload.
 */
private int uploadFile(final String fileName) {
    Log.d(TAG, "Uploading " + fileName);
    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    httppost = new HttpPost(UPLOAD_URL);
    final File file = new File(HSAndroid.getStorageDirectory(), fileName);
    if (!file.exists()) {
        // File may be deleted while in the queue for uploading
        Log.d(TAG, "Unable to upload " + fileName + ". File does not exist.");
        return UPLOAD_FAILED_FILE_NOT_FOUND_ERROR_CODE;
    }
    Log.d(TAG, "MAC ADDRESS: " + wifiInfo.getMacAddress());
    httppost.addHeader("MAC", wifiInfo.getMacAddress());

    final MultipartEntity mpEntity = new MultipartEntity();
    final ContentBody cbFile = new FileBody(file, "binary/octet-stream");
    mpEntity.addPart("uploadedfile", cbFile);

    httppost.setEntity(mpEntity);
    try {
        final HttpResponse response = httpclient.execute(httppost);
        final HttpEntity resEntity = response.getEntity();

        String responseMsg = "";
        if (resEntity != null) {
            responseMsg = EntityUtils.toString(resEntity);
            resEntity.consumeContent();
        }
        Log.i(TAG, "Server Response: " + responseMsg);
        if (responseMsg.contains("FAILURE")) {
            CURRENT_ERROR_CODE = UPLOAD_FAILED_ERROR_CODE;
            return UPLOAD_FAILED_ERROR_CODE;
        }
        // Move files to uploaded folder if successful
        else {
            Log.i(TAG, "Moving file to uploaded directory.");
            final File dest = new File(HSAndroid.getStorageDirectory(),
                    HSAndroid.getAppString(R.string.uploaded_file_path));
            if (!dest.isDirectory()) {
                if (!dest.mkdirs()) {
                    throw new IOException("ERROR: Unable to create directory " + dest.getName());
                }
            }

            if (!file.renameTo(new File(dest, file.getName()))) {
                throw new IOException("ERROR: Unable to transfer file " + file.getName());
            }
        }

    } catch (final MalformedURLException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = MALFORMEDURLEXCEPTION_ERROR_CODE;
        return MALFORMEDURLEXCEPTION_ERROR_CODE;
    } catch (final UnknownHostException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = UNKNOWNHOSTEXCEPTION_ERROR_CODE;
        return UNKNOWNHOSTEXCEPTION_ERROR_CODE;
    } catch (final IOException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = IOEXCEPTION_ERROR_CODE;
        return IOEXCEPTION_ERROR_CODE;
    } catch (final IllegalStateException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = ILLEGALSTATEEXCEPTION_ERROR_CODE;
        return ILLEGALSTATEEXCEPTION_ERROR_CODE;
    }
    return NO_ERROR_CODE;
}

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 av a  2s  .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;//from  w w w  . j a  v  a 2 s .c om
    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:it.restrung.rest.client.DefaultRestClientImpl.java

/**
 * Private helper to setup a multipart request body
 *//*from  w  w  w . ja v a2 s .  c  om*/
private static void setupMultipartBodyWithFile(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,
        APIPostParams apiPostParams, String body, File file) throws UnsupportedEncodingException {
    //MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    CountingMultipartEntity mpEntity = new CountingMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"), file != null ? body.length() + file.length() : body.length(),
            apiPostParams);
    mpEntity.addPart("body", new StringBody(body, Charset.forName("UTF-8")));
    if (file != null) {
        FileBody uploadFilePart = new FileBody(file, "application/octet-stream");
        mpEntity.addPart("file", uploadFilePart);
    }
    httpEntityEnclosingRequestBase.setHeader(mpEntity.getContentType());
    httpEntityEnclosingRequestBase.setEntity(mpEntity);
}

From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java

@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Other And"
        + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPISupportToFile")
public void testAddDocumentToAnAPIOtherFile() throws Exception {

    String fileNameAPIM629 = "APIM629.txt";
    String docName = "APIM629PublisherTestHowTo-File-summary";
    String docType = "Other";
    String sourceType = "file";
    String newType = "Type APIM629";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM629 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM629;
    String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag";

    //Send Http Post request to add a new file
    HttpPost httppost = new HttpPost(addDocUrl);
    File file = new File(filePathAPIM629);
    FileBody fileBody = new FileBody(file, "text/plain");

    //Create multipart entity to upload file as multipart file
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("docLocation", fileBody);
    multipartEntity.addPart("mode", new StringBody(""));
    multipartEntity.addPart("docName", new StringBody(docName));
    multipartEntity.addPart("docUrl", new StringBody(docUrl));
    multipartEntity.addPart("sourceType", new StringBody(sourceType));
    multipartEntity.addPart("summary", new StringBody(summary));
    multipartEntity.addPart("docType", new StringBody(docType));
    multipartEntity.addPart("version", new StringBody(apiVersion));
    multipartEntity.addPart("apiName", new StringBody(apiName));
    multipartEntity.addPart("action", new StringBody("addDocumentation"));
    multipartEntity.addPart("provider", new StringBody(apiProvider));
    multipartEntity.addPart("mimeType", new StringBody(mimeType));
    multipartEntity.addPart("newType", new StringBody(newType));
    multipartEntity.addPart("optionsRadios", new StringBody(docType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));

    httppost.setEntity(multipartEntity);

    //Upload created file and validate
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity));
    assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API ");
}

From source file:org.craftercms.social.UCGRestServicesTest.java

public static void main(String[] args) throws Exception {

    ProfileClient profileRestClient = new ProfileRestClientImpl();

    String token = profileRestClient.getAppToken("craftersocial", "craftersocial");
    Tenant tenant = profileRestClient.getTenantByName(token, "testing");
    String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId());
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", "testing"));

    qparams.add(new BasicNameValuePair("textContent", "Content"));

    URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    File file = new File(
            "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt");
    MultipartEntity me = new MultipartEntity();

    //The usual form parameters can be added this way
    //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

    /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
    This part will be considered as file part and the rest of them as usual form-data parts*/
    FileBody fileBody = new FileBody(file, "application/octect-stream");
    //me.addPart("ticket", new StringBody(token)) ;
    //me.addPart("target", new StringBody("my-test")) ;
    me.addPart("attachments", fileBody);

    httppost.setEntity(me);//w  w w.j a v a 2 s .  c  o m
    httpclient.execute(httppost);

}

From source file:com.stepsdk.android.api.APIClient.java

private MultipartEntity addFile(MultipartEntity mpEntity, String key, String fromPath) throws IOException {

    String filepath;//from   w  w w . j a  v  a  2 s .c o  m
    try {
        filepath = URLDecoder.decode(fromPath, "UTF-8"); // handle special character
    } catch (Exception e) {
        filepath = fromPath;
    }
    String fromFilename = filepath.substring(filepath.lastIndexOf("/") + 1);

    String filename = "";
    long filesize = 0;
    ContentBody cbFile = null;

    log(TAG, "from upload path: " + fromPath);

    // upload from content uri
    if (fromPath.indexOf("content://") > -1) {
        Uri uri = Uri.parse(fromPath);
        String mime = mContext.getContentResolver().getType(uri);
        String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
        String mediatype = mime.substring(0, mime.indexOf('/'));

        InputStream is = mContext.getContentResolver().openInputStream(uri);
        filesize = is.available();
        filename = mediatype + fromFilename + "." + extension;
        cbFile = new InputStreamBody(is, mime, filename);

    } else { //upload from file uri
        File file = new File(filepath);

        filesize = file.length();
        filename = fromFilename;
        cbFile = new FileBody(file, FileUtil.getMimeTypeFromFilePath(fromPath));
    }

    //final String finalfilename = filename;
    final long finalfilesize = filesize;
    //final int task_id = params[1].getIntExtra("cancel_task_id", 0);
    //final Intent cancelintent = params[1];
    //final Intent doneintent = params[2];

    mpEntity.addPart(key, cbFile);

    return mpEntity;
}

From source file:fm.smart.r1.ItemActivity.java

public AddImageResult addImage(File file, String media_entity, String author, String author_url,
        String attribution_license_id, String sentence_id, String item_id, String list_id) {
    String http_response = "";
    int status_code = 0;
    HttpClient client = null;/*from w  w w  .j  av  a 2  s.  c o  m*/
    try {
        client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://api.smart.fm/lists/" + list_id + "/items/" + item_id
                + "/sentences/" + sentence_id + "/images");
        // HttpPost post = new HttpPost("http://api.smart.fm/sentences/" +
        // sentence_id
        // + "/images");

        String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this);
        byte[] bytes = auth.getBytes();
        post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes)));

        // httppost.setHeader("Content-Type",
        // "application/x-www-form-urlencoded");

        post.setHeader("Host", "api.smart.fm");

        FileBody bin = new FileBody(file, "image/jpeg");
        StringBody media_entity_part = new StringBody(media_entity);
        StringBody author_part = new StringBody(author);
        StringBody author_url_part = new StringBody(author_url);
        StringBody attribution_license_id_part = new StringBody(attribution_license_id);
        StringBody sentence_id_part = new StringBody(sentence_id);
        StringBody api_key_part = new StringBody(Main.API_KEY);
        StringBody item_id_part = new StringBody(item_id);
        StringBody list_id_part = new StringBody(list_id);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("image[file]", bin);
        reqEntity.addPart("media_entity", media_entity_part);
        reqEntity.addPart("author", author_part);
        reqEntity.addPart("author_url", author_url_part);
        reqEntity.addPart("attribution_license_id", attribution_license_id_part);
        reqEntity.addPart("sentence_id", sentence_id_part);
        reqEntity.addPart("api_key", api_key_part);
        reqEntity.addPart("item_id", item_id_part);
        reqEntity.addPart("list_id", list_id_part);

        post.setEntity(reqEntity);

        Header[] array = post.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("DEBUG", array[i].toString());
        }

        Log.d("AddImage", "executing request " + post.getRequestLine());
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        status_code = response.getStatusLine().getStatusCode();

        Log.d("AddImage", "----------------------------------------");
        Log.d("AddImage", response.getStatusLine().toString());
        array = response.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("AddImage", array[i].toString());
        }
        if (resEntity != null) {
            Log.d("AddImage", "Response content length: " + resEntity.getContentLength());
            Log.d("AddImage", "Chunked?: " + resEntity.isChunked());
        }
        long length = response.getEntity().getContentLength();
        byte[] response_bytes = new byte[(int) length];
        response.getEntity().getContent().read(response_bytes);
        Log.d("AddImage", new String(response_bytes));
        http_response = new String(response_bytes);
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        // HttpEntity entity = response1.getEntity();
    } catch (IOException e) {
        /* Reset to Default image on any error. */
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return new AddImageResult(status_code, http_response);
}