Example usage for java.lang String String

List of usage examples for java.lang String String

Introduction

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

Prototype

String(char[] value, int off, int len, Void sig) 

Source Link

Usage

From source file:Main.java

public static void main(String[] argv) {
    byte[] bytes = new byte[] { 65, 66, 67, 68 };
    System.out.println(new String(bytes, 5, 1, 3));

}

From source file:Main.java

public static void main(String[] argv) {
    byte[] bytes = new byte[] { 65, 66, 67, 68 };
    System.out.println(new String(bytes, 1, 3, Charset.forName("ASCII")));

}

From source file:Main.java

public static void main(String[] argv) {
    byte[] bytes = new byte[] { 65, 66, 67, 68 };
    try {/*from w w  w.  j av a 2  s.  c  o  m*/
        System.out.println(new String(bytes, 1, 3, "ASCII"));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:MulticastSniffer.java

public static void main(String[] args) {

    InetAddress ia = null;/*from w  w  w.  j a  va2 s.  c o  m*/
    byte[] buffer = new byte[65509];
    DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
    int port = 0;

    try {
        try {
            ia = InetAddress.getByName(args[0]);
        } catch (UnknownHostException e) {
            //
        }
        port = Integer.parseInt(args[1]);
    } // end try
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java MulticastSniffer MulticastAddress port");
        System.exit(1);
    }

    try {
        MulticastSocket ms = new MulticastSocket(port);
        ms.joinGroup(ia);
        while (true) {
            ms.receive(dp);
            String s = new String(dp.getData(), 0, 0, dp.getLength());
            System.out.println(s);
        }
    } catch (SocketException se) {
        System.err.println(se);
    } catch (IOException ie) {
        System.err.println(ie);
    }

}

From source file:MulticastSniffer.java

public static void main(String[] args) {
    InetAddress ia = null;// w  w w . j  a  v a2  s  .c  om
    byte[] buffer = new byte[65535];
    DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
    int port = 0;

    // read the address from the command line
    try {
        try {
            ia = InetAddress.getByName(args[0]);
        } catch (UnknownHostException e) {
            System.err.println(e);
        }
        port = Integer.parseInt(args[1]);
    } catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java MulticastSniffer mcast-addr port");
        System.exit(1);
    }
    System.out.println("About to join " + ia);

    try {
        MulticastSocket ms = new MulticastSocket(port);
        ms.joinGroup(ia);
        while (true) {
            System.out.println("About to receive...");
            ms.receive(dp);
            String s = new String(dp.getData(), 0, 0, dp.getLength());
            System.out.println(s);
        }
    } catch (SocketException se) {
        System.err.println(se);
    } catch (IOException ie) {
        System.err.println(ie);
    }
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {/*w w  w. java2s.c  om*/
        if (args.length != 1)
            throw new IllegalArgumentException("Wrong number of args");

        // Get the port from the command line
        int port = Integer.parseInt(args[0]);

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If anyone sends us a
        // packet containing more than will fit into this buffer, the
        // excess will simply be discarded!
        byte[] buffer = new byte[2048];

        // Create a packet to receive data into the buffer
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Now loop forever, waiting to receive packets and printing them.
        for (;;) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Decode the bytes of the packet to characters, using the
            // UTF-8 encoding, and then display those characters.
            String msg = new String(buffer, 0, packet.getLength(), "UTF-8");
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            // Prior to Java 1.1, we'd just create a new packet each time.
            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:net.awl.edoc.pdfa.compression.FlateDecode.java

public static void main(String[] args) throws Exception {
    Inflater inf = new Inflater(false);

    File f = new File("resources/content_2_0.ufd");
    FileInputStream fis = new FileInputStream(f);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(fis, baos);/*from w  w  w . jav  a  2 s. co  m*/
    IOUtils.closeQuietly(fis);
    IOUtils.closeQuietly(baos);
    byte[] buf = baos.toByteArray();
    inf.setInput(buf);
    byte[] res = new byte[buf.length];
    int size = inf.inflate(res);
    String s = new String(res, 0, size, "utf8");
    System.err.println(s);

}

From source file:DaytimeClient.java

public static void main(String args[]) throws java.io.IOException {
    // Figure out the host and port we're going to talk to
    String host = args[0];/*from   w  w  w .  j  a  va2s .  c o m*/
    int port = 13;
    if (args.length > 1)
        port = Integer.parseInt(args[1]);

    // Create a socket to use
    DatagramSocket socket = new DatagramSocket();

    // Specify a 1-second timeout so that receive() does not block forever.
    socket.setSoTimeout(1000);

    // This buffer will hold the response. On overflow, extra bytes are
    // discarded: there is no possibility of a buffer overflow attack here.
    byte[] buffer = new byte[512];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port));

    // Try three times before giving up
    for (int i = 0; i < 3; i++) {
        try {
            // Send an empty datagram to the specified host (and port)
            packet.setLength(0); // make the packet empty
            socket.send(packet); // send it out

            // Wait for a response (or timeout after 1 second)
            packet.setLength(buffer.length); // make room for the response
            socket.receive(packet); // wait for the response

            // Decode and print the response
            System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII"));
            // We were successful so break out of the retry loop
            break;
        } catch (SocketTimeoutException e) {
            // If the receive call timed out, print error and retry
            System.out.println("No response");
        }
    }

    // We're done with the channel now
    socket.close();
}

From source file:PinotResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8099/query");
        CloseableHttpResponse res;//from   w  ww  .jav a2  s .c om

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{\"pql\":\"select count(*) from tpch_lineitem\"}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BUFFER);
                valid = new String(BUFFER, 0, length, "UTF-8").contains("\"value\":\"" + RECORD_NUMBER + "\"");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        // Start Benchmark
        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            post.setEntity(new StringEntity("{\"pql\":\"" + QUERIES[i] + "\"}"));

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                if (!isValid(res, null)) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                }
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            int validIdx = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            while (validIdx < TEST_ROUND) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                boolean valid;
                if (STORE_RESULT && validIdx == 0) {
                    valid = isValid(res, RESULT_DIR + File.separator + i + ".json");
                } else {
                    valid = isValid(res, null);
                }
                if (!valid) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                    res.close();
                    continue;
                }
                res.close();
                time[validIdx] = (int) (endTime - startTime);
                totalTime += time[validIdx];
                System.out.print(time[validIdx] + "ms ");
                validIdx++;
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;/*from  ww  w.j a va 2 s . c  o m*/

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}