Example usage for java.io DataInputStream readInt

List of usage examples for java.io DataInputStream readInt

Introduction

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

Prototype

public final int readInt() throws IOException 

Source Link

Document

See the general contract of the readInt method of DataInput.

Usage

From source file:org.apache.apex.malhar.stream.api.operator.FunctionOperator.java

@SuppressWarnings("unchecked")
private void readFunction() {
    try {//  w w  w. j  a  v a  2 s.c  om
        if (statelessF != null || statefulF != null) {
            return;
        }
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(annonymousFunctionClass));
        byte[] classNameBytes = new byte[input.readInt()];
        input.read(classNameBytes);
        String className = new String(classNameBytes);
        byte[] classData = new byte[input.readInt()];
        input.read(classData);
        Map<String, byte[]> classBin = new HashMap<>();
        classBin.put(className, classData);
        ByteArrayClassLoader byteArrayClassLoader = new ByteArrayClassLoader(classBin,
                Thread.currentThread().getContextClassLoader());
        statelessF = ((Class<FUNCTION>) byteArrayClassLoader.findClass(className)).newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.slc.sli.dal.encrypt.AesCipher.java

private Object decryptBinary(String data, Class<?> expectedType) {
    byte[] decoded = decryptToBytes(data);
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(decoded));
    try {/* ww w. j av a  2s . c o  m*/
        if (Boolean.class.equals(expectedType)) {
            return dis.readBoolean();
        } else if (Integer.class.equals(expectedType)) {
            return dis.readInt();
        } else if (Long.class.equals(expectedType)) {
            return dis.readLong();
        } else if (Double.class.equals(expectedType)) {
            return dis.readDouble();
        } else {
            throw new RuntimeException("Unsupported type: " + expectedType.getCanonicalName());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            dis.close();
        } catch (IOException e) {
            LOG.error("Unable to close DataInputStream!");
        }
    }
}

From source file:org.jreversepro.decompile.simulate.SwitchTable.java

/**
 * For 'tableswitch' opcode this fills the data structure - JSwitchTable.
 * /* w ww. ja  va 2s  .com*/
 * @param entries
 *          Bytecode entries that contain the case values and their target
 *          opcodes.
 * @param offset
 *          offset is the index of the current tableswitch instruction into
 *          the method bytecode array.
 * @param gotos
 *          Map of goto statements.
 * @throws IOException
 *           Thrown in case of an i/o error when reading from the bytes.
 */
private void createTableSwitch(byte[] entries, int offset, Map<Integer, Integer> gotos) throws IOException {
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new ByteArrayInputStream(entries));
        defaultByte = dis.readInt() + offset;
        int lowVal = dis.readInt();
        int highVal = dis.readInt();

        Map<Integer, CaseEntry> mapCases = new HashMap<Integer, CaseEntry>();
        for (int i = lowVal; i <= highVal; i++) {
            int curTarget = dis.readInt() + offset;
            String value = TypeInferrer.getValue(String.valueOf(i), this.datatype);
            CaseEntry ent = mapCases.get(Integer.valueOf(curTarget));
            if (ent == null) {
                mapCases.put(Integer.valueOf(curTarget), new CaseEntry(value, curTarget));
            } else {
                ent.addValue(value);
            }
        }
        cases = new ArrayList<CaseEntry>(mapCases.values());
    } finally {
        IOUtils.closeQuietly(dis);
    }
    processData(gotos);
}

From source file:org.jreversepro.decompile.simulate.SwitchTable.java

/**
 * For 'lookupswitch' opcode this fills the data structure - JSwitchTable.
 * //from  www.j a  v a 2  s .com
 * @param entries
 *          Bytecode entries that contain the case values and their target
 *          opcodes.
 * @param offset
 *          offset is the index of the current lookupswitch instruction into
 *          the method bytecode array.
 * @param gotos
 *          Map of goto statements.
 * 
 * @throws IOException
 *           Thrown in case of an i/o error when reading from the bytes.
 */
private void createLookupSwitch(byte[] entries, int offset, Map<Integer, Integer> gotos) throws IOException {
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new ByteArrayInputStream(entries));

        defaultByte = dis.readInt() + offset;
        int numVal = dis.readInt();

        Map<Integer, CaseEntry> mapCases = new HashMap<Integer, CaseEntry>();

        for (int i = 0; i < numVal; i++) {
            String value = TypeInferrer.getValue(String.valueOf(dis.readInt()), datatype);
            int curTarget = dis.readInt() + offset;

            CaseEntry ent = mapCases.get(Integer.valueOf(curTarget));
            if (ent == null) {
                mapCases.put(Integer.valueOf(curTarget), new CaseEntry(value, curTarget));
            } else {
                ent.addValue(value);
            }
        }
        cases = new ArrayList<CaseEntry>(mapCases.values());
    } finally {
        IOUtils.closeQuietly(dis);
    }
    processData(gotos);
}

From source file:org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager.java

/**
 * Load SecretManager state from fsimage.
 * // www  .j  a va  2s  .  co  m
 * @param in input stream to read fsimage
 * @throws IOException
 */
public synchronized void loadSecretManagerState(DataInputStream in) throws IOException {
    if (running) {
        // a safety check
        throw new IOException("Can't load state from image in a running SecretManager.");
    }
    currentId = in.readInt();
    loadAllKeys(in);
    delegationTokenSequenceNumber = in.readInt();
    loadCurrentTokens(in);
}

From source file:org.apache.apex.malhar.lib.function.FunctionOperator.java

@SuppressWarnings("unchecked")
private void readFunction() {
    try {/*from www.  j  a  v a 2  s .c  o m*/
        if (statelessF != null || statefulF.getValue() != null) {
            return;
        }
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(annonymousFunctionClass));
        byte[] classNameBytes = new byte[input.readInt()];
        input.read(classNameBytes);
        String className = new String(classNameBytes);
        byte[] classData = new byte[input.readInt()];
        input.read(classData);
        Map<String, byte[]> classBin = new HashMap<>();
        classBin.put(className, classData);
        ByteArrayClassLoader byteArrayClassLoader = new ByteArrayClassLoader(classBin,
                Thread.currentThread().getContextClassLoader());
        statelessF = ((Class<FUNCTION>) byteArrayClassLoader.findClass(className)).newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:J2MEWriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//www  .j a v  a 2  s .c  o m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            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();
            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);
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                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:epn.edu.ec.bibliotecadigital.cliente.Client.java

@Override
public void run() {
    try {/*from   w  w  w  .j  a  v  a 2s .  c  o m*/
        clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer);
        DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream());
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        String ipServer = dataInBalancer.readUTF();
        int portServer = dataInBalancer.readInt();
        clientSocketBalancer.close();
        Socket clientSocket = new Socket(ipServer, portServer);
        dataOut = new DataOutputStream(clientSocket.getOutputStream());
        dataOut.writeUTF(accion);
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        InputStream in;
        DataInputStream dataIn;
        switch (accion) {
        case "bajar":

            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF((String) params[1]);
            dataIn = new DataInputStream(clientSocket.getInputStream());
            boolean encontrado = dataIn.readBoolean();
            if (!encontrado) {
                System.out.println("Libro con el cdigo: " + params[1] + " no encontrado");
                break;
            }
            String fileName = dataIn.readUTF();
            System.out.println(
                    "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads");
            String home = System.getProperty("user.home");

            in = clientSocket.getInputStream();
            try {
                FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName));
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "subir":
            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF(((File) params[1]).getName());
            OutputStream out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                in = new FileInputStream((File) params[1]);

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "obtenerLista":
            ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Libros disponibles: \n");
            List<Libro> libros = (List<Libro>) inFromClient.readObject();
            System.out.println("\tCdigo\tNommbre\n");
            for (Libro lbr : libros) {
                System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre());
            }
            inFromClient.close();
            break;
        case "verificar":

            break;
        }
        dataOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:netinf.node.resolution.bocaching.impl.HTTPFileServer.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    String requestPath = httpExchange.getRequestURI().getPath();

    if (!requestPath.matches(REQUEST_PATH_PATTERN)) {
        LOG.debug("(HTTPFilesServer ) 403 Error");
        httpExchange.sendResponseHeaders(403, 0);
    } else {//from   w  w  w  . jav  a 2 s .  c o  m
        File file = new File(directory + requestPath);
        if (!file.exists()) {
            LOG.debug("(HTTPFilesServer ) 404 Error");
            httpExchange.sendResponseHeaders(404, 0);
        } else if (!file.canRead()) {
            LOG.debug("(HTTPFilesServer ) 403 Error");
            httpExchange.sendResponseHeaders(403, 0);
        } else {
            Headers h = httpExchange.getResponseHeaders();
            DataInputStream stream = new DataInputStream(new FileInputStream(file));

            // read content type and send
            if (!requestPath.contains("chunk")) {
                LOG.debug("(HTTPFilesServer ) Reading Content Type...");
                int contentTypeSize = stream.readInt();
                byte[] stringBuffer = new byte[contentTypeSize];
                stream.read(stringBuffer);
                h.set("Content-Type", new String(stringBuffer));
            }

            httpExchange.sendResponseHeaders(200, file.length());
            IOUtils.copy(stream, httpExchange.getResponseBody());

            // close streams
            IOUtils.closeQuietly(stream);
        }
    }
    httpExchange.close();
}

From source file:org.apache.hadoop.hive.ql.exec.persistence.RowContainer1.java

private Row[] deserialize(byte[] buf) throws HiveException {
    ByteArrayInputStream bais;/*www .j  a  va2s  .c  o m*/
    DataInputStream ois;

    try {
        bais = new ByteArrayInputStream(buf);
        ois = new DataInputStream(bais);
        int sz = ois.readInt();
        assert sz == blockSize : "deserialized size " + sz + " is not the same as block size " + blockSize;
        Row[] ret = (Row[]) new ArrayList[sz];

        for (int i = 0; i < sz; ++i) {
            if (serde != null && standardOI != null) {
                Writable val = serde.getSerializedClass().newInstance();
                val.readFields(ois);

                ret[i] = (Row) ObjectInspectorUtils.copyToStandardObject(serde.deserialize(val),
                        serde.getObjectInspector(), ObjectInspectorCopyOption.WRITABLE);
            } else {
                ret[i] = (Row) dummyRow;
            }
        }
        return ret;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HiveException(e);
    }
}