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

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

Introduction

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

Prototype

public static byte[] getBytesUtf8(final String string) 

Source Link

Document

Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte array.

Usage

From source file:com.tasktop.c2c.server.internal.profile.crypto.Rfc4716PublicKeyReader.java

/**
 * read a public key from the given text
 * /*from  ww w.j a v a  2  s. c  o  m*/
 * @param keySpec
 *            the key specification.
 * @return the key or null if no key was found
 */
public SshPublicKey readPublicKey(String keySpec) {
    BufferedReader reader = new BufferedReader(new StringReader(keySpec));
    String line;
    SshPublicKey key = null;
    boolean endFound = false;
    boolean dataStarted = false;
    boolean continueHeader = false;
    String base64Data = "";
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            // skip blank lines. They shouldn't really be in there, but if they are we can ignore them.
            if (line.length() != 0) {
                if (key == null) {
                    if (line.equals(START_MARKER)) {
                        key = new SshPublicKey();
                    }
                } else {
                    if (line.equals(END_MARKER)) {
                        endFound = true;
                        break;
                    } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) {
                        // skip headers
                        continueHeader = line.endsWith("\"");
                    } else {
                        dataStarted = true;

                        base64Data += line;
                    }
                }
            }
        }
        if (!endFound) {
            key = null;
        } else {
            if (base64Data.length() > 0) {
                byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

                Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0);
                String algorithm = keyReader.readString();
                if ("ssh-rsa".equals(algorithm)) {
                    key.setAlgorithm("RSA");

                    BigInteger exponent = keyReader.readMpint();
                    BigInteger modulus = keyReader.readMpint();

                    try {
                        KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
                        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

                        byte[] encoded = publicKey.getEncoded();

                        key.setKeyData(encoded);

                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) {
        key = null;
    }
    return key;
}

From source file:de.alpharogroup.crypto.hex.HexExtensionsTest.java

/**
 * Test method for {@link HexExtensions#encodeHex(byte[])}
 *///  www  .  ja va2  s  . co m
@Test
public void testEncodeHex() {
    final String secretMessage = "Secret message";
    final String expected = "536563726574206d657373616765";
    final char[] actualCharArray = HexExtensions.encodeHex(StringUtils.getBytesUtf8(secretMessage));
    final String actual = new String(actualCharArray);
    assertEquals(expected, actual);
}

From source file:dashboard.ImportCSV.java

public Integer importCSVlog(String u, int n) throws Exception {
    String s = "";
    Integer lines = 0;//from www. java  2  s  . com
    URL gigaURL = new URL(u);

    String loginPassword = "marketing:gigaspac3s";
    String base64EncodedString = Base64.encodeBase64String(StringUtils.getBytesUtf8(loginPassword));
    URLConnection conn = gigaURL.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + base64EncodedString);
    InputStream in = conn.getInputStream();

    BufferedReader br = null;

    try {
        br = new BufferedReader(new InputStreamReader(in));

        String inputLine = br.readLine();
        // Skip first line (headers)
        if (inputLine != null)
            inputLine = br.readLine();

        String ip = "";
        String build = "";
        String eventTime = "3/14/13 10:10 AM";
        int x = 0;
        // Loop - limited to n cycles (parameter defined by user)
        while (inputLine != null & lines < n) {
            String[] dataArray = inputLine.split(",");
            //for (String item : dataArray) s = item + "\t";
            x = 0;
            for (String ttt : dataArray)
                x++;
            if (x == 3) {

                ip = dataArray[0];
                build = dataArray[1];
                eventTime = dataArray[2];
            } else if (x == 4) {
                // Line format is corrupted (2 ip's)
                errors++;
                ip = dataArray[1];
                build = dataArray[2];
                eventTime = dataArray[3];
            }

            //s = s + "\n"; 
            inputLine = br.readLine(); // Read next line of data.
            lines++;

            // Track the event in Mixpanel (using the Java API)  - event time is TODAY
            //sendEventToMixpanel(ip, "Product Activation", eventTime, build);

            // Track the event in Mixpanel (using the POST import) - event time is as indicated - in the PAST
            postCSVEventToMixpanel(ip, "Version Check", eventTime, build);

        } // while
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close the file once all data has been read.
        if (br != null)
            br.close();
        return lines;
    }
}

From source file:mvm.rya.indexing.KeyParts.java

/**
 * this is the value to index.//from   ww w  .ja  v  a  2 s . co m
 * @return
 */
public Value getValue() {
    assert statement != null;
    return new Value(StringUtils.getBytesUtf8(StatementSerializer.writeStatement(statement)));
}

From source file:com.smartitengineering.cms.spi.impl.type.search.ContentTypeHelper.java

@Override
protected ContentType convertFromT2F(MultivalueMap<String, Object> toBean) {
    try {/*from  w  w  w  .j av  a  2  s .  c  om*/
        byte[] contentId = StringUtils.getBytesUtf8(toBean.getFirst(SolrFieldNames.ID).toString());
        ContentTypeId id = contentTypeLoader.getFromByteArray(contentId);
        return SmartContentAPI.getInstance().getContentTypeLoader().loadContentType(id);
    } catch (Exception ex) {
        logger.error("Error converting to content type, returning null!", ex);
    }
    return null;
}

From source file:dashboard.Mixpanel.java

public int postVersionCheckToMixpanel(String API_KEY, String TOKEN, String ip, String registrant,
        String eventName, String eventTime, String buildNum) throws IOException {

    String pattern = "M/dd/yy h:mm a";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    try {/*from   w ww . j  a  va 2  s . c o  m*/
        Date date = sdf.parse(eventTime);
        long timeInSecSinceEpoch = date.getTime();
        if (timeInSecSinceEpoch > 0)
            timeInSecSinceEpoch = timeInSecSinceEpoch / 1000;

        JSONObject obj1 = new JSONObject();
        obj1.put("distinct_id", ip);
        obj1.put("ip", ip);
        obj1.put("registrant", registrant);
        obj1.put("build", buildNum);
        obj1.put("time", timeInSecSinceEpoch);
        obj1.put("token", TOKEN);

        JSONObject obj2 = new JSONObject();
        obj2.put("event", eventName);
        obj2.put("properties", obj1);

        String s2 = obj2.toString();
        String encodedJSON = Base64.encodeBase64String(StringUtils.getBytesUtf8(s2));

        return postRequest(encodedJSON, API_KEY);
    } catch (Exception e) {
        System.out.println("\n>>> Can't POST Version Check event to Mixpanel.");
        //throw new RuntimeException("Can't POST to Mixpanel.", e);
        return 0;
    }
}

From source file:com.smartitengineering.cms.spi.impl.events.EventPublisherTest.java

@Test
public void testPublicationOfContent() {
    EventListener listener = injector.getInstance(EventListener.class);
    final Event mockEvent = mockery.mock(Event.class);
    final Content mockContent = mockery.mock(Content.class);
    final ContentId mockContentId = mockery.mock(ContentId.class);
    final WorkspaceId mockWorkspaceId = mockery.mock(WorkspaceId.class);
    final String msgContent = getContentMsg();
    mockery.checking(new Expectations() {

        {/*  ww w . j ava 2s .c  o m*/
            exactly(1).of(mockEvent).getEventSourceType();
            will(returnValue(Event.Type.CONTENT));
            exactly(1).of(mockEvent).getEventType();
            will(returnValue(Event.EventType.CREATE));
            exactly(1).of(mockEvent).getSource();
            will(returnValue(mockContent));
            exactly(1).of(mockContent).getContentId();
            will(returnValue(mockContentId));
            exactly(2).of(mockContentId).getWorkspaceId();
            will(returnValue(mockWorkspaceId));
            exactly(1).of(mockContentId).getId();
            will(returnValue(StringUtils.getBytesUtf8(CONTENT_ID)));
            exactly(1).of(mockWorkspaceId).getGlobalNamespace();
            will(returnValue(WORSPACE_NS));
            exactly(1).of(mockWorkspaceId).getName();
            will(returnValue(WORKSPACE_NAME));
            exactly(1).of(mockPublisher).publishEvent(with("text/plain"), with(msgContent));
            will(returnValue(Boolean.TRUE));
        }
    });
    listener.notify(mockEvent);
    mockery.assertIsSatisfied();
}

From source file:de.alpharogroup.crypto.hex.HexExtensionsTest.java

/**
 * Test method for {@link HexExtensions#encodeHex(byte[], boolean)}
 *//*w  ww  .j  a v a2 s . c  om*/
@Test
public void testEncodeHexBoolean() {
    final String secretMessage = "Secret message";
    final String expected = "536563726574206d657373616765";
    char[] actualCharArray = HexExtensions.encodeHex(StringUtils.getBytesUtf8(secretMessage), true);
    String actual = new String(actualCharArray);
    assertEquals(expected, actual);
    actualCharArray = HexExtensions.encodeHex(StringUtils.getBytesUtf8(secretMessage), false);
    actual = new String(actualCharArray);
    assertEquals(expected.toUpperCase(), actual);
}

From source file:com.smartitengineering.jetty.session.replication.SessionDataId.java

@Override
public void writeExternal(DataOutput output) throws IOException {
    output.write(StringUtils.getBytesUtf8(toString()));
}

From source file:com.cloudera.csd.tools.JsonUtil.java

/**
 * Serializes 'data' into a UTF8 byte array.
 * @param data//from ww  w .  j  a v a  2 s. c  o m
 * @return
 */
public static byte[] valueAsBytes(Object data) {
    return StringUtils.getBytesUtf8(valueAsString(data));
}