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:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*  w ww .j  av a 2  s  .  c  o  m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:ml.shifu.guagua.io.Bzip2BytableSerializer.java

/**
 * De-serialize from bytes to object. One should provide the class name before de-serializing the object.
 * /*w w  w.j a  v  a 2 s .  c  o  m*/
 * @throws NullPointerException
 *             if className or data is null.
 * @throws GuaguaRuntimeException
 *             if any io exception or other reflection exception.
 */
@Override
public RESULT bytesToObject(byte[] data, String className) {
    if (data == null || className == null) {
        throw new NullPointerException(
                String.format("data and className should not be null. data:%s, className:%s",
                        Arrays.toString(data), className));
    }
    @SuppressWarnings("unchecked")
    RESULT result = (RESULT) ReflectionUtils.newInstance(className);
    DataInputStream dataIn = null;
    try {
        InputStream in = new ByteArrayInputStream(data);
        InputStream gzipInput = new BZip2CompressorInputStream(in);
        dataIn = new DataInputStream(gzipInput);
        result.readFields(dataIn);
    } catch (Exception e) {
        throw new GuaguaRuntimeException(e);
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                throw new GuaguaRuntimeException(e);
            }
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available.//from  w  w w .ja  v  a2 s  . c o m
 *
 * @param inStream The DER InputStream with the certificate.
 * @return X509Certificate parsed from stream.
 * @throws JAXRException in case of IOException or CertificateException
 *  while parsing the stream.
 */
public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException {
    try {
        //possible options
        // - der x509 generated by keytool -export
        // - der x509 generated by openssh x509 (might require BC provider)

        // Get the CertificateFactory to parse the stream
        // if BouncyCastle provider available, use it
        CertificateFactory cf;
        try {
            Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            Constructor<?> constructor = clazz.getConstructor(new Class[] {});
            Provider bcProvider = (Provider) constructor.newInstance(new Object[] {});
            Security.addProvider(bcProvider);
            cf = CertificateFactory.getInstance("X.509", "BC");
        } catch (Exception e) {
            // log error if bc present but failed to instanciate/add provider
            if (!(e instanceof ClassNotFoundException)) {
                log.error(CommonResourceBundle.getInstance()
                        .getString("message.FailedToInstantiateBouncyCastleProvider"));
            }
            // fall back to default provider
            cf = CertificateFactory.getInstance("X.509");
        }

        // Read the stream to a local variable
        DataInputStream dis = new DataInputStream(inStream);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream certStream = new ByteArrayInputStream(bytes);

        // Parse the cert stream
        int i = 0;
        Collection<? extends Certificate> c = cf.generateCertificates(certStream);
        X509Certificate[] certs = new X509Certificate[c.toArray().length];
        for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) {
            certs[i++] = (X509Certificate) it.next();
        }

        // Some logging..
        if (log.isDebugEnabled()) {
            if (c.size() == 1) {
                log.debug("One certificate, no chain.");
            } else {
                log.debug("Certificate chain length: " + c.size());
            }
            log.debug("Subject DN: " + certs[0].getSubjectDN().getName());
            log.debug("Issuer DN: " + certs[0].getIssuerDN().getName());
        }

        // Do we need to return the chain?
        // do we need to verify if cert is self signed / valid?
        return certs[0];
    } catch (CertificateException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } catch (IOException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            inStream = null;
        }
    }
}

From source file:genepi.db.h2.H2Connector.java

public static String readFileAsString(InputStream is) throws java.io.IOException, URISyntaxException {

    DataInputStream in = new DataInputStream(is);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;//from www  . j  av a2s.com
    StringBuilder builder = new StringBuilder();
    while ((strLine = br.readLine()) != null) {
        builder.append("\n");
        builder.append(strLine);
    }

    in.close();

    return builder.toString();
}

From source file:edu.du.penrose.systems.fedoraApp.tests.UtilModsToFileTest.java

void writeModsToFile(String outputDirName, File inputFile, int fileCount) {

    BufferedReader br = null;/*from  w w  w.ja v a 2s  .  co m*/
    BufferedWriter bw = null;
    try {
        File outFile = null;
        FileInputStream fis = new FileInputStream(inputFile);
        FileOutputStream fos = null;

        DataInputStream in = new DataInputStream(fis);
        br = new BufferedReader(new InputStreamReader(in));

        String doucmentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        String oneLine = null;
        while (br.ready()) {
            oneLine = br.readLine();
            if (oneLine.contains("<mods:mods")) {

                outFile = new File(outputDirName + "\\mods_" + fileCount + ".xml");
                fos = new FileOutputStream(outFile);

                bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
                bw.write(doucmentType);
                bw.newLine();
                while (!oneLine.contains("</mods:mods")) { // null pointer on premature end of file.
                    bw.write(oneLine);
                    bw.newLine();
                    oneLine = br.readLine();
                }
                bw.write(oneLine);
                bw.newLine();
                bw.close();
                fileCount++;
            }
        } // while
    } catch (Exception e) {
        String errorMsg = "Exception:" + e;
        System.out.println(errorMsg);
    } finally {
        try {
            br.close();
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:gobblin.metrics.reporter.KafkaAvroEventReporterWithSchemaRegistryTest.java

@Test
public void test() throws Exception {

    MetricContext context = MetricContext.builder("context").build();

    MockKafkaPusher pusher = new MockKafkaPusher();
    KafkaAvroSchemaRegistry registry = Mockito.mock(KafkaAvroSchemaRegistry.class);
    Mockito.when(registry.register(Mockito.any(Schema.class))).thenAnswer(new Answer<String>() {
        @Override/*from  w  ww.j  a  v a  2 s .  com*/
        public String answer(InvocationOnMock invocation) throws Throwable {
            return register((Schema) invocation.getArguments()[0]);
        }
    });
    Mockito.when(registry.register(Mockito.any(Schema.class), Mockito.anyString()))
            .thenAnswer(new Answer<String>() {
                @Override
                public String answer(InvocationOnMock invocation) throws Throwable {
                    return register((Schema) invocation.getArguments()[0]);
                }
            });
    KafkaEventReporter kafkaReporter = KafkaAvroEventReporter.forContext(context).withKafkaPusher(pusher)
            .withSchemaRegistry(registry).build("localhost:0000", "topic");

    GobblinTrackingEvent event = new GobblinTrackingEvent(0l, "namespace", "name",
            Maps.<String, String>newHashMap());

    context.submitEvent(event);

    try {
        Thread.sleep(100);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    kafkaReporter.report();

    try {
        Thread.sleep(100);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    byte[] nextMessage = pusher.messageIterator().next();
    DataInputStream is = new DataInputStream(new ByteArrayInputStream(nextMessage));
    Assert.assertEquals(is.readByte(), KafkaAvroSchemaRegistry.MAGIC_BYTE);
    byte[] readId = new byte[20];
    Assert.assertEquals(is.read(readId), 20);
    String readStringId = Hex.encodeHexString(readId);
    Assert.assertTrue(this.schemas.containsKey(readStringId));

    Schema schema = this.schemas.get(readStringId);
    Assert.assertFalse(schema.toString().contains("avro.java.string"));

    is.close();
}

From source file:eu.delving.sip.files.ReportFile.java

public ReportFile(File reportFile, File reportIndexFile, File invalidFile, File linkFile, DataSet dataSet,
        String prefix) throws IOException {
    this.reportFile = reportFile;
    this.reportAccess = new RandomAccessFile(this.reportFile, "r");
    this.reportIndexAccess = new RandomAccessFile(reportIndexFile, "r");
    this.linkFile = new LinkFile(linkFile, dataSet, prefix);
    this.dataSet = dataSet;
    this.prefix = prefix;
    int recordCount = (int) (reportIndexAccess.length() / LONG_SIZE);
    recs = new ArrayList<Rec>(recordCount);
    for (int walk = 0; walk < recordCount; walk++)
        recs.add(new Rec(walk));
    DataInputStream invalidIn = new DataInputStream(new FileInputStream(invalidFile));
    int invalidCount = invalidIn.readInt();
    invalidRecs = new ArrayList<Rec>(invalidCount);
    for (int walk = 0; walk < invalidCount; walk++) {
        int recordNumber = invalidIn.readInt();
        invalidRecs.add(recs.get(recordNumber));
    }//from   w w w. j a v  a  2s  . c  o  m
    invalidIn.close();
}

From source file:mitm.common.security.crypto.PBEncryptedStreamParameters.java

private void fromInputStream(InputStream input) throws IOException {
    DataInputStream dis = new DataInputStream(input);

    long version = dis.readLong();

    if (version != serialVersionUID) {
        throw new SerializationException("Version expected '" + serialVersionUID + "' but got '" + version);
    }/*from w ww .j  a  v  a  2 s.c o  m*/

    algorithm = dis.readUTF();

    int saltSize = dis.readInt();

    this.salt = new byte[saltSize];

    dis.readFully(salt);

    this.iterationCount = dis.readInt();
}

From source file:juserdefaults.JUserDefaults.java

private void loadStorage() {
    File file = new File(storageFileName);
    String completeFileString = "";
    try {/*from  w w w .  j a va2s .c o m*/
        FileInputStream fstream = new FileInputStream(file.getAbsolutePath());

        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            completeFileString = completeFileString + strLine + "\n";
        }
        in.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }

    try {
        this.storageObject = new org.json.JSONObject(completeFileString);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

From source file:SearchMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w  w w  .j a  va  2  s  . co m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "Adam", "Bob", "Mary" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            if (recordstore.getNumRecords() > 0) {
                filter = new Filter("Mary");
                recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                while (recordEnumeration.hasNextElement()) {
                    recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt();
                    alert = new Alert("Reading", inputString, null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                filter.filterClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}