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(Charset charset) 

Source Link

Document

Encodes this String into a sequence of bytes using the given java.nio.charset.Charset charset , storing the result into a new byte array.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    SocketAddress serverAddr = new InetSocketAddress("localhost", 8989);
    Future<Void> result = channel.connect(serverAddr);
    result.get();/*from   w  ww  . j  av  a 2s  . co m*/
    System.out.println("Connected");
    Attachment attach = new Attachment();
    attach.channel = channel;
    attach.buffer = ByteBuffer.allocate(2048);
    attach.isRead = false;
    attach.mainThread = Thread.currentThread();

    Charset cs = Charset.forName("UTF-8");
    String msg = "Hello";
    byte[] data = msg.getBytes(cs);
    attach.buffer.put(data);
    attach.buffer.flip();

    ReadWriteHandler readWriteHandler = new ReadWriteHandler();
    channel.write(attach.buffer, attach, readWriteHandler);
    attach.mainThread.join();
}

From source file:com.project.finalproject.Send.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    try {//w w  w .j a v a2 s  . c o m
        InputStream is = new FileInputStream("hr.json");
        String jsontxt = IOUtils.toString(is);
        JSONObject jsonObject = new JSONObject(jsontxt);
        JSONArray stream = jsonObject.getJSONArray("stream");
        for (int i = 0; i < stream.length(); i++) {
            String message = stream.getJSONObject(i).getString("value");
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
            TimeUnit.SECONDS.sleep(1);
        }
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    channel.close();
    connection.close();
}

From source file:Main.java

public static void main(String[] args) {

    try {/*w w w  .j a  va  2s  . c  o m*/
        String str1 = "java2s.com";
        System.out.println("string1 = " + str1);
        // copy the contents of the String to a byte array
        byte[] arr = str1.getBytes("ASCII");

        String str2 = new String(arr);
        System.out.println("new string = " + str2);
    } catch (Exception e) {
        System.out.print(e.toString());
    }
}

From source file:Main.java

public static void main(String[] args) {

    try {/* ww  w.  j  a  va  2  s .  c  o  m*/
        String str1 = "java2s.com";
        System.out.println("string1 = " + str1);
        // copy the contents of the String to a byte array
        byte[] arr = str1.getBytes(Charset.forName("ASCII"));

        String str2 = new String(arr);
        System.out.println("new string = " + str2);
    } catch (Exception e) {
        System.out.print(e.toString());
    }
}

From source file:com.cliqset.magicsig.util.KeyTester.java

public static void main(String[] args) {
    try {//from   ww w  . j  a va  2 s .  co  m
        FileInputStream fis = new FileInputStream(keyFile);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
        String line = null;

        while ((line = reader.readLine()) != null) {
            MagicKey key = new MagicKey(line.getBytes("ASCII"));

            RSASHA256MagicSigAlgorithm alg = new RSASHA256MagicSigAlgorithm();
            byte[] sig = alg.sign(data, key);

            System.out.println(Base64.encodeBase64URLSafeString(sig));

            boolean verified = alg.verify(data, sig, key);

            if (!verified) {
                System.out.println("FAILED - " + line);
            }

            //System.out.println(lineSplit[0] + " " + key.toString(true));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Done.");
}

From source file:com.twitter.distributedlog.basic.ConsoleProxyMultiWriter.java

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;/*from  w  w w  .j  av  a2 s  . com*/
    }

    String finagleNameStr = args[0];
    final String streamList = args[1];

    DistributedLogClient client = DistributedLogClientBuilder.newBuilder()
            .clientId(ClientId.apply("console-proxy-writer")).name("console-proxy-writer").thriftmux(true)
            .finagleNameStr(finagleNameStr).build();
    String[] streamNameList = StringUtils.split(streamList, ',');
    DistributedLogMultiStreamWriter multiStreamWriter = DistributedLogMultiStreamWriter.newBuilder()
            .streams(Lists.newArrayList(streamNameList)).bufferSize(0).client(client).flushIntervalMs(0)
            .firstSpeculativeTimeoutMs(10000).maxSpeculativeTimeoutMs(20000).requestTimeoutMs(50000).build();

    // Setup Terminal
    Terminal terminal = Terminal.setupTerminal();
    ConsoleReader reader = new ConsoleReader();
    String line;
    while ((line = reader.readLine(PROMPT_MESSAGE)) != null) {
        multiStreamWriter.write(ByteBuffer.wrap(line.getBytes(UTF_8)))
                .addEventListener(new FutureEventListener<DLSN>() {
                    @Override
                    public void onFailure(Throwable cause) {
                        System.out.println("Encountered error on writing data");
                        cause.printStackTrace(System.err);
                        Runtime.getRuntime().exit(0);
                    }

                    @Override
                    public void onSuccess(DLSN value) {
                        // done
                    }
                });
    }

    multiStreamWriter.close();
    client.close();
}

From source file:org.eclipse.lyo.adapter.tdb.clients.OSLCTriplestoreAdapterResourceCreationClient.java

public static void main(String[] args) {

    String baseHTTPURI = "http://localhost:" + OSLC4JTDBApplication.portNumber + "/oslc4jtdb";
    String projectId = "default";

    // URI of the HTTP request
    String tdbResourceCreationFactoryURI = baseHTTPURI + "/services/" + projectId + "/resources";

    // create RDF to add to the triplestore
    Model resourceRDFModel = ModelFactory.createDefaultModel();
    Resource resource = ResourceFactory
            .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newBlock4");
    Property property = ResourceFactory//from w ww  .  ja v  a  2  s. c om
            .createProperty("http://localhost:8585/oslc4jtdb/services/default/resources/newProperty4");
    RDFNode object = ResourceFactory
            .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newObject4");
    resourceRDFModel.add(resource, property, object);
    StringWriter out = new StringWriter();
    resourceRDFModel.write(out, "RDF/XML");
    resourceRDFModel.write(System.out);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(tdbResourceCreationFactoryURI);
    String xml = out.toString();
    HttpEntity entity;
    try {
        entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        post.setHeader("Accept", "application/rdf+xml");
        HttpResponse response = client.execute(post);

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:jenkins.security.security218.ysoserial.exploit.JSF.java

public static void main(String[] args) {

    if (args.length < 3) {
        System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
        System.exit(-1);//from ww  w  . ja  va  2 s .co m
    }

    final Object payloadObject = Utils.makePayloadObject(args[1], args[2]);

    try {
        URL u = new URL(args[0]);

        URLConnection c = u.openConnection();
        if (!(c instanceof HttpURLConnection)) {
            throw new IllegalArgumentException("Not a HTTP url");
        }

        HttpURLConnection hc = (HttpURLConnection) c;
        hc.setDoOutput(true);
        hc.setRequestMethod("POST");
        hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream os = hc.getOutputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(payloadObject);
        oos.close();
        byte[] data = bos.toByteArray();
        String requestBody = "javax.faces.ViewState="
                + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
        os.write(requestBody.getBytes("US-ASCII"));
        os.close();

        System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    Utils.releasePayload(args[1], payloadObject);

}

From source file:MainClass.java

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

    URL u = new URL("http://www.java2s.com");
    String host = u.getHost();/* ww w . ja v a  2  s. co m*/
    int port = 80;
    String file = "/";

    SocketAddress remote = new InetSocketAddress(host, port);
    SocketChannel channel = SocketChannel.open(remote);
    FileOutputStream out = new FileOutputStream("yourfile.htm");
    FileChannel localFile = out.getChannel();

    String request = "GET " + file + " HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n" + "Accept: text/*\r\n"
            + "Connection: close\r\n" + "Host: " + host + "\r\n" + "\r\n";

    ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
    channel.write(header);

    ByteBuffer buffer = ByteBuffer.allocate(8192);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        localFile.write(buffer);
        buffer.clear();
    }

    localFile.close();
    channel.close();
}

From source file:com.zip.CreateZipWithOutputStreams.java

/**
 * @param args//  ww w .j  ava 2s  . com
 * @throws UnsupportedEncodingException 
 */
public static void main(String[] args) throws UnsupportedEncodingException {
    //      new CreateZipWithOutputStreams();
    //      zipFilesAndEncrypt("D:\\test\\download","D:\\test\\download\\1.zip","12345");
    //      unzipFile("D:\\test\\download\\1.zip","D:\\test\\download",null);
    String str = "/usr/local/aiomni/27/temp/offLineFolder/admin8a21848b4056b2e4014056b533240000/??????_1.xls";
    System.out.println(new String(str.getBytes("ISO8859-1"), "GBK"));
    System.out.println(System.getProperty("file.encoding"));
}