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

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

Introduction

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

Prototype

public MultipartEntityBuilder addTextBody(final String name, final String text) 

Source Link

Usage

From source file:com.norconex.committer.gsa.GsaCommitter.java

@Override
protected void commitBatch(List<ICommitOperation> batch) {

    File xmlFile = null;//ww  w  .  jav a2  s .c  om
    try {
        xmlFile = File.createTempFile("batch", ".xml");
        FileOutputStream fout = new FileOutputStream(xmlFile);
        XmlOutput xmlOutput = new XmlOutput(fout);
        Map<String, Integer> stats = xmlOutput.write(batch);
        fout.close();

        HttpPost post = new HttpPost(feedUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName());
        builder.addTextBody("datasource", "GSA_Commiter");
        builder.addTextBody("feedtype", "full");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(post);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: "
                    + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase());
        }
        LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved")
                + " removals to GSA");

    } catch (Exception e) {
        throw new CommitterException("Cannot index document batch to GSA.", e);
    } finally {
        FileUtils.deleteQuietly(xmlFile);
    }
}

From source file:org.exmaralda.webservices.BASChunkerConnector.java

public String callChunker(File bpfInFile, File audioFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println("Chunker called at " + dateFormat.format(date)); //2016/11/16 12:08:43        System.out.println("Chunker called at " + Date.);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (otherParameters != null) {
        builder.addTextBody("language", (String) otherParameters.get("language"));
    }//from www .  j av  a2  s  .  co  m

    builder.addTextBody("aligner", "fast");
    builder.addTextBody("force", "rescue");
    builder.addTextBody("minanchorlength", "2");
    builder.addTextBody("boost_minanchorlength", "3");

    // add the text file
    builder.addBinaryBody("bpf", bpfInFile);

    // add the audio file
    builder.addBinaryBody("audio", audioFile);

    System.out.println("All parameters set. ");

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(chunkerURL);
    httpPost.setEntity(builder.build());

    System.out.println("URI: " + httpPost.getURI().toString());

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity result = response.getEntity();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode == 200 && result != null) {
        String resultAsString = EntityUtils.toString(result);

        /*
        <WebServiceResponseLink>
            <success>true</success>
            <downloadLink>https://clarin.phonetik.uni-muenchen.de:443/BASWebServices/data/2019.01.03_15.58.41_9D4EECAD0791F9E9ED16DF35E66D1485/IDS_ISW_Chunker_Test_16kHz_OHNE_ANFANG.par</downloadLink>
            <output/>
            <warnings/>
        </WebServiceResponseLink>
        */

        // read the XML result string
        Document doc = FileIO.readDocumentFromString(resultAsString);

        // check if success == true
        Element successElement = (Element) XPath.selectSingleNode(doc, "//success");
        if (!((successElement != null) && successElement.getText().equals("true"))) {
            String errorText = "Call to BASChunker was not successful: "
                    + IOUtilities.elementToString(doc.getRootElement(), true);
            throw new IOException(errorText);
        }

        Element downloadLinkElement = (Element) XPath.selectSingleNode(doc, "//downloadLink");
        String downloadLink = downloadLinkElement.getText();

        // now we have the download link - just need to get the content as text
        String bpfOutString = downloadText(downloadLink);

        EntityUtils.consume(result);
        httpClient.close();

        return bpfOutString;
        //return resultAsString;
    } else {
        // something went wrong, throw an exception
        String reason = statusLine.getReasonPhrase();
        throw new IOException(reason);
    }

}

From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num,
        String namesInOrder, String signature, Factory<InputStream> factory) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addPart("uploadfile", new InputStreamBody(factory.create(), "uploadfile"))
            .addTextBody("rand_num", rand_num).addTextBody("url", url);

    for (Pair<String, String> pair : pairs) {
        builder.addTextBody(pair.a, pair.b);
    }/*from w  ww  .j  a va2s. c  o m*/

    HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature)
            .build();

    HttpPost post = new HttpPost(url);
    post.setEntity(entity);
    return new DalRequestImpl(post);
}

From source file:me.vertretungsplan.parser.LoginHandler.java

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse)
        throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }/* w w w.  j  a  v a  2s . co  m*/

    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }

    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch (type) {
    case "post":
        List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
        if (cookieList != null && !needsResponse) {
            for (Cookie cookie : cookieList)
                cookieStore.addCookie(cookie);

            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (checkUrl != null && checkText != null) {
                String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                if (!response.contains(checkText)) {
                    return null;
                }
            } else {
                return null;
            }
        }
        executor.clearCookies();
        Document preDoc = null;
        if (loginConfig.has(PARAM_PRE_URL)) {
            String preUrl = loginConfig.getString(PARAM_PRE_URL);
            String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
            preDoc = Jsoup.parse(preHtml);
        }

        String postUrl = loginConfig.getString(PARAM_URL);
        JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
        List<NameValuePair> nvps = new ArrayList<>();

        String typo3Challenge = null;

        if (loginData.has("_hiddeninputs") && preDoc != null) {
            for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                if (hidden.attr("name").equals("challenge")) {
                    typo3Challenge = hidden.attr("value");
                }
            }
        }

        for (String name : JSONObject.getNames(loginData)) {
            String value = loginData.getString(name);

            if (name.equals("_hiddeninputs"))
                continue;

            switch (value) {
            case "_login":
                value = login;
                break;
            case "_password":
                value = password;
                break;
            case "_password_md5":
                value = DigestUtils.md5Hex(password);
                break;
            case "_password_md5_typo3":
                value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                break;
            }

            nvps.add(new BasicNameValuePair(name, value));
        }
        Request request = Request.Post(postUrl);
        if (loginConfig.optBoolean("form-data", false)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair nvp : nvps) {
                builder.addTextBody(nvp.getName(), nvp.getValue());
            }
            request.body(builder.build());
        } else {
            request.bodyForm(nvps, Charset.forName("UTF-8"));
        }
        String html = executor.execute(request).returnContent().asString();
        if (cookieProvider != null)
            cookieProvider.saveCookies(auth, cookieStore.getCookies());

        String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
        String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
        if (checkUrl != null && checkText != null) {
            String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
            if (response.contains(checkText))
                throw new CredentialInvalidException();
        } else if (checkText != null) {
            if (html.contains(checkText))
                throw new CredentialInvalidException();
        }
        return html;
    case "basic":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "ntlm":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password, null, null);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "fixed":
        String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
        String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
        if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
            throw new CredentialInvalidException();
        }
        break;
    }
    return null;
}

From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java

@Override
public void run() {
    final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager();
    final String url = cs.getSnowmanServer().getApiUrl();
    for (;;) {/*ww w.  ja  v  a  2 s .com*/
        File obtainedFile;
        for (;;) {
            if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) {
                LOGGER.trace("killFlag == true");
                return;
            }
            obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile();

            if (obtainedFile == null) {
                Imager.waitALittleBit(300);
                continue;
            } else {
                break;
            }
        }

        boolean doUpload = true;
        while (doUpload) {
            try {
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    final HttpPost httppost = new HttpPost(url);
                    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM);

                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    builder.addPart(uploadNameCameraimage, fb);
                    builder.addTextBody(uploadNameFilename, obtainedFile.getName());
                    builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername());
                    builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword());
                    builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname());

                    final HttpEntity httpEntity = builder.build();
                    httppost.setEntity(httpEntity);

                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("executing request " + httppost.getRequestLine());
                    }

                    try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("response.getStatusLine(): " + response.getStatusLine());
                        }
                        final HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength());
                            }
                        }
                        final String resString = EntityUtils.toString(resEntity).trim();
                        EntityUtils.consume(resEntity);
                        if (resString.equals(responseSuccess)) {
                            doUpload = false;
                            LOGGER.trace("true: resString.equals(responseSuccess)");
                            LOGGER.trace("resString: {}", resString);
                        } else {
                            LOGGER.warn("false: resString.equals(responseSuccess)");
                            LOGGER.warn("resString: {}", resString);
                            // do not flood log files if an error occurred
                            Imager.waitALittleBit(2000);
                        }
                    }
                }
            } catch (NoHttpResponseException | SocketException e) {
                logIOExceptionAndWait(e);
            } catch (IOException e) {
                LOGGER.warn("Found unknown IOException", e);
            }
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete obtainedFile {}", obtainedFile);
        }
        final boolean delete = obtainedFile.delete();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete success {}", delete);
        }
        FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile);
    }
}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;/* www.  j  a v a 2 s. c om*/
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

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

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

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 w  w.j a v a  2s .  c om

                    } 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);
    }
}

From source file:org.apache.sling.testing.clients.osgi.OsgiConsoleClient.java

/**
 * Install a bundle using the Felix webconsole HTTP interface, with a specific start level
 * @param f/*  w  w  w.j av a 2 s.  c o  m*/
 * @param startBundle
 * @param startLevel
 * @return the sling response
 * @throws ClientException
 */
public SlingHttpResponse installBundle(File f, boolean startBundle, int startLevel) throws ClientException {
    // Setup request for Felix Webconsole bundle install
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("action", "install")
            .addBinaryBody("bundlefile", f);
    if (startBundle) {
        builder.addTextBody("bundlestart", "true");
    }
    if (startLevel > 0) {
        builder.addTextBody("bundlestartlevel", String.valueOf(startLevel));
        LOG.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        LOG.info("Installing bundle {} at default start level", f.getName());
    }

    return this.doPost(URL_BUNDLES, builder.build(), 302);

}