Example usage for java.lang String getBytes

List of usage examples for java.lang String getBytes

Introduction

In this page you can find the example usage for java.lang String getBytes.

Prototype

public byte[] getBytes() 

Source Link

Document

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Usage

From source file:com.github.liyp.test.TestMain.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // add a shutdown hook to stop the server
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override//  ww w  .j  a va2 s. c o m
        public void run() {
            System.out.println("########### shoutdown begin....");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("########### shoutdown end....");
        }
    }));

    System.out.println(args.length);
    Iterator<String> iterator1 = IteratorUtils
            .arrayIterator(new String[] { "one", "two", "three", "11", "22", "AB" });
    Iterator<String> iterator2 = IteratorUtils.arrayIterator(new String[] { "a", "b", "c", "33", "ab", "aB" });

    Iterator<String> chainedIter = IteratorUtils.chainedIterator(iterator1, iterator2);

    System.out.println("==================");

    Iterator<String> iter = IteratorUtils.filteredIterator(chainedIter, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            System.out.println("xx:" + arg0.toString());
            String str = (String) arg0;
            return str.matches("([a-z]|[A-Z]){2}");
        }
    });
    while (iter.hasNext()) {
        System.out.println(iter.next());
    }

    System.out.println("===================");

    System.out.println("asas".matches("[a-z]{4}"));

    System.out.println("Y".equals(null));

    System.out.println(String.format("%02d", 1000L));

    System.out.println(ArrayUtils.toString(splitAndTrim(" 11, 21,12 ,", ",")));

    System.out.println(new ArrayList<String>().toString());

    JSONObject json = new JSONObject("{\"keynull\":null}");
    json.put("bool", false);
    json.put("keya", "as");
    json.put("key2", 2212222222222222222L);
    System.out.println(json);
    System.out.println(json.get("keynull").equals(null));

    String a = String.format("{\"id\":%d,\"method\":\"testCrossSync\"," + "\"circle\":%d},\"isEnd\":true", 1,
            1);
    System.out.println(a.getBytes().length);

    System.out.println(new String[] { "a", "b" });

    System.out.println(new JSONArray("[\"aa\",\"\"]"));

    String data = String.format("%9d %s", 1, RandomStringUtils.randomAlphanumeric(10));
    System.out.println(data.getBytes().length);

    System.out.println(ArrayUtils.toString("1|2| 3|  333||| 3".split("\\|")));

    JSONObject j1 = new JSONObject("{\"a\":\"11111\"}");
    JSONObject j2 = new JSONObject(j1.toString());
    j2.put("b", "22222");
    System.out.println(j1 + " | " + j2);

    System.out.println("======================");

    String regex = "\\d+(\\-\\d+){2} \\d+(:\\d+){2}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("2015-12-28 15:46:14  _NC250_MD:motion de\n");
    String eventDate = matcher.find() ? matcher.group() : "";

    System.out.println(eventDate);
}

From source file:Test.java

public static void main(String[] args) throws Exception {

    AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
    InetSocketAddress address = new InetSocketAddress("localhost", 5000);

    Future<Void> future = client.connect(address);
    System.out.println("Client: Waiting for the connection to complete");
    future.get();// w  w  w  . ja va  2 s.  c o m

    String message = "";
    while (!message.equals("quit")) {
        System.out.print("Enter a message: ");
        Scanner scanner = new Scanner(System.in);
        message = scanner.nextLine();
        System.out.println("Client: Sending ...");
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        System.out.println("Client: Message sent: " + new String(buffer.array()));
        client.write(buffer);
    }
}

From source file:com.enitalk.controllers.paypal.Usd.java

public static void main(String[] args) throws IOException, ParseException {

    String rs = Request.Get("http://www.cbr.ru/scripts/XML_daily.asp")
            .addHeader("Content-type", "application/xml;charset=utf-8").execute().returnContent()
            .asString(Charset.forName("windows-1251"));

    Pair<AutoPilot, VTDNav> bb = getNavigator(rs.getBytes());
    String change = getChange(bb.getLeft(), bb.getRight());

    System.out.println("Rs " + change);
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    df.setDecimalFormatSymbols(symbols);
    BigDecimal dd = BigDecimal.valueOf(df.parse(change).doubleValue()).setScale(2, RoundingMode.CEILING);
    System.out.println("Dd " + dd);
}

From source file:com.sapienter.jbilling.tools.ConvertToBinHexa.java

/**
 * @param args/*from  w ww  . j a  v a  2 s .co  m*/
 */
public static void main(String[] args) {
    String driver = null;

    if (args.length < 3) {
        System.err.println("Usage: url username password [driver]");
        System.exit(1);
        return;
    }
    if (args.length < 4) {
        driver = "org.postgresql.Driver";
    } else {
        driver = args[3];
    }

    System.out.println("Converting credit cards ... ");
    int count = 0;
    try {
        connection = getConnection(args[0], args[1], args[2], driver);
        ResultSet rows = getCCRowsToUpdate();
        while (rows == null) { //rows.next() - skip CC
            int rowId = rows.getInt(1);
            String cryptedNumber = rows.getString(2);
            String cryptedName = rows.getString(3);
            int userId = rows.getInt(4);

            JBCrypto oldCrypt = JBCrypto.getCreditCardCrypto();
            oldCrypt.setUseHexForBinary(false);
            String plainNumber;
            try {
                plainNumber = oldCrypt.decrypt(cryptedNumber);
            } catch (Exception e) {
                plainNumber = "Not available";
                System.out.println("User id " + userId + " cc id " + rowId + " with bad cc number");
            }
            String plainName;
            try {
                plainName = oldCrypt.decrypt(cryptedName);
            } catch (RuntimeException e) {
                plainName = "Not available";
                System.out.println("User id " + userId + " cc id " + rowId + " with bad cc name");
            }
            // now recrypt using the new way
            JBCrypto newCrypt = JBCrypto.getCreditCardCrypto();
            newCrypt.setUseHexForBinary(true);
            cryptedName = newCrypt.encrypt(plainName);
            cryptedNumber = newCrypt.encrypt(plainNumber);
            //System.out.println("new " + cryptedName + " and " + cryptedNumber);
            updateCCRow(rowId, cryptedName, cryptedNumber);
            count++;
        }
        rows.close();

        System.out.println("Converting user passwords ... ");
        count = 0;
        rows = getUserRowsToUpdate();
        while (rows.next()) {
            int rowId = rows.getInt(1);
            String oldPassword = rows.getString(2);

            try {
                String newPassword = Util.binaryToString(Base64.decodeBase64(oldPassword.getBytes()));
                System.out.println("new " + newPassword + " old " + oldPassword);
                updateUserRow(rowId, newPassword);
                count++;
            } catch (Exception e) {
                System.out.println("Error with password " + oldPassword + " :" + e.getMessage());
            }
        }
        rows.close();

        connection.close();
    } catch (Exception e) {
        System.err.println("Error! " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
    System.out.println("Finished! " + count + " rows populated");

}

From source file:com.yobidrive.diskmap.buckets.BucketFNVHash.java

public static void main(String[] args) {
    // need to pass Ethernet address; can either use real one (shown here)
    EthernetAddress nic = EthernetAddress.fromInterface();
    // or bogus which would be gotten with: EthernetAddress.constructMulticastAddress()
    TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(nic);
    // also: we don't specify synchronizer, getting an intra-JVM syncer; there is
    // also external file-locking-based synchronizer if multiple JVMs run JUG

    int numIterations = 4096 * 16 * 24;
    int numBuckets = 4096 * 16 * 2;
    ;/*  w  w  w. j  a  v a  2  s . co  m*/
    int[] buckets = new int[numBuckets];
    BucketFNVHash hash = new BucketFNVHash(numBuckets);
    long smallest = Integer.MAX_VALUE;
    long biggest = Integer.MIN_VALUE;
    int collisionsI = 0;
    int collisions6 = 0;
    int collisions2 = 0;
    int collisions3 = 0;
    int collisions4 = 0;
    int collisions5 = 0;
    long smallestI = Integer.MAX_VALUE;
    long biggestI = Integer.MIN_VALUE;
    int counter = 0;
    int maxCols = 0;

    for (int i = 0; i < numIterations; i++) {
        String key = uuidGenerator.generate().toString();
        long valVoldemort = Math.abs(hash.hashVoldemort(key.getBytes()));
        if (valVoldemort < smallest)
            smallest = valVoldemort;
        if (valVoldemort > biggest)
            biggest = valVoldemort;

        long partition = valVoldemort % 16; // 16 partitions
        if (partition == 7) {
            counter++; // 1 more in partition
            int val = (int) hash.hash(key.getBytes());
            if (val < smallestI)
                smallestI = val;
            if (val > biggestI)
                biggestI = val;
            buckets[val]++;
            if (buckets[val] > maxCols)
                maxCols = buckets[val];
            if (buckets[val] > 1) {
                collisionsI++;
            }
            if (buckets[val] == 2) {
                collisions2++;
            }
            if (buckets[val] == 3) {
                collisions3++;
            }
            if (buckets[val] == 4) {
                collisions4++;
            }
            if (buckets[val] == 5) {
                collisions5++;
            }
            if (buckets[val] > 5) {
                collisions6++;
            }
        }

    }

    System.out.println("Smallest=" + smallest + ", Biggest=" + biggest + ", SmallestI=" + smallestI
            + ", BiggestI=" + biggestI + "/" + numBuckets + ", Partition rate="
            + ((float) counter / numIterations * 100) + "% (target 6,25%), Collision rate="
            + ((float) collisionsI * 100 / counter) + "%, Fill rate" + ((float) counter / numBuckets * 100)
            + ", Max cols=" + (maxCols - 1));
    System.out.println("Chains 2:" + ((float) collisions2 * 100 / collisionsI) + ", 3:"
            + ((float) collisions3 * 100 / collisionsI) + ", 4:" + ((float) collisions4 * 100 / collisionsI)
            + ", 5:" + ((float) collisions5 * 100 / collisionsI) + ", 6:"
            + ((float) collisions6 * 100 / collisionsI));
}

From source file:cz.alej.michalik.totp.util.TOTP.java

/**
 * Ukzka TOTP pro zprvu "12345678901234567890"
 *//*from w  ww  .  j av  a  2  s.c om*/
public static void main(String[] args) {
    // GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ v base32
    String secret = "12345678901234567890";
    System.out.printf("Heslo je: %s \nV Base32 to je: %s\n", secret,
            new Base32().encodeToString(secret.getBytes()));
    TOTP t = new TOTP(secret.getBytes());
    System.out.printf("%s\n", t);
    while (true) {
        int time = Integer.valueOf(new SimpleDateFormat("ss").format(new Date()));
        if (time % 30 == 0) {
            System.out.printf("%s\n", t);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    String s = "Chapter Count=200";
    String s2 = "Tutorial Count=15";

    // create a new input and output stream
    FileOutputStream fos = new FileOutputStream("properties.txt");
    FileInputStream fis = new FileInputStream("properties.txt");

    // write the first property in the output stream file
    fos.write(s.getBytes());

    // change the line between the two properties
    fos.write("\n".getBytes());

    // write next property
    fos.write(s2.getBytes());/*from  w ww .j a  v a  2 s.com*/

    // load from input stream
    prop.load(fis);

    // print the properties list from System.out
    prop.list(System.out);

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("test");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Object o = ois.readObject();//from  w w  w.  j a  v  a 2 s  . c o m
    if (!(o instanceof String)) {
        System.out.println("Unexpected data in file");
        System.exit(-1);
    }
    String data = (String) o;
    System.out.println("Got message " + data);
    o = ois.readObject();
    if (!(o instanceof byte[])) {
        System.out.println("Unexpected data in file");
        System.exit(-1);
    }
    byte origDigest[] = (byte[]) o;
    byte pass[] = "aaa".getBytes();
    byte buf[] = data.getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.update(pass);
    md.update(buf);
    byte digest1[] = md.digest();
    md.update(pass);
    md.update(digest1);
    System.out.println(MessageDigest.isEqual(md.digest(), origDigest));
}

From source file:com.mindquarry.management.user.UserManagementClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(UserManagementClient.class);
    log.info("Starting user management client..."); //$NON-NLS-1$

    // parse command line arguments
    CommandLine line = null;// ww  w  . j a v  a  2s .c  om
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed."); //$NON-NLS-1$
        printUsage();
        return;
    }
    // retrieve login data
    System.out.print("Please enter your login ID: "); //$NON-NLS-1$

    String user = readString();
    user = user.trim();

    System.out.print("Please enter your new password: "); //$NON-NLS-1$

    String password = readString();
    password = password.trim();
    password = new String(DigestUtils.md5(password));
    password = new String(Base64.encodeBase64(password.getBytes()));

    // start PWD change client
    UserManagementClient manager = new UserManagementClient();
    try {
        if (line.hasOption(O_DEL)) {
            manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        } else {
            manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        }
    } catch (Exception e) {
        log.error("Error while applying password changes.", e); //$NON-NLS-1$
    }
    log.info("User management client finished successfully."); //$NON-NLS-1$
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("test");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Object o = ois.readObject();/*w w  w . j ava  2  s .  co  m*/
    if (!(o instanceof String)) {
        System.out.println("Unexpected data in file");
        System.exit(-1);
    }
    String data = (String) o;
    System.out.println("Got message " + data);
    o = ois.readObject();
    if (!(o instanceof byte[])) {
        System.out.println("Unexpected data in file");
        System.exit(-1);
    }
    byte origDigest[] = (byte[]) o;
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.update(data.getBytes());
    if (MessageDigest.isEqual(md.digest(), origDigest))
        System.out.println("Message is valid");
    else
        System.out.println("Message was corrupted");
}