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:com.codedx.burp.ExportActionListener.java

private HttpResponse sendData(File data, String urlStr) throws IOException {
    CloseableHttpClient client = burpExtender.getHttpClient();
    if (client == null)
        return null;

    HttpPost post = new HttpPost(urlStr);
    post.setHeader("API-Key", burpExtender.getApiKey());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(data));

    HttpEntity entity = builder.build();
    post.setEntity(entity);/*from  w  ww . j  a va 2  s .c o m*/

    HttpResponse response = client.execute(post);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        EntityUtils.consume(resEntity);
    }
    client.close();

    return response;
}

From source file:org.plos.crepo.dao.objects.impl.ContentRepoObjectDaoImpl.java

private HttpEntity getObjectEntity(String bucketName, RepoObjectInput repoObjectInput, InputStream stream,
        CreationMethod creationType, String contentType) {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    multipartEntityBuilder.addTextBody("key", repoObjectInput.getKey());
    multipartEntityBuilder.addTextBody("bucketName", bucketName);
    multipartEntityBuilder.addTextBody("create", creationType.toString());
    multipartEntityBuilder.addTextBody("contentType", contentType);
    multipartEntityBuilder.addBinaryBody("file", stream);

    if (repoObjectInput.getDownloadName() != null) {
        multipartEntityBuilder.addTextBody("downloadName", repoObjectInput.getDownloadName());
    }//from www. jav  a  2  s.c om
    if (repoObjectInput.getTimestamp() != null) {
        multipartEntityBuilder.addTextBody("timestamp", repoObjectInput.getTimestamp().toString());
    }
    if (repoObjectInput.getCreationDate() != null) {
        multipartEntityBuilder.addTextBody("creationDateTime", repoObjectInput.getCreationDate().toString());
    }
    if (repoObjectInput.getTag() != null) {
        multipartEntityBuilder.addTextBody("tag", repoObjectInput.getTag());
    }
    if (repoObjectInput.getUserMetadata() != null) {
        multipartEntityBuilder.addTextBody("userMetadata", repoObjectInput.getUserMetadata());
    }

    return multipartEntityBuilder.build();

}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostMultiData(String url, String method, MobileApplicationBean mobileApplicationBean,
        String cookie) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Cookie", "JSESSIONID=" + cookie);
    MultipartEntityBuilder reqEntity;/*from w  w w  . j av  a  2s  .com*/
    if (method.equals("upload")) {
        reqEntity = MultipartEntityBuilder.create();
        FileBody fileBody = new FileBody(new File(mobileApplicationBean.getApkFile()));
        reqEntity.addPart("file", fileBody);
    } else {
        reqEntity = MultipartEntityBuilder.create();
        reqEntity.addPart("version",
                new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("provider",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("markettype",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("platform",
                new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("name",
                new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("description",
                new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
        FileBody bannerImageFile = new FileBody(new File(mobileApplicationBean.getBannerFilePath()));
        reqEntity.addPart("bannerFile", bannerImageFile);
        FileBody iconImageFile = new FileBody(new File(mobileApplicationBean.getIconFile()));
        reqEntity.addPart("iconFile", iconImageFile);
        FileBody screenShot1 = new FileBody(new File(mobileApplicationBean.getScreenShot1File()));
        reqEntity.addPart("screenshot1File", screenShot1);
        FileBody screenShot2 = new FileBody(new File(mobileApplicationBean.getScreenShot2File()));
        reqEntity.addPart("screenshot2File", screenShot2);
        FileBody screenShot3 = new FileBody(new File(mobileApplicationBean.getScreenShot3File()));
        reqEntity.addPart("screenshot3File", screenShot3);
        reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("mobileapp",
                new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("sso_ssoProvider",
                new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("appmeta",
                new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));
    }
    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpPost, responseHandler);
    if (!method.equals("upload")) {
        String id_part = responseBody.split(",")[2].split(":")[1];
        return id_part.substring(2, (id_part.length() - 2));
    }
    return responseBody;
}

From source file:com.buffalokiwi.api.API.java

/**
 * Perform a post-based request to some endpoint
 * @param url The URL/*from w  w w .  ja v  a 2 s  .c  o m*/
 * @param formData Key/Value pairs to send
 * @param files Key/File files to send
 * @param headers Extra headers to send
 * @return response
 * @throws APIException If something goes wrong
 */
@Override
public IAPIResponse post(final String url, final List<NameValuePair> formData,
        final Map<String, PostFile> files, final Map<String, String> headers) throws APIException {
    final HttpPost post = (HttpPost) createRequest(HttpMethod.POST, url, headers);

    //..Create a multi-part form data entity
    final MultipartEntityBuilder b = MultipartEntityBuilder.create();

    //..Set the mode
    b.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    setMultipartFileData(files, b);

    //..Check for non-file form data
    setMultipartFormData(formData, b);

    //..Attach the form data to the post request
    post.setEntity(b.build());

    //..Execute the request
    return executeRequest(post);
}

From source file:com.liferay.sync.engine.session.Session.java

private MultipartEntityBuilder _getMultipartEntityBuilder(Map<String, Object> parameters) {

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        if (_ignoredParameterKeys.contains(entry.getKey())) {
            continue;
        }/*from w w  w  .  j a  v a  2s .  c om*/

        multipartEntityBuilder.addPart(entry.getKey(), _getStringBody(entry.getValue()));
    }

    return multipartEntityBuilder;
}

From source file:com.frochr123.periodictasks.RefreshProjectorThread.java

public void updateProjectorImage() {
    if (!updateInProgress && !shutdownThreadRunning) {
        updateInProgress = true;/*from   w w  w .  jav a2 s. com*/

        new Thread() {
            @Override
            public void run() {
                try {
                    if (VisicutModel.getInstance() != null
                            && VisicutModel.getInstance().getSelectedLaserDevice() != null
                            && VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() != null
                            && !VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL()
                                    .isEmpty()) {
                        BufferedImage img = PreviewImageExport.generateImage(getProjectorWidth(),
                                getProjectorHeight(), !isShutdownInProgress());

                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        PreviewImageExport.writePngToOutputStream(outputStream, img);
                        byte[] imagePostDataByte = outputStream.toByteArray();

                        // Create HTTP client and cusomized config for timeouts
                        CloseableHttpClient httpClient = HttpClients.createDefault();
                        RequestConfig requestConfig = RequestConfig.custom()
                                .setSocketTimeout(DEFAULT_PROJECTOR_TIMEOUT)
                                .setConnectTimeout(DEFAULT_PROJECTOR_TIMEOUT)
                                .setConnectionRequestTimeout(DEFAULT_PROJECTOR_TIMEOUT).build();

                        // Create HTTP Post request
                        HttpPost httpPost = new HttpPost(
                                VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL());
                        httpPost.setConfig(requestConfig);

                        // Insert file upload
                        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                        multipartEntityBuilder.addBinaryBody("data", imagePostDataByte,
                                ContentType.APPLICATION_OCTET_STREAM, "data");
                        HttpEntity httpEntity = multipartEntityBuilder.build();
                        httpPost.setEntity(httpEntity);

                        // Set authentication information
                        String encodedCredentials = Helper.getEncodedCredentials(
                                VisicutModel.getInstance().getSelectedLaserDevice().getURLUser(),
                                VisicutModel.getInstance().getSelectedLaserDevice().getURLPassword());
                        if (!encodedCredentials.isEmpty()) {
                            httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
                        }

                        // Send request
                        CloseableHttpResponse res = httpClient.execute(httpPost);

                        // React to possible server side errors
                        if (res.getStatusLine() == null
                                || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                            throw new Exception("Server sent wrong HTTP status code: "
                                    + new Integer(res.getStatusLine().getStatusCode()).toString());
                        }

                        // Close everything correctly
                        res.close();
                        httpClient.close();
                    }
                }
                // This is caused internally in apache commons library for wrong authentication
                // Would need to add additional apache commons library file to get a correct exception back for that
                catch (NoClassDefFoundError error) {
                    // Set flag for exception handling, sleep and message
                    lastExceptionMessage = "Projector thread exception: Authentication error!";
                } catch (Exception e) {
                    // Set flag for exception handling, sleep and message
                    lastExceptionMessage = "Projector thread exception (2): " + e.getMessage();
                }

                updateInProgress = false;

                // Need to check if shutdown is set here first, otherwise these asynchronous calls
                // would always overwrite a call to shutdown in progress = true
                if (shutdownInProgress) {
                    shutdownInProgress = false;
                }
            }
        }.start();
    }
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException {
    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    List<NameValuePair> formParams = new ArrayList<>();
    postVariables.forEach((name, values) -> values.forEach(value -> {
        if (multipart) {
            if (value.startsWith("@")) {
                File f = new File(value.substring(1));
                multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName());
            } else {
                multipartBuilder.addTextBody(name, value);
            }//from w w  w.  j  a v a2s. co  m
        } else {
            formParams.add(new BasicNameValuePair(name, value));
        }
    }));
    if (multipart) {
        request.setEntity(multipartBuilder.build());
    } else {
        request.setEntity(new UrlEncodedFormEntity(formParams));
    }
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Activate autofocus on specified area (coordinates)
* 
* @param x    * @param y //from w  w w . ja  v  a 2 s  .  co  m
*/
public void autofocusPost(Integer x, Integer y, final Response.Listener<String> responseListener,
        final Response.ErrorListener errorListener) {
    Object postBody = null;

    // verify the required parameter 'x' is set
    if (x == null) {
        VolleyError error = new VolleyError("Missing the required parameter 'x' when calling autofocusPost",
                new ApiException(400, "Missing the required parameter 'x' when calling autofocusPost"));
    }

    // verify the required parameter 'y' is set
    if (y == null) {
        VolleyError error = new VolleyError("Missing the required parameter 'y' when calling autofocusPost",
                new ApiException(400, "Missing the required parameter 'y' when calling autofocusPost"));
    }

    // create path and map variables
    String path = "/autofocus".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    queryParams.addAll(ApiInvoker.parameterToPairs("", "x", x));
    queryParams.addAll(ApiInvoker.parameterToPairs("", "y", y));

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams,
                contentType, authNames, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String localVarResponse) {
                        responseListener.onResponse(localVarResponse);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        errorListener.onErrorResponse(error);
                    }
                });
    } catch (ApiException ex) {
        errorListener.onErrorResponse(new VolleyError(ex));
    }
}

From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java

protected Response doPostMultiPart(String filePath, String elementName, String url, String contentType) {
    try {/*w ww . jav a 2s  . c  o m*/

        if (StringUtil.isBlank(contentType)) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        url = URL_ENCODER.encode(RestHelper.urlFrom(getServerContext(), url));

        HttpPost post = new HttpPost(url);
        post.setHeader("Accept", MediaType.APPLICATION_JSON);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.write(fileStream(filePath), baos);
        entityBuilder.addPart(elementName, new ByteArrayBody(baos.toByteArray(), "test_file"));
        post.setEntity(entityBuilder.build());

        return new Response(post);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
        return null;
    }
}

From source file:org.hyperledger.fabric.sdkintegration.UpdateChannelIT.java

@Test
public void setup() {

    try {/*from w  w  w.j av  a 2 s  . c  o  m*/

        ////////////////////////////
        // Setup client

        //Create instance of client.
        HFClient client = HFClient.createNewInstance();

        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

        ////////////////////////////
        //Set up USERS

        //Persistence is not part of SDK. Sample file store is for demonstration purposes only!
        //   MUST be replaced with more robust application implementation  (Database, LDAP)
        File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties");
        sampleStoreFile.deleteOnExit();

        final SampleStore sampleStore = new SampleStore(sampleStoreFile);

        //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface

        ////////////////////////////
        // get users for all orgs

        for (SampleOrg sampleOrg : testSampleOrgs) {

            final String orgName = sampleOrg.getName();
            sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName));
        }

        ////////////////////////////
        //Reconstruct and run the channels
        SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
        Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg);

        // Getting foo channels current configuration bytes.
        byte[] channelConfigurationBytes = fooChannel.getChannelConfigurationBytes();

        HttpClient httpclient = HttpClients.createDefault();
        //            HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/decode/common.Config");
        //            httppost.setEntity(new ByteArrayEntity(channelConfigurationBytes));

        String responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes);

        //responseAsString is JSON but use just string operations for this test.

        if (!responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) {

            fail(format("Did not find expected batch timeout '%s', in:%s", ORIGINAL_BATCH_TIMEOUT,
                    responseAsString));
        }

        //Now modify the batch timeout
        String updateString = responseAsString.replace(ORIGINAL_BATCH_TIMEOUT, UPDATED_BATCH_TIMEOUT);

        HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/encode/common.Config");
        httppost.setEntity(new StringEntity(updateString));

        HttpResponse response = httpclient.execute(httppost);

        int statuscode = response.getStatusLine().getStatusCode();
        out("Got %s status for encoding the new desired channel config bytes", statuscode);
        assertEquals(200, statuscode);
        byte[] newConfigBytes = EntityUtils.toByteArray(response.getEntity());

        // Now send to configtxlator multipart form post with original config bytes, updated config bytes and channel name.
        httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/configtxlator/compute/update-from-configs");

        HttpEntity multipartEntity = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody("original", channelConfigurationBytes, ContentType.APPLICATION_OCTET_STREAM,
                        "originalFakeFilename")
                .addBinaryBody("updated", newConfigBytes, ContentType.APPLICATION_OCTET_STREAM,
                        "updatedFakeFilename")
                .addBinaryBody("channel", fooChannel.getName().getBytes()).build();

        httppost.setEntity(multipartEntity);

        response = httpclient.execute(httppost);
        statuscode = response.getStatusLine().getStatusCode();
        out("Got %s status for updated config bytes needed for updateChannelConfiguration ", statuscode);
        assertEquals(200, statuscode);

        byte[] updateBytes = EntityUtils.toByteArray(response.getEntity());

        UpdateChannelConfiguration updateChannelConfiguration = new UpdateChannelConfiguration(updateBytes);

        //To change the channel we need to sign with orderer admin certs which crypto gen stores:

        // private key: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/f1a9a940f57419a18a83a852884790d59b378281347dd3d4a88c2b820a0f70c9_sk
        //certificate:  src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem

        final String sampleOrgName = sampleOrg.getName();
        final SampleUser ordererAdmin = sampleStore.getMember(sampleOrgName + "OrderAdmin", sampleOrgName,
                "OrdererMSP",
                Util.findFileSk(Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/"
                        + testConfig.getFabricConfigGenVers()
                        + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/")
                        .toFile()),
                Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers()
                        + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem")
                        .toFile());

        client.setUserContext(ordererAdmin);

        //Ok now do actual channel update.
        fooChannel.updateChannelConfiguration(updateChannelConfiguration,
                client.getUpdateChannelConfigurationSignature(updateChannelConfiguration, ordererAdmin));

        Thread.sleep(3000); // give time for events to happen

        //Let's add some additional verification...

        client.setUserContext(sampleOrg.getPeerAdmin());

        final byte[] modChannelBytes = fooChannel.getChannelConfigurationBytes();

        responseAsString = configTxlatorDecode(httpclient, modChannelBytes);

        if (!responseAsString.contains(UPDATED_BATCH_TIMEOUT)) {
            //If it doesn't have the updated time out it failed.
            fail(format("Did not find updated expected batch timeout '%s', in:%s", UPDATED_BATCH_TIMEOUT,
                    responseAsString));
        }

        if (responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { //Should not have been there anymore!

            fail(format("Found original batch timeout '%s', when it was not expected in:%s",
                    ORIGINAL_BATCH_TIMEOUT, responseAsString));
        }

        assertTrue(eventCountFilteredBlock > 0); // make sure we got blockevent that were tested.updateChannelConfiguration
        assertTrue(eventCountBlock > 0); // make sure we got blockevent that were tested.

        //Should be no anchor peers defined.
        assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM));
        assertFalse(responseAsString.matches(REGX_S_ANCHOR_PEERS));

        // Get config update for adding an anchor peer.
        Channel.AnchorPeersConfigUpdateResult configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(
                fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(),
                Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051), null);

        assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration());
        assertTrue(configUpdateAnchorPeers.getPeersAdded().contains(PEER_0_ORG_1_EXAMPLE_COM_7051));

        //Now add anchor peer to channel configuration.
        fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(),
                client.getUpdateChannelConfigurationSignature(
                        configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin()));
        Thread.sleep(3000); // give time for events to happen

        // Getting foo channels current configuration bytes to check with configtxlator
        channelConfigurationBytes = fooChannel.getChannelConfigurationBytes();
        responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes);

        // Check is anchor peer in config block?
        assertTrue(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM));
        assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS));

        //Should see what's there.
        configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(),
                sampleOrg.getPeerAdmin(), null, null);

        assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything.
        assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should   be there.
        assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any
        assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything.
        assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // not updating anyting.

        //Now remove the anchor peer -- get the config update block.
        configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(),
                sampleOrg.getPeerAdmin(), null, Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051));

        assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration());
        assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should still be there.
        assertTrue(configUpdateAnchorPeers.getPeersRemoved().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer to remove.
        assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything.
        assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left.

        // Now do the actual update.
        fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(),
                client.getUpdateChannelConfigurationSignature(
                        configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin()));
        Thread.sleep(3000); // give time for events to happen
        // Getting foo channels current configuration bytes to check with configtxlator.
        channelConfigurationBytes = fooChannel.getChannelConfigurationBytes();
        responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes);

        assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); // should be gone!
        assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //ODDLY we still want this even if it's empty!

        //Should see what's there.
        configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(),
                sampleOrg.getPeerAdmin(), null, null);

        assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything.
        assertTrue(configUpdateAnchorPeers.getCurrentPeers().isEmpty()); // peer should be now gone.
        assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any
        assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything.
        assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left

        out("That's all folks!");

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}