Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

In this page you can find the example usage for java.io DataInputStream DataInputStream.

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:com.netflix.aegisthus.tools.SSTableExport.java

@SuppressWarnings("rawtypes")
public static void main(String[] args) throws IOException {
    String usage = String.format("Usage: %s <sstable>", SSTableExport.class.getName());

    CommandLineParser parser = new PosixParser();
    try {/*ww w  .  j a  v  a2  s . c  o m*/
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println(e1.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        System.exit(1);
    }

    if (cmd.getArgs().length != 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        System.exit(1);
    }
    Map<String, AbstractType> convertors = null;
    if (cmd.hasOption(COLUMN_NAME_TYPE)) {
        try {
            convertors = new HashMap<String, AbstractType>();
            convertors.put(SSTableScanner.COLUMN_NAME_KEY,
                    TypeParser.parse(cmd.getOptionValue(COLUMN_NAME_TYPE)));
        } catch (ConfigurationException e) {
            System.err.println(e.getMessage());
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        } catch (SyntaxException e) {
            System.err.println(e.getMessage());
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }
    }
    Descriptor.Version version = null;
    if (cmd.hasOption(OPT_VERSION)) {
        version = new Descriptor.Version(cmd.getOptionValue(OPT_VERSION));
    }

    if (cmd.hasOption(INDEX_SPLIT)) {
        String ssTableFileName;
        DataInput input = null;
        if ("-".equals(cmd.getArgs()[0])) {
            ssTableFileName = System.getProperty("aegisthus.file.name");
            input = new DataInputStream(new BufferedInputStream(System.in, 65536 * 10));
        } else {
            ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
            input = new DataInputStream(
                    new BufferedInputStream(new FileInputStream(ssTableFileName), 65536 * 10));
        }
        exportIndexSplit(ssTableFileName, input);
    } else if (cmd.hasOption(INDEX)) {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        exportIndex(ssTableFileName);
    } else if (cmd.hasOption(ROWSIZE)) {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        exportRowSize(ssTableFileName);
    } else if ("-".equals(cmd.getArgs()[0])) {
        if (version == null) {
            System.err.println("when streaming must supply file version");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }
        exportStream(version);
    } else {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        FileInputStream fis = new FileInputStream(ssTableFileName);
        InputStream inputStream = new DataInputStream(new BufferedInputStream(fis, 65536 * 10));
        long end = -1;
        if (cmd.hasOption(END)) {
            end = Long.valueOf(cmd.getOptionValue(END));
        }
        if (cmd.hasOption(OPT_COMP)) {
            CompressionMetadata cm = new CompressionMetadata(
                    new BufferedInputStream(new FileInputStream(cmd.getOptionValue(OPT_COMP)), 65536),
                    fis.getChannel().size());
            inputStream = new CompressionInputStream(inputStream, cm);
            end = cm.getDataLength();
        }
        DataInputStream input = new DataInputStream(inputStream);
        if (version == null) {
            version = Descriptor.fromFilename(ssTableFileName).version;
        }
        SSTableScanner scanner = new SSTableScanner(input, convertors, end, version);
        if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) {
            scanner.setMaxColSize(Long.parseLong(cmd.getOptionValue(OPT_MAX_COLUMN_SIZE)));
        }
        export(scanner);
        if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) {
            if (scanner.getErrorRowCount() > 0) {
                System.err.println(String.format("%d rows were too large", scanner.getErrorRowCount()));
            }
        }
    }
}

From source file:com.splout.db.dnode.TCPStreamer.java

/**
 * This main method can be used for testing the TCP interface directly to a
 * local DNode. Will ask for protocol input from Stdin and print output to
 * Stdout/*from w  w w.j  a v  a2 s. c  om*/
 */
public static void main(String[] args) throws UnknownHostException, IOException, SerializationException {
    SploutConfiguration config = SploutConfiguration.get();
    Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT));

    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
    DataOutputStream outToServer = new DataOutputStream(
            new BufferedOutputStream(clientSocket.getOutputStream()));

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter tablespace: ");
    String tablespace = reader.readLine();

    System.out.println("Enter version number: ");
    long versionNumber = Long.parseLong(reader.readLine());

    System.out.println("Enter partition: ");
    int partition = Integer.parseInt(reader.readLine());

    System.out.println("Enter query: ");
    String query = reader.readLine();

    outToServer.writeUTF(tablespace);
    outToServer.writeLong(versionNumber);
    outToServer.writeInt(partition);
    outToServer.writeUTF(query);

    outToServer.flush();

    byte[] buffer = new byte[0];
    boolean read;
    do {
        read = false;
        int nBytes = inFromServer.readInt();
        if (nBytes > 0) {
            buffer = new byte[nBytes];
            int inRead = inFromServer.read(buffer);
            if (inRead > 0) {
                Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class);
                read = true;
                System.out.println(Arrays.toString(res));
            }
        }
    } while (read);

    clientSocket.close();
}

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  /*from   www .  j a  va2s. c  om*/
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(target + "->" + ex);
                        }

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:Main.java

public static String execCmd(String cmd) {

    String result = "";
    DataInputStream dis = null;//  w  ww  .  jav  a 2  s . c om

    try {
        Process p = Runtime.getRuntime().exec(cmd);
        dis = new DataInputStream(p.getInputStream());
        String line = null;
        while ((line = dis.readLine()) != null) {
            line += "\n";
            result += line;
        }
        p.waitFor();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

public static long byteArrayToLong(byte[] input) {
    try {/*from ww w . j  a va2s .c  om*/
        ByteArrayInputStream bis = new ByteArrayInputStream(input);
        DataInputStream dis = new DataInputStream(bis);
        long numb = dis.readLong();
        dis.close();
        return numb;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static byte[] readFileToByteArray(File file) {
    try {//from  w w w . ja va 2  s . co  m
        byte[] fileData = new byte[(int) file.length()];
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(fileData);
        dis.close();
        return fileData;
    } catch (IOException e) {
        return null;
    }
}

From source file:Main.java

public static String readFile(String path) throws IOException {
    InputStream is = new FileInputStream(new File(path));
    DataInputStream ds = new DataInputStream(is);
    // Estimated capacity, potential risk ???
    byte[] bytes = new byte[is.available()];
    ds.readFully(bytes);// w w  w .  ja v  a 2s . co m
    String text = new String(bytes);
    is.close();
    ds.close();
    return text;
}

From source file:Main.java

public static DataInputStream getStream(String filePath) throws Exception {
    URL url1 = new URL(filePath);
    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
    DataInputStream in = new DataInputStream(conn.getInputStream());
    return in;/* ww  w  .ja v a2 s  .c o m*/
}

From source file:Main.java

public static boolean tempMapAvailable() {
    try {// w w  w  . ja  v a 2s  .c o  m
        FileInputStream instream = new FileInputStream("tempMapSave");
        DataInputStream in = new DataInputStream(instream);
        BufferedReader buffered = new BufferedReader(new InputStreamReader(in));

        if (buffered.readLine() != "null") {
            return true;
        }
    } catch (Exception e) {
    }

    return false;
}

From source file:Main.java

public static HashMap<String, String> load(InputStream is) {
    String appInfo[] = null;/*  ww w  .j a va  2 s.  c  o  m*/
    HashMap<String, String> appMap = new HashMap<String, String>();
    try {
        DataInputStream bis = new DataInputStream(is);
        String txt = "";
        do {
            txt = bis.readLine();
            if (txt != null) {
                txt = new String(txt.trim().getBytes("ISO-8859-1"), "UTF-8");
                ;
                appInfo = txt.split(":");
                appMap.put(appInfo[0], appInfo[1]);
            }
        } while (txt != null && !"".equals(txt));
        bis.readLine();

    } catch (IOException e) {

    } finally {
        return appMap;
    }
}