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:Main.java

public static void main(String[] args) throws Exception {
    String s = "<p>" + "  <media type='audio' id='au008093' rights='aaa'>" + "    <title>title</title>"
            + "  this is a test." + "</p>";
    InputStream is = new ByteArrayInputStream(s.getBytes());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(is);//from   ww w. ja  va2 s . com

    Node rootElement = d.getDocumentElement();
    System.out.println(nodeToString(rootElement));
}

From source file:RSA.java

/** Trivial test program. */
public static void main(String[] args) {
    RSA rsa = new RSA(1024);

    String text1 = "Yellow and Black Border Collies";
    System.out.println("Plaintext: " + text1);
    BigInteger plaintext = new BigInteger(text1.getBytes());

    BigInteger ciphertext = rsa.encrypt(plaintext);
    System.out.println("Ciphertext: " + ciphertext);
    plaintext = rsa.decrypt(ciphertext);

    String text2 = new String(plaintext.toByteArray());
    System.out.println("Plaintext: " + text2);
}

From source file:loanbroker.normalizer.NormalizerTeachersJsonBank.java

public static void main(String[] args) {
    try {/*from w w  w .  j a v  a2 s.  c om*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        factory.setPort(5672);
        factory.setUsername("student");
        factory.setPassword("cph");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //String queueName = channel.queueDeclare().getQueue();
        //channel.queueBind(queueName, EXCHANGE_NAME, "");   
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, true, consumer);
        //producer 
        Channel channelOutput = connection.createChannel();
        channelOutput.exchangeDeclare(ExchangeName.GLOBAL, "direct");
        String queueName = channelOutput.queueDeclare().getQueue();
        channelOutput.queueBind(queueName, ExchangeName.GLOBAL, "normalizerToAggregator");

        LoanResponse loanResponse;
        while (true) {
            System.out.println("Reading");
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println("CorrelationId: " + delivery.getProperties().getCorrelationId());

            String message = new String(delivery.getBody());

            JSONObject jsonObj = new JSONObject(message);

            loanResponse = new LoanResponse(jsonObj.getInt("ssn"), jsonObj.getDouble("interestRate"),
                    "Teachers Json Bank", delivery.getProperties().getCorrelationId());
            System.out.println("renter: " + loanResponse.getInterestRate());
            System.out.println("ssn: " + loanResponse.getSsn());
            System.out.println("bank : " + loanResponse.getBank());
            //             System.out.println(" [x] Received '" + message + "'");
            System.out.println("JSON:" + loanResponse);
            System.out.println("TOstring:" + jsonObj.toString());
            Gson g = new Gson();
            String fm = g.toJson(loanResponse);
            channelOutput.basicPublish("TeamFirebug", "normalizerToAggregator", null, fm.getBytes());

        }

    } catch (IOException | TimeoutException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.npower.dm.util.XMLPrettyFormatter.java

/**
 * TestCase & Demo./*from   www  . jav a  2  s.c  o  m*/
 * @param args
 */
public static void main(String[] args) {
    try {
        //String text = "<A><B></B></A>";
        //XMLPrettyFormatter formatter = new XMLPrettyFormatter(text);
        File file = new File("D:/Zhao/MyWorkspace/nWave-DM-Common/metadata/ddf/sony_ericsson/M600_DDF.xml");
        XMLPrettyFormatter formatter = new XMLPrettyFormatter(file);
        String result = formatter.format();
        FileOutputStream out = new FileOutputStream("C:/temp/M600_DDF.xml");
        out.write(result.getBytes());
        out.close();
    } catch (DocumentException e) {
        log.info("XMLPrettyFormatter:" + e);
    } catch (IOException e) {
        log.info("XMLPrettyFormatter:" + e);
    }
}

From source file:Main.java

public static void main(String[] args) {
    String destFile = "luci2.txt";

    // Get the line separator for the current platform
    String lineSeparator = System.getProperty("line.separator");

    String line1 = "test";
    String line2 = "test1";

    String line3 = "test2";
    String line4 = "test3";

    try (FileOutputStream fos = new FileOutputStream(destFile)) {
        fos.write(line1.getBytes());
        fos.write(lineSeparator.getBytes());

        fos.write(line2.getBytes());/*from w ww .j  av a  2 s.  c  om*/
        fos.write(lineSeparator.getBytes());

        fos.write(line3.getBytes());
        fos.write(lineSeparator.getBytes());

        fos.write(line4.getBytes());

        // Flush the written bytes to the file 
        fos.flush();

        System.out.println("Text has  been  written to " + (new File(destFile)).getAbsolutePath());
    } catch (Exception e2) {
        e2.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket sock = new Socket(args[0], Integer.parseInt(args[1]));
    GZIPOutputStream zip = new GZIPOutputStream(sock.getOutputStream());
    String line;
    BufferedReader bis = new BufferedReader(new FileReader(args[2]));
    while (true) {
        line = bis.readLine();/*from  ww w . j a v a  2 s .  c o m*/
        if (line == null)
            break;
        line = line + "\n";
        zip.write(line.getBytes(), 0, line.length());
    }
    zip.finish();
    zip.close();
    sock.close();
}

From source file:com.mycompany.mavenpost.HttpTest.java

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

    System.out.println("this is a test program");
    HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php");

    // Request parameters and other properties.
    String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
    String authHeader = "Basic " + new String(encodedAuth);
    //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh";

    httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json");

    Map<String, Object> params = new LinkedHashMap<>();
    params.put("SERVICE", "customer.get");

    JSONObject json = new JSONObject();
    json.put("SERVICE", "customer.get");

    //Map<String, Object> params2 = new LinkedHashMap<>();

    //params2.put("CUSTOMER_NUMBER","5");
    JSONObject array = new JSONObject();
    array.put("CUSTOMER_NUMBER", "2");

    json.put("FILTER", array);

    StringEntity param = new StringEntity(json.toString());
    httppost.setEntity(param);// w  w w  . jav a  2  s.  co m

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(httppost);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("The status code is  " + statusCode);

    //Execute and get the response.
    HttpEntity entity = response.getEntity();

    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
    }
    if (entity != null) {
        String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual                     
        // parsing JSON
        //JSONObject result = new JSONObject(retSrc);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(retSrc);
        String prettyJsonString = gson.toJson(je);
        System.out.println(prettyJsonString);
    }
    //if (entity != null) {
    //    InputStream instream = entity.getContent();
    //    try {
    //  final BufferedReader reader = new BufferedReader(
    //                    new InputStreamReader(instream));
    //            String line = null;
    //            while ((line = reader.readLine()) != null) {
    //                System.out.println(line);
    //            }
    //            reader.close();
    //    } finally {
    //        instream.close();
    //    }
    //}
}

From source file:loanbroker.normalizer.NormalizerOurJsonBank.java

public static void main(String[] args) {
    try {// w  w  w . j a  va2s . c  om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        factory.setPort(5672);
        factory.setUsername("student");
        factory.setPassword("cph");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, EXCHANGE_NAME, "");
        //channel.queueDeclare(RPC_QUEUE_NAME,false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        //producer 
        Channel channelOutput = connection.createChannel();
        channelOutput.exchangeDeclare(ExchangeName.GLOBAL, "direct");
        String queueNameProducer = channelOutput.queueDeclare().getQueue();
        channelOutput.queueBind(queueNameProducer, ExchangeName.GLOBAL, RoutingKeys.NormalizerToAggregator);

        LoanResponse loanResponse;
        while (true) {
            System.out.println("Reading");
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println("CorrelationId: " + delivery.getProperties().getCorrelationId());

            String message = new String(delivery.getBody());

            JSONObject jsonObj = new JSONObject(message);

            loanResponse = new LoanResponse(jsonObj.getInt("ssn"), Math.ceil(jsonObj.getDouble("interestRate")),
                    "Our Json Bank", delivery.getProperties().getCorrelationId());
            System.out.println("renter: " + loanResponse.getInterestRate());
            System.out.println("ssn: " + loanResponse.getSsn());
            System.out.println("bank : " + loanResponse.getBank());
            System.out.println("JSON:" + loanResponse);
            System.out.println("TOstring:" + jsonObj.toString());
            Gson g = new Gson();
            String fm = g.toJson(loanResponse);
            channelOutput.basicPublish(ExchangeName.GLOBAL, RoutingKeys.NormalizerToAggregator, null,
                    fm.getBytes());

        }

    } catch (IOException | TimeoutException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.manning.blogapps.chapter10.examples.AuthGetJava.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.out.println("USAGE: authget <username> <password> <url>");
        System.exit(-1);//  w w  w  . j  a va  2 s .  c  o m
    }
    String credentials = args[0] + ":" + args[1];

    URL url = new URL(args[2]);
    URLConnection conn = url.openConnection();

    conn.setRequestProperty("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String s = null;
    while ((s = in.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:com.amalto.workbench.utils.PasswordUtil.java

public static void main(String args[]) {
    Base64 base64 = new Base64();
    String str = "qwe";//$NON-NLS-1$
    byte[] enbytes = null;
    String encodeStr = null;/*w  w w  . j ava 2 s . co m*/
    byte[] debytes = null;
    String decodeStr = null;
    enbytes = base64.encode(str.getBytes());
    encodeStr = new String(enbytes);
    debytes = base64.decode(enbytes);
    decodeStr = new String(debytes);
    System.out.println("plain password:" + str); //$NON-NLS-1$
    System.out.println("encrypted password:" + encodeStr); //$NON-NLS-1$
    System.out.println("decrypted password:" + decodeStr); //$NON-NLS-1$
}