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:edu.msu.cme.rdp.taxatree.TreeBuilder.java

public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        System.err.println("USAGE: TreeBuilder <idmapping> <merges.bin> <newick_out>");
        return;/*  w  w  w.java  2 s. com*/
    }

    IdMapping<Integer> idMapping = IdMapping.fromFile(new File(args[0]));
    DataInputStream mergeStream = new DataInputStream(new BufferedInputStream(new FileInputStream(args[1])));
    TaxonHolder lastMerged = null;
    int taxid = 0;
    final Map<Integer, Double> distMap = new HashMap();
    Map<Integer, TaxonHolder> taxonMap = new HashMap();

    try {
        while (true) {
            if (mergeStream.readBoolean()) { // Singleton
                int cid = mergeStream.readInt();
                int intId = mergeStream.readInt();
                TaxonHolder<Taxon> holder;

                List<String> seqids = idMapping.getIds(intId);
                if (seqids.size() == 1) {
                    holder = new TaxonHolder(new Taxon(taxid++, seqids.get(0), ""));
                } else {
                    holder = new TaxonHolder(new Taxon(taxid++, "", ""));
                    for (String seqid : seqids) {
                        int id = taxid++;
                        distMap.put(id, 0.0);
                        TaxonHolder th = new TaxonHolder(new Taxon(id, seqid, ""));
                        th.setParent(holder);
                        holder.addChild(th);
                    }
                }

                lastMerged = holder;
                taxonMap.put(cid, holder);
            } else {
                int ci = mergeStream.readInt();
                int cj = mergeStream.readInt();
                int ck = mergeStream.readInt();
                double dist = (double) mergeStream.readInt() / DistanceCalculator.MULTIPLIER;

                TaxonHolder holder = new TaxonHolder(new Taxon(taxid++, "", ""));

                taxonMap.put(ck, holder);
                holder.addChild(taxonMap.get(ci));
                taxonMap.get(ci).setParent(holder);
                distMap.put(ci, dist);
                holder.addChild(taxonMap.get(cj));
                taxonMap.get(cj).setParent(holder);
                distMap.put(cj, dist);

                lastMerged = holder;
            }
        }
    } catch (EOFException e) {

    }

    if (lastMerged == null) {
        throw new IOException("No merges in file");
    }

    PrintStream newickTreeOut = new PrintStream(new File(args[2]));
    NewickPrintVisitor visitor = new NewickPrintVisitor(newickTreeOut, false, new NewickDistanceFactory() {

        public float getDistance(int i) {
            return distMap.get(i).floatValue();
        }

    });

    lastMerged.biDirectionDepthFirst(visitor);
    newickTreeOut.close();
}

From source file:DownloadFileFromURL.java

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

    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/pg11.TXT");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/lorem.TXT");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/pg1661.TXT");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/cacerts");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/eula.rtf");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/Story.JPG");
    urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/solarwinds.png");

    for (int iUrl = 0; iUrl < urlList.size(); iUrl++) {

        try {/*from   ww  w. j  a va 2 s.  c  o  m*/
            String urlString = urlList.get(iUrl);
            //All File Locations go here
            url = new URL(urlString);

        } catch (MalformedURLException ex) {
            Logger.getLogger(DownloadFileFromURL.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            // open all the url connections here.
            con = url.openConnection();

        } catch (IOException ex) {
            Logger.getLogger(DownloadFileFromURL.class.getName()).log(Level.SEVERE, null, ex);
        }

        dis = new DataInputStream(con.getInputStream());
        fileData = new byte[con.getContentLength()];

        for (int q = 0; q < fileData.length; q++) {
            fileData[q] = dis.readByte();
        }
        dis.close(); // close the data input stream               

        String fName = FilenameUtils.getName(url.getPath());

        fos = new FileOutputStream(new File(fName)); //FILE Save Location goes here
        fos.write(fileData); // write out the file we want to save.
        fos.close(); // close the output stream writer       

    } // end of for

}

From source file:SecurityManagerTest.java

public static void main(String[] args) throws Exception {
    try {/* w  ww .  ja  v a 2  s  . c om*/
        System.setSecurityManager(new PasswordSecurityManager("Booga Booga"));
    } catch (SecurityException se) {
        System.err.println("SecurityManager already set!");
    }

    DataInputStream in = new DataInputStream(new FileInputStream("inputtext.txt"));
    DataOutputStream out = new DataOutputStream(new FileOutputStream("outputtext.txt"));
    String inputString;
    while ((inputString = in.readLine()) != null) {
        out.writeBytes(inputString);
        out.writeByte('\n');
    }
    in.close();
    out.close();
}

From source file:DataIODemo.java

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

    // write the data out
    DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt"));

    double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    int[] units = { 12, 8, 13, 29, 50 };
    String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);//ww w.j  av a 2 s  . c  o  m
        out.writeChar('\t');
        out.writeInt(units[i]);
        out.writeChar('\t');
        out.writeChars(descs[i]);
        out.writeChar('\n');
    }
    out.close();

    // read it in again
    DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt"));

    double price;
    int unit;
    StringBuffer desc;
    double total = 0.0;

    try {
        while (true) {
            price = in.readDouble();
            in.readChar(); // throws out the tab
            unit = in.readInt();
            in.readChar(); // throws out the tab
            char chr;
            desc = new StringBuffer(20);
            char lineSep = System.getProperty("line.separator").charAt(0);
            while ((chr = in.readChar()) != lineSep)
                desc.append(chr);
            System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
            total = total + unit * price;
        }
    } catch (EOFException e) {
    }
    System.out.println("For a TOTAL of: $" + total);
    in.close();
}

From source file:RSATest.java

public static void main(String[] args) {
    try {//from w ww.j av  a2  s  .com
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {// w ww .  java2 s . c o  m
        if (args[0].equals("-genkeypair")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-sign")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            PrivateKey privkey = (PrivateKey) keyIn.readObject();
            keyIn.close();

            Signature signalg = Signature.getInstance("DSA");
            signalg.initSign(privkey);

            File infile = new File(args[1]);
            InputStream in = new FileInputStream(infile);
            int length = (int) infile.length();
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            signalg.update(message);
            byte[] signature = signalg.sign();

            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            int signlength = signature.length;
            out.writeInt(signlength);
            out.write(signature, 0, signlength);
            out.write(message, 0, length);
            out.close();
        } else if (args[0].equals("-verify")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2]));
            PublicKey pubkey = (PublicKey) keyIn.readObject();
            keyIn.close();

            Signature verifyalg = Signature.getInstance("DSA");
            verifyalg.initVerify(pubkey);

            File infile = new File(args[1]);
            DataInputStream in = new DataInputStream(new FileInputStream(infile));
            int signlength = in.readInt();
            byte[] signature = new byte[signlength];
            in.read(signature, 0, signlength);

            int length = (int) infile.length() - signlength - 4;
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            verifyalg.update(message);
            if (!verifyalg.verify(signature))
                System.out.print("not ");
            System.out.println("verified");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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(/* ww w.ja va  2 s .c  o m*/
                "         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:hyperloglog.tools.HyperLogLogCLI.java

public static void main(String[] args) {
    Options options = new Options();
    addOptions(options);/* w ww. j  a  v  a2  s . c  o m*/

    CommandLineParser parser = new BasicParser();
    CommandLine cli = null;
    long n = 0;
    long seed = 123;
    EncodingType enc = EncodingType.SPARSE;
    int p = 14;
    int hb = 64;
    boolean bitPack = true;
    boolean noBias = true;
    int unique = -1;
    String filePath = null;
    BufferedReader br = null;
    String outFile = null;
    String inFile = null;
    FileOutputStream fos = null;
    DataOutputStream out = null;
    FileInputStream fis = null;
    DataInputStream in = null;
    try {
        cli = parser.parse(options, args);

        if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) {
            System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt "
                    + "<OR> hll -d -i /tmp/out.hll");
            usage(options);
            return;
        }

        if (cli.hasOption('n')) {
            n = Long.parseLong(cli.getOptionValue('n'));
        }

        if (cli.hasOption('e')) {
            String value = cli.getOptionValue('e');
            if (value.equals(EncodingType.DENSE.name())) {
                enc = EncodingType.DENSE;
            }
        }

        if (cli.hasOption('p')) {
            p = Integer.parseInt(cli.getOptionValue('p'));
            if (p < 4 && p > 16) {
                System.out.println("Warning! Out-of-range value specified for p. Using to p=14.");
                p = 14;
            }
        }

        if (cli.hasOption('h')) {
            hb = Integer.parseInt(cli.getOptionValue('h'));
        }

        if (cli.hasOption('c')) {
            noBias = Boolean.parseBoolean(cli.getOptionValue('c'));
        }

        if (cli.hasOption('b')) {
            bitPack = Boolean.parseBoolean(cli.getOptionValue('b'));
        }

        if (cli.hasOption('f')) {
            filePath = cli.getOptionValue('f');
            br = new BufferedReader(new FileReader(new File(filePath)));
        }

        if (filePath != null && cli.hasOption('n')) {
            System.out.println("'-f' (input file) specified. Ignoring -n.");
        }

        if (cli.hasOption('s')) {
            if (cli.hasOption('o')) {
                outFile = cli.getOptionValue('o');
                fos = new FileOutputStream(new File(outFile));
                out = new DataOutputStream(fos);
            } else {
                System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll");
                usage(options);
                return;
            }
        }

        if (cli.hasOption('d')) {
            if (cli.hasOption('i')) {
                inFile = cli.getOptionValue('i');
                fis = new FileInputStream(new File(inFile));
                in = new DataInputStream(fis);
            } else {
                System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll");
                usage(options);
                return;
            }
        }

        // return after deserialization
        if (fis != null && in != null) {
            long start = System.currentTimeMillis();
            HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in);
            long end = System.currentTimeMillis();
            System.out.println(deserializedHLL.toString());
            System.out.println("Count after deserialization: " + deserializedHLL.count());
            System.out.println("Deserialization time: " + (end - start) + " ms");
            return;
        }

        // construct hll and serialize it if required
        HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc)
                .setNumHashBits(hb).setNumRegisterIndexBits(p).build();

        if (br != null) {
            Set<String> hashset = new HashSet<String>();
            String line;
            while ((line = br.readLine()) != null) {
                hll.addString(line);
                hashset.add(line);
            }
            n = hashset.size();
        } else {
            Random rand = new Random(seed);
            for (int i = 0; i < n; i++) {
                if (unique < 0) {
                    hll.addLong(rand.nextLong());
                } else {
                    int val = rand.nextInt(unique);
                    hll.addLong(val);
                }
            }
        }

        long estCount = hll.count();
        System.out.println("Actual count: " + n);
        System.out.println(hll.toString());
        System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%");
        if (fos != null && out != null) {
            long start = System.currentTimeMillis();
            HyperLogLogUtils.serializeHLL(out, hll);
            long end = System.currentTimeMillis();
            System.out.println("Serialized hyperloglog to " + outFile);
            System.out.println("Serialized size: " + out.size() + " bytes");
            System.out.println("Serialization time: " + (end - start) + " ms");
            out.close();
        }
    } catch (ParseException e) {
        System.err.println("Invalid parameter.");
        usage(options);
    } catch (NumberFormatException e) {
        System.err.println("Invalid type for parameter.");
        usage(options);
    } catch (FileNotFoundException e) {
        System.err.println("Specified file not found.");
        usage(options);
    } catch (IOException e) {
        System.err.println("Exception occured while reading file.");
        usage(options);
    }
}

From source file:createSod.java

/**
 * @param args//  w ww  .j a v  a2 s .c  om
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:Messenger.TorLib.java

public static void main(String[] args) {
    String req = "-r";
    String targetHostname = "tor.eff.org";
    String targetDir = "index.html";
    int targetPort = 80;

    if (args.length > 0 && args[0].equals("-h")) {
        System.out.println("Tinfoil/TorLib - interface for using Tor from Java\n"
                + "By Joe Foley<foley@mit.edu>\n" + "Usage: java Tinfoil.TorLib <cmd> <args>\n"
                + "<cmd> can be: -h for help\n" + "              -r for resolve\n"
                + "              -w for wget\n" + "For -r, the arg is:\n"
                + "  <hostname> Hostname to DNS resolve\n" + "For -w, the args are:\n"
                + "   <host> <path> <optional port>\n"
                + " for example, http://tor.eff.org:80/index.html would be\n" + "   tor.eff.org index.html 80\n"
                + " Since this is a demo, the default is the tor website.\n");
        System.exit(2);/*w ww .  j  a  va  2 s.  c o  m*/
    }

    if (args.length >= 4)
        targetPort = new Integer(args[2]).intValue();
    if (args.length >= 3)
        targetDir = args[2];
    if (args.length >= 2)
        targetHostname = args[1];
    if (args.length >= 1)
        req = args[0];

    if (req.equals("-r")) {
        System.out.println(TorResolve(targetHostname));
    } else if (req.equals("-w")) {
        try {
            Socket s = TorSocket(targetHostname, targetPort);
            DataInputStream is = new DataInputStream(s.getInputStream());
            PrintStream out = new java.io.PrintStream(s.getOutputStream());

            //Construct an HTTP request
            out.print("GET  /" + targetDir + " HTTP/1.0\r\n");
            out.print("Host: " + targetHostname + ":" + targetPort + "\r\n");
            out.print("Accept: */*\r\n");
            out.print("Connection: Keep-Aliv\r\n");
            out.print("Pragma: no-cache\r\n");
            out.print("\r\n");
            out.flush();

            // this is from Java Examples In a Nutshell
            final InputStreamReader from_server = new InputStreamReader(is);
            char[] buffer = new char[1024];
            int chars_read;

            // read until stream closes
            while ((chars_read = from_server.read(buffer)) != -1) {
                // loop through array of chars
                // change \n to local platform terminator
                // this is a nieve implementation
                for (int j = 0; j < chars_read; j++) {
                    if (buffer[j] == '\n')
                        System.out.println();
                    else
                        System.out.print(buffer[j]);
                }
                System.out.flush();
            }
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}