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:org.veronicadb.core.memorygraph.storage.SimpleLocalFileStorageSink.java

protected byte[] readGraphBloom(DataInputStream stream) throws IOException {
    byte[] bloom = new byte[stream.readInt()];
    stream.readFully(bloom);
    return bloom;
}

From source file:J2MEImageLoader.java

public void run() {
    HttpConnection hc = null;/*from  w  ww . j  a  va 2s  .co m*/
    DataInputStream in = null;

    try {
        hc = (HttpConnection) Connector.open("http://www.y.com/image.gif");
        int length = (int) hc.getLength();
        byte[] data = null;
        if (length != -1) {
            data = new byte[length];
            in = new DataInputStream(hc.openInputStream());
            in.readFully(data);
        } else {
            int chunkSize = 512;
            int index = 0;
            int readLength = 0;
            in = new DataInputStream(hc.openInputStream());
            data = new byte[chunkSize];
            do {
                if (data.length < index + chunkSize) {
                    byte[] newData = new byte[index + chunkSize];
                    System.arraycopy(data, 0, newData, 0, data.length);
                    data = newData;
                }
                readLength = in.read(data, index, chunkSize);
                index += readLength;
            } while (readLength == chunkSize);
            length = index;
        }
        Image image = Image.createImage(data, 0, length);
        ImageItem imageItem = new ImageItem(null, image, 0, null);
        mForm.append(imageItem);
        mForm.setTitle("Done.");
    } catch (IOException ioe) {
        mForm.setTitle("Error.");
    }
}

From source file:org.silverpeas.dbbuilder.DBBuilderPiece.java

public DBBuilderPiece(Console console, String pieceName, String actionName, boolean traceMode)
        throws Exception {
    this.console = console;
    this.traceMode = traceMode;
    this.actionName = actionName;
    this.pieceName = pieceName;
    if (pieceName.endsWith(".jar")) {
        content = "";
    } else {//from www .  jav  a 2  s .com
        // charge son contenu sauf pour un jar qui doit tre dans le classpath
        File myFile = new File(pieceName);
        if (!myFile.exists() || !myFile.isFile() || !myFile.canRead()) {
            console.printMessage("\t\t***Unable to load : " + pieceName);
            throw new Exception("Unable to find or load : " + pieceName);
        }
        int fileSize = (int) myFile.length();
        byte[] data = new byte[fileSize];
        DataInputStream in = new DataInputStream(new FileInputStream(pieceName));
        try {
            in.readFully(data);
        } finally {
            IOUtils.closeQuietly(in);
        }
        content = new String(data, Charsets.UTF_8);
    }
    Properties res = DBBuilder.getdbBuilderResources();
    if (res != null) {
        for (Enumeration e = res.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            String value = res.getProperty(key);
            content = StringUtil.sReplace("${" + key + '}', value, content);
        }
    }
}

From source file:com.igormaznitsa.jcp.it.maven.ITPreprocessorMojo.java

@Test
@SuppressWarnings("unchecked")
public void testPreprocessorUsage() throws Exception {
    final File testDir = ResourceExtractor.simpleExtractResources(this.getClass(), "./dummy_maven_project");

    final Verifier verifier = new Verifier(testDir.getAbsolutePath());

    verifier.deleteArtifact("com.igormaznitsa", "DummyMavenProjectToTestJCP", "1.0-SNAPSHOT", "jar");
    verifier.executeGoal("package");
    assertFalse("Folder must be removed", new File("./dummy_maven_project/target").exists());

    final File resultJar = ResourceExtractor.simpleExtractResources(this.getClass(),
            "./dummy_maven_project/DummyMavenProjectToTestJCP-1.0-SNAPSHOT.jar");

    verifier.verifyErrorFreeLog();/*from w ww  . ja  va2 s .c o  m*/
    verifier.verifyTextInLog("PREPROCESSED_TESTING_COMPLETED");
    verifier.verifyTextInLog("Cleaning has been started");
    verifier.verifyTextInLog("Removing preprocessed source folder");
    verifier.verifyTextInLog("Removing preprocessed test source folder");
    verifier.verifyTextInLog("Scanning for deletable directories");
    verifier.verifyTextInLog("Deleting directory:");
    verifier.verifyTextInLog("Cleaning has been completed");
    verifier.verifyTextInLog(" mvn.project.property.some.datapass.base=***** ");
    verifier.verifyTextInLog(" mvn.project.property.some.private.key=***** ");

    final JarAnalyzer jarAnalyzer = new JarAnalyzer(resultJar);
    List<JarEntry> classEntries;
    try {
        classEntries = (List<JarEntry>) jarAnalyzer.getClassEntries();

        for (final JarEntry ce : classEntries) {
            assertFalse(ce.getName().contains("excludedfolder"));
        }

        assertEquals("Must have only class", 1, classEntries.size());
        final JarEntry classEntry = classEntries.get(0);
        assertNotNull(findClassEntry(jarAnalyzer, "com/igormaznitsa/dummyproject/testmain2.class"));

        DataInputStream inStream = null;
        final byte[] buffer = new byte[(int) classEntry.getSize()];
        Class<?> instanceClass = null;
        try {
            inStream = new DataInputStream(jarAnalyzer.getEntryInputStream(classEntry));
            inStream.readFully(buffer);

            instanceClass = new ClassLoader() {

                public Class<?> loadClass(final byte[] data) throws ClassNotFoundException {
                    return defineClass(null, data, 0, data.length);
                }
            }.loadClass(buffer);
        } finally {
            IOUtils.closeQuietly(inStream);
        }

        if (instanceClass != null) {
            final Object instance = instanceClass.newInstance();
            assertEquals("Must return the project name", "Dummy Maven Project To Test JCP",
                    instanceClass.getMethod("test").invoke(instance));
        } else {
            fail("Unexpected state");
        }
    } finally {
        jarAnalyzer.closeQuietly();
    }
}

From source file:mitm.common.security.password.PBEncryptionParameters.java

private void fromByteArray(byte[] encoded) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(encoded);

    DataInputStream in = new DataInputStream(bis);

    long version = in.readLong();

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

    int saltSize = in.readInt();

    this.salt = new byte[saltSize];

    in.readFully(salt);

    this.iterationCount = in.readInt();

    int encryptedSize = in.readInt();

    this.encryptedData = new byte[encryptedSize];

    in.readFully(encryptedData);
}

From source file:org.carbondata.query.util.CacheUtil.java

/**
 * Below method is responsible for reading the sort index and sort reverse index
 *
 * @param levelFileName/* ww  w.  j  a  va 2  s .co m*/
 * @return List<int[][]>
 * @throws IOException
 */
public static List<int[][]> getLevelSortOrderAndReverseIndex(String levelFileName) throws IOException {
    if (!FileFactory.isFileExist(levelFileName + CarbonCommonConstants.LEVEL_SORT_INDEX_FILE_EXT,
            FileFactory.getFileType(levelFileName + CarbonCommonConstants.LEVEL_SORT_INDEX_FILE_EXT))) {
        return null;
    }
    DataInputStream dataInputStream = null;
    List<int[][]> sortIndexAndReverseIndexArray = new ArrayList<int[][]>(
            CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
    long size = 0;
    ByteBuffer buffer = null;
    try {
        dataInputStream = FileFactory.getDataInputStream(
                levelFileName + CarbonCommonConstants.LEVEL_SORT_INDEX_FILE_EXT,
                FileFactory.getFileType(levelFileName));
        size = FileFactory.getCarbonFile(levelFileName + CarbonCommonConstants.LEVEL_SORT_INDEX_FILE_EXT,
                FileFactory.getFileType(levelFileName)).getSize();
        // CHECKSTYLE:OFF Approval No:Approval-V1R2C10_005
        buffer = ByteBuffer.allocate((int) size);
        // CHECKSTYLE:ON
        dataInputStream.readFully(buffer.array());
        sortIndexAndReverseIndexArray.add(getIndexArray(buffer));
        sortIndexAndReverseIndexArray.add(getIndexArray(buffer));
    } catch (IOException e) {
        LOGGER.error(e);
        throw e;
    } finally {
        CarbonUtil.closeStreams(dataInputStream);
    }
    return sortIndexAndReverseIndexArray;
}

From source file:com.facebook.infrastructure.db.Column.java

private IColumn defreeze(DataInputStream dis, String name) throws IOException {
    IColumn column = null;/*from  w w  w . j ava 2 s .  co m*/
    boolean delete = dis.readBoolean();
    long ts = dis.readLong();
    int size = dis.readInt();
    byte[] value = new byte[size];
    dis.readFully(value);
    column = new Column(name, value, ts, delete);
    return column;
}

From source file:org.apache.hadoop.dfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf./*  w w  w  .  ja v a  2s. co  m*/
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, FSConstants.READ_TIMEOUT);
        sock.setSoTimeout(FSConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

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 www .ja va  2  s.co  m

    algorithm = dis.readUTF();

    int saltSize = dis.readInt();

    this.salt = new byte[saltSize];

    dis.readFully(salt);

    this.iterationCount = dis.readInt();
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

final public static _CRYPTOfactory getInstance(InputStream in) throws ClassNotFoundException,
        NoSuchAlgorithmException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    final DataInputStream d = new DataInputStream(in);
    int start = 0;
    final int type_length = d.readInt();
    start = start + 4;//from w  w  w  . jav  a 2 s  .  co m
    final int cipher_length = d.readInt();
    start = start + 4;
    final int salter_length = d.readInt();
    start = start + 4;
    final int key_length = d.readInt();
    start = start + 4;
    final StringBuilder type = new StringBuilder();
    final StringBuilder cipher = new StringBuilder();
    final StringBuilder salter = new StringBuilder();
    final byte[] key = new byte[key_length];
    for (int i = 0; i < type_length; i++)
        type.append((char) d.readByte());
    for (int i = 0; i < cipher_length; i++)
        cipher.append((char) d.readByte());
    for (int i = 0; i < salter_length; i++)
        salter.append((char) d.readByte());
    d.readFully(key);
    return new _CRYPTOfactory(
            (Crypter) Class.forName(_CRYPTOfactory.class.getPackage().getName() + "." + type + "Crypter")
                    .getConstructor(byte[].class, String.class, SecureRandom.class)
                    .newInstance(key, cipher.toString(), SecureRandom.getInstance(salter.toString())));
}