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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

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  v  a2  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.execute.category.CategoriesTests.java

License:asdf

@Test
public void importCategories() throws Exception {

    String importResourceDir = config.getImportTypesConfigDir() + File.separator + "categoryTypesTest.zip";

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("categoriesZip", new FileBody(new File(importResourceDir)));

    RestResponse importResult = CategoryRestUtils.importCategories(mpBuilder, sdncAdminUserDetails.getUserId());
    assertEquals("Check response code after Import", BaseRestUtils.STATUS_CODE_CREATED,
            importResult.getErrorCode().intValue());

    Map<String, Object> map = ResponseParser.parseToObjectUsingMapper(importResult.getResponse(), Map.class);
    assertEquals("Check  entries count", 2, map.size());

    List<Map<String, Object>> resources = (List<Map<String, Object>>) map.get("resources");
    assertEquals("Check resource category  entries count", 1, resources.size());

    List<Map<String, Object>> services = (List<Map<String, Object>>) map.get("services");
    assertEquals("Check resource category  entries count", 2, services.size());

    RestResponse allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "resources");
    List<CategoryDefinition> resourceCategories = ResponseParser.parseCategories(allCategories);
    for (Map<String, Object> resource : resources) {
        boolean exist = false;

        for (CategoryDefinition categ : resourceCategories) {
            if (categ.getName().equals(resource.get("name"))) {
                exist = true;/*w ww. ja  va 2  s  .c o m*/
                break;
            }
        }
        assertTrue("Check existance resource category  " + resource.get("name"), exist);
    }

    allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "services");
    List<CategoryDefinition> servicesCategories = ResponseParser.parseCategories(allCategories);
    for (Map<String, Object> service : services) {
        boolean exist = false;

        for (CategoryDefinition categ : servicesCategories) {
            if (categ.getName().equals(service.get("name"))) {
                exist = true;
                break;
            }
        }
        assertTrue("Check existance service category  " + service.get("name"), exist);
    }
}

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

    }
}