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:fm.smart.r1.activity.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;/*  w ww.jav  a2  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 = Main.username(this) + ":" + Main.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);
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

/**
 * Push a file attachment to the server/* w  w  w.ja va2 s .  c om*/
 * @param remoteTaskId
 * @param fileMetadata
 */
public void pushAttachment(long remoteTaskId, Metadata fileMetadata) {
    if (!ActFmPreferenceService.isPremiumUser())
        return;

    if (!fileMetadata.containsNonNullValue(FileMetadata.FILE_PATH) || remoteTaskId <= 0)
        return;

    File f = new File(fileMetadata.getValue(FileMetadata.FILE_PATH));
    if (!f.exists())
        return;

    ArrayList<Object> params = new ArrayList<Object>();
    params.add("task_id");
    params.add(remoteTaskId);
    params.add("token");
    params.add(token);

    try {
        MultipartEntity entity = new MultipartEntity();
        FileBody body = new FileBody(f, fileMetadata.getValue(FileMetadata.FILE_TYPE));
        entity.addPart("file", body);

        JSONObject result = actFmInvoker.post("task_attachment_create", entity,
                params.toArray(new Object[params.size()]));

        fileMetadata.setValue(FileMetadata.REMOTE_ID, result.optLong("id"));
        fileMetadata.setValue(FileMetadata.URL, result.optString("url"));
        metadataService.save(fileMetadata);
    } catch (ActFmServiceException e) {
        handleException("push-attacgment-error", e);
    } catch (IOException e) {
        handleException("push-attacgment-error", e);
    }
}

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

@Override
// BEGIN custom/*from ww w  . j  av  a 2 s.com*/
//    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:ti.modules.titanium.network.TiHTTPClient.java

private int addTitaniumFileAsPostData(String name, Object value) {
    try {//from w  ww .  ja  va2s .  co  m
        // TiResourceFile cannot use the FileBody approach directly, because it requires
        // a java File object, which you can't get from packaged resources. So
        // TiResourceFile uses the approach we use for blobs, which is write out the
        // contents to a temp file, then use that for the FileBody.
        if (value instanceof TiBaseFile && !(value instanceof TiResourceFile)) {
            TiBaseFile baseFile = (TiBaseFile) value;
            FileBody body = new FileBody(baseFile.getNativeFile(),
                    TiMimeTypeHelper.getMimeType(baseFile.nativePath()));
            parts.put(name, body);
            return (int) baseFile.getNativeFile().length();

        } else if (value instanceof TiBlob || value instanceof TiResourceFile) {
            TiBlob blob;
            if (value instanceof TiBlob) {
                blob = (TiBlob) value;
            } else {
                blob = ((TiResourceFile) value).read();
            }
            String mimeType = blob.getMimeType();
            File tmpFile = File.createTempFile("tixhr",
                    "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt"));
            FileOutputStream fos = new FileOutputStream(tmpFile);
            fos.write(blob.getBytes());
            fos.close();

            tmpFiles.add(tmpFile);

            FileBody body = new FileBody(tmpFile, mimeType);
            parts.put(name, body);
            return blob.getLength();

        } else {
            if (value != null) {
                Log.e(TAG, name + " is a " + value.getClass().getSimpleName());

            } else {
                Log.e(TAG, name + " is null");
            }
        }

    } catch (IOException e) {
        Log.e(TAG, "Error adding post data (" + name + "): " + e.getMessage());
    }
    return 0;
}

From source file:gov.osti.services.Metadata.java

/**
 * Send this Metadata to the ARCHIVER external support process.
 *
 * Needs a CODE ID and one of either an ARCHIVE FILE or REPOSITORY LINK.
 *
 * If nothing supplied to archive, do nothing.
 *
 * @param codeId the CODE ID for this METADATA
 * @param repositoryLink (optional) the REPOSITORY LINK value, or null if none
 * @param archiveFile (optional) the File recently uploaded to ARCHIVE, or null if none
 * @param archiveContainer (optional) the Container recently uploaded to ARCHIVE, or null if none
 * @throws IOException on IO transmission errors
 *//* w  w w  .jav  a  2s  .  c o m*/
private static void sendToArchiver(Long codeId, String repositoryLink, File archiveFile, File archiveContainer)
        throws IOException {
    if ("".equals(ARCHIVER_URL))
        return;

    // Nothing sent?
    if (StringUtils.isBlank(repositoryLink) && null == archiveFile && null == archiveContainer)
        return;

    // set up a connection
    CloseableHttpClient hc = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
            .setSocketTimeout(300000).setConnectTimeout(300000).setConnectionRequestTimeout(300000).build())
            .build();

    try {
        HttpPost post = new HttpPost(ARCHIVER_URL);
        // attributes to send
        ObjectNode request = mapper.createObjectNode();
        request.put("code_id", codeId);
        request.put("repository_link", repositoryLink);

        // determine if there's a file to send or not
        if (null == archiveFile && null == archiveContainer) {
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "application/json");

            post.setEntity(new StringEntity(request.toString(), "UTF-8"));
        } else {
            MultipartEntityBuilder mpe = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("project", new StringBody(request.toString(), ContentType.APPLICATION_JSON));

            if (archiveFile != null)
                mpe.addPart("file", new FileBody(archiveFile, ContentType.DEFAULT_BINARY));

            if (archiveContainer != null)
                mpe.addPart("container", new FileBody(archiveContainer, ContentType.DEFAULT_BINARY));

            post.setEntity(mpe.build());
        }
        HttpResponse response = hc.execute(post);

        int statusCode = response.getStatusLine().getStatusCode();

        if (HttpStatus.SC_OK != statusCode && HttpStatus.SC_CREATED != statusCode) {
            throw new IOException("Archiver Error: " + EntityUtils.toString(response.getEntity()));
        }
    } catch (IOException e) {
        log.warn("Archiver request error: " + e.getMessage());
        throw e;
    } finally {
        try {
            if (null != hc)
                hc.close();
        } catch (IOException e) {
            log.warn("Close Error: " + e.getMessage());
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

private MultipartEntity getMultipartEntity(API api, String externalPublisher, String action)
        throws org.wso2.carbon.registry.api.RegistryException, IOException, UserStoreException,
        APIManagementException {//w w w . ja va 2s  .  c  o m

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {
        entity.addPart(APIConstants.API_ACTION, new StringBody(action));
        entity.addPart("name", new StringBody(api.getId().getApiName()));
        entity.addPart("version", new StringBody(api.getId().getVersion()));
        entity.addPart("provider", new StringBody(externalPublisher));
        entity.addPart("description", new StringBody(checkValue(api.getDescription())));
        entity.addPart("endpoint", new StringBody(checkValue(api.getUrl())));
        entity.addPart("sandbox", new StringBody(checkValue(api.getSandboxUrl())));
        entity.addPart("wsdl", new StringBody(checkValue(api.getWsdlUrl())));
        entity.addPart("wadl", new StringBody(checkValue(api.getWadlUrl())));
        entity.addPart("endpoint_config", new StringBody(checkValue(api.getEndpointConfig())));

        String registryIconUrl = getFullRegistryIconUrl(api.getThumbnailUrl());
        URL url = new URL(getIconUrlWithHttpRedirect(registryIconUrl));

        File fileToUpload = new File("tmp/icon");
        if (!fileToUpload.exists()) {
            if (!fileToUpload.createNewFile()) {
                String message = "Unable to create a new temp file";
                log.error(message);
                throw new APIManagementException(message);
            }
        }
        FileUtils.copyURLToFile(url, fileToUpload);
        FileBody fileBody = new FileBody(fileToUpload, "application/octet-stream");
        entity.addPart("apiThumb", fileBody);
        // fileToUpload.delete();

        StringBuilder tagsSet = new StringBuilder();
        Iterator it = api.getTags().iterator();
        int j = 0;
        while (it.hasNext()) {
            Object tagObject = it.next();
            tagsSet.append((String) tagObject);
            if (j != api.getTags().size() - 1) {
                tagsSet.append(',');
            }
            j++;
        }

        entity.addPart("tags", new StringBody(checkValue(tagsSet.toString())));
        StringBuilder tiersSet = new StringBuilder();
        Iterator tier = api.getAvailableTiers().iterator();
        int k = 0;
        while (tier.hasNext()) {
            Object tierObject = tier.next();
            Tier availTier = (Tier) tierObject;
            tiersSet.append(availTier.getName());
            if (k != api.getAvailableTiers().size() - 1) {
                tiersSet.append(',');
            }
            k++;
        }
        entity.addPart("tiersCollection", new StringBody(checkValue(tiersSet.toString())));
        entity.addPart("context", new StringBody(api.getContext()));
        entity.addPart("bizOwner", new StringBody(checkValue(api.getBusinessOwner())));
        entity.addPart("bizOwnerMail", new StringBody(checkValue(api.getBusinessOwnerEmail())));
        entity.addPart("techOwnerMail", new StringBody(checkValue(api.getTechnicalOwnerEmail())));
        entity.addPart("techOwner", new StringBody(checkValue(api.getTechnicalOwner())));
        entity.addPart("visibility", new StringBody(api.getVisibility()));
        entity.addPart("roles", new StringBody(checkValue(api.getVisibleRoles())));
        entity.addPart("endpointType", new StringBody(checkValue(String.valueOf(api.isEndpointSecured()))));
        entity.addPart("endpointAuthType",
                new StringBody(checkValue(String.valueOf(api.isEndpointAuthDigest()))));
        entity.addPart("epUsername", new StringBody(checkValue(api.getEndpointUTUsername())));
        entity.addPart("epPassword", new StringBody(checkValue(api.getEndpointUTPassword())));

        entity.addPart("apiOwner", new StringBody(api.getId().getProviderName()));
        entity.addPart("advertiseOnly", new StringBody("true"));

        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
        entity.addPart("redirectURL", new StringBody(getExternalStoreRedirectURL(tenantId)));
        if (api.getTransports() == null) {
            entity.addPart("http_checked", new StringBody(""));
            entity.addPart("https_checked", new StringBody(""));
        } else {
            String[] transports = api.getTransports().split(",");
            if (transports.length == 1) {
                if ("https".equals(transports[0])) {
                    entity.addPart("http_checked", new StringBody(""));
                    entity.addPart("https_checked", new StringBody(transports[0]));

                } else {
                    entity.addPart("https_checked", new StringBody(""));
                    entity.addPart("http_checked", new StringBody(transports[0]));
                }
            } else {
                entity.addPart("http_checked", new StringBody("http"));
                entity.addPart("https_checked", new StringBody("https"));
            }
        }
        entity.addPart("resourceCount", new StringBody(String.valueOf(api.getUriTemplates().size())));

        Iterator urlTemplate = api.getUriTemplates().iterator();
        int i = 0;
        while (urlTemplate.hasNext()) {
            Object templateObject = urlTemplate.next();
            URITemplate template = (URITemplate) templateObject;
            entity.addPart("uriTemplate-" + i, new StringBody(template.getUriTemplate()));
            entity.addPart("resourceMethod-" + i,
                    new StringBody(template.getMethodsAsString().replaceAll("\\s", ",")));
            entity.addPart("resourceMethodAuthType-" + i,
                    new StringBody(String.valueOf(template.getAuthTypeAsString().replaceAll("\\s", ","))));
            entity.addPart("resourceMethodThrottlingTier-" + i,
                    new StringBody(template.getThrottlingTiersAsString().replaceAll("\\s", ",")));
            i++;
        }
        return entity;
    } catch (UnsupportedEncodingException e) {
        throw new IOException("Error while adding the API to external APIStore :", e);
    }
}

From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java

private void testUploadKeystore(String keystoreFormat, String filePath, String keyAlias, String storePassword)
        throws Exception {
    ClientRepresentation client = getClient(testRealm.getRealm(), app3.getId()).toRepresentation();
    final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);

    // Load the keystore file
    URL fileUrl = (getClass().getClassLoader().getResource(filePath));
    if (fileUrl == null) {
        throw new IOException("File not found: " + filePath);
    }/*  www . j  a  va 2 s .co m*/
    File keystoreFile = new File(fileUrl.getFile());
    ContentType keystoreContentType = ContentType.create(Files.probeContentType(keystoreFile.toPath()));

    // Get admin access token, no matter it's master realm's admin
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doGrantAccessTokenRequest(AuthRealm.MASTER,
            AuthRealm.ADMIN, AuthRealm.ADMIN, null, "admin-cli", null);
    assertEquals(200, accessTokenResponse.getStatusCode());

    final String url = suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/realms/"
            + testRealm.getRealm() + "/clients/" + client.getId()
            + "/certificates/jwt.credential/upload-certificate";

    // Prepare the HTTP request
    FileBody fileBody = new FileBody(keystoreFile, keystoreContentType);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody)
            .addTextBody("keystoreFormat", keystoreFormat).addTextBody("keyAlias", keyAlias)
            .addTextBody("storePassword", storePassword).addTextBody("keyPassword", "undefined").build();
    HttpPost httpRequest = new HttpPost(url);
    httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenResponse.getAccessToken());
    httpRequest.setEntity(entity);

    // Send the request
    HttpClient httpClient = HttpClients.createDefault();
    HttpResponse httpResponse = httpClient.execute(httpRequest);
    assertEquals(200, httpResponse.getStatusLine().getStatusCode());

    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    String pem;

    // Assert the uploaded certificate
    if (!keystoreFormat.equals(CERTIFICATE_PEM)) {
        InputStream keystoreIs = new FileInputStream(keystoreFile);
        KeyStore keyStore = getKeystore(keystoreIs, storePassword, keystoreFormat);
        keystoreIs.close();
        pem = KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias));
    } else {
        pem = new String(Files.readAllBytes(keystoreFile.toPath()));
    }

    assertCertificate(client, certOld, pem);
}