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:bluej.collect.DataCollectorImpl.java

public static void codePadException(Package pkg, String command, String exception) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[codepad][outcome]", CollectUtility.toBody("exception"));
    mpe.addPart("event[codepad][command]", CollectUtility.toBody(command));
    mpe.addPart("event[codepad][exception]", CollectUtility.toBody(exception));
    submitEvent(pkg.getProject(), pkg, EventName.CODEPAD, new PlainEvent(mpe));
}

From source file:com.makotosan.vimeodroid.vimeo.Methods.java

public void uploadFile(String endpoint, String ticketId, File file, String filename, ProgressListener listener,
        OnTransferringHandler handler) throws OAuthMessageSignerException, OAuthExpectationFailedException,
        OAuthCommunicationException, ClientProtocolException, IOException {
    // final int chunkSize = 512 * 1024; // 512 kB
    // final long pieces = file.length() / chunkSize;
    int chunkId = 0;

    final HttpPost request = new HttpPost(endpoint);

    // BufferedInputStream stream = new BufferedInputStream(new
    // FileInputStream(file));

    // for (chunkId = 0; chunkId < pieces; chunkId++) {
    // byte[] buffer = new byte[chunkSize];

    // stream.skip(chunkId * chunkSize);

    // stream.read(buffer);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("chunk_id", new StringBody(String.valueOf(chunkId)));
    entity.addPart("ticket_id", new StringBody(ticketId));
    request.setEntity(new CountingRequestEntity(entity, listener)); // ,
    // chunkId//from   w ww .  j  a  v  a 2s. c  o  m
    // *
    // chunkSize));
    // ByteArrayInputStream arrayStream = new ByteArrayInputStream(buffer);

    Authentication.signRequest(getConsumerInfo(), request);

    entity.addPart("file_data", new FileBody(file));
    // entity.addPart("file_data", new InputStreamBody(arrayStream,
    // filename));

    final HttpClient client = app.getHttpClient();

    handler.onTransferring(request);
    final HttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        responseEntity.consumeContent();
    }
    // }
}

From source file:com.parworks.androidlibrary.ar.ARSiteImpl.java

private MultipartEntity getEntityFromVertices(List<Vertex> vertices) {
    MultipartEntity entity = new MultipartEntity();

    for (Vertex currentVertex : vertices) {
        try {//from   www. j  av  a 2  s . c o m
            entity.addPart("v",
                    new StringBody((int) currentVertex.getxCoord() + "," + (int) currentVertex.getyCoord()));
        } catch (UnsupportedEncodingException e) {
            throw new ARException(e);
        }
    }
    return entity;
}

From source file:bluej.collect.DataCollectorImpl.java

public static void renamedClass(Package pkg, final File oldSourceFile, final File newSourceFile) {
    final ProjectDetails projDetails = new ProjectDetails(pkg.getProject());
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("rename"));
    mpe.addPart("source_histories[][content]", CollectUtility.toBodyLocal(projDetails, oldSourceFile));
    mpe.addPart("source_histories[][name]", CollectUtility.toBodyLocal(projDetails, newSourceFile));
    submitEvent(pkg.getProject(), pkg, EventName.RENAME, new PlainEvent(mpe) {

        @Override/*w w w  .j  a v  a  2 s .  c  om*/
        public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) {
            // We need to change the fileVersions hash to move the content across from the old file
            // to the new file:
            FileKey oldKey = new FileKey(projDetails, CollectUtility.toPath(projDetails, oldSourceFile));
            FileKey newKey = new FileKey(projDetails, CollectUtility.toPath(projDetails, newSourceFile));
            fileVersions.put(newKey, fileVersions.get(oldKey));
            fileVersions.remove(oldKey);
            return super.makeData(sequenceNum, fileVersions);
        }

    });
}

From source file:org.openremote.modeler.service.impl.ResourceServiceImpl.java

public void saveTemplateResourcesToBeehive(Template template) {
    boolean share = template.getShareTo() == Template.PUBLIC;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();
    String beehiveRootRestURL = configuration.getBeehiveRESTRootUrl();
    String url = "";
    if (!share) {
        url = beehiveRootRestURL + "account/" + userService.getAccount().getOid() + "/template/"
                + template.getOid() + "/resource/";
    } else {/*  w  ww  . j av  a 2  s . c  o m*/
        url = beehiveRootRestURL + "account/0/template/" + template.getOid() + "/resource/";
    }
    try {
        httpPost.setURI(new URI(url));
        File templateZip = getTemplateResource(template);
        if (templateZip == null) {
            serviceLog.warn("There are no template resources for template \"" + template.getName()
                    + "\"to save to beehive!");
            return;
        }
        FileBody resource = new FileBody(templateZip);
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("resource", resource);

        this.addAuthentication(httpPost);
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);

        if (200 != response.getStatusLine().getStatusCode()) {
            throw new BeehiveNotAvailableException("Failed to save template to Beehive, status code: "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (NullPointerException e) {
        serviceLog.warn("There are no template resources for template \"" + template.getName()
                + "\"to save to beehive!");
    } catch (IOException e) {
        throw new BeehiveNotAvailableException("Failed to save template to Beehive", e);
    } catch (URISyntaxException e) {
        throw new IllegalRestUrlException(
                "Invalid Rest URL: " + url + " to save template resource to beehive! ", e);
    }
}

From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java

private JobInfo send(final File metadataFile, final BinaryData binaryData, final Collection<File> studyFiles,
        final StudyQueryInfo studyQueryInfo) throws IOException, SAXException {
    final HttpPost httpPost = new HttpPost(studyQueryInfo == null ? createURI : updateURI);
    final MultipartEntity entity = new MultipartEntity();

    if (studyQueryInfo != null) {
        entity.addPart(HttpMessagePart.STUDY_UUID.toString(), new StringBody(studyQueryInfo.studyUUID));
    }/* w ww .j  ava  2 s . c  o m*/

    final StudyMetadata study = useXMLNotGPB ? StudyIO.parseFromXML(metadataFile)
            : StudyIO.parseFromGPB(metadataFile);
    if (studyQueryInfo != null) {
        //Specify current study version
        entity.addPart(HttpMessagePart.OLD_VERSION.toString(), new StringBody(studyQueryInfo.studyVersion));
    }

    //Pretty significant in-memory operations, so scoping to get references released ASAP
    {
        final byte[] metaInBuffer;
        {
            final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(10000);
            if (useXMLNotGPB) {
                StudyIO.writeToXML(study, metaOut);
            } else {
                StudyIO.writeToGPB(study, metaOut);
            }
            metaInBuffer = metaOut.toByteArray();
        }
        final ByteArrayInputStream metaIn = new ByteArrayInputStream(metaInBuffer);
        //We must distinguish MIME types for GPB vs. XML so that the server can handle them properly
        entity.addPart(metadataFile.getName(), new InputStreamBody(metaIn,
                useXMLNotGPB ? "text/xml" : "application/octet-stream", metadataFile.getName()));
    }

    //We support only one type
    assert binaryData instanceof BinaryDcmData;
    {
        int i = 0;
        for (final InputStream binaryStream : iter(((BinaryDcmData) binaryData).streamIterator())) {
            final String fileName = "binary" + i++;
            entity.addPart(fileName, new InputStreamBody(binaryStream, fileName));
        }
    }

    //Debugging only
    //        int i = 0;
    //        for (final InputStream binaryStream: Iter.iter(((BinaryDcmData) binaryData).streamIterator())) {
    //            final OutputStream testout = new BufferedOutputStream(new FileOutputStream("E:/testdata/" + i), 10000);
    //            for(;;) {
    //                final int val = binaryStream.read();
    //                if (val == -1) {
    //                    break;
    //                }
    //                testout.write(val);
    //            }
    //            testout.close();
    //            ++i;
    //        }

    httpPost.setEntity(entity);

    final String response = httpClient.execute(httpPost, new BasicResponseHandler());
    final long uploadEndTime = System.currentTimeMillis();

    LOG.debug("Server response:" + response);

    final String jobID;
    final String studyID;
    final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes()));
    try {
        jobID = xPath.evaluate("/jobStatus/@jobID", responseDoc).trim();
        studyID = xPath.evaluate("/jobStatus/@studyUUID", responseDoc).trim();
    } catch (final XPathExpressionException e) {
        //This shouldn't happen
        throw new RuntimeException(e);
    }
    final JobInfo jobInfo = new JobInfo(jobID, studyID, studyFiles, uploadEndTime);
    jobIDInfo.put(jobID, jobInfo);
    return jobInfo;
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendObjectMap(Map<String, Object> fileMap, String serverURL) throws Exception {
    log.info("sendObjectMap - serverURL: " + serverURL);
    ResponseVS responseVS = null;//from  ww w.j  a  v  a2  s  .com
    if (fileMap == null || fileMap.isEmpty())
        throw new Exception(ContextVS.getInstance().getMessage("requestWithoutFileMapErrorMsg"));
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    ContentTypeVS responseContentType = null;
    try {
        httpPost = new HttpPost(serverURL);
        Set<String> fileNames = fileMap.keySet();
        MultipartEntity reqEntity = new MultipartEntity();
        for (String objectName : fileNames) {
            Object objectToSend = fileMap.get(objectName);
            if (objectToSend instanceof File) {
                File file = (File) objectToSend;
                log.info("sendObjectMap - fileName: " + objectName + " - filePath: " + file.getAbsolutePath());
                FileBody fileBody = new FileBody(file);
                reqEntity.addPart(objectName, fileBody);
            } else if (objectToSend instanceof byte[]) {
                byte[] byteArray = (byte[]) objectToSend;
                reqEntity.addPart(objectName, new ByteArrayBody(byteArray, objectName));
            }
        }
        httpPost.setEntity(reqEntity);
        response = httpClient.execute(httpPost);
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - contentTypeVS: " + responseContentType
                + " - connManager stats: " + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        String statusLine = null;
        if (response != null)
            statusLine = response.getStatusLine().toString();
        log.log(Level.SEVERE, ex.getMessage() + " - StatusLine: " + statusLine, ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:sjizl.com.FileUploadTest.java

private void doFileUpload(String path) {

    String username = "";
    String password = "";
    String foto = "";
    String foto_num = "";
    SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
    username = sp.getString("username", null);
    password = sp.getString("password", null);
    foto = sp.getString("foto", null);
    foto_num = sp.getString("foto_num", null);

    File file1 = new File(path);

    String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password="
            + password;/*from  w w w . java 2  s.  c o  m*/
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);
        FileBody bin1 = new FileBody(file1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploadedfile1", bin1);

        reqEntity.addPart("user", new StringBody("User"));
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);
        if (resEntity != null) {
            Log.i("RESPONSE", response_str);
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        // res.setTextColor(Color.GREEN);
                        // res.setText("n Response from server : n " + response_str);

                        CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                                "Upload Complete! ", null, R.drawable.iconbd);

                        Brows();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    } catch (Exception ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }

    //RegisterActivity.login(username,password,getApplicationContext());

}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * Update users current location//from w  ww . j  av  a2s.c o  m
 * 
 * @param userId
 *            The users id.
 * 
 * @param secureToken
 *            The users secureToken.
 * @param latitude
 * @param longitude
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderHTTPException
 */
public void updateUser(String userId, String secureToken, double latitude, double longitude)
        throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException {
    try {
        HttpClient httpClient = getNewHttpClient();
        HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId);
        httpput.addHeader(getAuthenticationHeader(userId, secureToken));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.LATITUDE,
                new StringBody(String.valueOf(latitude), Charset.forName(JOConfig.UTF_8)));
        entity.addPart(JOConfig.LONGITUDE,
                new StringBody(String.valueOf(longitude), Charset.forName(JOConfig.UTF_8)));

        httpput.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpput);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];/* w  ww  . j av a2  s.c  o  m*/
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}