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

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

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

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. ja v  a2s.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;
}

From source file:ch.tatool.app.export.ServerDataExporter.java

private HttpEntity getHttpEntity(Module module, int fromSessionIndex, String filename, File tmpFile) {
    // we use a multipart entity to send over the files
    MultipartEntity entity = new MultipartEntity();

    // get tatool online information for module
    Map<String, String> moduleProperties = module.getModuleProperties();
    String subjectCode = moduleProperties.get(Module.PROPERTY_MODULE_CODE);
    if (subjectCode == null || subjectCode.isEmpty()) {
        subjectCode = module.getUserAccount().getName();
    }/*from w  w w  .j  a  va  2 s . c om*/

    String moduleID = moduleProperties.get(Module.PROPERTY_MODULE_ID);

    // InputStreamBody does not provide a content length (-1), so the server complains about the request length not
    // being defined. FileBody does not allow setting the name (which is different from the temp file name
    // Easiest solution: subclass of FileBody that allows overwriting the filename with a new one
    FileBodyExt fileBody = new FileBodyExt(tmpFile);
    fileBody.setFilename(filename);
    entity.addPart("file", fileBody);

    // add some additional data
    try {
        Charset utf8CharSet = Charset.forName("UTF-8");
        entity.addPart("fromSessionIndex", new StringBody(String.valueOf(fromSessionIndex), utf8CharSet));
        entity.addPart("subjectCode", new StringBody(subjectCode, utf8CharSet));
        entity.addPart("moduleID", new StringBody(moduleID, utf8CharSet));
    } catch (UnsupportedEncodingException e) {
        // should not happen
        logger.error("Unable to set write form parts", e);
    } catch (IllegalArgumentException e) {
        // should not happen
        logger.error("Missing settings for tatool online", e);
        return null;
    }

    return entity;
}

From source file:com.stepsdk.android.api.APIClient.java

public HttpEntity postRequest(String url, Map<String, String> params, Map<String, String> files)
        throws NetworkDownException, HttpGetException, HttpPostException, IOException {

    MultipartEntity mpEntity = new CountingMultipartEntity(new ProgressListener() {
        private int prevPercentage = 0;

        @Override//from w  w  w. j  a  v a2 s  .  co m
        public void transferred(long num) {
            int percentage = (int) num;
            if (percentage > prevPercentage) {
                prevPercentage = percentage;
            }
        }
    });

    Iterator<Entry<String, String>> i = params.entrySet().iterator();
    while (i.hasNext()) {
        Entry<String, String> next = i.next();
        mpEntity.addPart(next.getKey(), new StringBody(next.getValue()));
    }

    i = files.entrySet().iterator();
    while (i.hasNext()) {
        Entry<String, String> next = i.next();
        mpEntity = addFile(mpEntity, next.getKey(), next.getValue());
    }

    HttpEntity response = httpPost(url, mpEntity);
    return response;
}

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

private MultipartEntity getMultipartEntity(API api, String externalPublisher, String action)
        throws org.wso2.carbon.registry.api.RegistryException, IOException, UserStoreException,
        APIManagementException {/*from ww w. ja  v a 2s.  co  m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

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

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

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

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

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

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

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

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

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

From source file:com.poomoo.edao.activity.UploadPicsActivity.java

private void upload(File file) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(eDaoClientConfig.imageurl); // ?Post?,Post
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, eDaoClientConfig.timeout);
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, eDaoClientConfig.timeout);

    MultipartEntity entity = new MultipartEntity(); // ,
    // List<File> list = new ArrayList<File>();
    // // File//from w ww  .j av  a 2 s  .  co  m
    // list.add(file1);
    // list.add(file2);
    // list.add(file3);
    // list.add(file4);
    // System.out.println("list.size():" + list.size());
    // for (int i = 0; i < list.size(); i++) {
    // ContentBody body = new FileBody(list.get(i));
    // entity.addPart("file", body); // ???
    // }
    System.out.println(
            "upload" + "uploadCount" + ":" + uploadCount + "filelist.size" + ":" + filelist.size());
    entity.addPart("file", new FileBody(file));

    post.setEntity(entity); // ?Post?
    Message message = new Message();
    try {
        entity.addPart("imageType", new StringBody(String.valueOf(uploadCount + 1), Charset.forName("utf-8")));
        entity.addPart("userId", new StringBody(userId, Charset.forName("utf-8")));
        HttpResponse response;
        response = client.execute(post);
        // Post
        if (response.getStatusLine().getStatusCode() == 200) {
            uploadCount++;
            message.what = 1;
        } else
            message.what = 2;
        // return EntityUtils.toString(response.getEntity(), "UTF-8"); //
        // ??
    } catch (Exception e) {
        // TODO ? catch ?
        e.printStackTrace();
        message.what = 2;
        System.out.println("IOException:" + e.getMessage());
    } finally {
        client.getConnectionManager().shutdown(); // ?
        myHandler.sendMessage(message);
    }
}

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

/**
 * Synchronously augment an image towards a list of sites
 * /* w  w  w.  ja  va2s. c  om*/
 * @param image
 *            an inputstream containing the image
 * @return the augmented data
 */
public AugmentedData augmentImageGroup(List<String> sites, InputStream image) {
    Map<String, String> params = new HashMap<String, String>();

    MultipartEntity imageEntity = new MultipartEntity();
    InputStreamBody imageInputStreamBody = new InputStreamBody(image, "image");
    imageEntity.addPart("image", imageInputStreamBody);

    for (String siteId : sites) {
        try {
            imageEntity.addPart("site", new StringBody(siteId));
        } catch (UnsupportedEncodingException e) {
            throw new ARException(e);
        }
    }

    HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature);
    HttpResponse serverResponse = httpUtils
            .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_PATH, imageEntity, params);

    HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode());

    ARResponseHandler responseHandler = new ARResponseHandlerImpl();
    AugmentImageGroupResponse augmentImageGroupResponse = responseHandler.handleResponse(serverResponse,
            AugmentImageGroupResponse.class);

    if (augmentImageGroupResponse.getSuccess() == false) {
        throw new ARException(
                "Successfully communicated with the server, failed to augment the image. Perhaps the site does not exist or has no overlays.");
    }

    //      List<AugmentedData> result = new ArrayList<AugmentedData>();
    //      for(SiteImageBundle bundle : augmentImageGroupResponse.getCandidates()) {
    //         AugmentedData augmentedImage = null;
    //         while (augmentedImage == null) {
    //            augmentedImage = getAugmentResult(bundle.getSite(), bundle.getImgId());
    //         }
    //         result.add(augmentedImage);
    //      }
    List<AugmentedData> result = getAugmentedImageGroupResult(augmentImageGroupResponse.getSitesToCheck(),
            augmentImageGroupResponse.getImgId());

    // combine different results
    AugmentedData finalData = null;
    for (AugmentedData data : result) {
        if (data.isLocalization()) {
            if (finalData == null) {
                finalData = data;
            } else {
                finalData.getOverlays().addAll(data.getOverlays());
            }
        }
    }

    return finalData;
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java

private MultipartEntity createLoginPasswordSSHKeyMultipart(String login, String pass, String ssh)
        throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("username", new StringBody(login));
    entity.addPart("password", new StringBody(pass));

    if (ssh != null && !ssh.isEmpty()) {
        entity.addPart("sshKey", new ByteArrayBody(ssh.getBytes(), MediaType.APPLICATION_OCTET_STREAM, null));
    }/*from  w  ww.  j av  a  2  s  .c  o  m*/

    return entity;
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java

/**
 * Submits a XML file to the REST part by using an HTTP client.
 *
 * @param sessionId the id of the client which submits the job
 * @param file      the XML file that is submitted
 * @return an error message upon failure, "id=<jobId>" upon success
 * @throws RestServerException/*from w  ww  .  j av a  2 s. com*/
 * @throws ServiceException
 */
public String submitXMLFile(String sessionId, File file) throws RestServerException, ServiceException {
    HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/submit");
    method.addHeader("sessionId", sessionId);

    boolean isJar = isJarFile(file);

    try {
        String name = isJar ? "jar" : "file";
        String mime = isJar ? "application/java-archive" : "application/xml";
        String charset = "ISO-8859-1";

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(file, name, mime, charset));
        method.setEntity(entity);

        HttpResponse execute = httpClient.execute(method);
        InputStream is = execute.getEntity().getContent();
        String ret = convertToString(is);

        if (execute.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
            return ret;
        } else {
            throw new RestServerException(execute.getStatusLine().getStatusCode(), ret);
        }
    } catch (IOException e) {
        throw new ServiceException("Failed to read response: " + e.getMessage());
    } finally {
        method.releaseConnection();
        if (file != null) {
            file.delete();
        }
    }
}

From source file:duthientan.mmanm.com.Main.java

private void btnUploadFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadFileActionPerformed
    // TODO add your handling code here:
    if (!fileUploadPath.equals("")) {
        progressBarCipher.setIndeterminate(true);
        new Thread(new Runnable() {
            @Override/*w w  w.j  a v  a2 s .c o m*/
            public void run() {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                            HttpVersion.HTTP_1_1);
                    HttpPost httppost = new HttpPost("http://localhost:4000/api/upload");
                    File file = new File(fileUploadPath);
                    MultipartEntity mpEntity = new MultipartEntity();
                    ContentBody cbFile = new FileBody(file);
                    mpEntity.addPart("files", cbFile);
                    httppost.addHeader("id", id);
                    httppost.addHeader("x-access-token", token);
                    httppost.setEntity(mpEntity);
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity resEntity = response.getEntity();
                    progressBarCipher.setIndeterminate(false);
                    JFrame frame = new JFrame("Upload Completed");
                    JOptionPane.showMessageDialog(frame, "File Uploaded");
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    } else {
        JFrame frame = new JFrame("File not Found");
        JOptionPane.showMessageDialog(frame, "Plase Choice File Upload");
    }
}