Example usage for org.apache.commons.codec.binary Base64 encodeBase64

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64

Introduction

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

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:com.tess4j.rest.Tess4jV1SmokeTest.java

@Test
public void testDoOcr() throws IOException {
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);

    Image image = new Image();
    InputStream inputStream = ClassLoader.getSystemResourceAsStream("eurotext.png");
    image.setUserId("arun0009");
    image.setExtension(".png");
    image.setImage(Base64.encodeBase64(IOUtils.toByteArray(inputStream)));
    String response = given().contentType("application/json").headers(headers).when().body(image).expect()
            .statusCode(200).post("http://localhost:8080/ocr/v0.9/upload").asString();
    System.out.println(response);
}

From source file:com.rackspacecloud.blueflood.io.serializers.TimerSerializationTest.java

@Test
public void testV1RoundTrip() throws IOException {
    // build up a Timer
    TimerRollup r0 = new TimerRollup().withSum(42).withCountPS(23.32d).withAverage(56).withVariance(853.3245d)
            .withMinValue(2).withMaxValue(987).withCount(345);
    r0.setPercentile("foo", 741.32d);
    r0.setPercentile("bar", 0.0323d);

    if (System.getProperty("GENERATE_TIMER_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream(
                "src/test/resources/serializations/timer_version_" + Constants.VERSION_1_TIMER + ".bin", false);
        os.write(Base64.encodeBase64(new NumericSerializer.TimerRollupSerializer().toByteBuffer(r0).array()));
        os.write("\n".getBytes());
        os.close();//from w  ww  .jav a  2 s .  c  om
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    // ensure historical reads work.
    int version = 0;
    int maxVersion = Constants.VERSION_1_TIMER;

    int count = 0;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/timer_version_" + version + ".bin"));
        ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        TimerRollup r1 = new NumericSerializer.TimerRollupSerializer().fromByteBuffer(bb);
        Assert.assertEquals(r0, r1);
        count++;
        version++;
    }

    Assert.assertTrue("Nothing was tested", count > 0);
}

From source file:com.mindquarry.desktop.preferences.profile.Profile.java

public static String encodeBase64(String text) {
    try {//from ww w  .jav a 2 s . co  m
        return new String(Base64.encodeBase64(text.getBytes("UTF-8")), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return new String(Base64.encodeBase64(text.getBytes()));
    }
}

From source file:com.cloud.bridge.util.S3SoapAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * //from  w  ww .  j  a  v  a  2 s. c o  m
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 */
private static String calculateRFC2104HMAC(String signIt, String secretKey) {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));

    } catch (Exception e) {
        logger.error("Failed to generate keyed HMAC on soap request: " + e.getMessage());
        return null;
    }
    return result.trim();
}

From source file:com.tomcat.monitor.zabbix.ZabbixSender.java

public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host,
        final String key, final String value) throws IOException {

    final byte[] response = new byte[1024];

    final long start = System.currentTimeMillis();

    final int TIMEOUT = zabbixTimeout * 1000;

    final StringBuilder message = new StringBuilder("<req><host>");
    message.append(new String(Base64.encodeBase64(host.getBytes())));
    message.append("</host><key>");
    message.append(new String(Base64.encodeBase64(key.getBytes())));
    message.append("</key><data>");
    message.append(new String(Base64.encodeBase64(value.getBytes())));
    message.append("</data></req>");

    if (log.isDebugEnabled()) {
        log.debug("sending " + message);
    }/* w  w  w . ja v  a  2  s .c  o  m*/

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    try {
        zabbix = new Socket(zabbixServer, zabbixPort);
        zabbix.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(zabbix.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = zabbix.getInputStream();
        final int read = in.read(response);
        if (log.isDebugEnabled()) {
            log.debug("received " + new String(response));
        }
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'");
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (zabbix != null) {
            zabbix.close();
        }
    }
    log.info("send() " + (System.currentTimeMillis() - start) + " ms");
}

From source file:io.apiman.common.util.AesEncrypter.java

/**
 * Encrypt./*from   www  . j  a va2  s. c  o  m*/
 * @param plainText the plain text
 * @param secretKey the secret key
 * @return the string
 */
public static String encrypt(String secretKey, String plainText) {
    if (plainText == null) {
        return null;
    }
    byte[] encrypted;
    Cipher cipher;
    try {
        SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);

        cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }
    try {
        encrypted = cipher.doFinal(plainText.getBytes());
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException(e);
    } catch (BadPaddingException e) {
        throw new RuntimeException(e);
    }
    return "$CRYPT::" + new String(Base64.encodeBase64(encrypted)); //$NON-NLS-1$
}

From source file:gov.nih.nci.system.web.client.RESTfulDeleteClient.java

public Response delete(String url) {
    try {//from  w w w .j  a  v a  2s .  c  om
        if (url == null) {
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_URL</code>");
            buffer.append("<message>Invalid URL: " + url + "</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }
        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        if (userName != null && password != null) {
            String base64encodedUsernameAndPassword = new String(
                    Base64.encodeBase64((userName + ":" + password).getBytes()));
            client.header("Authorization", "Basic " + base64encodedUsernameAndPassword);
        }

        return client.delete();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.tomakehurst.wiremock.http.BodyTest.java

@Test
public void constructsFromBase64() {
    byte[] base64Encoded = Base64.encodeBase64("this content".getBytes());
    String encodedText = stringFromBytes(base64Encoded);
    Body body = Body.fromOneOf(null, null, null, encodedText);

    assertThat(body.asString(), is("this content"));
    assertThat(body.isBinary(), is(true));
}

From source file:com.arwantech.docjavaui.utils.TripleDES.java

public String encrypt(String unencryptedString) {
    String encryptedString = null;
    try {//from   w  w  w  .ja va  2s.com
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
        byte[] encryptedText = cipher.doFinal(plainText);
        encryptedString = new String(Base64.encodeBase64(encryptedText));
    } catch (InvalidKeyException | UnsupportedEncodingException | IllegalBlockSizeException
            | BadPaddingException e) {
        e.printStackTrace();
    }
    return encryptedString;
}

From source file:gaffer.accumulo.utils.IngestUtils.java

/**
 * Get the existing splits from a table in Accumulo and write a splits file.
 * The number of splits is returned.//w  w w  . j  a v  a 2 s .  c  om
 * 
 * @param conn  An existing connection to an Accumulo instance
 * @param table  The table name
 * @param fs  The FileSystem in which to create the splits file
 * @param splitsFile  A path for the splits file
 * @return The number of splits in the table
 * @throws TableNotFoundException
 * @throws IOException
 */
public static int createSplitsFile(Connector conn, String table, FileSystem fs, Path splitsFile)
        throws TableNotFoundException, IOException {
    // Get the splits from the table
    Collection<Text> splits = conn.tableOperations().getSplits(table);

    // Write the splits to file
    if (splits.isEmpty()) {
        return 0;
    }
    PrintStream out = new PrintStream(new BufferedOutputStream(fs.create(splitsFile, true)));
    for (Text split : splits) {
        out.println(new String(Base64.encodeBase64(split.getBytes())));
    }
    out.close();

    return splits.size();
}