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) throws UnsupportedEncodingException 

Source Link

Usage

From source file:org.opencastproject.remotetest.server.MultiPartTest.java

@Test
public void testMultiPartPost() throws Exception {

    String mp = "<oc:mediapackage xmlns:oc=\"http://mediapackage.opencastproject.org\" id=\"10.0000/1\" start=\"2007-12-05T13:40:00\" duration=\"1004400000\"></oc:mediapackage>";

    InputStream is = null;//from   w  ww. java  2s  . c  om
    try {
        is = getClass().getResourceAsStream("/av.mov");
        InputStreamBody fileContent = new InputStreamBody(is, "av.mov");
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("mediaPackage", new StringBody(mp));
        mpEntity.addPart("flavor", new StringBody("presentation/source"));
        mpEntity.addPart("userfile", fileContent);
        HttpPost httppost = new HttpPost(BASE_URL + "/ingest/addAttachment");
        httppost.setEntity(mpEntity);
        HttpResponse response = httpClient.execute(httppost);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.semantictools.jsonld.impl.AppspotContextPublisher.java

@Override
public void publish(LdAsset asset) throws LdPublishException {

    String uri = asset.getURI();//from   www  .  jav a2 s.  c  o  m

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(SERVLET_URL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    try {

        String content = asset.loadContent();

        entity.addPart(URI, new StringBody(uri));
        entity.addPart(FILE_UPLOAD, new StringBody(content));
        post.setEntity(entity);

        logger.debug("uploading... " + uri);

        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();

        client.getConnectionManager().shutdown();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new LdPublishException(uri, null);
        }

    } catch (Exception e) {
        throw new LdPublishException(uri, e);
    }

}

From source file:io.github.data4all.util.upload.GpxTrackUtil.java

/**
 * Returns a {@link CloseableUpload} containing all nessesary informations
 * for the upload to the OSM API.//  w ww  .ja  v a  2  s. c om
 * 
 * @param context
 *            the application context
 * @param user
 *            The {@link User} who uploads the Changeset.
 * @param track
 *            the gpx xml string
 * @param description
 *            The trace description.
 * @param tags
 *            A string containing tags for the trace. (comma seperated)
 * @param visibility
 *            One of the following: private, public, trackable,
 *            identifiable.
 * @param callback
 *            The callback object for interaction with the
 *            {@link ResultReceiver}.
 * @return {@link CloseableUpload} object
 * @throws OsmException
 *             Indicates an failure in an osm progess.
 */
public static CloseableUpload upload(Context context, User user, String track, String description, String tags,
        String visibility, Callback<Integer> callback) throws OsmException {
    final HttpPost request = getUploadPost(user);

    final MultipartEntity reqEntity = new MultiCallbackEntry(callback);
    final FileBody fileBody = new FileBody(createGpxFile(context, track, "file.gpx"));

    try {
        reqEntity.addPart("file", fileBody);
        reqEntity.addPart("description", new StringBody(description));
        reqEntity.addPart("tags", new StringBody(tags));
        reqEntity.addPart("visibility", new StringBody(visibility));
    } catch (UnsupportedEncodingException e) {
        Log.e(GpxTrackUtil.class.getSimpleName(), "Exception: ", e);
    }

    request.setEntity(reqEntity);
    request.addHeader("ContentType", "multipart/form-data");
    // Setting the Entity

    // final HttpEntity entity = new MultiCallbackEntry(callback);
    // request.setEntity(entity);

    return new CloseableUpload(request);
}

From source file:com.glodon.paas.document.api.FileRestAPITest.java

@Test
public void uploadFileForMultiPart() throws IOException {
    File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null);
    java.io.File file = new ClassPathResource("file/testupload.file").getFile();
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody(file.getName());
    StringBody sbPosition = new StringBody("0");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);//from  w  w w  .j a  v  a2 s  . co  m

    File uploadFile = getFile(simpleCall(post), null);
    assertEquals(file.getName(), uploadFile.getFullName());
    assertTrue(file.length() == uploadFile.getSize());
    assertEquals(parentFile.getId(), uploadFile.getParentId());
}

From source file:org.apache.sling.validation.testservices.ValidationServiceTest.java

@Test
public void testInvalidRequestModel1() throws IOException, JSONException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1"));
    entity.addPart("field1", new StringBody("Hello World"));
    entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation"));
    RequestExecutor re = getRequestExecutor().execute(
            getRequestBuilder().buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity))
            .assertStatus(200);/* w w w  . j a  v a  2  s  .  c o m*/
    String content = re.getContent();
    JSONObject jsonResponse = new JSONObject(content);
    assertFalse(jsonResponse.getBoolean("valid"));
    JSONObject failure = jsonResponse.getJSONArray("failures").getJSONObject(0);
    assertEquals("Property does not match the pattern \"^\\p{Upper}+$\".", failure.get("message"));
    assertEquals("field1", failure.get("location"));
    assertEquals(10, failure.get("severity"));
    failure = jsonResponse.getJSONArray("failures").getJSONObject(1);
    assertEquals("Missing required property with name \"field2\".", failure.get("message"));
    assertEquals("", failure.get("location")); // location is empty as the property is not found (property name is part of the message rather)
    assertEquals(0, failure.get("severity"));
}

From source file:org.n52.sir.IT.HarvestScheduleIT.java

@Before
public void uploadAFileAndRetrieveScriptId() throws ClientProtocolException, IOException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/OpenSensorSearch/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "User"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    // upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("User"));
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/script/submit");
    post.setEntity(multipartEntity);/*from w  w  w  . jav  a  2  s  . c  om*/
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);
    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    System.setProperty(SCRIPT_ID, scriptId + "");
}

From source file:org.n52.sir.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);//from  ww w.  ja v  a2  s .c  o m
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SOLRSearchSensorDAO DAO = new SOLRSearchSensorDAO();
    Collection<SirSearchResultElement> results = DAO.searchByContact(randomString);

    assertTrue(results.size() > 0);

    new SolrConnection().deleteByQuery("contacts:" + randomString);
}

From source file:org.n52.oss.IT.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);/*  w w w.ja  va2  s  .com*/
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SolrConnection c = new SolrConnection("http://localhost:8983/solr", 2000);
    SOLRSearchSensorDAO dao = new SOLRSearchSensorDAO(c);
    Collection<SirSearchResultElement> results = dao.searchByContact(randomString);

    assertTrue(results.size() > 0);

    // FIXME use transactional delete operation, or just use a mocked up database
    c.deleteSensor("contacts:" + randomString);
}

From source file:org.andrico.andjax.http.HttpMessageFactory.java

/**
 * Create a new http uri request with more standard datatypes.
 * /*from  w ww . jav  a  2 s . c  o  m*/
 * @param url The url to push the request to.
 * @param params String parameters to pass in the post.
 * @throws URISyntaxException
 */
public HttpMessage create(String url, Map<String, String> params) throws URISyntaxException {
    MultipartEntity multipartEntity = null;
    if (params != null) {
        multipartEntity = new MultipartEntity();
        for (final String key : params.keySet()) {
            try {
                multipartEntity.addPart(key, new StringBody(params.get(key)));
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return this.createFromParts(url, multipartEntity);
}

From source file:com.surevine.alfresco.connector.SecurityModelConnector.java

public void setSecurityModel(final String securityModel) throws AlfrescoException {
    final Map<String, ContentBody> parts = new HashMap<String, ContentBody>();

    try {//from  ww w .  ja  va2  s  .  c om
        parts.put("updateNodeRef", new StringBody("workspace://SpacesStore/enhanced_security_custom_model"));
        parts.put("filedata", new InputStreamBody(new ByteArrayInputStream(securityModel.getBytes()),
                "text/xml", "enhancedSecurityCustomModel.xml"));
    } catch (final UnsupportedEncodingException e) {
        LOG.error("Failed to populate multipart form for updating security model.", e);
    }

    final AlfrescoHttpResponse response = doHttpPost(alfrescoUrlBase + "/wcservice/api/upload.html", parts);

    if (response.getHttpResponse().getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new AlfrescoException("Update of security model failed with status code "
                + response.getHttpResponse().getStatusLine().getStatusCode());
    }
}