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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation,
        String zipLocation) throws IOException {

    Gson gson = new Gson();
    String gsonToSend = null;/*from   w  ww.  j a va 2  s.  co  m*/
    RestResponse restResponse = new RestResponse();
    BufferedReader br = null;
    //
    //
    //
    //
    // try {
    //
    // String sCurrentLine;
    //
    // br = new BufferedReader(new FileReader(jsonLocation));
    //
    // while ((sCurrentLine = br.readLine()) != null) {
    // System.out.println(sCurrentLine);
    // }
    //
    // } catch (IOException e) {
    // e.printStackTrace();
    // } finally {
    // try {
    // if (br != null)br.close();
    // gsonToSend = br.toString();
    // } catch (IOException ex) {
    // ex.printStackTrace();
    // }
    // }

    gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next();
    logger.debug("gsonToSend: {}", gsonToSend);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation)));
    mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON));

    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("USER_ID", "adminid");
    httpPost.setEntity(mpBuilder.build());

    CloseableHttpClient client = HttpClients.createDefault();
    CloseableHttpResponse response = client.execute(httpPost);
    try {
        logger.debug("----------------------------------------");
        logger.debug("response.getStatusLine(): {}", response.getStatusLine());
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            logger.debug("Response content length: {}", resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
    } finally {

        response.close();
        client.close();
    }

    restResponse.setErrorCode(response.getStatusLine().getStatusCode());
    restResponse.setResponse(response.getEntity().toString());

    return restResponse;

}

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 ww  .  j  a  v a  2 s .com*/
    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();//  w  w  w .  j  a  va 2  s.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);
        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();/*  ww w  . j a  va 2s . c  o  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   www  .ja  va2  s.  c  o  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 a  v  a 2 s.  c o 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  2 s .com
    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 ww  w. j  av a  2s .  c om*/

    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 w  w. ja  va  2s .c  o  m*/
    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.
 *//* w  w w.  j  av a2s. c o 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();
}