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.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testRetrieveFIlteredMultipartDatastreams() throws Exception {

    final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest10");
    assertEquals(201, getStatus(objMethod));
    final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest10/datastreams/");

    final MultipartEntity multiPartEntity = new MultipartEntity();
    multiPartEntity.addPart("ds1", new StringBody("asdfg"));
    multiPartEntity.addPart("ds2", new StringBody("qwerty"));

    post.setEntity(multiPartEntity);//from   www .j  a va2s . c o m

    final HttpResponse postResponse = client.execute(post);
    assertEquals(201, postResponse.getStatusLine().getStatusCode());

    // TODO: we should actually evaluate the multipart response for the
    // things we're expecting
    final HttpGet getDSesMethod = new HttpGet(
            serverAddress + "objects/FedoraDatastreamsTest10/datastreams/__content__?dsid=ds1");
    final HttpResponse response = client.execute(getDSesMethod);
    assertEquals(200, response.getStatusLine().getStatusCode());
    final String content = EntityUtils.toString(response.getEntity());

    assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find());
    assertFalse("Didn't expect to find the second datastream!",
            compile("qwerty", DOTALL).matcher(content).find());

}

From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*  w  w w  .j  a  v  a 2 s.c  om*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntity requestMultipartEntity = new MultipartEntity();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");

    // add auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        StringBody authPart = new StringBody(auth, Charset.forName(getEncoding()));
        requestMultipartEntity.addPart("auth", authPart);
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        requestMultipartEntity.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    //getAuthConsumer().sign( request );

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

From source file:com.puppetlabs.puppetdb.javaclient.impl.HttpComponentsConnector.java

@Override
public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType,
        String fileName, final long fileSize, Class<V> type) throws IOException {
    HttpPost request = new HttpPost(createURI(uri));
    configureRequest(request);//from w  w  w. j a va 2s .  c o m

    MultipartEntity entity = new MultipartEntity();
    for (Map.Entry<String, String> entry : stringParts.entrySet())
        entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart("file", new InputStreamBody(in, mimeType, fileName) {
        @Override
        public long getContentLength() {
            return fileSize;
        }
    });
    request.setEntity(entity);
    return executeRequest(request, type, null);
}

From source file:gov.nist.appvet.tool.AsynchronousService.java

public void sendReport(String appid, String toolrisk, String reportPath) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    httpclient = SSLWrapper.wrapClient(httpclient);

    try {/*  w  w w.j av  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 (PASS,FAIL,WARNING,ERROR)
        // * file: 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(toolrisk, Charset.forName("UTF-8")));

        File report = new File(reportPath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);

        HttpPost httpPost = new HttpPost(Properties.appVetURL);
        httpPost.setEntity(entity);
        log.debug("Sending report to AppVet");

        // Send the app to the tool
        final HttpResponse response = httpclient.execute(httpPost);
        httpPost = null;
        log.debug("Received: " + response.getStatusLine());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cellbots.eyes.EyesActivity.java

private void appEngineUploadImage(byte[] imageData) {
    Log.e("app engine remote eyes", "called");
    try {//  w w  w . ja  v  a 2 s  .  com
        YuvImage yuvImage = new YuvImage(imageData, previewFormat, previewWidth, previewHeight, null);
        yuvImage.compressToJpeg(r, 20, out); // Tweak the quality here - 20
        // seems pretty decent for
        // quality + size.
        Log.e("app engine remote eyes", "upload starting");
        HttpPost httpPost = new HttpPost(postUrl);
        Log.e("app engine perf", "0");
        MultipartEntity entity = new MultipartEntity();
        Log.e("app engine perf", "1");
        entity.addPart("img", new InputStreamBody(new ByteArrayInputStream(out.toByteArray()), "video.jpg"));
        Log.e("app engine perf", "2");
        httpPost.setEntity(entity);
        Log.e("app engine perf", "3");
        HttpResponse response = httpclient.execute(httpPost);
        Log.e("app engine remote eyes", "result: " + response.getStatusLine());
        Log.e("app engine remote eyes", "upload complete");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        resetAppEngineConnection();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        resetAppEngineConnection();
    } catch (IOException e) {
        e.printStackTrace();
        resetAppEngineConnection();
    } finally {
        out.reset();
        if (mCamera != null) {
            mCamera.addCallbackBuffer(mCallbackBuffer);
        }
        isUploading = false;
        Log.e("app engine remote eyes", "finished");
    }
}

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

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

    String fileNameAPIM624 = "APIM624.txt";
    String docName = "APIM624PublisherTestHowTo-File-summary";
    String docType = "public forum";
    String sourceType = "file";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM624 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM624;
    String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag";

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

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

    httppost.setEntity(multipartEntity);

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

From source file:ro.teodorbaciu.commons.client.ws.BaseWsMethods.java

/**
 * Handles the communication details with the server.
 * //from   ww w.  ja  va  2s.c  o m
 * @param moduleName the name of the module
 * @param op the operation to call
 * @param targetUrl the url to post the call
 * @param wsParamsList contains the parameters to submit for the webservice call
 * @return the result of the call
 * @throws Exception if an error occurs
 */
private String callServerMultipartPost(String moduleName, String op, String targetUrl,
        List<NameValuePair> wsParamsList, File fileToUpload, WriteListener writeListener)
        throws AuthorizationRequiredException, OperationForbiddenException, UnsupportedEncodingException,
        ClientProtocolException, IOException {

    if (currentRequest != null) {
        throw new RuntimeException("Another webservice request is still executing !");
    }

    MultipartEntity reqEntity = null;
    if (writeListener != null) {
        reqEntity = new MultipartEntityWithProgressMonitoring(writeListener);
    } else {
        reqEntity = new MultipartEntity();
    }

    for (NameValuePair pair : wsParamsList) {
        reqEntity.addPart(pair.getName(), new StringBody(pair.getValue()));
    }
    reqEntity.addPart("data", new FileBody(fileToUpload));

    String postUrl = targetUrl + "?module=" + moduleName + "&op=" + op;
    HttpPost post = new HttpPost(postUrl);
    post.setEntity(reqEntity);

    return processServerPost(post);
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * uploads measurements data as a batch file
 * @param dbIterator//w w  w  .  ja v a2 s  . c om
 * @param latLonFormat
 * @param count
 * @param max
 * @return number of uploaded measurements
 */
private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count,
        int max) {
    writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")");

    try {
        StringBuilder sb = new StringBuilder(
                "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n");

        int thisBatchSize = 0;
        while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) {
            Measurement meassurement = dbIterator.next();

            sb.append(latLonFormat.format(meassurement.getLat())).append(",");
            sb.append(latLonFormat.format(meassurement.getLon())).append(",");
            sb.append(meassurement.getMcc()).append(",");
            sb.append(meassurement.getMnc()).append(",");
            sb.append(meassurement.getLac()).append(",");
            sb.append(meassurement.getCellid()).append(",");
            sb.append(meassurement.getGsmSignalStrength()).append(",");
            sb.append(meassurement.getTimestamp()).append(",");
            sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(",");
            sb.append((int) meassurement.getSpeed()).append(",");
            sb.append((int) meassurement.getBearing()).append(",");
            sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : "");
            sb.append("\n");

            thisBatchSize++;
        }

        HttpResponse response = null;

        writeToLog("Upload request URL: " + httppost.getURI());

        if (uploadThreadRunning) {
            String csv = sb.toString();

            writeToLog("Upload data: " + csv);

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("key", new StringBody(apiKey));
            mpEntity.addPart("appId", new StringBody(appId));
            mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()),
                    "text/csv", MULTIPART_FILENAME));

            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            // reqEntity is the MultipartEntity instance
            mpEntity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
            bArrEntity.setContentType(mpEntity.getContentType());

            httppost.setEntity(bArrEntity);

            response = httpclient.execute(httppost);
            if (response == null) {
                writeToLog("Upload: null HTTP-response");
                throw new IllegalStateException("no HTTP-response from server");
            }

            HttpEntity resEntity = response.getEntity();

            writeToLog(
                    "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine());

            if (resEntity != null) {
                resEntity.consumeContent();
            }

            if (response.getStatusLine() == null) {
                writeToLog(": " + "null HTTP-status-line");
                throw new IllegalStateException("no HTTP-status returned");
            }

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IllegalStateException(
                        "HTTP-status code returned : " + response.getStatusLine().getStatusCode());
            }
        }

        return count + thisBatchSize;

    } catch (IOException e) {
        throw new IllegalStateException("IO-Error: " + e.getMessage());
    }
}

From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java

public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException {
    HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());

    //   nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
    //   for (int i = 0; i < parametres.length; i += 2) {
    //       nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
    //   }/* w ww.ja  v a  2s.c om*/
    //   method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    if (file != null) {
        MultipartEntity multipartEntity = new MultipartEntity();

        //      String string = nameValuePairs.toString();
        // dirty fix to remove the enclosing entity{}
        //      String substring = string.substring(string.indexOf("{"),
        //            string.lastIndexOf("}") + 1);
        try {
            multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel()));
            multipartEntity.addPart("category", new StringBody(category.toString()));
            multipartEntity.addPart("name", new StringBody(title));
            if (level != null) {
                multipartEntity.addPart("level", new StringBody(level.toString()));
            }
        } catch (UnsupportedEncodingException e) {
            throw new JiwigoException(e);
        }

        //      StringBody contentBody = new StringBody(substring,
        //            Charset.forName("UTF-8"));
        //      multipartEntity.addPart("entity", contentBody);
        FileBody fileBody = new FileBody(file);
        multipartEntity.addPart("image", fileBody);
        ((HttpPost) httpMethod).setEntity(multipartEntity);
    }

    HttpResponse response;
    StringBuilder sb = new StringBuilder();
    try {
        response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);

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

        switch (responseStatusCode) {
        case HttpURLConnection.HTTP_CREATED:
            break;
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new JiwigoException("status code was : " + responseStatusCode);
        default:
            throw new JiwigoException("status code was : " + responseStatusCode);
        }

        HttpEntity resultEntity = response.getEntity();
        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);

        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            reader.close();
        }
    } catch (ClientProtocolException e) {
        throw new JiwigoException(e);
    } catch (IOException e) {
        throw new JiwigoException(e);
    }
    String stringResult = sb.toString();

}

From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java

private RestResponse postMultiPartRequest(File bagitFile) {
    HttpClient httpclient = new DefaultHttpClient();
    FileBody uploadFilePart = new FileBody(bagitFile);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("upload-file", uploadFilePart);
    HttpPost httpPost = new HttpPost(DOCSTORE_URL + LICENSES_URL);
    httpPost.setEntity(reqEntity);/*from  w  w w.  j av  a  2s . c  o  m*/
    httpPost.addHeader("multipart/form-data", "text/xml");
    RestResponse restResponse = new RestResponse();
    try {
        EntityUtils.consume(reqEntity);
        HttpResponse response = httpclient.execute(httpPost);
        restResponse.setResponse(response);
        restResponse.setResponseBody(getEncodeEntityValue(response.getEntity()));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return restResponse;
}