Search in sources :

Example 41 with StringBody

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

the class Channel method checkin.

public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid, boolean merge, Flow flow, long fileSize, String filename, InputStream inputStream) throws ServerException, UserException {
    String address = baseAddress + "/upload";
    HttpPost httppost = new HttpPost(address);
    try {
        Long topicId = getServiceInterface().initiateCheckin(poid, deserializerOid);
        // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now
        InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("topicId", new StringBody("" + topicId, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("token", new StringBody(token, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("deserializerOid", new StringBody("" + deserializerOid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("merge", new StringBody("" + merge, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("poid", new StringBody("" + poid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("comment", new StringBody("" + comment, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("sync", new StringBody("" + (flow == Flow.SYNC), ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("compression", new StringBody("deflate", ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("data", data);
        httppost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = closeableHttpClient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            JsonParser jsonParser = new JsonParser();
            InputStreamReader in = new InputStreamReader(httpResponse.getEntity().getContent());
            try {
                JsonElement result = jsonParser.parse(new JsonReader(in));
                if (result instanceof JsonObject) {
                    JsonObject jsonObject = (JsonObject) result;
                    if (jsonObject.has("exception")) {
                        JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject();
                        String exceptionType = exceptionJson.get("__type").getAsString();
                        String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString() : "unknown";
                        if (exceptionType.equals(UserException.class.getSimpleName())) {
                            throw new UserException(message);
                        } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                            throw new ServerException(message);
                        }
                    } else {
                        if (jsonObject.has("topicId")) {
                            return jsonObject.get("topicId").getAsLong();
                        } else {
                            throw new ServerException("No topicId found in response: " + jsonObject.toString());
                        }
                    }
                }
            } finally {
                in.close();
            }
        }
    } catch (ClientProtocolException e) {
        throw new ServerException(e);
    } catch (IOException e) {
        throw new ServerException(e);
    } catch (PublicInterfaceNotFoundException e) {
        throw new ServerException(e);
    } finally {
        httppost.releaseConnection();
    }
    return -1;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ServerException(org.bimserver.shared.exceptions.ServerException) InputStreamReader(java.io.InputStreamReader) DeflaterInputStream(java.util.zip.DeflaterInputStream) HttpResponse(org.apache.http.HttpResponse) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringBody(org.apache.http.entity.mime.content.StringBody) JsonElement(com.google.gson.JsonElement) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) JsonReader(com.google.gson.stream.JsonReader) UserException(org.bimserver.shared.exceptions.UserException) JsonParser(com.google.gson.JsonParser)

Example 42 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 43 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project scheduling by ow2-proactive.

the class RestSchedulerPushPullFileTest method testIt.

public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
    File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
    // you can test pushing pulling a big file :
    // testPushFile = new File("path_to_a_big_file");
    File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
    if (destFile.exists()) {
        destFile.delete();
    }
    // PUSHING THE FILE
    String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
    // either we encode or we test human readable path (with no special character inside)
    HttpPost reqPush = new HttpPost(pushfileUrl);
    setSessionHeader(reqPush);
    // we push a xml job as a simple test
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
    multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile), MediaType.APPLICATION_OCTET_STREAM, null));
    reqPush.setEntity(multipartEntity);
    HttpResponse response = executeUriRequest(reqPush);
    System.out.println(response.getStatusLine());
    assertHttpStatusOK(response);
    Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());
    Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(testPushFile, destFile));
    // LISTING THE TARGET DIRECTORY
    String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
    HttpGet reqPullList = new HttpGet(pullListUrl);
    setSessionHeader(reqPullList);
    HttpResponse response2 = executeUriRequest(reqPullList);
    System.out.println(response2.getStatusLine());
    assertHttpStatusOK(response2);
    InputStream is = response2.getEntity().getContent();
    List<String> lines = IOUtils.readLines(is);
    HashSet<String> content = new HashSet<>(lines);
    System.out.println(lines);
    Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));
    // PULLING THE FILE
    String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8") : destPath.replace("\\", "/") + "/" + testPushFile.getName()));
    HttpGet reqPull = new HttpGet(pullfileUrl);
    setSessionHeader(reqPull);
    HttpResponse response3 = executeUriRequest(reqPull);
    System.out.println(response3.getStatusLine());
    assertHttpStatusOK(response3);
    InputStream is2 = response3.getEntity().getContent();
    File answerFile = tmpFolder.newFile();
    FileUtils.copyInputStreamToFile(is2, answerFile);
    Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(answerFile, testPushFile));
    // DELETING THE HIERARCHY
    String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
    String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/")));
    HttpDelete reqDelete = new HttpDelete(deleteUrl);
    setSessionHeader(reqDelete);
    HttpResponse response4 = executeUriRequest(reqDelete);
    System.out.println(response4.getStatusLine());
    assertHttpStatusOK(response4);
    Assert.assertTrue(destFile + " still exist", !destFile.exists());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpDelete(org.apache.http.client.methods.HttpDelete) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) File(java.io.File) HashSet(java.util.HashSet)

Example 44 with StringBody

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

the class HttpClientMultipartLiveTest method givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions.

// tests
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
    final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
    final File file = new File(url.getPath());
    final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
    final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
    // 
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    builder.addPart("text1", stringBody1);
    builder.addPart("text2", stringBody2);
    final HttpEntity entity = builder.build();
    // 
    post.setEntity(entity);
    response = client.execute(post);
    final int statusCode = response.getStatusLine().getStatusCode();
    final String responseString = getContent();
    final String contentTypeInHeader = getContentTypeHeader();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
    // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
    assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
    System.out.println(responseString);
    System.out.println("POST Content Type: " + contentTypeInHeader);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) URL(java.net.URL) Test(org.junit.Test)

Example 45 with StringBody

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

the class HttpTestUtils method upload.

public static int upload(String resource, 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));
        }
        b.addPart("data", new FileBody(resourceFile(resource)));
        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();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) StringBody(org.apache.http.entity.mime.content.StringBody) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse)

Aggregations

StringBody (org.apache.http.entity.mime.content.StringBody)65 HttpPost (org.apache.http.client.methods.HttpPost)44 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)40 FileBody (org.apache.http.entity.mime.content.FileBody)30 HttpResponse (org.apache.http.HttpResponse)29 File (java.io.File)25 Test (org.junit.Test)25 HttpEntity (org.apache.http.HttpEntity)21 IOException (java.io.IOException)15 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)15 TestHttpClient (io.undertow.testutils.TestHttpClient)14 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 Header (org.apache.http.Header)6 HttpClient (org.apache.http.client.HttpClient)6 FormBodyPart (org.apache.http.entity.mime.FormBodyPart)6 HashMap (java.util.HashMap)5 Map (java.util.Map)5 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)5 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)5 RequestBuilder (org.apache.sling.testing.tools.http.RequestBuilder)5