Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

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

Prototype

public StringBody(final String text, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.jaeksoft.searchlib.scheduler.task.TaskUploadMonitor.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {
    String url = properties.getValue(propUrl);
    URI uri;/*from   w ww  .  j av  a 2  s. co m*/
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    }
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);
    String instanceId = properties.getValue(propInstanceId);

    CredentialItem credentialItem = null;
    if (!StringUtils.isEmpty(login) && !StringUtils.isEmpty(password))
        credentialItem = new CredentialItem(CredentialType.BASIC_DIGEST, null, login, password, null, null);
    HttpDownloader downloader = client.getWebCrawlMaster().getNewHttpDownloader(true);
    try {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("instanceId",
                new StringBody(instanceId, ContentType.TEXT_PLAIN));

        new Monitor().writeToPost(entityBuilder);
        DownloadItem downloadItem = downloader.post(uri, credentialItem, null, null, entityBuilder.build());
        if (downloadItem.getStatusCode() != 200)
            throw new SearchLibException(
                    "Wrong code status:" + downloadItem.getStatusCode() + " " + downloadItem.getReasonPhrase());
        taskLog.setInfo("Monitoring data uploaded");
    } catch (ClientProtocolException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    } catch (IllegalStateException e) {
        throw new SearchLibException(e);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    } finally {
        downloader.release();
    }

}

From source file:fedroot.dacs.http.DacsPostRequest.java

/**
 * the following, which includes parameters in the multipart entity is not grokked
 * by DACS multipart parsing/*from   ww  w .  j a v a2  s . c  o  m*/
 * @param webServiceRequest
 * @return
 */
private HttpPost multipartBrokenPost(WebServiceRequest webServiceRequest) {
    try {
        HttpPost multipartPost = new HttpPost(webServiceRequest.getBaseURI());
        //            multipartPost.setHeader("Content-Type", webServiceRequest.getEnclosureType());
        multipartPost.setHeader("Content-Transfer-Encoding", "7bit");
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                "----HttpClientBoundarynSbUMwsZpJVNlFYK", Charset.forName("US-ASCII"));

        for (NameValuePair nameValuePair : webServiceRequest.getNameValuePairs()) {
            multipartEntity.addPart(nameValuePair.getName(),
                    new StringBody(new String(nameValuePair.getValue().getBytes(), Charset.forName("US-ASCII")),
                            Charset.forName("US-ASCII")));
        }
        for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) {
            multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody());
        }
        multipartPost.setEntity(multipartEntity);
        return multipartPost;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage());
    }
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * ?NOSurl//from  w  ww. j  a va2s . co  m
 * tongkn
 * @param bytes
 * @return
 */
public static String uploadFile2Nos(byte[] bytes, String fileName) throws Exception {
    if (bytes == null) {
        return null;
    }
    HttpResponse response = null;
    String result = null;
    try {
        //web ??
        String filedir = "tmpfile";
        File dir = new File(filedir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        //            FileBody bin = new FileBody(FileUtils.getFileFromBytes(
        //                    bytes, filedir +"/file-"+ System.currentTimeMillis()+"-"+fileName));
        //ByteArrayBody
        ByteArrayBody bin = new ByteArrayBody(bytes, fileName);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", bin);
        reqEntity.addPart("video", new StringBody("false", Charset.forName("UTF-8")));
        //            reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8")));
        response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity);
        if (response != null) {
            String jsonString = EntityUtils.toString(response.getEntity());
            JSONObject json = JSON.parseObject(jsonString);
            if ("success".equals(json.getString("msg"))) {
                return json.getString("url");
            }
        }
    } catch (Exception e) {
        LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e);
        throw new Exception();
    } finally {
        HttpToolKit.closeQuiet(response);
    }
    return result;
}

From source file:org.fabrician.maven.plugins.GridlibUploadMojo.java

public void execute() throws MojoExecutionException {
    String username = brokerUsername;
    String password = brokerPassword;
    if (serverId != null && !"".equals(serverId)) {
        // TODO: implement server_id
        throw new MojoExecutionException("serverId is not yet supported");
    } else if (brokerUsername == null || "".equals(brokerUsername) || brokerPassword == null
            || "".equals(brokerPassword)) {
        throw new MojoExecutionException("serverId or brokerUsername and brokerPassword must be set");
    }//w ww.  j a v a2  s  .  c  om

    DirectoryScanner ds = new DirectoryScanner();
    ds.setIncludes(mIncludes);
    ds.setExcludes(mExcludes);
    ds.setBasedir(".");
    ds.setCaseSensitive(true);
    ds.scan();

    String[] files = ds.getIncludedFiles();
    if (files == null) {
        getLog().info("No files found to upload");
    } else {
        getLog().info("Found " + files.length + " file to upload");

        for (String file : files) {
            File gridlibFilename = new File(file);
            getLog().info("Uploading " + gridlibFilename + " to " + brokerUrl);

            DefaultHttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            Credentials cred = new UsernamePasswordCredentials(username, password);
            httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, cred);

            try {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("gridlibOverwrite",
                        new StringBody(String.valueOf(gridlibOverwrite), Charset.forName("UTF-8")));
                entity.addPart("gridlibArchive", new FileBody(gridlibFilename));

                HttpPost method = new HttpPost(brokerUrl);
                method.setEntity(entity);

                HttpResponse response = httpclient.execute(method);
                StatusLine status = response.getStatusLine();
                int code = status.getStatusCode();
                if (code >= 400 && code <= 500) {
                    throw new MojoExecutionException(
                            "Failed to upload " + gridlibFilename + " to " + brokerUrl + ": " + code);
                }
            } catch (Exception e) {
                throw new MojoExecutionException(e.getMessage());
            }
        }
    }
}

From source file:it.polimi.diceH2020.plugin.net.NetworkManager.java

/**
 * Sends to the backend the models to be simulated
 * //from w w w  .  ja va  2s  .  c o m
 * @param files
 *            The model files
 * @param scenario
 *            The scenario parameter
 * @throws UnsupportedEncodingException
 */
public void sendModel(List<File> files, String scenario) throws UnsupportedEncodingException {
    HttpClient httpclient = HttpClients.createDefault();
    HttpResponse response;
    HttpPost post = new HttpPost(uploadRest);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("scenario", new StringBody(scenario, ContentType.DEFAULT_TEXT));

    for (File file : files) {
        builder.addPart("file[]", new FileBody(file));
    }

    post.setEntity(builder.build());
    try {
        response = httpclient.execute(post);
        String json = EntityUtils.toString(response.getEntity());
        HttpPost repost = new HttpPost(this.getLink(json));
        response = httpclient.execute(repost);
        String js = EntityUtils.toString(response.getEntity());
        parseJson(js);
        System.out.println("Code : " + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            System.err.println("Error: POST not succesfull");
        } else {
        }
        System.out.println(Configuration.getCurrent().getID());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static int upload(File file, String url, String schema, StringBuilder response) throws IOException {
    HttpPost post = new HttpPost(url);
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        MultipartEntityBuilder b = MultipartEntityBuilder.create();
        if (schema != null) {
            b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN));
        }//from  www. j  a  v  a  2s .c  o m
        b.addPart("data", new FileBody(file));
        post.setEntity(b.build());
        HttpResponse r = client.execute(post);
        if (response != null) {
            InputStream is = r.getEntity().getContent();
            int n;
            while ((n = is.read()) > 0) {
                response.append((char) n);
            }
            is.close();
        }
        return r.getStatusLine().getStatusCode();
    }
}

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

public MultipartEntityBuilder addTextBody(String name, String text, ContentType contentType) {
    return addPart(name, new StringBody(text, contentType));
}

From source file:com.autonomy.aci.client.transport.AciParameter.java

@Override
public void addToEntity(final MultipartEntityBuilder builder, final Charset charset) {
    builder.addPart(name, new StringBody(value, ContentType.create("text/plain", charset)));
}

From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

/**
 * Submit an application bundle to execute as a job.
 *//*from w  w w.j a va  2s  .  com*/
public static JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle,
        JsonObject jobConfigOverlay) throws ClientProtocolException, IOException {

    final String serviceName = jstring(service, "name");
    final JsonObject credentials = service.getAsJsonObject("credentials");

    String url = getJobSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials));
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody)
            .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + serviceName + "): submit job response:"
            + jsonResponse.toString());

    return jsonResponse;
}

From source file:com.brightcove.com.uploader.helper.MediaAPIHelper.java

/**
 * Executes a file upload write api call against the given URI.
 * This is useful for create_video and add_image
 * @param json the json representation of the call you are making
 * @param file the file you are uploading
 * @param uri the api servlet you want to execute against
 * @return json response from api/*from   w w  w .  j  a  v  a 2s .co  m*/
 * @throws BadEnvironmentException
 * @throws MediaAPIError
 */
public JsonNode executeWrite(JsonNode json, File file, URI uri) throws BadEnvironmentException, MediaAPIError {

    mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    FileBody fileBody = null;

    if (file != null) {
        fileBody = new FileBody(file);
    }

    try {
        entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new BadEnvironmentException("UTF-8 no longer supported");
    }

    if (file != null) {
        entityIn.addPart(file.getName(), fileBody);
    }
    method.setEntity(entityIn);

    return executeCall(method);
}