Example usage for org.apache.commons.codec.binary StringUtils newStringUtf8

List of usage examples for org.apache.commons.codec.binary StringUtils newStringUtf8

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary StringUtils newStringUtf8.

Prototype

public static String newStringUtf8(final byte[] bytes) 

Source Link

Document

Constructs a new String by decoding the specified array of bytes using the UTF-8 charset.

Usage

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

private String[] getAuthHeaderTokens(HttpServletRequest request, String authType)
        throws HttpAuthenticationException {
    String authHeaderBase64 = getAuthHeader(request, authType);
    String authHeaderString = StringUtils.newStringUtf8(Base64.decodeBase64(authHeaderBase64.getBytes()));
    String[] creds = authHeaderString.split(":");
    return creds;
}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageAttachment() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some text".getBytes());

    runner.run();/*from  w  w w  .  ja va 2 s. co  m*/

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());

    assertTrue(message.getContent() instanceof MimeMultipart);

    final MimeMultipart multipart = (MimeMultipart) message.getContent();
    final BodyPart part = multipart.getBodyPart(0);
    final InputStream is = part.getDataHandler().getInputStream();
    final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
    assertEquals("Message Body", decodedText);

    final BodyPart attachPart = multipart.getBodyPart(1);
    final InputStream attachIs = attachPart.getDataHandler().getInputStream();
    final String text = IOUtils.toString(attachIs, "UTF-8");
    assertEquals("Some text", text);

    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

From source file:org.apache.samza.monitor.JobsClient.java

/**
 * This method initiates http get request on the request url and returns the
 * response returned from the http get.//from ww  w.  ja  v  a  2s. c  o m
 * @param requestUrl url on which the http get request has to be performed.
 * @return the http get response.
 * @throws IOException if there are problems with the http get request.
 */
private byte[] httpGet(String requestUrl) throws IOException {
    GetMethod getMethod = new GetMethod(requestUrl);
    try {
        int responseCode = httpClient.executeMethod(getMethod);
        LOG.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
        byte[] response = getMethod.getResponseBody();
        if (responseCode != HttpStatus.SC_OK) {
            throw new SamzaException(
                    String.format("Received response code: %s for get request on: %s, with message: %s.",
                            responseCode, requestUrl, StringUtils.newStringUtf8(response)));
        }
        return response;
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.samza.rest.proxy.job.YarnRestJobStatusProvider.java

/**
 * Issues a HTTP Get request to the provided url and returns the response
 * @param requestUrl the request url/*from w  w  w  .  ja  va  2s  . c  o m*/
 * @return the response
 * @throws IOException if there are problems with the http get request.
 */
byte[] httpGet(String requestUrl) throws IOException {
    GetMethod getMethod = new GetMethod(requestUrl);
    try {
        int responseCode = this.httpClient.executeMethod(getMethod);
        LOGGER.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
        byte[] response = getMethod.getResponseBody();
        if (responseCode != HttpStatus.SC_OK) {
            throw new SamzaException(
                    String.format("Received response code: %s for get request on: %s, with message: %s.",
                            responseCode, requestUrl, StringUtils.newStringUtf8(response)));
        }
        return response;
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.asimba.wa.integrationtest.saml2.sp.SAMLSPHandler.java

private void handleAssertionConsumerService(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    _logger.info("Handling assertion consumer for {}", _entityId);
    Response samlResponse = new Response();

    // Get response from request (must be in POST-data)
    String samlResponseString = request.getParameter("SAMLResponse");
    if (samlResponseString == null) {
        _logger.error("Did not receive SAMLResponse parameter");
        return;/*ww  w .  j av a  2 s. c  o m*/
    }

    // Base64-decode the incoming message
    samlResponseString = StringUtils.newStringUtf8(Base64.decode(samlResponseString));

    _logger.info("Received SAMLResponse:\n{}", samlResponseString);

    samlResponse.loadResponse(samlResponseString);

    _logger.info("Succesfully received unverified SAMLResponse message");
    _samlResponse = samlResponse;

    response.getWriter().print("OK");
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.parser.beans.types.Base64Function.java

public String getEncodedValue() {
    return StringUtils.newStringUtf8(Base64.encodeBase64(toEncode.getValue().getBytes()));
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.parser.deserializers.ValueDeserializerTest.java

@Test
public void testDeserializeBase64() throws PrivateEc2ParserException {
    SimpleValue mapJson = ParserUtils.mapJson(SimpleValue.class,
            "{\"Value\": { \"Fn::Base64\" : \"hello world\" }}");
    assertNotNull(mapJson.getValueType());
    String helloWorldBase64 = StringUtils.newStringUtf8(Base64.encodeBase64("hello world".getBytes()));
    Assert.assertThat(mapJson.getValueType().getValue(), CoreMatchers.is("hello world"));
    Assert.assertThat(((Base64Function) mapJson.getValueType()).getEncodedValue(),
            CoreMatchers.is(helloWorldBase64));
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.parser.deserializers.ValueDeserializerTest.java

@Test
public void testDeserializeBase64AndJoin() throws Exception {
    String template = "{\"Value\": { \"Fn::Base64\" : { \"Fn::Join\" : [\" \", [\"hello\",\"pretty\",\"world\"]]}}}";
    SimpleValue mapJson = ParserUtils.mapJson(SimpleValue.class, template);
    assertNotNull(mapJson.getValueType());
    String base64 = StringUtils.newStringUtf8(Base64.encodeBase64("hello pretty world ".getBytes()));
    Assert.assertThat(mapJson.getValueType().getValue(), CoreMatchers.is("hello pretty world "));
    assertThat(((Base64Function) mapJson.getValueType()).getEncodedValue(), is(base64));
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private Instance createEC2Instance(final PrivateEc2Template cfnTemplate, final ProvisioningContextImpl ctx,
        final boolean management, final String machineName, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {

    final ComputeTemplate template = this.getManagerComputeTemplate();
    final InstanceProperties properties = cfnTemplate.getEC2Instance().getProperties();

    final String availabilityZone = properties.getAvailabilityZone() == null ? null
            : properties.getAvailabilityZone().getValue();
    final Placement placement = availabilityZone == null ? null : new Placement(availabilityZone);
    final String imageId = properties.getImageId() == null ? null : properties.getImageId().getValue();
    final String instanceType = properties.getInstanceType() == null ? null
            : properties.getInstanceType().getValue();
    final String keyName = properties.getKeyName() == null ? null : properties.getKeyName().getValue();
    final String privateIpAddress = properties.getPrivateIpAddress() == null ? null
            : properties.getPrivateIpAddress().getValue();
    final List<String> securityGroupIds = properties.getSecurityGroupIdsAsString();
    final List<String> securityGroups = properties.getSecurityGroupsAsString();

    S3Object s3Object = null;
    try {/*from  w  ww. j a v  a  2  s  .  c o m*/

        String userData = null;
        if (properties.getUserData() != null) {
            // Generate ENV script for the provisioned machine
            final StringBuilder sb = new StringBuilder();
            final String script = management ? this.generateManagementCloudifyEnv(ctx)
                    : this.generateCloudifyEnv(ctx);

            s3Object = this.uploadCloudDir(ctx, script, management);
            final String cloudFileS3 = this.amazonS3Uploader.generatePresignedURL(s3Object);

            String cloudFileDir = (String) template.getRemoteDirectory();
            // Remove '/' from the path if it's the last char.
            if (cloudFileDir.length() > 1 && cloudFileDir.endsWith("/")) {
                cloudFileDir = cloudFileDir.substring(0, cloudFileDir.length() - 1);
            }
            final String endOfLine = " >> /tmp/cloud.txt\n";
            sb.append("#!/bin/bash\n");
            sb.append("export TMP_DIRECTORY=/tmp").append(endOfLine);
            sb.append("export S3_ARCHIVE_FILE='" + cloudFileS3 + "'").append(endOfLine);
            sb.append("wget -q -O $TMP_DIRECTORY/cloudArchive.tar.gz $S3_ARCHIVE_FILE").append(endOfLine);
            sb.append("mkdir -p " + cloudFileDir).append(endOfLine);
            sb.append("tar zxvf $TMP_DIRECTORY/cloudArchive.tar.gz -C " + cloudFileDir).append(endOfLine);
            sb.append("rm -f $TMP_DIRECTORY/cloudArchive.tar.gz").append(endOfLine);
            sb.append("echo ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);
            sb.append("chmod 755 ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT)
                    .append(endOfLine);
            sb.append("source ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);

            sb.append(properties.getUserData().getValue());
            userData = sb.toString();
            logger.fine("Instanciate ec2 with user data:\n" + userData);
            userData = StringUtils.newStringUtf8(Base64.encodeBase64(userData.getBytes()));
        }

        List<BlockDeviceMapping> blockDeviceMappings = null;
        AWSEC2Volume volumeConfig = null;
        if (properties.getVolumes() != null) {
            blockDeviceMappings = new ArrayList<BlockDeviceMapping>(properties.getVolumes().size());
            for (final VolumeMapping volMapping : properties.getVolumes()) {
                volumeConfig = cfnTemplate.getEC2Volume(volMapping.getVolumeId().getValue());
                blockDeviceMappings
                        .add(this.createBlockDeviceMapping(volMapping.getDevice().getValue(), volumeConfig));
            }
        }

        final RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
        runInstancesRequest.withPlacement(placement);
        runInstancesRequest.withImageId(imageId);
        runInstancesRequest.withInstanceType(instanceType);
        runInstancesRequest.withKeyName(keyName);
        runInstancesRequest.withPrivateIpAddress(privateIpAddress);
        runInstancesRequest.withSecurityGroupIds(securityGroupIds);
        runInstancesRequest.withSecurityGroups(securityGroups);
        runInstancesRequest.withMinCount(1);
        runInstancesRequest.withMaxCount(1);
        runInstancesRequest.withBlockDeviceMappings(blockDeviceMappings);
        runInstancesRequest.withUserData(userData);

        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("EC2::Instance request=" + runInstancesRequest);
        }

        final RunInstancesResult runInstances = this.ec2.runInstances(runInstancesRequest);
        if (runInstances.getReservation().getInstances().size() != 1) {
            throw new CloudProvisioningException(
                    "Request runInstace fails (request=" + runInstancesRequest + ").");
        }

        Instance ec2Instance = runInstances.getReservation().getInstances().get(0);
        ec2Instance = this.waitRunningInstance(ec2Instance, duration, unit);
        this.tagEC2Instance(ec2Instance, machineName, cfnTemplate.getEC2Instance());
        this.tagEC2Volumes(ec2Instance.getInstanceId(), cfnTemplate);

        final boolean debug = BooleanUtils.toBoolean((String) template.getCustom().get("debugMode"));
        if (debug) {
            debugExecutors.submit(new EC2Console(ec2Instance.getInstanceId(), ec2Instance.getPublicIpAddress(),
                    DEFAULT_CLOUDIFY_AGENT_PORT));
        }
        this.waitRunningAgent(ec2Instance.getPublicIpAddress(), duration, unit);

        return ec2Instance;
    } finally {
        if (s3Object != null) {
            this.amazonS3Uploader.deleteS3Object(s3Object.getBucketName(), s3Object.getKey());
        }
    }
}

From source file:org.cogroo.addon.util.SecurityUtil.java

public String encode(byte[] key) {
    return StringUtils.newStringUtf8(Base64.encodeBase64(key, false));
}