Example usage for org.apache.http.entity.mime MultipartEntityBuilder build

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:be.ugent.psb.coexpnetviz.io.JobServer.java

private HttpEntity makeRequestEntity(JobDescription job) throws UnsupportedEncodingException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    // Action to request of server
    entityBuilder.addTextBody("__controller", "api");
    entityBuilder.addTextBody("__action", "execute_job");

    // Baits //w w  w .j a va 2s  . c  o m
    if (job.getBaitGroupSource() == BaitGroupSource.FILE) {
        entityBuilder.addBinaryBody("baits_file", job.getBaitGroupPath().toFile(), ContentType.TEXT_PLAIN,
                job.getBaitGroupPath().getFileName().toString());
    } else if (job.getBaitGroupSource() == BaitGroupSource.TEXT) {
        entityBuilder.addTextBody("baits", job.getBaitGroupText());
    } else {
        assert false;
    }

    // Expression matrices
    for (Path path : job.getExpressionMatrixPaths()) {
        entityBuilder.addBinaryBody("matrix[]", path.toFile(), ContentType.TEXT_PLAIN, path.toString());
    }

    // Correlation method
    String correlationMethod = null;
    if (job.getCorrelationMethod() == CorrelationMethod.MUTUAL_INFORMATION) {
        correlationMethod = "mutual_information";
    } else if (job.getCorrelationMethod() == CorrelationMethod.PEARSON) {
        correlationMethod = "pearson_r";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("correlation_method", correlationMethod);

    // Cutoffs
    entityBuilder.addTextBody("lower_percentile_rank", Double.toString(job.getLowerPercentile()));
    entityBuilder.addTextBody("upper_percentile_rank", Double.toString(job.getUpperPercentile()));

    // Gene families source
    String orthologsSource = null;
    if (job.getGeneFamiliesSource() == GeneFamiliesSource.PLAZA) {
        orthologsSource = "plaza";
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.CUSTOM) {
        orthologsSource = "custom";
        entityBuilder.addBinaryBody("gene_families", job.getGeneFamiliesPath().toFile(), ContentType.TEXT_PLAIN,
                job.getGeneFamiliesPath().getFileName().toString());
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.NONE) {
        orthologsSource = "none";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("gene_families_source", orthologsSource);

    return entityBuilder.build();
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

@Override
public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz)
        throws RestEndpointIOException {
    HttpPost post = new HttpPost(spliceUrl(resource));

    try {/*from  w w w .  j  av a2s . co m*/

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) {
            Serializer serializer = getSupportedSerializer(serializedPart);
            builder.addPart(serializedPart.getPartName(),
                    new StringBody(new String(serializer.serialize(serializedPart.getRequest())),
                            ContentType.parse(serializer.getMimeType())));
        }

        for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) {
            builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(),
                    ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename()));
        }

        /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client
         *  Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426
         *
         *  The main idea is to replace MultipartEntity with NByteArrayEntity once first
         * doesn't support #getContent method
         *  which is required for async client implementation. So, we are copying response
         *  body as byte array to NByteArrayEntity to
         *  leave it unmodified.
         *
         *  Alse we need to add boundary value to content type header. Details are here:
         *  http://en.wikipedia.org/wiki/Delimiter#Content_boundary
         *  MultipartEntity generates correct header by yourself, but we need to put it
         *  manually once we replaced entity type to NByteArrayEntity
         */
        String boundary = "-------------" + UUID.randomUUID().toString();
        builder.setBoundary(boundary);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        builder.build().writeTo(baos);

        post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA));
        post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary);

    } catch (Exception e) {
        throw new RestEndpointIOException("Unable to build post multipart request", e);
    }
    return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz));
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#unlock(org.opentravel.schemacompiler.repository.RepositoryItem,
 *      boolean)//from   ww w .ja  v a  2s  . c o m
 */
@SuppressWarnings("unchecked")
@Override
public void unlock(RepositoryItem item, boolean commitWIP) throws RepositoryException {
    InputStream wipContent = null;
    boolean success = false;
    try {
        validateRepositoryItem(item);
        manager.getFileManager().startChangeSet();

        // Build the HTTP request for the remote service
        RepositoryItemIdentityType itemIdentity = createItemIdentity(item);
        Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller();
        HttpPost request = newPostRequest(UNLOCK_ENDPOINT);

        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        StringWriter xmlWriter = new StringWriter();

        if (commitWIP) {
            File wipFile = manager.getFileManager().getLibraryWIPContentLocation(item.getBaseNamespace(),
                    item.getFilename());

            if (!wipFile.exists()) {
                throw new RepositoryException("The work-in-process file does not exist: " + item.getFilename());
            }
            wipContent = new FileInputStream(wipFile);
            mpEntity.addBinaryBody("fileContent", toByteArray(wipContent), ContentType.DEFAULT_BINARY,
                    item.getFilename());
            // mpEntity.addPart( "fileContent", new InputStreamBody(wipContent,
            // item.getFilename()) );
        }
        marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter);
        mpEntity.addTextBody("item", xmlWriter.toString(), ContentType.TEXT_XML);
        request.setEntity(mpEntity.build());

        // Send the web service request and unmarshall the updated meta-data from the response
        log.info("Sending lock request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(request);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Lock response received - Status OK");

        Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller();
        JAXBElement<LibraryInfoType> jaxbElement = (JAXBElement<LibraryInfoType>) unmarshaller
                .unmarshal(response.getEntity().getContent());

        // Update the local cache with the content we just received from the remote web service
        manager.getFileManager().saveLibraryMetadata(jaxbElement.getValue());

        // Update the local repository item with the latest state information
        ((RepositoryItemImpl) item).setState(RepositoryItemState.MANAGED_UNLOCKED);
        ((RepositoryItemImpl) item).setLockedByUser(null);

        // Force a re-download of the updated content to make sure the local copy is
        // synchronized
        // with the remote repository.
        downloadContent(item, true);

        success = true;

    } catch (JAXBException e) {
        throw new RepositoryException("The format of the library meta-data is unreadable.", e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        // Close the WIP content input stream
        try {
            if (wipContent != null)
                wipContent.close();
        } catch (Throwable t) {
        }

        // Commit or roll back the changes based on the result of the operation
        if (success) {
            manager.getFileManager().commitChangeSet();
        } else {
            try {
                manager.getFileManager().rollbackChangeSet();
            } catch (Throwable t) {
                log.error("Error rolling back the current change set.", t);
            }
        }
    }
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the general MAUS service, for forced alignment given a WAV file and a phonemic transcription.
 * @param LANGUAGE <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param SIGNAL The signal, in WAV format.
 * @param BPF Phonemic transcription of the utterance to be segmented. Format is a <a href="http://www.bas.uni-muenchen.de/forschung/Bas/BasFormatseng.html">BAS Partitur Format (BPF)</a> file with a KAN tier.
 * @param MINPAUSLEN Controls the behaviour of optional inter-word silence. If set to 1, maus will detect all inter-word silence intervals that can be found (minimum length for a silence interval is then 10 msec = 1 frame). If set to values n&gt;1, the minimum length for an inter-word silence interval to be detected is set to n&times;10 msec.
 * @param STARTWORD If set to a value n&gt;0, this option causes maus to start the segmentation with the word number n (word numbering in BPF starts with 0).
 * @param ENDWORD If set to a value n&lt;999999, this option causes maus to end the segmentation with the word number n (word numbering in BPF starts with 0). 
 * @param RULESET MAUS rule set file; UTF-8 encoded; one rule per line; two different file types defined by the extension: '*.nrul' : phonological rule set without statistical information
 * @param OUTFORMAT Defines the output format:
 *  <ul>// ww  w  . ja  v a 2s .c o m
 *   <li>"TextGrid" - a praat compatible TextGrid file</li> 
 *   <li>"par" or "mau-append" - the input BPF file with a new (or replaced) tier MAU</li>
 *   <li>"csv" or "mau" - only the BPF MAU tier (CSV table)</li> 
 *   <li>"legacyEMU" - a file with extension *.EMU that contains in the first part the Emu hlb file (*.hlb) and in the second part the Emu phonetic segmentation (*.phonetic)</li>
 *   <li>emuR - an Emu compatible *_annot.json file</li>
 *  </ul>
 * @param MAUSSHIFT If set to n, this option causes the calculated MAUS segment boundaries to be shifted by n msec (default: 10) into the future.
 * @param INSPROB The option INSPROB influences the probability of deletion of segments. It is a constant factor (a constant value added to the log likelihood score) after each segment. Therefore, a higher value of INSPROB will cause the probability of segmentations with more segments go up, thus decreasing the probability of deletions (and increasing the probability of insertions, which are rarely modelled in the rule sets).
 * @param INSKANTEXTGRID Switch to create an additional tier in the TextGrid output file with a word segmentation labelled with the canonic phonemic transcript.
 * @param INSORTTEXTGRID Switch to create an additional tier ORT in the TextGrid output file with a word segmentation labelled with the orthographic transcript (taken from the input ORT tier)
 * @param USETRN  If set to true, the service searches the input BPF for a TRN tier. The synopsis for a TRN entry is: 'TRN: (start-sample) (duration-sample) (word-link-list) (label)', e.g. 'TRN: 23654 56432 0,1,2,3,4,5,6 sentence1' (the speech within the recording 'sentence1' starts with sample 23654, last for 56432 samples and covers the words 0-6). If only one TRN entry is found, the segmentation is restricted within a time range given by this TRN tier entry.
 * @param OUTSYMBOL Defines the encoding of phonetic symbols in output. 
 *  <ul>
 *   <li>"sampa" - (default), phonetic symbols are encoded in language specific SAM-PA (with some coding differences to official SAM-PA</li>
 *   <li>"ipa" - the service produces UTF-8 IPA output.</li> 
 *   <li>"manner" - the service produces IPA manner of articulation for each segment; possible values are: silence, vowel, diphthong, plosive, nasal, fricative, affricate, approximant, lateral-approximant, ejective.</li>
 *   <li>"place" - the service produces IPA place of articulation for each segment; possible values are: silence, labial, dental, alveolar, post-alveolar, palatal, velar, uvular, glottal, front, central, back.</li> </ul>
 * @param NOINITIALFINALSILENCE Switch to suppress the automatic modeling on a leading/trailing silence interval. 
 * @param WEIGHT weights the influence of the statistical pronunciation model against the acoustical scores. More precisely WEIGHT is multiplied to the pronunciation model score (log likelihood) before adding the score to the acoustical score within the search. Since the pronunciation model in most cases favors the canonical pronunciation, increasing WEIGHT will at some point cause MAUS to choose always the canonical pronunciation; lower values of WEIGHT will favor less probable paths be selected according to acoustic evidence
 * @param MODUS Operation modus of MAUS: 
 *  <ul>
 *   <li>"standard" (default) - the segmentation and labelling using the MAUS technique as described in Schiel ICPhS 1999.</li> 
 *   <li>"align" - a forced alignment is performed on the input SAM-PA string defined in the KAN tier of the BPF.</li>
 * </ul>
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured.
 */
public BASResponse MAUS(String LANGUAGE, InputStream SIGNAL, InputStream BPF, String OUTFORMAT,
        String OUTSYMBOL, Integer MINPAUSLEN, Integer STARTWORD, Integer ENDWORD, InputStream RULESET,
        Integer MAUSSHIFT, Double INSPROB, Boolean INSKANTEXTGRID, Boolean INSORTTEXTGRID, Boolean USETRN,
        Boolean NOINITIALFINALSILENCE, Double WEIGHT, String MODUS)
        throws IOException, ParserConfigurationException {
    if (OUTSYMBOL == null)
        OUTSYMBOL = "sampa";
    // "40 msec seems to be the border of perceivable silence, we set this option default to 5"
    if (MINPAUSLEN == null)
        MINPAUSLEN = 5;
    HttpPost request = new HttpPost(getMAUSUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("LANGUAGE", languageTagger.tag(LANGUAGE))
            .addBinaryBody("SIGNAL", SIGNAL, ContentType.create("audio/wav"), "BAS.wav")
            .addBinaryBody("BPF", BPF, ContentType.create("text/plain-bas"), "BAS.par")
            .addTextBody("OUTFORMAT", OUTFORMAT).addTextBody("OUTSYMBOL", OUTSYMBOL);
    if (USETRN != null)
        builder.addTextBody("USETRN", USETRN.toString());
    if (MINPAUSLEN != null)
        builder.addTextBody("MINPAUSLEN", MINPAUSLEN.toString());
    if (STARTWORD != null)
        builder.addTextBody("STARTWORD", STARTWORD.toString());
    if (ENDWORD != null)
        builder.addTextBody("ENDWORD", ENDWORD.toString());
    if (RULESET != null)
        builder.addBinaryBody("RULESET", RULESET, ContentType.create("text/plain"), "RULESET.txt");
    if (MAUSSHIFT != null)
        builder.addTextBody("MAUSSHIFT", MAUSSHIFT.toString());
    if (INSPROB != null)
        builder.addTextBody("INSPROB", INSPROB.toString());
    if (INSKANTEXTGRID != null)
        builder.addTextBody("INSKANTEXTGRID", INSKANTEXTGRID.toString());
    if (INSORTTEXTGRID != null)
        builder.addTextBody("INSORTTEXTGRID", INSORTTEXTGRID.toString());
    if (NOINITIALFINALSILENCE != null)
        builder.addTextBody("NOINITIALFINALSILENCE", NOINITIALFINALSILENCE.toString());
    if (WEIGHT != null)
        builder.addTextBody("WEIGHT", WEIGHT.toString());
    if (MODUS != null)
        builder.addTextBody("MODUS", MODUS.toString());
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}

From source file:com.adobe.aem.demomachine.communities.Loader.java

private static String doThumbnail(ResourceResolver rr, LinkedList<InputStream> lIs, String hostname,
        String port, String adminPassword, String csvfile, String filename, String sitename, int maxretries) {

    if (filename == null || filename.equals(""))
        return null;

    String pathToFile = "/content/dam/resources/resource-thumbnails/" + sitename + "/" + filename;

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(MIME.UTF8_CHARSET);
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    addBinaryBody(builder, lIs, rr, "file", csvfile, filename);
    builder.addTextBody("fileName", filename, ContentType.create("text/plain", MIME.UTF8_CHARSET));

    logger.debug("Posting file for thumbnails with name: " + filename);

    Loader.doPost(hostname, port, pathToFile, "admin", adminPassword, builder.build(), null);

    doWaitWorkflows(hostname, port, adminPassword, "thumbnail", maxretries);

    return pathToFile + "/file";

}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostMultiData(String url, String method, MobileApplicationBean mobileApplicationBean,
        String cookie) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Cookie", "JSESSIONID=" + cookie);
    MultipartEntityBuilder reqEntity;
    if (method.equals("upload")) {
        reqEntity = MultipartEntityBuilder.create();
        FileBody fileBody = new FileBody(new File(mobileApplicationBean.getApkFile()));
        reqEntity.addPart("file", fileBody);
    } else {/*  ww  w .  java 2  s .co m*/
        reqEntity = MultipartEntityBuilder.create();
        reqEntity.addPart("version",
                new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("provider",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("markettype",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("platform",
                new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("name",
                new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("description",
                new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
        FileBody bannerImageFile = new FileBody(new File(mobileApplicationBean.getBannerFilePath()));
        reqEntity.addPart("bannerFile", bannerImageFile);
        FileBody iconImageFile = new FileBody(new File(mobileApplicationBean.getIconFile()));
        reqEntity.addPart("iconFile", iconImageFile);
        FileBody screenShot1 = new FileBody(new File(mobileApplicationBean.getScreenShot1File()));
        reqEntity.addPart("screenshot1File", screenShot1);
        FileBody screenShot2 = new FileBody(new File(mobileApplicationBean.getScreenShot2File()));
        reqEntity.addPart("screenshot2File", screenShot2);
        FileBody screenShot3 = new FileBody(new File(mobileApplicationBean.getScreenShot3File()));
        reqEntity.addPart("screenshot3File", screenShot3);
        reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("mobileapp",
                new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("sso_ssoProvider",
                new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("appmeta",
                new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));
    }
    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpPost, responseHandler);
    if (!method.equals("upload")) {
        String id_part = responseBody.split(",")[2].split(":")[1];
        return id_part.substring(2, (id_part.length() - 2));
    }
    return responseBody;
}

From source file:service.OrderService.java

private String sendRequestForUnloadInShop(Order order, ServiceResult result) throws Exception {
    List<String> missing = new ArrayList();
    List<String> directionNames = new ArrayList();
    for (Direction dir : order.getDirections()) {
        String dirName = (dir.getNameForShop() != null ? dir.getNameForShop() : "");
        if (dirName.isEmpty()) {
            missing.add(//from  w ww  .ja v  a  2s.c  o m
                    "? ?    ? ? "
                            + dir.getName());
        }
        directionNames.add(dirName);
    }
    String orderName = "";
    if (order.getOrderType() != null && order.getOrderType().getNameForShop() != null) {
        orderName = order.getOrderType().getNameForShop();
    }
    if (orderName.isEmpty()) {
        missing.add(
                "? ?    ?  ");
    }
    String subject = (order.getSubject() != null ? order.getSubject() : "");
    if (subject.isEmpty()) {
        missing.add(" ");
    }
    String price = (order.getCost() != null ? order.getCost().toString() : "0");
    String numberOfPages = (order.getNumberOfPages() != null ? order.getNumberOfPages() : "");
    if (numberOfPages.isEmpty()) {
        missing.add("? ?");
    }
    String fileName = "order" + order.getOrderId() + ".zip";

    if (missing.isEmpty()) {
        String url = "http://zaochnik5.ru/up/uploadfile.php";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder multipart = MultipartEntityBuilder.create();
        multipart.addTextBody("type_work", orderName);
        multipart.addTextBody("name_work", subject);
        multipart.addTextBody("price", price);
        multipart.addTextBody("table_of_contents", "-");
        for (String dirName : directionNames) {
            multipart.addTextBody("napravlenie", dirName);
        }
        multipart.addTextBody("kol-vo_str", numberOfPages);
        multipart.addTextBody("fail", fileName);
        multipart.addTextBody("order_number", order.getOrderId().toString());
        multipart.addTextBody("kol-vo_order", "1");
        multipart.addTextBody("published", "0");
        multipart.addTextBody("srvkey", "8D9ucTqL4Ga2ZkLCmctR");
        byte[] zipBytes = getZipAllReadyFiles(order);
        multipart.addPart("upload", new ByteArrayBody(zipBytes, fileName));
        HttpEntity ent = multipart.build();
        post.setEntity(ent);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        return IOUtils.toString(response.getEntity().getContent());
    } else {
        String missingStr = "";
        for (String str : missing) {
            missingStr += str + ", ";
        }
        result.addError(
                "?  ,  ?  :"
                        + missingStr);
        return "";
    }
}

From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java

public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_)
        throws ColdFusionException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol);
        HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_);

        MultipartEntityBuilder me = MultipartEntityBuilder.create();
        me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        if (methodArgs_ != null) {
            for (String s : methodArgs_.keySet()) {
                Object obj = methodArgs_.get(s);

                if (obj != null) {
                    if (obj instanceof String) {
                        me.addTextBody(s, (String) obj);
                    } else if (obj instanceof Integer) {
                        me.addTextBody(s, ((Integer) obj).toString());
                    } else if (obj instanceof File) {
                        me.addBinaryBody(s, (File) obj);
                    } else if (obj instanceof IDocument) {
                        me.addBinaryBody(s, ((IDocument) obj).getFile());
                        //me.addTextBody( "name", ((IDocument)obj).getFileName() );
                        //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType );
                    } else if (obj instanceof IDocument[]) {
                        for (int i = 0; i < ((IDocument[]) obj).length; i++) {
                            IDocument iDocument = ((IDocument[]) obj)[i];
                            me.addBinaryBody(s, iDocument.getFile());
                            //me.addTextBody("name", iDocument.getFileName() );
                            //me.addTextBody("contentType", iDocument.getContentType().contentType );
                        }//from   w ww.  j a  v  a 2s.com

                    } else if (obj instanceof BufferedImage) {

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ImageIO.write((BufferedImage) obj, "jpg", baos);

                        String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME);
                        String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE))
                                .getExtension();
                        ContentType _contentType = ContentType.create(_mimeType);
                        me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName);
                    } else if (obj instanceof byte[]) {
                        me.addBinaryBody(s, (byte[]) obj);
                    } else if (obj instanceof Map) {
                        ObjectMapper mapper = new ObjectMapper();
                        String _json = mapper.writeValueAsString(obj);

                        me.addTextBody(s, _json);
                    }
                }
            }
        }

        HttpEntity httpEntity = me.build();
        method.setEntity(httpEntity);

        HttpResponse response = httpClient.execute(host, method);//, responseHandler);

        // Examine the response status
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                //return inputStream;

                byte[] _body = IOUtils.toByteArray(inputStream);

                MultiValueMap _headers = new LinkedMultiValueMap();
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equalsIgnoreCase("content-length")) {
                        _headers.add(header.getName(), header.getValue());
                    } else if (header.getName().equalsIgnoreCase("content-type")) {
                        _headers.add(header.getName(), header.getValue());

                        // special condition to add zip to the file name.
                        if (header.getValue().indexOf("text/") > -1) {
                            //add nothing extra
                        } else if (header.getValue().indexOf("zip") > -1) {
                            if (methodArgs_.get("file") != null) {
                                String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                                _headers.add("Content-Disposition",
                                        "attachment; filename=\"" + _fileName + ".zip\"");
                            }
                        } else if (methodArgs_.get("file") != null) {
                            String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                            _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\"");
                        }

                    }
                }

                return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK);
                //Map json = (Map)deSerializeJson(inputStream);
                //return json;
            }
        }

        MultiValueMap _headers = new LinkedMultiValueMap();
        _headers.add("Content-Type", "text/plain");
        return new ResponseEntity(response.getStatusLine().toString(), _headers,
                org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}