Example usage for java.io DataInputStream readFully

List of usage examples for java.io DataInputStream readFully

Introduction

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

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

See the general contract of the readFully method of DataInput .

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {
    InputStream is = new FileInputStream("c:\\test.txt");
    DataInputStream dis = new DataInputStream(is);

    int length = dis.available();

    byte[] buf = new byte[length];

    dis.readFully(buf);

    for (byte b : buf) {
        char c = (char) b;
        System.out.print(c);//from   w w  w . j  a  va2 s .c  o  m
    }

}

From source file:org.apache.nutch.parse.ext.WaxExtParser.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: WaxExtParser PDF_FILE...");
        System.exit(1);/* w  w w.  ja  v a  2s.  c  o  m*/
    }

    Configuration conf = NutchwaxConfiguration.getConfiguration();
    WaxExtParser parser = new WaxExtParser();
    parser.setConf(conf);

    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        String url = "file:" + name;
        File file = new File(name);
        byte[] bytes = new byte[(int) file.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file));

        try {
            in.readFully(bytes);
            Parse parse = parser
                    .getParse(new Content(url, url, bytes, "application/pdf", new Metadata(), conf));
            System.out.println(parse.getData().getTitle());
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:org.apache.nutch.parse.html.HtmlParser.java

public static void main(String[] args) throws Exception {
    //LOG.setLevel(Level.FINE);
    String name = args[0];/*from  ww w  .  ja  v a  2 s. c  o  m*/
    String url = "file:" + name;
    File file = new File(name);
    byte[] bytes = new byte[(int) file.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    in.readFully(bytes);
    Configuration conf = NutchConfiguration.create();
    HtmlParser parser = new HtmlParser();
    parser.setConf(conf);
    Parse parse = parser.getParse(new Content(url, url, bytes, "text/html", new Metadata(), conf)).get(url);
    System.out.println("data: " + parse.getData());

    System.out.println("text: " + parse.getText());

}

From source file:org.apache.nutchbase.parse.html.HtmlParserHbase.java

public static void main(String[] args) throws Exception {
    //LOG.setLevel(Level.FINE);
    String name = args[0];//from   www  . j  a  va 2 s  .  c om
    String url = "file:" + name;
    File file = new File(name);
    byte[] bytes = new byte[(int) file.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    in.readFully(bytes);
    Configuration conf = NutchConfiguration.create();
    HtmlParserHbase parser = new HtmlParserHbase();
    parser.setConf(conf);
    RowPart row = new RowPart(Bytes.toBytes(TableUtil.reverseUrl(url)));
    row.setBaseUrl(url);
    row.setContent(bytes);
    row.setContentType("text/html");
    ParseHbase parse = parser.getParse(url, row);
    System.out.println("title: " + parse.getTitle());
    System.out.println("text: " + parse.getText());
    System.out.println("outlinks: " + Arrays.toString(parse.getOutlinks()));

}

From source file:createSod.java

/**
 * @param args/*from w ww.ja  v  a 2 s .c o m*/
 * @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:org.apache.nutch.parse.feed.FeedParser.java

/**
 * Runs a command line version of this {@link Parser}.
 * //ww w . j a v a 2  s . co m
 * @param args
 *          A single argument (expected at arg[0]) representing a path on the
 *          local filesystem that points to a feed file.
 * 
 * @throws Exception
 *           If any error occurs.
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: FeedParser <feed>");
        System.exit(1);
    }
    String name = args[0];
    String url = "file:" + name;
    Configuration conf = NutchConfiguration.create();
    FeedParser parser = new FeedParser();
    parser.setConf(conf);
    File file = new File(name);
    byte[] bytes = new byte[(int) file.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    in.readFully(bytes);
    ParseResult parseResult = parser
            .getParse(new Content(url, url, bytes, "application/rss+xml", new Metadata(), conf));
    for (Entry<Text, Parse> entry : parseResult) {
        System.out.println("key: " + entry.getKey());
        Parse parse = entry.getValue();
        System.out.println("data: " + parse.getData());
        System.out.println("text: " + parse.getText() + "\n");
    }
}

From source file:edu.stanford.epad.common.pixelmed.SegmentationObjectsFileWriter.java

/**
 * This demo gets segmentation maps from map_file, then inserts the maps twice as two segments.
 * /*from w w w  .j  a v  a  2s.c om*/
 * @param args: java SegmentationObjectsFileWriter dicom_file map_file output_file mode mode is "BINARY" or
 *          "FRACTIONAL".
 */
public static void main(String[] args) {
    String input_file = args[0];// "./DicomFiles/CT0010";//
    String map_file = args[1];// "./TEMP/CT0010.mapbin";//
    String output_file = args[2];// "./TEMP/CT0010.sobin";//"segmentation_test_out.dcm";
    // String mode = args[3]; //"BINARY";

    byte[] pixels = null;
    SegmentationObjectsFileWriter obj = null;
    short image_width = 0, image_height = 0, image_frames = 0;

    // Read pixel array from the map_file.
    File file = new File(map_file);
    DataInputStream dis = null;
    pixels = new byte[(int) file.length()];
    try {
        dis = new DataInputStream((new FileInputStream(file)));
        dis.readFully(pixels);
        dis.close();
    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {
        IOUtils.closeQuietly(dis);
    }

    try {
        DicomInputStream i_stream = new DicomInputStream(new FileInputStream(input_file));
        AttributeList list = new AttributeList();
        list.read(i_stream);

        { // Get sequence format.
            image_width = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.Columns, 1);
            image_height = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.Rows, 1);
            image_frames = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.NumberOfFrames,
                    1);
        }

        short[] orientation = new short[] { 1, 0, 0, 0, 0, 1 };
        double[] spacing = new double[] { 0.65, 0.8 };
        double thickness = 0.5;
        AttributeList[] lists = new AttributeList[1];
        lists[0] = list;
        obj = new SegmentationObjectsFileWriter(lists, orientation, spacing, thickness);

        CodedConcept category = new CodedConcept("C0085089" /* conceptUniqueIdentifier */,
                "260787004" /* SNOMED CID */, "SRT" /* codingSchemeDesignator */,
                "SNM3" /* legacyCodingSchemeDesignator */, null /* codingSchemeVersion */,
                "A-00004" /* codeValue */, "Physical Object" /* codeMeaning */, null /* codeStringEquivalent */,
                null /* synonynms */);
        CodedConcept type = new CodedConcept("C0018787" /* conceptUniqueIdentifier */,
                "80891009" /* SNOMED CID */, "SRT" /* codingSchemeDesignator */,
                null /* legacyCodingSchemeDesignator */, null /* codingSchemeVersion */,
                "T-32000" /* codeValue */, "Heart" /* codeMeaning */, null /* codeStringEquivalent */,
                null /* synonynms */);
        double[][] positions = new double[image_frames][3];
        /*
         * void AddAllFrames(byte [] frames, int frame_num, int image_width, int image_height, String type, double [][]
         * positions, short [] patient_orientation, double slice_thickness, double [] pixel_spacing, short stack_id)
         */
        // Segment 1
        obj.addOneSegment("Segment No.1 is for ...", category, type);
        obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", (short) 0, positions);
        short stack_id = 2;
        positions[0][0] = 0.2;
        obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", stack_id, positions);
        // Segment 2
        // obj.AddOneSegment(null, null, null);
        obj.addOneSegment("Segment No.2 is for ...", category, type);
        obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", (short) 1, positions);
        obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", stack_id, positions);

        obj.saveDicomFile(output_file);

    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace(System.err);
        System.exit(0);
    }
}

From source file:Main.java

public static byte[] readBytes(DataInputStream is, int i) throws IOException {
    byte[] data = new byte[i];
    is.readFully(data);

    return data;//from w w w.j  a  va  2  s . c om
}

From source file:Main.java

public static File WriteStreamToFile(InputStream resStream) {
    try {//  w w  w  .  ja  v  a2 s. co m
        byte[] bytes = new byte[resStream.available()];
        File tmpFile = File.createTempFile("z4-", ".tmp");
        tmpFile.deleteOnExit();
        DataInputStream dis = new DataInputStream(resStream);
        dis.readFully(bytes);
        FileOutputStream foutStream = new FileOutputStream(tmpFile.getPath());
        foutStream.write(bytes);
        foutStream.close();
        dis.close();
        return tmpFile;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static byte[] readFileToByteArray(File file) {
    try {/*w ww . j av  a 2s . c  om*/
        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;
    }
}