Example usage for com.google.common.base Charsets US_ASCII

List of usage examples for com.google.common.base Charsets US_ASCII

Introduction

In this page you can find the example usage for com.google.common.base Charsets US_ASCII.

Prototype

Charset US_ASCII

To view the source code for com.google.common.base Charsets US_ASCII.

Click Source Link

Document

US-ASCII: seven-bit ASCII, the Basic Latin block of the Unicode character set (ISO646-US).

Usage

From source file:suneido.compiler.CompileFile.java

public static void main(String[] args) throws IOException {
    //      Repl.setup();
    String src = Files.asCharSource(new File("compilefile.src"), Charsets.US_ASCII).read();
    Object result = Compiler.compile("Test", src, new PrintWriter(System.out), true);
    System.out.println(result);/*from   ww w  .  jav  a  2s .c  o m*/
}

From source file:org.apache.flume.tcphammer.Hammer.java

public static void main(String[] args) {

    // usage/*ww  w .  ja  v  a2 s.c  o  m*/
    if (args.length != 6) {
        System.out.println("Usage: Hammer hostname port tag event_size events_per_sec log_interval_secs");
        System.exit(1);
    }

    String host = args[0];
    InetAddress addr;
    String localhost;
    try {
        addr = InetAddress.getByName(host);
        localhost = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        throw new RuntimeException("Cannot resolve host", e);
    }
    int port = Integer.parseInt(args[1]);
    String tag = args[2];
    int eventSize = Integer.parseInt(args[3]);
    int eventsPerSec = Integer.parseInt(args[4]);
    int logIntervalSecs = Integer.parseInt(args[5]);

    Socket sock;
    OutputStream out;

    try {
        logger.info("Connecting to {}:{}...", host, port);
        sock = new Socket(addr, port);
        out = new BufferedOutputStream(sock.getOutputStream());
    } catch (IOException e) {
        throw new RuntimeException("Socket problem", e);
    }

    ByteBuffer bbEnd = ByteBuffer.wrap(" ".getBytes(Charsets.US_ASCII));
    ByteBuffer bbMsg = ByteBuffer.allocate(eventSize);
    byte[] backingArray = bbMsg.array();

    // fill the backing array with X's
    for (int i = 0; i < eventSize; i++) {
        backingArray[i] = 'X';
    }
    backingArray[eventSize - 1] = '\n'; // plus a newline

    logger.info("Starting up {}/{}...", localhost, tag);

    long lastLogTime = System.nanoTime();
    long curLogIntervalNanosSlept = 0; // #nanos slept this log interval
    long curLogIntervalEventsSent = 0; // #events sent this log interval
    long lastSleepTime = System.nanoTime();

    // send the same date over and over; too slow to generate it
    //String base = "<13>" + DateTime.now() + " " + localhost + " " + tag + " ";
    //ByteBuffer bbStart = ByteBuffer.wrap(base.getBytes(Charsets.US_ASCII));

    long eventCount = 0;
    int eventsThisSec = 0;
    while (true) {
        String base = "<13>" + DateTime.now() + " " + localhost + " " + tag + " ";
        ByteBuffer bbStart = ByteBuffer.wrap(base.getBytes(Charsets.US_ASCII));
        bbMsg.put(bbStart);
        bbMsg.put(Long.toString(eventCount).getBytes(Charsets.US_ASCII));
        bbMsg.put(bbEnd);
        try {
            out.write(backingArray, 0, eventSize);
        } catch (IOException e) {
            // failed; try to reconnect
            try {
                logger.info("Caught IOException, trying to reconnect...", e);
                out.close();
                sock.close();
                sock = new Socket(addr, port);
                out = new BufferedOutputStream(sock.getOutputStream());
            } catch (IOException e2) {
                logger.error("Socket reconnect problem. Events: " + eventCount, e2);
                System.exit(1);
            }
        }

        //bbStart.flip();
        bbEnd.flip();
        bbMsg.clear();

        eventCount++;
        eventsThisSec++;
        curLogIntervalEventsSent++;

        // only check every N# events
        if (eventCount % 200L == 0) {
            long curLogTime = System.nanoTime();

            // log on 1-minute intervals
            long logDelta = curLogTime - lastLogTime;
            if (logDelta >= logIntervalSecs * SECOND_IN_NANOS) {
                logger.info(
                        "Alive. Interval: {} ms; Throttled: {} ms = {}%; "
                                + "Events: {}; Rate: {} evt/sec; Total events: {}",
                        new Object[] { logDelta / 1000000, curLogIntervalNanosSlept / 1000000,
                                String.format("%.2f",
                                        (100 * (double) curLogIntervalNanosSlept / (double) logDelta)),
                                curLogIntervalEventsSent,
                                String.format("%.2f",
                                        (double) curLogIntervalEventsSent / ((double) logDelta / 1000000000D)),
                                eventCount, });
                lastLogTime = curLogTime;
                curLogIntervalNanosSlept = 0;
                curLogIntervalEventsSent = 0;
            }
        }

        // allow for burst, then sleep
        if (eventsThisSec >= eventsPerSec) {
            // sleep for the rest of the second
            long curTime = System.nanoTime();
            long delta = curTime - lastSleepTime;
            if (delta <= SECOND_IN_NANOS) {
                long nanosToSleep = SECOND_IN_NANOS - delta;
                curLogIntervalNanosSlept += nanosToSleep;
                try {
                    Thread.sleep(TimeUnit.MILLISECONDS.convert(nanosToSleep, TimeUnit.NANOSECONDS));
                } catch (InterruptedException e) {
                    logger.error("Interrupted. Exiting.", e);
                    return;
                }
            }
            lastSleepTime = System.nanoTime();
            eventsThisSec = 0;
        }

    }
}

From source file:com.aerofs.netty.socks.sample.SocksTestClient.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        LOGGER.warn("required parameters: host port version");
        System.exit(1);//from  ww w  . j  av  a  2s  . com
    }

    SocksVersion socksVersion = Integer.parseInt(args[0]) == 5 ? SocksVersion.SOCKS_V_5_0
            : SocksVersion.SOCKS_V_4_0;
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    String socksProxyHost = System.getProperty("socksProxyHost");
    int socksProxyPort = Integer.parseInt(System.getProperty("socksProxyPort"));

    InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
    SocksTestClient client = new SocksTestClient(socksVersion, socksProxyHost, socksProxyPort,
            new Credentials());
    try {
        // connect
        ChannelFuture connectFuture = client.connect(host, port);
        connectFuture.await(10, TimeUnit.SECONDS);
        if (!connectFuture.isSuccess()) {
            throw new IOException(String.format("fail connect to %s:%d", host, port));
        }

        Channel channel = connectFuture.getChannel();
        LOGGER.info("write TEST to {}", channel);

        // write
        ChannelFuture writeFuture = channel
                .write(ChannelBuffers.copiedBuffer("TEST".getBytes(Charsets.US_ASCII)));
        writeFuture.await(10, TimeUnit.SECONDS);
        if (!writeFuture.isSuccess()) {
            throw new IOException(String.format("fail write to %s:%d", host, port));
        }

        // close
        channel.close().awaitUninterruptibly();
    } catch (Exception e) {
        LOGGER.warn("terminate SOCKS test client", e);
    } finally {
        client.shutdown();
    }
}

From source file:net.galaxy.weather.Main.java

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

    String version = "UNDEF";
    Enumeration<URL> resources = Main.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
    try {/*from  www  .j av  a  2s . c  o  m*/
        while (resources.hasMoreElements()) {
            Manifest manifest = new Manifest(resources.nextElement().openStream());
            Attributes attributes = manifest.getMainAttributes();
            if ("weatherstation".equals(attributes.getValue("Bundle-SymbolicName"))) {
                version = attributes.getValue("Bundle-Version");
            }
        }
    } catch (IOException ex) {
        logger.warn("Error while reading MANIFEST: " + ex.getMessage());
        System.exit(255);
    }
    System.out.println("Weather Station v. " + version + "\nCopyright (C) 2012  Pavel Boldyrev\n"
            + "This program comes with ABSOLUTELY NO WARRANTY; see the Apache License Version 2.0 for more details <http://www.apache.org/licenses/LICENSE-2.0>\n");

    final BlockingQueue<MeasurementDto> queue = new LinkedBlockingDeque<>(4);
    final Map<Integer, SignalQuality> nodes = new HashMap<>();
    Thread processor = new Thread(new DataProcessor(queue), "PROCESSOR");
    processor.start();

    int exitStatus = 0;
    try {
        RFBee bee = new RFBeeImpl(MESSAGE_TERMINATOR);
        bee.registerReceiveCallback(new ReceiveCallback() {
            @Override
            public void receive(ReceivedMessage message) {
                try {
                    int src = message.getSrc();
                    SignalQuality sq = message.getSignalQuality();
                    nodes.put(src, sq);
                    logger.info("Signal quality from SRC[{}] : {}", src, sq);

                    queue.put(MeasurementParser.parse(src,
                            new String(message.getPayload(), Charsets.US_ASCII).trim()));
                } catch (InterruptedException ex) {
                    logger.error("Interrupted", ex);
                }
            }
        });

        logger.info("Listening...");
        synchronized (Main.class) {
            Main.class.wait();
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        exitStatus = 255;
    }

    processor.interrupt();
    logger.info("FINISHED");
    System.exit(exitStatus);
}

From source file:com.nebula2d.util.ByteUtils.java

public static String decodeBase64String(String base64) {
    byte[] decodedBytes = BaseEncoding.base64().decode(base64);
    return new String(decodedBytes, Charsets.US_ASCII);
}

From source file:org.hopestarter.wallet.util.Nfc.java

public static NdefRecord createMime(final String mimeType, final byte[] payload) {
    final byte[] mimeBytes = mimeType.getBytes(Charsets.US_ASCII);
    final NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
    return mimeRecord;
}

From source file:zeitcoin.wallet.util.Nfc.java

public static NdefRecord createMime(@Nonnull final String mimeType, @Nonnull final byte[] payload) {
    final byte[] mimeBytes = mimeType.getBytes(Charsets.US_ASCII);
    final NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
    return mimeRecord;
}

From source file:org.hopestarter.wallet.util.Nfc.java

@Nullable
public static byte[] extractMimePayload(final String mimeType, final NdefMessage message) {
    final byte[] mimeBytes = mimeType.getBytes(Charsets.US_ASCII);

    for (final NdefRecord record : message.getRecords()) {
        if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA && Arrays.equals(record.getType(), mimeBytes))
            return record.getPayload();
    }//w ww .j  a  v a  2 s .  co  m

    return null;
}

From source file:org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader.java

public static NetconfMessageHeader fromBytes(final byte[] bytes) {
    // the length is variable therefore bytes between headerBegin and
    // headerEnd mark the length
    // the length should be only numbers and therefore easily parsed with
    // ASCII/* w  ww .j a  va2  s . c o m*/
    long length = Long.parseLong(Charsets.US_ASCII
            .decode(ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1))
            .toString());

    return new NetconfMessageHeader(length);
}

From source file:com.pinterest.rocksplicator.controller.util.ZookeeperConfigParser.java

public static String parseEndpoints(String zkHostsFile, String zkCluster) {
    Yaml yaml = new Yaml();
    try {/*from w ww  .  ja v a 2s  . com*/
        String cluster = "default";
        if (!Strings.isNullOrEmpty(zkCluster)) {
            cluster = zkCluster;
        }
        String content = Files.toString(new File(zkHostsFile), Charsets.US_ASCII);
        Map<String, Map<String, List<String>>> config = (Map) yaml.load(content);
        List<String> endpoints = config.get("clusters").get(cluster);
        return String.join(",", endpoints);
    } catch (Exception e) {
        LOG.error("Cannot parse Zookeeper endpoints!", e);
        return null;
    }
}