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

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

Introduction

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

Prototype

public StringBody(final String text, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

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

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

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

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

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

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

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

        publishProgress(i + 1, values.length);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            MimeTypeMap m = MimeTypeMap.getSingleton();

            long byteCount = 0L;

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

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

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

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

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

            httppost.setEntity(entity);

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

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

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

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

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

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

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

    return mResults;
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormParamWithMultipart() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();/*from   w  w  w . j  a va 2s .  c o m*/
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:lucee.runtime.tag.Http.java

private void _doEndTag() throws PageException, IOException {

    long start = System.nanoTime();
    HttpClientBuilder builder = HTTPEngine4Impl.getHttpClientBuilder();
    ssl(builder);//from  w ww  .  j  av a2s .  com

    // redirect
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    // cookies
    BasicCookieStore cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    ConfigWeb cw = pageContext.getConfig();
    HttpRequestBase req = null;
    HttpContext httpContext = null;

    CacheHandler cacheHandler = null;
    String cacheId = null;

    // HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port);
    {
        if (StringUtil.isEmpty(charset, true))
            charset = ((PageContextImpl) pageContext).getWebCharset().name();
        else
            charset = charset.trim();

        // check if has fileUploads
        boolean doUploadFile = false;
        for (int i = 0; i < this.params.size(); i++) {
            if ((this.params.get(i)).getType() == HttpParamBean.TYPE_FILE) {
                doUploadFile = true;
                break;
            }
        }

        // parse url (also query string)
        int len = this.params.size();
        StringBuilder sbQS = new StringBuilder();
        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            int type = param.getType();
            // URL
            if (type == HttpParamBean.TYPE_URL) {
                if (sbQS.length() > 0)
                    sbQS.append('&');
                sbQS.append(param.getEncoded() ? urlenc(param.getName(), charset) : param.getName());
                sbQS.append('=');
                sbQS.append(param.getEncoded() ? urlenc(param.getValueAsString(), charset)
                        : param.getValueAsString());
            }
        }

        String host = null;
        HttpHost httpHost;
        try {
            URL _url = HTTPUtil.toURL(url, port, encoded);
            httpHost = new HttpHost(_url.getHost(), _url.getPort());
            host = _url.getHost();
            url = _url.toExternalForm();
            if (sbQS.length() > 0) {
                // no existing QS
                if (StringUtil.isEmpty(_url.getQuery())) {
                    url += "?" + sbQS;
                } else {
                    url += "&" + sbQS;
                }
            }
        } catch (MalformedURLException mue) {
            throw Caster.toPageException(mue);
        }

        // cache
        if (cachedWithin != null) {

            cacheId = createCacheId();

            cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_HTTP, null)
                    .getInstanceMatchingObject(cachedWithin, null);

            if (cacheHandler instanceof CacheHandlerPro) {

                CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin);

                if (cacheItem instanceof HTTPCacheItem) {
                    pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData());
                    return;
                }
            } else if (cacheHandler != null) { // TODO this else block can be removed when all cache handlers implement CacheHandlerPro

                CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);

                if (cacheItem instanceof HTTPCacheItem) {
                    pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData());
                    return;
                }
            }
        }

        // cache not found, process and cache result if needed

        // select best matching method (get,post, post multpart (file))

        boolean isBinary = false;
        boolean doMultiPart = doUploadFile || this.multiPart;

        HttpEntityEnclosingRequest eeReqPost = null;
        HttpEntityEnclosingRequest eeReq = null;

        if (this.method == METHOD_GET) {
            req = new HttpGetWithBody(url);
            eeReq = (HttpEntityEnclosingRequest) req;
        } else if (this.method == METHOD_HEAD) {
            req = new HttpHead(url);
        } else if (this.method == METHOD_DELETE) {
            isBinary = true;
            req = new HttpDeleteWithBody(url);
            eeReq = (HttpEntityEnclosingRequest) req;
        } else if (this.method == METHOD_PUT) {
            isBinary = true;
            HttpPut put = new HttpPut(url);
            eeReqPost = put;
            req = put;
            eeReq = put;
        } else if (this.method == METHOD_TRACE) {
            isBinary = true;
            req = new HttpTrace(url);
        } else if (this.method == METHOD_OPTIONS) {
            isBinary = true;
            req = new HttpOptions(url);
        } else if (this.method == METHOD_PATCH) {
            isBinary = true;
            eeReq = HTTPPatchFactory.getHTTPPatch(url);
            req = (HttpRequestBase) eeReq;
        } else {
            isBinary = true;
            eeReqPost = new HttpPost(url);
            req = (HttpPost) eeReqPost;
            eeReq = eeReqPost;
        }

        boolean hasForm = false;
        boolean hasBody = false;
        boolean hasContentType = false;
        // Set http params
        ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>();

        StringBuilder acceptEncoding = new StringBuilder();
        java.util.List<NameValuePair> postParam = eeReqPost != null ? new ArrayList<NameValuePair>() : null;

        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            int type = param.getType();

            // URL
            if (type == HttpParamBean.TYPE_URL) {
                // listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(),
                // http.charset)));
            }
            // Form
            else if (type == HttpParamBean.TYPE_FORM) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post");
                if (eeReqPost != null) {
                    if (doMultiPart) {
                        parts.add(new FormBodyPart(param.getName(),
                                new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset))));
                    } else {
                        postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString()));
                    }
                }
                // else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString());
            }
            // CGI
            else if (type == HttpParamBean.TYPE_CGI) {
                if (param.getEncoded())
                    req.addHeader(urlenc(param.getName(), charset), urlenc(param.getValueAsString(), charset));
                else
                    req.addHeader(param.getName(), param.getValueAsString());
            }
            // Header
            else if (type == HttpParamBean.TYPE_HEADER) {
                if (param.getName().equalsIgnoreCase("content-type"))
                    hasContentType = true;

                if (param.getName().equalsIgnoreCase("Content-Length")) {
                } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) {
                    acceptEncoding.append(headerValue(param.getValueAsString()));
                    acceptEncoding.append(", ");
                } else
                    req.addHeader(param.getName(), headerValue(param.getValueAsString()));
            }
            // Cookie
            else if (type == HttpParamBean.TYPE_COOKIE) {
                HTTPEngine4Impl.addCookie(cookieStore, host, param.getName(), param.getValueAsString(), "/",
                        charset);
            }
            // File
            else if (type == HttpParamBean.TYPE_FILE) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam type file can't only be used, when method of the tag http equal post");
                // if(param.getFile()==null) throw new ApplicationException("httpparam type file can't only be used, when method of the tag http equal
                // post");
                String strCT = getContentType(param);
                ContentType ct = HTTPUtil.toContentType(strCT, null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                if (doMultiPart) {
                    try {
                        Resource res = param.getFile();
                        parts.add(new FormBodyPart(param.getName(),
                                new ResourceBody(res, mt, res.getName(), cs)));
                        // parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
                    } catch (FileNotFoundException e) {
                        throw new ApplicationException("can't upload file, path is invalid", e.getMessage());
                    }
                }
            }
            // XML
            else if (type == HttpParamBean.TYPE_XML) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                hasContentType = true;
                req.addHeader("Content-type", mt + "; charset=" + cs);
                if (eeReq == null)
                    throw new ApplicationException(
                            "type xml is only supported for methods get, delete, post, and put");
                HTTPEngine4Impl.setBody(eeReq, param.getValueAsString(), mt, cs);
            }
            // Body
            else if (type == HttpParamBean.TYPE_BODY) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = null;
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                if (eeReq == null)
                    throw new ApplicationException(
                            "type body is only supported for methods get, delete, post, and put");
                HTTPEngine4Impl.setBody(eeReq, param.getValue(), mt, cs);

            } else {
                throw new ApplicationException("invalid type [" + type + "]");
            }

        }

        // post params
        if (postParam != null && postParam.size() > 0)
            eeReqPost.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset));

        if (compression) {
            acceptEncoding.append("gzip");
        } else {
            acceptEncoding.append("deflate;q=0");
            req.setHeader("TE", "deflate;q=0");
        }
        req.setHeader("Accept-Encoding", acceptEncoding.toString());

        // multipart
        if (doMultiPart && eeReq != null) {
            hasContentType = true;
            boolean doIt = true;
            if (!this.multiPart && parts.size() == 1) {
                ContentBody body = parts.get(0).getBody();
                if (body instanceof StringBody) {
                    StringBody sb = (StringBody) body;
                    try {
                        org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType
                                .create(sb.getMimeType(), sb.getCharset());
                        String str = IOUtil.toString(sb.getReader());
                        StringEntity entity = new StringEntity(str, ct);
                        eeReq.setEntity(entity);

                    } catch (IOException e) {
                        throw Caster.toPageException(e);
                    }
                    doIt = false;
                }
            }

            if (doIt) {

                MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create().setStrictMode();

                // enabling the line below will append charset=... to the Content-Type header
                // if (!StringUtil.isEmpty(charset, true))
                // mpeBuilder.setCharset(CharsetUtil.toCharset(charset));

                Iterator<FormBodyPart> it = parts.iterator();
                while (it.hasNext()) {
                    FormBodyPart part = it.next();
                    mpeBuilder.addPart(part);
                }

                eeReq.setEntity(mpeBuilder.build());
            }
            // eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
        }

        if (hasBody && hasForm)
            throw new ApplicationException("mixing httpparam  type file/formfield and body/XML is not allowed");

        if (!hasContentType) {
            if (isBinary) {
                if (hasBody)
                    req.addHeader("Content-type", "application/octet-stream");
                else
                    req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset);
            } else {
                if (hasBody)
                    req.addHeader("Content-type", "text/html; charset=" + charset);
            }
        }

        // set User Agent
        if (!hasHeaderIgnoreCase(req, "User-Agent"))
            req.setHeader("User-Agent", this.useragent);

        // set timeout
        setTimeout(builder, checkRemainingTimeout());

        // set Username and Password
        if (this.username != null) {
            if (this.password == null)
                this.password = "";
            if (AUTH_TYPE_NTLM == this.authType) {
                if (StringUtil.isEmpty(this.workStation, true))
                    throw new ApplicationException(
                            "attribute workstation is required when authentication type is [NTLM]");
                if (StringUtil.isEmpty(this.domain, true))
                    throw new ApplicationException(
                            "attribute domain is required when authentication type is [NTLM]");

                HTTPEngine4Impl.setNTCredentials(builder, this.username, this.password, this.workStation,
                        this.domain);
            } else
                httpContext = HTTPEngine4Impl.setCredentials(builder, httpHost, this.username, this.password,
                        preauth);
        }

        // set Proxy
        ProxyData proxy = null;
        if (!StringUtil.isEmpty(this.proxyserver)) {
            proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser,
                    this.proxypassword);
        }
        if (pageContext.getConfig().isProxyEnableFor(host)) {
            proxy = pageContext.getConfig().getProxyData();
        }
        HTTPEngine4Impl.setProxy(builder, req, proxy);

    }

    CloseableHttpClient client = null;
    try {
        if (httpContext == null)
            httpContext = new BasicHttpContext();

        Struct cfhttp = new StructImpl();
        cfhttp.setEL(ERROR_DETAIL, "");
        pageContext.setVariable(result, cfhttp);

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        client = builder.build();
        Executor4 e = new Executor4(pageContext, this, client, httpContext, req, redirect);
        HTTPResponse4Impl rsp = null;

        if (timeout == null || timeout.getMillis() <= 0) {
            try {
                rsp = e.execute(httpContext);
            }

            catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
                if (!throwonerror) {
                    if (t instanceof SocketTimeoutException)
                        setRequestTimeout(cfhttp);
                    else
                        setUnknownHost(cfhttp, t);
                    return;
                }
                throw toPageException(t, rsp);

            }
        } else {
            e.start();
            try {
                synchronized (this) {// print.err(timeout);
                    this.wait(timeout.getMillis());
                }
            } catch (InterruptedException ie) {
                throw Caster.toPageException(ie);
            }
            if (e.t != null) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, e.t);
                    return;
                }
                throw toPageException(e.t, rsp);
            }

            rsp = e.response;

            if (!e.done) {
                req.abort();
                if (throwonerror)
                    throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408,
                            "Time-out", rsp == null ? null : rsp.getURL());
                setRequestTimeout(cfhttp);
                return;
                // throw new ApplicationException("timeout");
            }
        }

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset());
        int statCode = 0;
        // Write Response Scope
        // String rawHeader=httpMethod.getStatusLine().toString();
        String mimetype = null;
        String contentEncoding = null;

        // status code
        cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim()));
        cfhttp.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode()));
        cfhttp.set(STATUS_TEXT, (rsp.getStatusText()));
        cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion()));

        // responseHeader
        lucee.commons.net.http.Header[] headers = rsp.getAllHeaders();
        StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " ");
        Struct responseHeader = new StructImpl();
        Struct cookie;
        Array setCookie = new ArrayImpl();
        Query cookies = new QueryImpl(
                new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0,
                "cookies");

        for (int i = 0; i < headers.length; i++) {
            lucee.commons.net.http.Header header = headers[i];
            // print.ln(header);

            raw.append(header.toString() + " ");
            if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                setCookie.append(header.getValue());
                parseCookie(cookies, header.getValue());
            } else {
                // print.ln(header.getName()+"-"+header.getValue());
                Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null);
                if (value == null)
                    responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue());
                else {
                    Array arr = null;
                    if (value instanceof Array) {
                        arr = (Array) value;
                    } else {
                        arr = new ArrayImpl();
                        responseHeader.set(KeyImpl.getInstance(header.getName()), arr);
                        arr.appendEL(value);
                    }
                    arr.appendEL(header.getValue());
                }
            }

            // Content-Type
            if (header.getName().equalsIgnoreCase("Content-Type")) {
                mimetype = header.getValue();
                if (mimetype == null)
                    mimetype = NO_MIMETYPE;
            }

            // Content-Encoding
            if (header.getName().equalsIgnoreCase("Content-Encoding")) {
                contentEncoding = header.getValue();
            }

        }
        cfhttp.set(RESPONSEHEADER, responseHeader);
        cfhttp.set(KeyConstants._cookies, cookies);
        responseHeader.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode()));
        responseHeader.set(EXPLANATION, (rsp.getStatusText()));
        if (setCookie.size() > 0)
            responseHeader.set(SET_COOKIE, setCookie);

        // is text
        boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype);

        // is multipart
        boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype);

        cfhttp.set(KeyConstants._text, Caster.toBoolean(isText));

        // mimetype charset
        // boolean responseProvideCharset=false;
        if (!StringUtil.isEmpty(mimetype, true)) {
            if (isText) {
                String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null);
                if (types[0] != null)
                    cfhttp.set(KeyConstants._mimetype, types[0]);
                if (types[1] != null)
                    cfhttp.set(CHARSET, types[1]);

            } else
                cfhttp.set(KeyConstants._mimetype, mimetype);
        } else
            cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE);

        // File
        Resource file = null;

        if (strFile != null && strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile);
        } else if (strFile != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strFile);
        } else if (strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath);
            // Resource dir = file.getParentResource();
            if (file.isDirectory()) {
                file = file.getRealResource(req.getURI().getPath());// TODO was getName()
                // ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName()
            }

        }
        if (file != null)
            pageContext.getConfig().getSecurityManager().checkFileLocation(file);

        // filecontent
        InputStream is = null;
        if (isText && getAsBinary != GET_AS_BINARY_YES) {
            String str;
            try {

                // read content
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    if (is != null && isGzipEncoded(contentEncoding))
                        is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is)
                                : new GZIPInputStream(is);
                }
                try {
                    try {
                        str = is == null ? ""
                                : IOUtil.toString(is, responseCharset, checkRemainingTimeout().getMillis());
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream) {
                            str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(),
                                    responseCharset, checkRemainingTimeout().getMillis());
                        } else
                            throw eof;
                    }
                } catch (UnsupportedEncodingException uee) {
                    str = IOUtil.toString(is, (Charset) null, checkRemainingTimeout().getMillis());
                }
            } catch (IOException ioe) {
                throw Caster.toPageException(ioe);
            } finally {
                IOUtil.closeEL(is);
            }

            if (str == null)
                str = "";
            if (resolveurl) {
                // if(e.redirectURL!=null)url=e.redirectURL.toExternalForm();
                str = new URLResolver().transform(str, e.response.getTargetURL(), false);
            }
            cfhttp.set(KeyConstants._filecontent, str);
            try {
                if (file != null) {
                    IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false);
                }
            } catch (IOException e1) {
            }

            if (name != null) {
                Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders);
                pageContext.setVariable(name, qry);
            }
        }
        // Binary
        else {
            byte[] barr = null;
            if (isGzipEncoded(contentEncoding)) {
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is);
                }

                try {
                    try {
                        barr = is == null ? new byte[0] : IOUtil.toBytes(is);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream)
                            barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData());
                        else
                            throw eof;
                    }
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                } finally {
                    IOUtil.closeEL(is);
                }
            } else {
                try {
                    if (method != METHOD_HEAD)
                        barr = rsp.getContentAsByteArray();
                    else
                        barr = new byte[0];
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                }
            }
            // IF Multipart response get file content and parse parts
            if (barr != null) {
                if (isMultipart) {
                    cfhttp.set(KeyConstants._filecontent, MultiPartResponseUtils.getParts(barr, mimetype));
                } else {
                    cfhttp.set(KeyConstants._filecontent, barr);
                }
            } else
                cfhttp.set(KeyConstants._filecontent, "");

            if (file != null) {
                try {
                    if (barr != null)
                        IOUtil.copy(new ByteArrayInputStream(barr), file, true);
                } catch (IOException ioe) {
                    throw Caster.toPageException(ioe);
                }
            }
        }

        // header
        cfhttp.set(KeyConstants._header, raw.toString());
        if (!isStatusOK(rsp.getStatusCode())) {
            String msg = rsp.getStatusCode() + " " + rsp.getStatusText();
            cfhttp.setEL(ERROR_DETAIL, msg);
            if (throwonerror) {
                throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL());
            }
        }

        // TODO: check if we can use statCode instead of rsp.getStatusCode() everywhere and cleanup the code
        if (cacheHandler != null && rsp.getStatusCode() == 200) {
            // add to cache
            cacheHandler.set(pageContext, cacheId, cachedWithin,
                    new HTTPCacheItem(cfhttp, url, System.nanoTime() - start));
        }
    } finally {
        if (client != null)
            client.close();
    }
}

From source file:com.behance.sdk.services.BehanceSDKPublishProjectService.java

private BehanceSDKPublishProjectTaskResult publishProjectOnServer(
          BehanceSDKPublishProjectServiceParamsDTO paramBehanceSDKPublishProjectServiceParamsDTO,
          BehanceSDKPublishProjectStatusDTO paramBehanceSDKPublishProjectStatusDTO) {
      BehanceSDKPublishProjectTaskResult localBehanceSDKPublishProjectTaskResult = new BehanceSDKPublishProjectTaskResult();
      BehanceSDKPublishedProjectDTO localBehanceSDKPublishedProjectDTO = new BehanceSDKPublishedProjectDTO();
      String str1 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectTitle();
      localBehanceSDKPublishedProjectDTO.setProjectTitle(str1);
      localBehanceSDKPublishProjectTaskResult.setPublishedProject(localBehanceSDKPublishedProjectDTO);
      List localList = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectModules();
      paramBehanceSDKPublishProjectStatusDTO.setProjectTitle(str1);
      paramBehanceSDKPublishProjectStatusDTO
              .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_STARTED);
      paramBehanceSDKPublishProjectStatusDTO
              .setProgressPercentage(getProgressPercentage(BehanceSDKPublishProjectProgressState.PUBLISH_STARTED,
                      paramBehanceSDKPublishProjectServiceParamsDTO));
      broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
      Object localObject4 = null;
      HashMap localHashMap = new HashMap();
      localHashMap.put("clientId", paramBehanceSDKPublishProjectServiceParamsDTO.getAppClientId());
      Object localObject1 = localObject4;
      ContentType localContentType;/*w ww  . j av a2  s .  c o m*/
      Object localObject5;
      String str2;
      try {
          localContentType = ContentType.create("text/plain", "UTF-8");
          localObject1 = localObject4;
          localObject5 = BehanceSDKUrlUtil.getUrlFromTemplate(
                  "{server_root_url}/v2/project/editor?{key_client_id_param}={clientId}", localHashMap);
          localObject1 = localObject4;
          str2 = BehanceSDKUserManager.getInstance().checkExpiryAndGetAccessToken();
          Object localObject2 = localObject5;
          if (str2 != null) {
              localObject1 = localObject4;
              localObject2 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject5, "access_token",
                      str2);
          }
          localObject1 = localObject4;
          localObject2 = new HttpPost((String) localObject2);
          localObject1 = localObject4;
          localObject6 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCoverImageByteArray();
          localObject1 = localObject4;
          localObject5 = MultipartEntityBuilder.create();
          localObject1 = localObject4;
          localObject6 = new ByteArrayInputStream((byte[]) localObject6);
          localObject1 = localObject4;
          ((MultipartEntityBuilder) localObject5).addPart("image", new InputStreamBody((InputStream) localObject6,
                  paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCoverImageFileName()));
          localObject1 = localObject4;
          ((MultipartEntityBuilder) localObject5).addTextBody("title", str1, localContentType);
          localObject1 = localObject4;
          ((HttpPost) localObject2).setEntity(((MultipartEntityBuilder) localObject5).build());
          localObject1 = localObject4;
          localObject2 = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject2);
          localObject1 = localObject4;
          ((ByteArrayInputStream) localObject6).close();
          localObject1 = localObject4;
          if (((HTTPResponse) localObject2).getStatusCode() != 201) {
              localObject1 = localObject4;
              paramBehanceSDKPublishProjectStatusDTO
                      .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED);
              localObject1 = localObject4;
              paramBehanceSDKPublishProjectStatusDTO
                      .setReasonPhrase(((HTTPResponse) localObject2).getReasonPhrase());
              localObject1 = localObject4;
              broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
              localObject1 = localObject4;
              cleanupCreativeCloudResources(localList);
              localObject1 = localObject4;
              localBehanceSDKPublishProjectTaskResult
                      .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CREATION_FAILED);
              localObject1 = localObject4;
              localBehanceSDKPublishProjectTaskResult
                      .setReasonPhrase(((HTTPResponse) localObject2).getReasonPhrase());
              return localBehanceSDKPublishProjectTaskResult;
          }
          localObject1 = localObject4;
          localObject2 = (JSONObject) new JSONObject(((HTTPResponse) localObject2).getResponseString())
                  .get("project");
          localObject1 = localObject4;
          localObject5 = ((JSONObject) localObject2).optString("id");
          localObject1 = localObject5;
          localBehanceSDKPublishedProjectDTO.setProjectId((String) localObject5);
          localObject1 = localObject5;
          localObject4 = ((JSONObject) localObject2).optString("url");
          localObject1 = localObject5;
          localBehanceSDKPublishedProjectDTO.setProjectUrl((String) localObject4);
          localObject1 = localObject5;
          paramBehanceSDKPublishProjectStatusDTO.setProjectId((String) localObject5);
          localObject1 = localObject5;
          paramBehanceSDKPublishProjectStatusDTO.setProjectUrl((String) localObject4);
          localObject1 = localObject5;
          if (!isActiveUploadCancelled()) {
              break label563;
          }
          localObject1 = localObject5;
          handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO,
                  paramBehanceSDKPublishProjectServiceParamsDTO);
          localObject1 = localObject5;
          localBehanceSDKPublishProjectTaskResult
                  .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED);
          return localBehanceSDKPublishProjectTaskResult;
      } catch (Throwable localThrowable) {
          logger.error(localThrowable, "Problem publishing project", new Object[0]);
          cleanupCreativeCloudResources(localList);
          if (!isActiveUploadCancelled()) {
              break label1715;
          }
      }
      handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO,
              paramBehanceSDKPublishProjectServiceParamsDTO);
      localBehanceSDKPublishProjectTaskResult
              .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED);
      return localBehanceSDKPublishProjectTaskResult;
      label563: localObject1 = localObject5;
      paramBehanceSDKPublishProjectStatusDTO
              .setProgressState(BehanceSDKPublishProjectProgressState.PROJECT_DRAFT_CREATION_SUCCESSFUL);
      localObject1 = localObject5;
      paramBehanceSDKPublishProjectStatusDTO.setProgressPercentage(
              getProgressPercentage(BehanceSDKPublishProjectProgressState.PROJECT_DRAFT_CREATION_SUCCESSFUL,
                      paramBehanceSDKPublishProjectServiceParamsDTO));
      localObject1 = localObject5;
      broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
      localObject1 = localObject5;
      localObject4 = localThrowable.optJSONObject("covers");
      int i;
      Iterator localIterator;
      if (localObject4 != null) {
          localObject1 = localObject5;
          localObject3 = ((JSONObject) localObject4).optString("202");
          localObject1 = localObject5;
          localObject4 = ((JSONObject) localObject4).optString("404");
          localObject1 = localObject5;
          localBehanceSDKPublishedProjectDTO.setProjectImageUrl((String) localObject3);
          if (localObject4 != null) {
              localObject1 = localObject5;
              if (((String) localObject4).length() > 0) {
                  localObject1 = localObject5;
                  paramBehanceSDKPublishProjectStatusDTO.setProjectCoverImageUrl((String) localObject4);
              }
          }
      } else {
          localObject1 = localObject5;
          localObject4 = BehanceSDKUrlUtil.getUrlFromTemplate(
                  "{server_root_url}/v2/project/editor/{PROJECTID}/modules?{key_client_id_param}={clientId}",
                  localHashMap).replace("{PROJECTID}", (CharSequence) localObject5);
          localObject3 = localObject4;
          if (str2 != null) {
              localObject1 = localObject5;
              localObject3 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject4, "access_token",
                      str2);
          }
          i = 0;
          localObject1 = localObject5;
          localIterator = localList.iterator();
      }
      ProjectModule localProjectModule;
      label1147: label1173: do {
          localObject1 = localObject5;
          if (!localIterator.hasNext()) {
              break label1284;
          }
          localObject1 = localObject5;
          localProjectModule = (ProjectModule) localIterator.next();
          localObject1 = localObject5;
          if (isActiveUploadCancelled()) {
              localObject1 = localObject5;
              handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO,
                      paramBehanceSDKPublishProjectServiceParamsDTO);
              localObject1 = localObject5;
              localBehanceSDKPublishProjectTaskResult
                      .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED);
              return localBehanceSDKPublishProjectTaskResult;
              localObject1 = localObject5;
              paramBehanceSDKPublishProjectStatusDTO.setProjectCoverImageUrl((String) localObject3);
              break;
          }
          i += 1;
          localObject1 = localObject5;
          ProjectModuleTypes localProjectModuleTypes = localProjectModule.getType();
          localObject1 = localObject5;
          Object localObject7 = MultipartEntityBuilder.create();
          localObject6 = null;
          localObject1 = localObject5;
          if (localProjectModuleTypes != ProjectModuleTypes.IMAGE) {
              localObject1 = localObject5;
              if (localProjectModuleTypes != ProjectModuleTypes.CREATIVECLOUD_ASSET) {
              }
          } else {
              localObject1 = localObject5;
              ((MultipartEntityBuilder) localObject7).addTextBody("type", "image");
              localObject1 = localObject5;
              localObject4 = ((ImageModule) localProjectModule).getFileForUpload();
              localObject1 = localObject5;
              ((MultipartEntityBuilder) localObject7).addPart("image", new FileBody((File) localObject4));
              localObject1 = localObject5;
              localObject6 = ((MultipartEntityBuilder) localObject7).build();
              localObject1 = localObject5;
              localObject7 = new HttpPost((String) localObject3);
              localObject1 = localObject5;
              ((HttpPost) localObject7).setEntity(new CustomHttpEntityWrapper((HttpEntity) localObject6,
                      new ProjectModuleUploadEntityWrapperCallback(paramBehanceSDKPublishProjectServiceParamsDTO,
                              paramBehanceSDKPublishProjectStatusDTO, (HttpPost) localObject7, i, null)));
              localObject1 = localObject5;
              localObject6 = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject7);
              localObject1 = localObject5;
              if (localProjectModuleTypes != ProjectModuleTypes.IMAGE) {
                  break label1147;
              }
              localObject1 = localObject5;
              if (((File) localObject4).equals(((ImageModule) localProjectModule).getFile())) {
                  break label1147;
              }
              localObject1 = localObject5;
              ((File) localObject4).delete();
          }
          for (;;) {
              localObject1 = localObject5;
              if (!isActiveUploadCancelled()) {
                  break label1173;
              }
              localObject1 = localObject5;
              handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO,
                      paramBehanceSDKPublishProjectServiceParamsDTO);
              localObject1 = localObject5;
              localBehanceSDKPublishProjectTaskResult
                      .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED);
              return localBehanceSDKPublishProjectTaskResult;
              localObject1 = localObject5;
              localObject4 = localObject6;
              if (localProjectModuleTypes != ProjectModuleTypes.EMBED) {
                  break;
              }
              localObject1 = localObject5;
              ((MultipartEntityBuilder) localObject7).addTextBody("type", "embed");
              localObject1 = localObject5;
              ((MultipartEntityBuilder) localObject7).addPart("html", new StringBody(
                      ((EmbedModule) localProjectModule).getEmbedContent(), ContentType.APPLICATION_XHTML_XML));
              localObject4 = localObject6;
              break;
              localObject1 = localObject5;
              if (localProjectModuleTypes == ProjectModuleTypes.CREATIVECLOUD_ASSET) {
                  localObject1 = localObject5;
                  localProjectModule.deleteFromFileSystem();
              }
          }
          localObject1 = localObject5;
      } while (((HTTPResponse) localObject6).getStatusCode() == 201);
      localObject1 = localObject5;
      deleteProject((String) localObject5, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap);
      localObject1 = localObject5;
      cleanupCreativeCloudResources(localList);
      localObject1 = localObject5;
      paramBehanceSDKPublishProjectStatusDTO
              .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED);
      localObject1 = localObject5;
      paramBehanceSDKPublishProjectStatusDTO.setReasonPhrase(((HTTPResponse) localObject6).getReasonPhrase());
      localObject1 = localObject5;
      broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
      localObject1 = localObject5;
      localBehanceSDKPublishProjectTaskResult
              .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.MODULE_ADD_FAILED);
      localObject1 = localObject5;
      localBehanceSDKPublishProjectTaskResult.setFailedMoudle(localProjectModule);
      localObject1 = localObject5;
      localBehanceSDKPublishProjectTaskResult.setReasonPhrase(((HTTPResponse) localObject6).getReasonPhrase());
      return localBehanceSDKPublishProjectTaskResult;
      label1284: localObject1 = localObject5;
      localObject4 = BehanceSDKUrlUtil.getUrlFromTemplate(
              "{server_root_url}/v2/project/editor/{PROJECTID}?{key_client_id_param}={clientId}", localHashMap)
              .replace("{PROJECTID}", (CharSequence) localObject5);
      Object localObject3 = localObject4;
      if (str2 != null) {
          localObject1 = localObject5;
          localObject3 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject4, "access_token", str2);
      }
      localObject1 = localObject5;
      localObject4 = new HttpPut((String) localObject3);
      localObject1 = localObject5;
      Object localObject6 = MultipartEntityBuilder.create();
      localObject1 = localObject5;
      ((MultipartEntityBuilder) localObject6).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
      localObject1 = localObject5;
      ((MultipartEntityBuilder) localObject6).addTextBody("title", str1, localContentType);
      localObject1 = localObject5;
      localObject3 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCreativeFields();
      localObject1 = localObject5;
      if (!TextUtils.isEmpty((CharSequence) localObject3)) {
          localObject1 = localObject5;
          ((MultipartEntityBuilder) localObject6).addTextBody("fields", (String) localObject3, localContentType);
      }
      localObject1 = localObject5;
      localObject3 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectTags();
      localObject1 = localObject5;
      if (!TextUtils.isEmpty((CharSequence) localObject3)) {
          localObject1 = localObject5;
          ((MultipartEntityBuilder) localObject6).addTextBody("tags", (String) localObject3, localContentType);
      }
      localObject1 = localObject5;
      ((MultipartEntityBuilder) localObject6).addTextBody("description",
              paramBehanceSDKPublishProjectServiceParamsDTO.getProjectDescription(), localContentType);
      localObject1 = localObject5;
      ((MultipartEntityBuilder) localObject6).addTextBody("license",
              paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCopyright(), localContentType);
      localObject1 = localObject5;
      if (paramBehanceSDKPublishProjectServiceParamsDTO.isProjectContainsAdultContent()) {
      }
      for (localObject3 = "1";; localObject3 = "0") {
          localObject1 = localObject5;
          ((MultipartEntityBuilder) localObject6).addTextBody("mature_content", (String) localObject3,
                  localContentType);
          localObject1 = localObject5;
          ((MultipartEntityBuilder) localObject6).addTextBody("published", "1", localContentType);
          localObject1 = localObject5;
          ((HttpPut) localObject4).setEntity(((MultipartEntityBuilder) localObject6).build());
          localObject1 = localObject5;
          localObject3 = BehanceSDKHTTPUtils.doHTTPPut((HttpPut) localObject4);
          localObject1 = localObject5;
          if (((HTTPResponse) localObject3).getStatusCode() == 200) {
              localObject1 = localObject5;
              localBehanceSDKPublishProjectTaskResult
                      .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.SUCCESS);
              localObject1 = localObject5;
              paramBehanceSDKPublishProjectStatusDTO
                      .setProgressState(BehanceSDKPublishProjectProgressState.MODULES_UPLOAD_SUCCESSFUL);
              localObject1 = localObject5;
              paramBehanceSDKPublishProjectStatusDTO.setProgressPercentage(
                      getProgressPercentage(BehanceSDKPublishProjectProgressState.MODULES_UPLOAD_SUCCESSFUL,
                              paramBehanceSDKPublishProjectServiceParamsDTO));
              localObject1 = localObject5;
              broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
              return localBehanceSDKPublishProjectTaskResult;
          }
          localObject1 = localObject5;
          deleteProject((String) localObject5, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap);
          localObject1 = localObject5;
          paramBehanceSDKPublishProjectStatusDTO
                  .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED);
          localObject1 = localObject5;
          paramBehanceSDKPublishProjectStatusDTO.setReasonPhrase(((HTTPResponse) localObject3).getReasonPhrase());
          localObject1 = localObject5;
          broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
          localObject1 = localObject5;
          localBehanceSDKPublishProjectTaskResult
                  .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.PUBLISH_FAILED);
          localObject1 = localObject5;
          localBehanceSDKPublishProjectTaskResult
                  .setReasonPhrase(((HTTPResponse) localObject3).getReasonPhrase());
          return localBehanceSDKPublishProjectTaskResult;
          label1715: if (!TextUtils.isEmpty(localObject1)) {
              deleteProject(localObject1, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap);
          }
          paramBehanceSDKPublishProjectStatusDTO
                  .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED);
          paramBehanceSDKPublishProjectStatusDTO.setException((Throwable) localObject3);
          broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO);
          localBehanceSDKPublishProjectTaskResult
                  .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.EXCEPTION);
          localBehanceSDKPublishProjectTaskResult.setException((Throwable) localObject3);
          return localBehanceSDKPublishProjectTaskResult;
      }
  }

From source file:de.fun2code.google.cloudprint.CloudPrintConnection.java

/**
 * Submits a new print job.//from  w  w w .  j  a  va 2s  .  c  o m
 * 
 * @param printer
 *            Printer to use.
 * @param document
 *            Document to send.
 * @param contentType
 *            Mime Type
 * @param capabilities
 *            Capabilities (optional).
 * @param listener
 *            Update listener that receives upload notifications in percent.
 * @return <tt>true</tt> on success, otherwise <tt>false</tt>.
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public boolean submit(Printer printer, File document, String contentType, String capabilities,
        UploadListener listener) throws ClientProtocolException, IOException, JSONException {
    if (!document.exists()) {
        lastResponse.setSuccess(false);
        lastResponse.setMessage("Document does not exist.");
        return false;
    }

    if (capabilities == null) {
        capabilities = "";
    }

    HttpPost post = new HttpPost(GCP_BASE_URL + "/" + GCP_CMD_SUBMIT);
    addGcpHeaders(post);

    FileBody doc = new CountingFileBody(document, listener);

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("content", doc);
    reqEntity.addPart("output", new StringBody("json", Charset.forName("UTF-8")));
    reqEntity.addPart("printerid", new StringBody(printer.getId(), Charset.forName("UTF-8")));
    reqEntity.addPart("capabilities", new StringBody(capabilities, Charset.forName("UTF-8")));
    reqEntity.addPart("contentType", new StringBody(contentType, Charset.forName("UTF-8")));
    reqEntity.addPart("title", new StringBody(document.getName(), Charset.forName("UTF-8")));
    post.setEntity(reqEntity);

    HttpResponse response = httpclient.execute(post);
    int code = response.getStatusLine().getStatusCode();

    String responseStr = EntityUtils.toString(response.getEntity());

    if (code == HttpStatus.SC_OK) {
        JSONObject json = new JSONObject(responseStr);
        if (json.has("message")) {
            lastResponse.setMessage(json.getString("message"));
        }

        if (json.getBoolean("success")) {
            lastResponse.setSuccess(true);
            return true;
        } else {
            lastResponse.setSuccess(false);
            return false;
        }
    } else {
        lastResponse.setSuccess(false);
        lastResponse.setMessage("HTTP result code: " + code);
        return false;
    }
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/* ww w  . j  a  v a2  s  .  c o m*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");

    // Send multipart/form-data request
    connection = request("/test/v1/formDataParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void tesFormParamWithCollection() throws IOException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }//  ww w  .  j  av  a 2  s . co  m

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");

    // Send x-form-url-encoded request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    rawData = "names=WSO2&names=IBM&names=IBM";
    encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");

    // Send multipart/form-data request
    connection = request("/test/v1/formParamWithSet", HttpMethod.POST);
    builder = MultipartEntityBuilder.create();
    builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN));
    builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN));
    build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "3");
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Sets request information for the type of POST request. This is determined 
 * by the post type provided.//from w ww  .ja v a2s . c o  m
 * @param postTypeStr is a String with the postType.
 * @param Obj is a Javascript object to set for the request.
 * @param ContentType is a String with the content-type for the custom request.
 * @throws ic9exception Exception
 * @throws UnsupportedEncodingException Exception
 */
@SuppressWarnings("unchecked")
private void setPostInfo(String postTypeStr, Object Obj, String ContentType)
        throws ic9exception, UnsupportedEncodingException {
    postType pt = this.getPostType(postTypeStr);
    if (pt == postType.URL_ENCODED) {
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : jobj.keySet()) {
            Object val = jobj.get(key);
            nvps.add(new BasicNameValuePair(key, val.toString()));
        }
        this.respEnt = new UrlEncodedFormEntity(nvps);
    } else if (pt == postType.MULTIPART) {
        MultipartEntityBuilder mpEntBuilder = MultipartEntityBuilder.create();
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        for (String key : jobj.keySet()) {
            Map<String, Object> part = (Map<String, Object>) jobj.get(key);
            if (part.containsKey("name") && part.containsKey("data")) {
                String pkey = (String) part.get("name");
                if (part.get("data") instanceof byte[]) {
                    byte[] data = (byte[]) part.get("data");
                    mpEntBuilder.addPart(key, new ByteArrayBody(data, pkey));
                } else if (part.get("data") instanceof String) {
                    String data = (String) part.get("data");
                    mpEntBuilder.addPart(key,
                            new StringBody(data, org.apache.http.entity.ContentType.DEFAULT_TEXT));
                }
            } else
                throw new ic9exception(
                        "httpClient.setPotInfo(): Multipart from data expects and object of httpPart objects.");
        }
        this.respEnt = mpEntBuilder.build();
    } else {
        if (Obj instanceof String) {
            StringEntity se = new StringEntity((String) Obj);
            if (ContentType != null)
                se.setContentType(ContentType);
            else
                throw new ic9exception(
                        "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            this.respEnt = se;
        } else if (Obj instanceof Map) {
            Map<String, Object> tobj = (Map<String, Object>) Obj;

            if (tobj.containsKey("data") && tobj.get("data") instanceof byte[]) {
                if (ContentType != null) {
                    ByteArrayEntity bae = new ByteArrayEntity((byte[]) Obj);
                    bae.setContentType(ContentType);
                    this.respEnt = bae;
                } else
                    throw new ic9exception(
                            "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            } else
                throw new ic9exception(
                        "httpClient.setPostInfo(): Provided object is not of type Buffer or is missing 'data' attribute. (data should be byte[])");
        } else
            throw new ic9exception(
                    "httpClient.setPostInfo(): Second argument to POST call expecting String or Buffer object.");
    }
}

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 .  j a va 2 s.  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());
        }
    }
}