Example usage for java.io BufferedInputStream BufferedInputStream

List of usage examples for java.io BufferedInputStream BufferedInputStream

Introduction

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

Prototype

public BufferedInputStream(InputStream in) 

Source Link

Document

Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

Usage

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {//from  w  w  w .j  av a  2s  .  c  om
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(//from  www  .ja va  2  s  .  com
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

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/* ww  w .  j a  va2s.co  m*/
 */
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:ai.susi.geo.GeoJsonReader.java

public static void main(String[] args) {
    File f = new File(args[0]);
    try {/*from   www .j  a v  a  2 s . c o  m*/
        GeoJsonReader reader = new GeoJsonReader(new BufferedInputStream(new FileInputStream(f)),
                Runtime.getRuntime().availableProcessors() * 2 + 1);
        new Thread(reader).start();
        Feature feature;
        while ((feature = reader.take()) != POISON_FEATURE)
            System.out.println(feature.toString());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.tsavo.trade.TradeBot.java

public static void main(String[] args)
        throws InterruptedException, EngineException, AudioException, EngineStateError, PropertyVetoException,
        KeyManagementException, NoSuchAlgorithmException, ExchangeException, NotAvailableFromExchangeException,
        NotYetImplementedForExchangeException, IOException {
    //initSSL(); // Setup the SSL certificate to interact with mtgox over
    // secure http.

    //System.setProperty("org.joda.money.CurrencyUnitDataProvider", "org.joda.money.CryptsyCurrencyUnitDataProvider");
    Portfolio portfolio = new Portfolio();
    File dest = new File("portfolio.json");
    if (dest.exists()) {
        InputStream file;/*from  w ww  .  j  a  v a 2  s .  c o  m*/
        try {
            file = new FileInputStream(dest);
            InputStream buffer = new BufferedInputStream(file);
            // ObjectInput input;
            // input = new ObjectInputStream(buffer);
            ObjectMapper mapper = new ObjectMapper();
            portfolio = mapper.readValue(buffer, Portfolio.class);
            file.close();
            // input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Finder finder = new Finder(portfolio);
    System.out.println("System initialized successfully. Looking for opportunities...");
    while (true) {
        finder.run();
        Thread.sleep(10000);
    }
}

From source file:Main.java

public static Object Read(String filename) throws FileNotFoundException {
    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
    Object obj = decoder.readObject();
    decoder.close();//  ww w .  j  a va 2s.  c  o  m
    return obj;
}

From source file:ConsoleInput.java

public static String readLine() {
    StringBuffer response = new StringBuffer();
    try {/*from   www.  j a v  a 2 s  .  c  o  m*/
        BufferedInputStream buff = new BufferedInputStream(System.in);
        int in = 0;
        char inChar;
        do {
            in = buff.read();
            inChar = (char) in;
            if ((in != -1) & (in != '\n') & (in != '\r')) {
                response.append(inChar);
            }
        } while ((in != -1) & (inChar != '\n') & (in != '\r'));
        buff.close();
        return response.toString();
    } catch (IOException e) {
        System.out.println("Exception: " + e.getMessage());
        return null;
    }
}

From source file:Main.java

public static byte[] readFully(File file) throws IOException {
    final InputStream in = new BufferedInputStream(new FileInputStream(file));
    try {//w  w  w .  j ava 2  s . c o m
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] buffer = new byte[1 << 20];
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        in.close();
    }
}

From source file:Main.java

public static Object read(String filename) throws Exception {
    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
    Object o = decoder.readObject();
    decoder.close();/*w ww . j av a  2 s  .  co m*/
    return o;
}

From source file:Main.java

public static String readInputStream(InputStream i) throws IOException {
    BufferedInputStream s = new BufferedInputStream(i);
    byte[] buf = new byte[512];
    int len = -1;
    StringBuilder sb = new StringBuilder();

    while ((len = s.read(buf, 0, buf.length)) != -1) {
        sb.append(new String(buf, 0, len));
    }/*from   w w  w  . j ava  2  s.  c om*/

    return sb.toString();
}