Search in sources :

Example 46 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project vorto by eclipse.

the class DefaultModelPublisher method uploadModelImage.

@Override
public void uploadModelImage(ModelId modelId, String imageBas64) throws ModelPublishException {
    String uploadImageUrl = String.format("%s/rest/model/image?namespace=%s&name=%s&version=%s", getRequestContext().getBaseUrl(), modelId.getNamespace(), modelId.getName(), modelId.getVersion());
    HttpPost uploadImage = new HttpPost(uploadImageUrl);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("fileName", new StringBody("vortomodel.png", ContentType.DEFAULT_TEXT)).addPart("fileDescription", new StringBody("", ContentType.DEFAULT_TEXT)).addPart("file", new ByteArrayBody(Base64.getDecoder().decode(imageBas64.getBytes()), ContentType.APPLICATION_OCTET_STREAM, "vortomodel.png")).build();
    uploadImage.setEntity(entity);
    try {
        execute(uploadImage, new TypeToken<Void>() {
        }.getType());
    } catch (Throwable ex) {
        if (!(ex instanceof ModelPublishException)) {
            throw new RuntimeException(ex);
        } else {
            throw ((ModelPublishException) ex);
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) TypeToken(com.google.gson.reflect.TypeToken) ModelPublishException(org.eclipse.vorto.repository.api.upload.ModelPublishException) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody)

Example 47 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project stanbol by apache.

the class MultipartRequestTest method testUploadWithMetadata.

/**
 * Stanbol also supports to upload pre-existing metadata with the content.
 * This UnitTest uses an example that parsed TextAnnotations for free text
 * tags provided by users that are than linked to Entities in DBPedia
 * @throws IOException
 */
@Test
public void testUploadWithMetadata() throws IOException {
    // create the metadata
    RDFTerm user = new PlainLiteralImpl("Rupert Westenthaler");
    final IRI contentItemId = new IRI("http://www.example.com/test.html");
    Graph metadata = new SimpleGraph();
    addTagAsTextAnnotation(metadata, contentItemId, "Germany", DBPEDIA_PLACE, user);
    addTagAsTextAnnotation(metadata, contentItemId, "Europe", DBPEDIA_PLACE, user);
    addTagAsTextAnnotation(metadata, contentItemId, "NATO", DBPEDIA_ORGANISATION, user);
    addTagAsTextAnnotation(metadata, contentItemId, "Silvio Berlusconi", DBPEDIA_PERSON, user);
    String rdfContentType = SupportedFormat.RDF_XML;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    serializer.serialize(out, metadata, rdfContentType);
    String rdfContent = new String(out.toByteArray(), UTF8);
    MultipartEntityBuilder ciBuilder = MultipartEntityBuilder.create();
    // add the metadata
    /*
         * NOTE: We need here to override the getFilename, because this MUST
         *       BE the URI of the ContentItem. This is important, because the
         *       Metadata do contain triples about that ContentItem and therefore
         *       it MUST BE assured that the URI of the ContentItem created by
         *       the Stanbol Enhancer is the same of as the URI used in the
         *       Metadata!
         */
    ciBuilder.addPart("metadata", new StringBody(rdfContent, ContentType.create(rdfContentType).withCharset(UTF8)) {

        @Override
        public String getFilename() {
            // uri of the ContentItem
            return contentItemId.getUnicodeString();
        }
    });
    // add the content
    ciBuilder.addTextBody("content", HTML_CONTENT, ContentType.TEXT_HTML.withCharset(UTF8));
    // send the request
    String receivedContent = executor.execute(builder.buildPostRequest(getEndpoint()).withHeader("Accept", "text/rdf+nt").withEntity(ciBuilder.build())).assertStatus(200).assertContentRegexp(// and the expected enhancements based on the parsed content
    "http://purl.org/dc/terms/creator.*LanguageDetectionEnhancementEngine", "http://purl.org/dc/terms/language.*en", "http://fise.iks-project.eu/ontology/entity-label.*Paris", "http://purl.org/dc/terms/creator.*org.apache.stanbol.enhancer.engines.opennlp.*NamedEntityExtractionEnhancementEngine", "http://fise.iks-project.eu/ontology/entity-label.*Bob Marley", // additional enhancements based on parsed metadata
    "http://fise.iks-project.eu/ontology/entity-reference.*http://dbpedia.org/resource/Germany.*", "http://fise.iks-project.eu/ontology/entity-reference.*http://dbpedia.org/resource/NATO.*", "http://fise.iks-project.eu/ontology/entity-reference.*http://dbpedia.org/resource/Silvio_Berlusconi.*", "http://fise.iks-project.eu/ontology/entity-reference.*http://dbpedia.org/resource/Europe.*").getContent();
    log.debug("Content:\n{}\n", receivedContent);
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) StringBody(org.apache.http.entity.mime.content.StringBody) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test)

Example 48 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project stanbol by apache.

the class MultipartRequestTest method testUploadMultipleContents.

/**
 * This uploads the HTML as well as the plain text version of an content.
 * This allows it CMS to parse already available alternate content versions
 * in a single request. Stanbol can than still use the original content
 * (e.g. to extract metadata) but other engines that require the alternate
 * version (e.g. plain text version) of an document will directly use the
 * parsed version .<p>
 * This UnitTest ensures this by adding a "secret" extension the to plain
 * text version and than checks if the two entities mentioned in that
 * part are included in the extracted entities.
 * @throws IOException
 */
@Test
public void testUploadMultipleContents() throws IOException {
    // It is a secret, that Berlin is the capital of Germany
    String extraTextConent = TEXT_CONTENT + "\nIt is a secret, that the city of Berlin is the capital of Germany since 1990.";
    // The multipartBuilder used to construct the contentItem for the contentItem
    MultipartEntityBuilder ciBuilder = MultipartEntityBuilder.create();
    String boundary = "contentItem-47jjksnbue73fnis";
    ciBuilder.setBoundary(boundary);
    // use a small extension to deal with multipart/alternate
    Map<String, ContentBody> alternates = new LinkedHashMap<String, ContentBody>();
    alternates.put("http://www.example.com/test.html", new StringBody(HTML_CONTENT, ContentType.TEXT_HTML.withCharset(UTF8)));
    alternates.put("http://www.example.com/test.txt", new StringBody(extraTextConent, ContentType.TEXT_PLAIN.withCharset(UTF8)));
    ciBuilder.addPart("content", new MultipartContentBody(alternates, "contentParts", ContentType.create("multipart/alternate")));
    String receivedContent = executor.execute(builder.buildPostRequest(getEndpoint()).withHeader("Accept", "text/rdf+nt").withEntity(ciBuilder.build())).assertStatus(200).assertContentRegexp(// and the expected enhancements in the metadata
    "http://purl.org/dc/terms/creator.*LanguageDetectionEnhancementEngine", "http://purl.org/dc/terms/language.*en", "http://fise.iks-project.eu/ontology/entity-label.*Paris", "http://purl.org/dc/terms/creator.*org.apache.stanbol.enhancer.engines.opennlp.*NamedEntityExtractionEnhancementEngine", "http://fise.iks-project.eu/ontology/entity-label.*Bob Marley", // check also for expeted entities extracted from the secret Text part!
    "http://fise.iks-project.eu/ontology/entity-label.*Berlin", "http://fise.iks-project.eu/ontology/entity-label.*Germany").getContent();
    log.debug("Content:\n{}\n", receivedContent);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) AbstractContentBody(org.apache.http.entity.mime.content.AbstractContentBody) ContentBody(org.apache.http.entity.mime.content.ContentBody) StringBody(org.apache.http.entity.mime.content.StringBody) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 49 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project undertow by undertow-io.

the class MultiPartForwardTestCase method createMultiPartFormPostEntity.

private MultipartEntity createMultiPartFormPostEntity() throws IOException {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("foo", new StringBody("bar"));
    return entity;
}
Also used : MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody)

Example 50 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project undertow by undertow-io.

the class MultiPartTestCase method testMultiPartRequest.

@Test
public void testMultiPartRequest() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8);
        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\r\n" + "parameter count: 1\r\n" + "parameter name count: 1\r\n" + "name: formValue\r\n" + "filename: null\r\n" + "content-type: null\r\n" + "Content-Disposition: form-data; name=\"formValue\"\r\n" + "size: 7\r\n" + "content: myValue\r\n" + "name: file\r\n" + "filename: uploadfile.txt\r\n" + "content-type: application/octet-stream\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\r\n" + "Content-Type: application/octet-stream\r\n" + "size: 13\r\n" + "content: file contents\r\n", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Aggregations

StringBody (org.apache.http.entity.mime.content.StringBody)72 HttpPost (org.apache.http.client.methods.HttpPost)50 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)42 HttpResponse (org.apache.http.HttpResponse)33 FileBody (org.apache.http.entity.mime.content.FileBody)31 File (java.io.File)26 Test (org.junit.Test)25 HttpEntity (org.apache.http.HttpEntity)24 IOException (java.io.IOException)19 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 InputStreamReader (java.io.InputStreamReader)7 HttpClient (org.apache.http.client.HttpClient)7 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 Header (org.apache.http.Header)6 ClientProtocolException (org.apache.http.client.ClientProtocolException)6 InputStream (java.io.InputStream)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5