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.kie.workbench.common.stunner.client.widgets.palette.factory.icons.svg.SVGIconRendererTest.java

protected void initDataURI(final String header, final InputStream imageStream) throws Exception {
    renderer.render(resource);// w  w  w  .  j  av a2s  .co m
    when(resource.getResource()).thenReturn(dataResource);
    when(dataResource.getSafeUri()).thenReturn(safeUri);
    StringBuilder sb = new StringBuilder();
    sb.append(header);
    sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(IOUtils.toByteArray(imageStream))));
    when(safeUri.asString()).thenReturn(sb.toString());
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.utils.StringUtility.java

public static String responseAsString(HttpResponseWrapper response) {
    return StringUtils.newStringUtf8(response.getContent());
}

From source file:org.saadahmed.codec.Base64Hex.java

/**
 * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
 * <p>/*from w ww . ja  v  a 2 s .  co m*/
 * When encoding the line length and line separator are given in the constructor, and the encoding table is
 * STANDARD_ENCODE_TABLE.
 * </p>
 * <p>
 * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
 * </p>
 * <p>
 * When decoding all variants are supported.
 * </p>
 *
 * @param lineLength
 *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
 *            4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when
 *            decoding.
 * @param lineSeparator
 *            Each line of encoded data will end with this sequence of bytes.
 * @throws IllegalArgumentException
 *             Thrown when the provided lineSeparator included some base64 characters.
 * @since 1.4
 */
public Base64Hex(final int lineLength, final byte[] lineSeparator) {
    super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, lineLength,
            lineSeparator == null ? 0 : lineSeparator.length);
    // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
    // @see test case Base64Test.testConstructors()
    if (lineSeparator != null) {
        if (containsAlphabetOrPad(lineSeparator)) {
            final String sep = StringUtils.newStringUtf8(lineSeparator);
            throw new IllegalArgumentException(
                    "lineSeparator must not contain base64 characters: [" + sep + "]");
        }
        if (lineLength > 0) { // null line-sep forces no chunking rather than throwing IAE
            this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
            this.lineSeparator = new byte[lineSeparator.length];
            System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
        } else {
            this.encodeSize = BYTES_PER_ENCODED_BLOCK;
            this.lineSeparator = null;
        }
    } else {
        this.encodeSize = BYTES_PER_ENCODED_BLOCK;
        this.lineSeparator = null;
    }
    this.decodeSize = this.encodeSize - 1;
}

From source file:org.saadahmed.codec.Base64Hex.java

/**
 * Encodes binary data using the base64 algorithm but does not chunk the output.
 *
 * NOTE:  We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
 * single-line non-chunking (commons-codec-1.5).
 *
 * @param binaryData/*from   ww  w . j  a  v a 2 s  .  c  om*/
 *            binary data to encode
 * @return String containing Base64 characters.
 * @since 1.4 (NOTE:  1.4 chunked the output, whereas 1.5 does not).
 */
public static String encodeBase64HexString(final byte[] binaryData) {
    return StringUtils.newStringUtf8(encodeBase64Hex(binaryData, false));
}

From source file:org.saadahmed.codec.Base64HexTest.java

/**
 * Test the Base64 implementation/*  w  w w.  jav a  2  s .  c  o m*/
 */
@Test
public void testBase64() {
    final String content = "Hello World";
    String encodedContent;
    byte[] encodedBytes = Base64Hex.encodeBase64Hex(StringUtils.getBytesUtf8(content));
    encodedContent = StringUtils.newStringUtf8(encodedBytes);
    assertEquals("encoding Hello World", "I6LiR6yWLszoR6G", encodedContent);

    Base64Hex b64Hex = new Base64Hex(BaseNCodec.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking
    encodedBytes = b64Hex.encode(StringUtils.getBytesUtf8(content));
    encodedContent = StringUtils.newStringUtf8(encodedBytes);
    assertEquals("encoding Hello World", "I6LiR6yWLszoR6G", encodedContent);

    b64Hex = new Base64Hex(0, null); // null lineSeparator same as saying no-chunking
    encodedBytes = b64Hex.encode(StringUtils.getBytesUtf8(content));
    encodedContent = StringUtils.newStringUtf8(encodedBytes);
    assertEquals("encoding Hello World", "I6LiR6yWLszoR6G", encodedContent);

    // bogus characters to decode (to skip actually) {e-acute*6}
    final byte[] decode = b64Hex.decode("I6LiR6yWLszoR6G");
    String decodeString = StringUtils.newStringUtf8(decode);
    assertEquals("decode Hello World", "Hello World", decodeString);
}

From source file:org.skfiy.typhon.rnsd.service.handler.AppleRechargingHandler.java

@Override
public RechargingBO handle(JSONObject json) throws TradeValidatedException {
    String uri;/*from   w w w.j  ava  2 s  .  c  o m*/
    if ("Sandbox".equalsIgnoreCase(json.getString("environment"))) {
        uri = SANDBOX_URL;
    } else {
        uri = VERIFY_URL;
    }

    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost post = new HttpPost(uri);

    List<NameValuePair> nvps = new ArrayList<>();

    String receiptStr = json.getString("data");
    Matcher m = P.matcher(receiptStr);
    m.find();

    String signature = m.group(2).replaceAll(" ", "+");
    receiptStr = receiptStr.replace(m.group(2), signature);

    String receiptData = org.skfiy.typhon.rnsd.Base64.encodeBytes(receiptStr.getBytes());
    JSONObject receiptJson = new JSONObject();
    receiptJson.put("receipt-data", receiptData);

    try {

        post.setEntity(new StringEntity(receiptJson.toJSONString(), ContentType.APPLICATION_JSON));
        CloseableHttpResponse resp = hc.execute(post);

        String str = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
        JSONObject result = JSON.parseObject(str);

        if (result.getIntValue("status") != 0) {
            throw new TradeValidatedException("success", "no verify");
        }

        JSONObject receipt = result.getJSONObject("receipt");

        // result
        Recharging recharging = new Recharging();
        recharging.setTradeId(receipt.getString("transaction_id"));
        recharging.setPlatform(Platform.apple.getLabel());

        String callbackInfo = StringUtils.newStringUtf8(Base64.decodeBase64(json.getString("callbackInfo")));
        JSONObject extra = JSON.parseObject(callbackInfo);

        recharging.setUid(extra.getString("uid"));
        recharging.setRegion(extra.getString("region"));
        recharging.setGoods(extra.getString("goods"));

        LOG.debug("{}", extra);

        recharging.setAmount(extra.getInteger("goods"));
        recharging.setCreationTime(System.currentTimeMillis() / 1000);
        recharging.setChannel(Platform.apple.getLabel());

        return (new RechargingBO(recharging, "success"));
    } catch (Exception ex) {
        throw new TradeValidatedException("success", ex.getMessage());
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:org.skfiy.typhon.rnsd.service.handler.LJRechargingHandler.java

@Override
public RechargingBO handle(JSONObject json) throws TradeValidatedException {
    validate(json);//from   w  w w.ja  v a2 s  . c  o m

    int price = json.getIntValue("price") / 100;

    Recharging recharging = new Recharging();
    recharging.setTradeId(json.getString("orderId"));
    recharging.setPlatform(Platform.lj.getLabel());

    String callbackInfo = StringUtils.newStringUtf8(Base64.decodeBase64(json.getString("callbackInfo")));
    JSONObject extra = JSON.parseObject(callbackInfo);

    String goods = extra.getString("goods");
    if (!goodsPrices.containsKey(goods) || price != goodsPrices.get(goods).intValue()) {
        throw new TradeValidatedException("fail", "goods price error");
    }

    recharging.setUid(extra.getString("uid"));
    recharging.setRegion(extra.getString("region"));
    recharging.setGoods(goods);

    recharging.setAmount(price);
    recharging.setCreationTime(System.currentTimeMillis() / 1000);
    recharging.setChannel(json.getString("channelLabel"));

    return (new RechargingBO(recharging, "success"));
}

From source file:org.skfiy.typhon.rnsd.service.handler.UCRechargingHandler.java

@Override
public RechargingBO handle(JSONObject json) throws TradeValidatedException {
    validate(json);//  w  ww. j  ava  2 s.  co  m

    JSONObject data = json.getJSONObject("data");
    Recharging recharging = new Recharging();
    recharging.setTradeId(data.getString("orderId"));
    recharging.setPlatform(Platform.uc.getLabel());

    String callbackInfo = StringUtils.newStringUtf8(Base64.decodeBase64(data.getString("callbackInfo")));
    JSONObject extra = JSON.parseObject(callbackInfo);
    recharging.setUid(extra.getString("uid"));
    recharging.setRegion(extra.getString("region"));
    recharging.setGoods(extra.getString("goods"));

    recharging.setAmount(data.getDouble("amount").intValue());
    recharging.setCreationTime(System.currentTimeMillis() / 1000);

    return (new RechargingBO(recharging, "SUCCESS"));
}

From source file:org.slc.sli.dal.encrypt.AesCipher.java

@Override
public Object decrypt(String data) {
    String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':');
    // String[] splitData = data.split(":");
    if (splitData.length != 2) {
        return null;
    } else {//from   w  ww . ja v  a  2 s.c o m
        if (splitData[0].equals("ESTRING")) {
            return StringUtils.newStringUtf8(decryptToBytes(splitData[1]));
        } else if (splitData[0].equals("EBOOL")) {
            return decryptBinary(splitData[1], Boolean.class);
        } else if (splitData[0].equals("EINT")) {
            return decryptBinary(splitData[1], Integer.class);
        } else if (splitData[0].equals("ELONG")) {
            return decryptBinary(splitData[1], Long.class);
        } else if (splitData[0].equals("EDOUBLE")) {
            return decryptBinary(splitData[1], Double.class);
        } else {
            return null;
        }
    }
}

From source file:org.wso2.carbon.apimgt.importexport.utils.AuthenticatorUtil.java

/**
 * Checks whether user has provided non blank username and password for authentication
 *
 * @param headers Http Headers of the request
 * @return boolean Whether a user name and password has been provided for authentication
 * @throws APIExportException If an error occurs while extracting username and password from
 *                            the header
 *//*from   w ww.ja  v  a  2s  .com*/
private static boolean isValidCredentials(HttpHeaders headers) throws APIExportException {

    //Fetch authorization header
    final List<String> authorization = headers.getRequestHeader(AUTHORIZATION_PROPERTY);

    //If no authorization information present; block access
    if (authorization == null || authorization.isEmpty()) {
        return false;
    }

    //Get encoded username and password
    final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

    //Decode username and password
    String usernameAndPassword;
    usernameAndPassword = StringUtils.newStringUtf8(Base64.decodeBase64(encodedUserPassword.getBytes()));

    if (usernameAndPassword != null) {
        //Split username and password tokens
        final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
        username = tokenizer.nextToken();
        password = tokenizer.nextToken();

        if (username != null && password != null) {
            return true;
        }
    }

    return false;
}