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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:org.openecomp.sdc.ci.tests.utilities.OnboardingUtils.java

private static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user)
        throws Exception {
    Config config = Utils.getConfig();//  w  w  w. ja v a  2 s.c om
    CloseableHttpResponse response = null;

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename)));

    String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/upload",
            config.getCatalogBeHost(), config.getCatalogBePort(), vspid);

    Map<String, String> headersMap = prepareHeadersMap(user.getUserId());
    headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data");

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        RestResponse restResponse = new RestResponse();

        Iterator<String> iterator = headersMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = headersMap.get(key);
            httpPost.addHeader(key, value);
        }
        httpPost.setEntity(mpBuilder.build());
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer);
            responseBody = writer.toString();
            try {

            } finally {
                instream.close();
            }
        }

        restResponse.setErrorCode(response.getStatusLine().getStatusCode());
        restResponse.setResponse(responseBody);

        return restResponse;

    } finally {
        closeResponse(response);
        closeHttpClient(client);

    }
}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

@SuppressWarnings("unused")
private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
        throws IOException {
    Config config = Utils.getConfig();//from w ww . j a  va 2 s  .co m
    CloseableHttpResponse response = null;
    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
    mpBuilder.addPart("resourceMetadata",
            new StringBody(
                    getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
                    ContentType.APPLICATION_JSON));

    String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
            config.getCatalogBePort());

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("USER_ID", userRole.getUserId());
        httpPost.setEntity(mpBuilder.build());
        response = client.execute(httpPost);
        return response.getStatusLine().getStatusCode();
    } finally {
        closeResponse(response);
        closeHttpClient(client);

    }
}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
        throws Exception {
    Config config = Utils.getConfig();//from  w  ww  . j a v a2 s  . co m
    CloseableHttpResponse response = null;
    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
    mpBuilder.addPart("resourceMetadata",
            new StringBody(
                    getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"),
                    ContentType.APPLICATION_JSON));

    String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
            config.getCatalogBePort());

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        RestResponse restResponse = new RestResponse();
        httpPost.addHeader("USER_ID", importer.getUserId());
        httpPost.setEntity(mpBuilder.build());
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer);
            responseBody = writer.toString();
            try {

            } finally {
                instream.close();
            }
        }

        restResponse.setErrorCode(response.getStatusLine().getStatusCode());
        restResponse.setResponse(responseBody);

        if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
            resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
            resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
            resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
            resourceDetails.setCreatorUserId(importer.getUserId());
            resourceDetails.setCreatorFullName(importer.getFullName());
        }

        return restResponse;

    } finally {
        closeResponse(response);
        closeHttpClient(client);

    }

}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole)
        throws IOException {
    Config config = Utils.getConfig();//from  w w  w.  jav a 2  s. co m

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
    mpBuilder.addPart("resourceMetadata", new StringBody(
            getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
    HttpEntity requestEntity = mpBuilder.build();
    String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("USER_ID", userRole.getUserId());

    return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
        throws IOException {
    Config config = Utils.getConfig();//from   ww w.  j  ava  2  s.co  m

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
    mpBuilder.addPart("resourceMetadata", new StringBody(
            getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
    HttpEntity requestEntity = mpBuilder.build();
    String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
            config.getCatalogBePort());
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("USER_ID", userRole.getUserId());

    return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
        throws IOException {
    Config config = Utils.getConfig();//  w  w w  . j a  va  2s  .  c o  m
    CloseableHttpResponse response = null;
    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
    mpBuilder.addPart("resourceMetadata",
            new StringBody(
                    getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
                    ContentType.APPLICATION_JSON));

    String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
            config.getCatalogBePort());

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        RestResponse restResponse = new RestResponse();
        httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
        httpPost.setEntity(mpBuilder.build());
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer);
            responseBody = writer.toString();
            try {

            } finally {
                instream.close();
            }
        }

        restResponse.setErrorCode(response.getStatusLine().getStatusCode());
        // restResponse.setResponse(response.getEntity().toString());
        restResponse.setResponse(responseBody);
        return restResponse;
    } finally {
        closeResponse(response);
        closeHttpClient(client);

    }
}

From source file:org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils.java

public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
        throws IOException {
    Config config = Utils.getConfig();/*from   w w w  .jav a2s. c o m*/

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

    mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
    HttpEntity requestEntity = mpBuilder.build();
    String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("USER_ID", userRole.getUserId());

    return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
}

From source file:org.openecomp.sdc.uici.tests.utilities.OnboardUtility.java

private static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, String userId)
        throws Exception {
    Config config = Utils.getConfig();/*from  w  ww  .  java 2  s  . com*/
    CloseableHttpResponse response = null;

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(filepath, filename)));

    String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/upload",
            config.getCatalogBeHost(), config.getCatalogBePort(), vspid);

    Map<String, String> headersMap = prepareHeadersMap(userId);
    headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data");

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        RestResponse restResponse = new RestResponse();

        Iterator<String> iterator = headersMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = headersMap.get(key);
            httpPost.addHeader(key, value);
        }
        httpPost.setEntity(mpBuilder.build());
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer);
            responseBody = writer.toString();
            try {

            } finally {
                instream.close();
            }
        }

        restResponse.setErrorCode(response.getStatusLine().getStatusCode());
        restResponse.setResponse(responseBody);

        return restResponse;

    } finally {
        closeResponse(response);
        closeHttpClient(client);

    }
}

From source file:org.openstreetmap.josm.plugins.mapillary.oauth.UploadUtils.java

/**
 * @param file File that is going to be uploaded
 * @param hash Information attached to the upload
 * @throws IllegalArgumentException if the hash doesn't contain all the needed keys.
 *///  www. ja v a 2  s.co m
private static void uploadFile(File file, Map<String, String> hash) throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpPost httpPost = new HttpPost(UPLOAD_URL);

    try (CloseableHttpClient httpClient = builder.build()) {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        for (String key : keys) {
            if (hash.get(key) == null)
                throw new IllegalArgumentException();
            entityBuilder.addPart(key, new StringBody(hash.get(key), ContentType.TEXT_PLAIN));
        }
        entityBuilder.addPart("file", new FileBody(file));
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().toString().contains("204")) {
                PluginState.imageUploaded();
                Main.info(PluginState.getUploadString() + " (Mapillary)");
            } else {
                Main.info("Upload error");
            }
        }
    }
    if (!file.delete()) {
        Main.error("MapillaryPlugin: File could not be deleted during upload");
    }
    MapillaryUtils.updateHelpText();
}

From source file:org.rapidoid.http.HttpClient.java

public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback,
        boolean fullResponse) {

    headers = U.safe(headers);//from  w w  w  .  j av  a2 s .  co  m
    data = U.safe(data);
    files = U.safe(files);

    HttpRequestBase req;
    boolean canHaveBody = false;

    if ("GET".equalsIgnoreCase(verb)) {
        req = new HttpGet(uri);
    } else if ("DELETE".equalsIgnoreCase(verb)) {
        req = new HttpDelete(uri);
    } else if ("OPTIONS".equalsIgnoreCase(verb)) {
        req = new HttpOptions(uri);
    } else if ("HEAD".equalsIgnoreCase(verb)) {
        req = new HttpHead(uri);
    } else if ("TRACE".equalsIgnoreCase(verb)) {
        req = new HttpTrace(uri);
    } else if ("POST".equalsIgnoreCase(verb)) {
        req = new HttpPost(uri);
        canHaveBody = true;
    } else if ("PUT".equalsIgnoreCase(verb)) {
        req = new HttpPut(uri);
        canHaveBody = true;
    } else if ("PATCH".equalsIgnoreCase(verb)) {
        req = new HttpPatch(uri);
        canHaveBody = true;
    } else {
        throw U.illegalArg("Illegal HTTP verb: " + verb);
    }

    for (Entry<String, String> e : headers.entrySet()) {
        req.addHeader(e.getKey(), e.getValue());
    }

    if (canHaveBody) {
        HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

        if (body != null) {

            NByteArrayEntity entity = new NByteArrayEntity(body);

            if (contentType != null) {
                entity.setContentType(contentType);
            }

            entityEnclosingReq.setEntity(entity);
        } else {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (Entry<String, String> entry : files.entrySet()) {
                String filename = entry.getValue();
                File file = IO.file(filename);
                builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
            }

            for (Entry<String, String> entry : data.entrySet()) {
                builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                builder.build().writeTo(stream);
            } catch (IOException e) {
                throw U.rte(e);
            }

            byte[] bytes = stream.toByteArray();
            NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);

            entityEnclosingReq.setEntity(entity);
        }
    }

    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    return execute(client, req, callback, fullResponse);
}