Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

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

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:org.ez.flickr.api.CommandArguments.java

public MultipartEntity getBody(Map<String, String> additionalParameters) {
    try {/*from   www.  j ava2 s .  co  m*/
        MultipartEntity entity = new MultipartEntity();

        for (Parameter param : params) {
            if (!param.internal) {
                if (param.value instanceof File) {
                    entity.addPart(param.key, new FileBody((File) param.value));
                } else if (param.value instanceof String) {
                    entity.addPart(param.key, new StringBody((String) param.value, UTF8));
                }
            }
        }
        for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
            entity.addPart(entry.getKey(), new StringBody(entry.getValue(), UTF8));
        }

        return entity;

    } catch (UnsupportedEncodingException ex) {
        throw new UnsupportedOperationException(ex.getMessage(), ex);
    }
}

From source file:org.odk.voice.storage.InstanceUploader.java

public int uploadInstance(int instanceId) {
    // configure connection
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
    HttpClientParams.setRedirecting(params, false);

    // setup client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpPost httppost = new HttpPost(serverUrl);

    MultipartEntity entity = new MultipartEntity();

    // using file storage

    //        // get instance file
    //        File instanceDir = new File(instancePath);
    ////  w  ww .j  av  a 2  s.  c o m
    //        // find all files in parent directory
    //        File[] files = instanceDir.listFiles();
    //        if (files == null) {
    //            log.warn("No files to upload in " + instancePath);
    //        }

    // mime post
    //          for (int j = 0; j < files.length; j++) {
    //              File f = files[j];
    //              if (f.getName().endsWith(".xml")) {
    //                  // uploading xml file
    //                  entity.addPart("xml_submission_file", new FileBody(f,"text/xml"));
    //                  log.info("added xml file " + f.getName());
    //              } else if (f.getName().endsWith(".wav")) {
    //                  // upload audio file
    //                  entity.addPart(f.getName(), new FileBody(f, "audio/wav"));
    //                  log.info("added audio file" + f.getName());
    //              } else {
    //                log.info("unsupported file type, not adding file: " + f.getName());
    //              }
    //          }

    // using database storage      
    DbAdapter dba = null;
    try {
        dba = new DbAdapter();
        byte[] xml = dba.getInstanceXml(instanceId);
        if (xml == null) {
            log.error("No XML for instanceId " + instanceId);
            return STATUS_ERROR;
        }
        entity.addPart("xml_submission_file", new InputStreamBody(new ByteArrayInputStream(xml), "text/xml"));
        List<InstanceBinary> binaries = dba.getBinariesForInstance(instanceId);
        for (InstanceBinary b : binaries) {
            entity.addPart(b.name, new InputStreamBody(new ByteArrayInputStream(b.binary), b.mimeType, b.name));
        }
    } catch (SQLException e) {
        log.error("SQLException uploading instance", e);
        return STATUS_ERROR;
    } finally {
        dba.close();
    }

    httppost.setEntity(entity);

    // prepare response and return uploaded
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IOException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IllegalStateException e) {
        log.error(e);
        return STATUS_ERROR;
    }

    // check response.
    // TODO: This isn't handled correctly.
    String responseUrl = null;
    Header[] h = response.getHeaders("Location");
    if (h != null && h.length > 0) {
        responseUrl = h[0].getValue();
    } else {
        log.error("Location header was absent");
        return STATUS_ERROR;
    }
    int responseCode = response.getStatusLine().getStatusCode();
    log.info("Response code:" + responseCode);

    // verify that your response came from a known server
    if (responseUrl != null && serverUrl.contains(responseUrl) && responseCode == 201) {
        return STATUS_OK;
    }
    return STATUS_ERROR;
}

From source file:org.apache.sling.validation.testservices.ValidationServiceTest.java

@Test
public void testInvalidRequestModel1() throws IOException, JSONException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1"));
    entity.addPart("field1", new StringBody("Hello World"));
    entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation"));
    RequestExecutor re = getRequestExecutor().execute(
            getRequestBuilder().buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity))
            .assertStatus(200);/*w w  w. j  a  va 2  s  .  com*/
    String content = re.getContent();
    JSONObject jsonResponse = new JSONObject(content);
    assertFalse(jsonResponse.getBoolean("valid"));
    JSONObject failure = jsonResponse.getJSONArray("failures").getJSONObject(0);
    assertEquals("Property does not match the pattern \"^\\p{Upper}+$\".", failure.get("message"));
    assertEquals("field1", failure.get("location"));
    assertEquals(10, failure.get("severity"));
    failure = jsonResponse.getJSONArray("failures").getJSONObject(1);
    assertEquals("Missing required property with name \"field2\".", failure.get("message"));
    assertEquals("", failure.get("location")); // location is empty as the property is not found (property name is part of the message rather)
    assertEquals(0, failure.get("severity"));
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.integration.ITScriptConsolePlugin.java

private void execute(ContentBody code) throws Exception {
    RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());

    final MultipartEntity entity = new MultipartEntity();
    // Add Sling POST options
    entity.addPart("lang", new StringBody("groovy"));
    entity.addPart("code", code);
    executor.execute(/*from  w  w w.  j  av  a  2 s .  c  om*/
            rb.buildPostRequest("/system/console/sc").withEntity(entity).withCredentials("admin", "admin"))
            .assertStatus(200);
}

From source file:org.dataconservancy.ui.it.support.ValidatingMetadataFileRequest.java

public HttpPost asHttpPost() {
    if (fileToTest == null) {
        throw new IllegalStateException("File not set: call setFileToTest(File) first");
    }/*w w  w. ja va2  s  .com*/

    String validatingMetadataFileUrl = urlConfig.getAdminValidatingMetadataFilePathPostUrl().toString();
    HttpPost post = new HttpPost(validatingMetadataFileUrl);
    MultipartEntity entity = new MultipartEntity();
    try {
        entity.addPart(STRIPES_EVENT, new StringBody("Validate", Charset.forName("UTF-8")));
        entity.addPart("metadataFormatId", new StringBody(formatId, Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    FileBody fileBody = new FileBody(fileToTest);
    entity.addPart("sampleMetadataFile", fileBody);
    post.setEntity(entity);

    return post;
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

public void uninstallBundle(String symbolicName, File f) throws Exception {
    final long bundleId = getBundleId(symbolicName);

    log.info("Uninstalling bundle {} with bundleId {}", symbolicName, bundleId);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("uninstall"));
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH + "/" + bundleId)
            .withCredentials(username, password).withEntity(entity)).assertStatus(200);
}

From source file:com.glodon.paas.document.api.FileRestAPITest.java

@Test
public void uploadFileForMultiPart() throws IOException {
    File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null);
    java.io.File file = new ClassPathResource("file/testupload.file").getFile();
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody(file.getName());
    StringBody sbPosition = new StringBody("0");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);//from w w  w . ja  v a 2 s .c  o m

    File uploadFile = getFile(simpleCall(post), null);
    assertEquals(file.getName(), uploadFile.getFullName());
    assertTrue(file.length() == uploadFile.getSize());
    assertEquals(parentFile.getId(), uploadFile.getParentId());
}

From source file:com.mobileuni.helpers.FileManager.java

public void UploadToUrl(String siteUrl, String token, String filepath) {

    String url = siteUrl + "/webservice/upload.php?token=" + token;
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url);
    File file = new File(filepath);

    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(filepath.substring(filepath.lastIndexOf("."))));

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, mimetype);
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);//  w w  w .  j av a 2s.  c om
    Log.d(TAG, "upload executing request " + httppost.getRequestLine());
    try {

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        Log.d(TAG, "upload line status " + response.getStatusLine());
        if (resEntity != null) {
            Log.d(TAG, "upload " + EntityUtils.toString(resEntity));
            //JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
        } else {
            Log.d(TAG, "upload error: " + EntityUtils.toString(resEntity));
        }

    } catch (Exception ex) {
        Log.d(TAG, "Error: " + ex);
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java

/** This method should be used for sending files back to AppVet. */
public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpClient = SSLWrapper.wrapClient(httpClient);

    try {/*from   w w w  .  j a  v a 2 s. co m*/
        /*
         * To send reports back to AppVet, the following parameters must be
         * sent: - command: SUBMIT_REPORT - username: AppVet username -
         * password: AppVet password - appid: The app ID - toolid: The ID of
         * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH,
         * ERROR) - report: The report file.
         */
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8")));
        entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8")));
        entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8")));
        entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8")));
        entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8")));
        entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8")));
        File report = new File(reportFilePath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);
        HttpPost httpPost = new HttpPost(Properties.appvetUrl);
        httpPost.setEntity(entity);
        // Send the report to AppVet
        log.debug("Sending report file to AppVet");
        final HttpResponse response = httpClient.execute(httpPost);
        log.debug("Received from AppVet: " + response.getStatusLine());
        HttpEntity httpEntity = response.getEntity();
        InputStream is = httpEntity.getContent();
        String result = IOUtils.toString(is, "UTF-8");
        log.info(result);
        // Clean up
        httpPost = null;
        return true;
    } catch (Exception e) {
        log.error(e.toString());
        return false;
    }
}

From source file:bluej.collect.DataCollectorImpl.java

/**
 * Submits an event with no extra data.  A useful short-hand for calling submitEvent
 * with no content in the event./*from   w w  w.  j  a  va  2  s.  c  om*/
 */
private static void submitEventNoData(Project project, Package pkg, EventName eventName) {
    submitEvent(project, pkg, eventName, new PlainEvent(new MultipartEntity()));
}