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:net.sf.keystore_explorer.crypto.x509.X509ExtensionSet.java

private static Map<String, byte[]> loadExtensions(DataInputStream dis) throws IOException {
    Map<String, byte[]> extensions = new HashMap<String, byte[]>();

    int extensionCnt = dis.readInt();

    for (int i = 0; i < extensionCnt; i++) {
        int oidLen = dis.readInt();

        char[] oidChars = new char[oidLen];

        for (int j = 0; j < oidLen; j++) {
            oidChars[j] = dis.readChar();
        }/*from   ww w . ja  va2 s  .c o  m*/

        String oid = new String(oidChars);

        int valueLen = dis.readInt();
        byte[] value = new byte[valueLen];

        dis.readFully(value);

        extensions.put(oid, value);
    }

    return extensions;
}

From source file:org.wso2.carbon.analytics.datasource.core.util.GenericUtils.java

public static Object deserializeObject(InputStream in) throws IOException {
    if (in == null) {
        return null;
    }/*from w w  w .  j av a  2s  .c  o m*/
    if (in.available() == 0) {
        throw new EOFException();
    }
    DataInputStream dataIn = new DataInputStream(in);
    int size = dataIn.readInt();
    byte[] buff = new byte[size];
    dataIn.readFully(buff);
    Kryo kryo = kryoTL.get();
    try (Input input = new Input(buff)) {
        return kryo.readClassAndObject(input);
    }
}

From source file:org.nuras.mcpha.Client.java

/**
 * Get histogram data/*from ww w.  ja v a 2 s  .  co  m*/
 * 
 * @param chan
 * @return 
 * @throws java.io.IOException 
 */
synchronized public static IntBuffer mcphaGetHistogramData(long chan) throws IOException {
    sendCommand(MCPHA_COMMAND_READ_HISTOGRAM_DATA, chan, 0);

    DataInputStream in = new DataInputStream(deviceSocket.getInputStream());

    ByteBuffer data = ByteBuffer.allocate(65536);
    data.order(ByteOrder.nativeOrder());
    in.readFully(data.array());

    return data.asIntBuffer();
}

From source file:org.nuras.mcpha.Client.java

/**
 * Get oscilloscope data which are 16-bit signed integer values.
 * The channels are interleaved sample-by-sample (ch1, ch2, ch1, ch2, etc).
 * /*from w  ww  .j a  va  2 s  .  c o m*/
 * @return a ShortBuffer of channel data values.
 * @throws java.io.IOException 
 */
synchronized public static ShortBuffer mcphaGetOsilloscopeData() throws IOException {
    sendCommand(MCPHA_COMMAND_READ_OSCILLOSCOPE_DATA, 0L, 0L);

    DataInputStream in = new DataInputStream(deviceSocket.getInputStream());

    ByteBuffer data = ByteBuffer.allocate(65536);
    data.order(ByteOrder.nativeOrder());
    in.readFully(data.array());

    return data.asShortBuffer();
}

From source file:com.bonsai.wallet32.HDWallet.java

public static JSONObject deserialize(WalletApplication walletApp, KeyCrypter keyCrypter, KeyParameter aesKey)
        throws IOException, InvalidCipherTextException, JSONException {

    File file = walletApp.getHDWalletFile(null);
    String path = file.getPath();

    try {/*from  ww w.  j  a v a  2s .  com*/
        mLogger.info("restoring HDWallet from " + path);
        int len = (int) file.length();

        // Open persisted file.
        DataInputStream dis = new DataInputStream(new FileInputStream(file));

        // Read IV from file.
        byte[] iv = new byte[KeyCrypterGroestl.BLOCK_LENGTH/*KeyCrypterScrypt.BLOCK_LENGTH*/];
        dis.readFully(iv);

        // Read the ciphertext from the file.
        byte[] cipherBytes = new byte[len - iv.length];
        dis.readFully(cipherBytes);
        dis.close();

        // Decrypt the ciphertext.
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), iv);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);
        int minimumSize = cipher.getOutputSize(cipherBytes.length);
        byte[] outputBuffer = new byte[minimumSize];
        int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, outputBuffer, 0);
        int length2 = cipher.doFinal(outputBuffer, length1);
        int actualLength = length1 + length2;
        byte[] decryptedBytes = new byte[actualLength];
        System.arraycopy(outputBuffer, 0, decryptedBytes, 0, actualLength);

        // Parse the decryptedBytes.
        String jsonstr = new String(decryptedBytes);

        /*
        // THIS CONTAINS THE SEED!
        // Have to break the message into chunks for big messages ...
        String msg = jsonstr;
        while (msg.length() > 1024) {
        String chunk = msg.substring(0, 1024);
        mLogger.error(chunk);
        msg = msg.substring(1024);
        }
        mLogger.error(msg);
        */

        JSONObject node = new JSONObject(jsonstr);
        return node;

    } catch (IOException ex) {
        mLogger.warn("trouble reading " + path + ": " + ex.toString());
        throw ex;
    } catch (RuntimeException ex) {
        mLogger.warn("trouble restoring wallet: " + ex.toString());
        throw ex;
    } catch (InvalidCipherTextException ex) {
        mLogger.warn("wallet decrypt failed: " + ex.toString());
        throw ex;
    }
}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowHelper.java

/**
 * Helper method to perform the actual substitution.
 *
 * @param pTask The task whose working directory should be checked for
 * substitution./*w w w.j  a  v a2  s.  c  o m*/
 * @param pTargetPath The target path.
 *
 * @throws IOException If the replacement operation fails for some reason.
 * @throws URISyntaxException If any of the URLs in the task (input, output,
 * temp or working dir URL) is invalid.
 */
private static void performSubstitution(DataWorkflowTask pTask, File pDirectory)
        throws IOException, URISyntaxException {
    File[] relevantFileList = pDirectory.listFiles(VAR_FILTER);
    LOGGER.info("Substituting variables in " + relevantFileList.length
            + ((relevantFileList.length == 1) ? " file" : " files"));

    for (File f : relevantFileList) {
        if (f.length() > 10 * FileUtils.ONE_MB) {
            LOGGER.warn(
                    "File {} has a size of {} bytes. Variable substitution is only supported for files with less than 10MB. File is skipped.",
                    f, f.length());
            continue;
        }
        //perform replacement
        LOGGER.info(" * Substituting variables in file '" + f.getPath() + "'");
        DataInputStream din = null;
        FileOutputStream fout = null;
        try {
            LOGGER.info("   - Reading input file");
            byte[] data = new byte[(int) f.length()];
            din = new DataInputStream(new FileInputStream(f));
            din.readFully(data);

            LOGGER.info("   - Substituting variables");
            String dataString = new String(data);

            String accessPointId = pTask.getExecutionEnvironment().getStagingAccessPointId();
            AbstractStagingAccessPoint accessPoint = StagingConfigurationManager.getSingleton()
                    .getAccessPointById(accessPointId);
            LOGGER.debug("  - Obtaining local path for input dir URL {}", pTask.getInputDirectoryUrl());
            File localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getInputDirectoryUrl()),
                    getTaskContext(pTask));
            LOGGER.debug("  - Local path is: {}", localPath);
            String inputDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for output dir URL {}", pTask.getOutputDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getOutputDirectoryUrl()),
                    getTaskContext(pTask));
            String outputDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for working dir URL {}", pTask.getWorkingDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getWorkingDirectoryUrl()),
                    getTaskContext(pTask));
            String workingDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for temp dir URL {}", pTask.getTempDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getTempDirectoryUrl()),
                    getTaskContext(pTask));
            String tempDirReplacement = localPath.getCanonicalPath();

            LOGGER.info("     " + DATA_IN_DIR + ": " + inputDirReplacement);
            LOGGER.info("     " + DATA_OUT_DIR + ": " + outputDirReplacement);
            LOGGER.info("     " + TEMP_DIR + ": " + tempDirReplacement);
            LOGGER.info("     " + WORKING_DIR + ": " + workingDirReplacement);
            //replace all variables
            //To obtain a proper path format the input paths are put into a file object and the URI path is used for replacement. Therefore differences between
            //source and destination platform are not relevant. Due to the URI.toPath() returns the path with leading slash, we use the path beginning with
            //the second index to avoid problems with other programming languages not able to deal with the leading slash.
            dataString = dataString.replaceAll(Pattern.quote(DATA_IN_DIR_VARIABLE), inputDirReplacement)
                    .replaceAll(Pattern.quote(DATA_OUT_DIR_VARIABLE), outputDirReplacement)
                    .replaceAll(Pattern.quote(TEMP_DIR_VARIABLE), tempDirReplacement)
                    .replaceAll(Pattern.quote(WORKING_DIR_VARIABLE), workingDirReplacement);
            LOGGER.info("   - Writing output file");
            fout = new FileOutputStream(f);
            fout.write(dataString.getBytes());
            fout.flush();
            LOGGER.info(" * Substituting operations finished successfully");
        } finally {
            try {
                if (din != null) {
                    din.close();
                }
            } catch (IOException ioe) {
            }
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
    LOGGER.info("Directory {} processed successfully", pDirectory);
}

From source file:dualcontrol.CryptoClientDemo.java

private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data)
        throws Exception {
    Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory()
            .createSocket(hostAddress, port);
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    dos.writeShort(data.length);/*from   ww  w  . ja  va2 s  . c  om*/
    dos.write(data);
    dos.flush();
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    byte[] ivBytes = new byte[dis.readShort()];
    dis.readFully(ivBytes);
    byte[] bytes = new byte[dis.readShort()];
    dis.readFully(bytes);
    if (new String(data).contains("DECRYPT")) {
        System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes));
    } else {
        System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes));
    }
    socket.close();
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a public key stored in a local file
 * <p>/*from   www . j  a  va  2s  . co m*/
 * 
 * @param pubPath path to the public key on the local filesystem
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException the key could not be retrieved or is malformed
 */
public static PublicKey getPublicKey(String pubPath) throws KeyException {
    byte[] bytes;
    File f = new File(pubPath);
    FileInputStream fin;

    String algo = "", tmp = "";

    // recover public key bytes
    try {
        fin = new FileInputStream(f);
        DataInputStream in = new DataInputStream(fin);
        int read, tot = 0;
        while ((read = in.read()) != '\n') {
            algo += (char) read;
            tot++;
        }
        tot++;
        while ((read = in.read()) != '\n') {
            tmp += (char) read;
            tot++;
        }
        tot++;

        bytes = new byte[(int) f.length() - tot];
        in.readFully(bytes);
        in.close();
    } catch (Exception e) {
        throw new KeyException("Could not retrieve public key from " + pubPath, e);
    }

    // reconstruct public key
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    PublicKey pubKey;
    KeyFactory keyFactory;

    try {
        keyFactory = KeyFactory.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyException("Cannot initialize key factory", e);
    }

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new KeyException("Cannot re-generate public key", e);
    }

    return pubKey;
}

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

public CommitLogEntry deserialize(DataInputStream dis) throws IOException {
    byte[] value = new byte[dis.readInt()];
    dis.readFully(value);
    return new CommitLogEntry(value);
}

From source file:io.undertow.servlet.test.proprietry.TransferTestCase.java

@Test
public void testServletRequest() throws Exception {
    TestListener.init(2);//from www . j a  v a2 s .c  o m
    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/aa");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final byte[] response = HttpClientUtils.readRawResponse(result);
        Path file = Paths.get(TXServlet.class.getResource(TXServlet.class.getSimpleName() + ".class").toURI());
        byte[] expected = new byte[(int) Files.size(file)];
        DataInputStream dataInputStream = new DataInputStream(Files.newInputStream(file));
        dataInputStream.readFully(expected);
        dataInputStream.close();
        Assert.assertArrayEquals(expected, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}