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.jackrabbit.core.persistence.mem.InMemBundlePersistenceManager.java

/**
 * Reads the content of the hash maps from the file system
 *
 * @throws Exception if an error occurs//from  w  w w.j av a  2s. c  o  m
 */
public synchronized void loadContents() throws Exception {
    // read item states
    FileSystemResource fsRes = new FileSystemResource(wspFS, BUNDLE_FILE_PATH);
    if (!fsRes.exists()) {
        return;
    }
    BufferedInputStream bis = new BufferedInputStream(fsRes.getInputStream());
    DataInputStream in = new DataInputStream(bis);

    try {
        int n = in.readInt(); // number of entries
        while (n-- > 0) {
            String s = in.readUTF(); // id
            NodeId id = NodeId.valueOf(s);
            int length = in.readInt(); // data length
            byte[] data = new byte[length];
            in.readFully(data); // data
            // store in map
            bundleStore.put(id, data);
        }
    } finally {
        in.close();
    }

    // read references
    fsRes = new FileSystemResource(wspFS, REFS_FILE_PATH);
    bis = new BufferedInputStream(fsRes.getInputStream());
    in = new DataInputStream(bis);

    try {
        int n = in.readInt(); // number of entries
        while (n-- > 0) {
            String s = in.readUTF(); // target id
            NodeId id = NodeId.valueOf(s);
            int length = in.readInt(); // data length
            byte[] data = new byte[length];
            in.readFully(data); // data
            // store in map
            refsStore.put(id, data);
        }
    } finally {
        in.close();
    }

    if (!useFileBlobStore) {
        // read blobs
        fsRes = new FileSystemResource(wspFS, BLOBS_FILE_PATH);
        bis = new BufferedInputStream(fsRes.getInputStream());
        in = new DataInputStream(bis);

        try {
            int n = in.readInt(); // number of entries
            while (n-- > 0) {
                String id = in.readUTF(); // id
                int length = in.readInt(); // data length
                byte[] data = new byte[length];
                in.readFully(data); // data
                // store in map
                blobs.put(id, data);
            }
        } finally {
            in.close();
        }
    }
}

From source file:org.prorefactor.refactor.PUB.java

private void readStrings(DataInputStream in) throws IOException {
    int size = in.readInt();
    stringArray = new String[size];
    for (int i = 0; i < size; i++) {
        stringArray[i] = in.readUTF();/*from ww w. j a v  a 2s.co  m*/
    }
}

From source file:SortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*  w ww. j  a  va2s .  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[] = { "Mary", "Bob", "Adam" };
            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 = new String[3];
            int z = 0;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            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");
                comparator.compareClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:org.commoncrawl.service.listcrawler.HDFSFileIndex.java

private void loadIndexFromLocalFile() throws IOException {
    LOG.info("Loading Index from Local File:" + _localIndexFilePath);
    // now open an input stream to the local file ...
    FileInputStream fileInputStream = new FileInputStream(_localIndexFilePath);
    DataInputStream dataStream = new DataInputStream(fileInputStream);

    try {//from   w  w  w. jav a2s  .c o m
        // deserialize bloom filter 
        _bloomFilter = BloomFilter.serializer().deserialize(dataStream);
        _indexHintCount = dataStream.readInt();

        int indexHintDataSize = _indexHintCount * INDEX_HINT_SIZE;
        // and deserialize index hints 
        _indexHints = ByteBuffer.allocate(indexHintDataSize);

        dataStream.readFully(_indexHints.array());

        // load index data buffer size 
        _indexDataSize = dataStream.readInt();
        // and capture offset information 
        _indexDataOffset = (int) fileInputStream.getChannel().position();
    } finally {
        if (fileInputStream != null) {
            fileInputStream.close();
        }
    }
    LOG.info("Successfully loaded Index");
}

From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java

@Override
public List<DateTime> decompressDateTimes(final byte[] compressedTimes) {
    final List<DateTime> dateTimeList = new ArrayList<DateTime>(compressedTimes.length * 4);
    final ByteArrayInputStream byteStream = new ByteArrayInputStream(compressedTimes);
    final DataInputStream byteDataStream = new DataInputStream(byteStream);
    int opcode = 0;
    int lastTime = 0;
    try {//  w w w  . ja  v a  2s.c  om
        while (true) {
            opcode = byteDataStream.read();
            if (opcode == -1) {
                break;
            }

            if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) {
                lastTime = byteDataStream.readInt();
                dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) {
                final int repeatCount = byteDataStream.readUnsignedByte();
                final int delta = byteDataStream.readUnsignedByte();
                for (int i = 0; i < repeatCount; i++) {
                    lastTime = lastTime + delta;
                    dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
                }
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) {
                final int repeatCount = byteDataStream.readUnsignedShort();
                final int delta = byteDataStream.readUnsignedByte();
                for (int i = 0; i < repeatCount; i++) {
                    lastTime = lastTime + delta;
                    dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
                }
            } else {
                // The opcode is itself a singleton delta
                lastTime = lastTime + opcode;
                dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
            }
        }
    } catch (IOException e) {
        log.error(e, "In decompressTimes(), exception decompressing");
    }
    return dateTimeList;
}

From source file:com.project.qrypto.keymanagement.KeyManager.java

/**
 * Load a Keystore. Uses either internal or external memory depending on settings.
 * @param context the context to use.//from   ww w.  ja v a2s  .  c o m
 * 
 * @throws IOException if the stream is bad
 * @throws InvalidCipherTextException if the key or data is bad
 */
public void load(Context context) throws IOException, InvalidCipherTextException {

    DataInputStream stream = null;
    if (passwordProtected) {
        byte[] data = AES.handle(false, IOUtils.toByteArray(getAssociatedInFileStream(context)), keyStoreKey);
        stream = new DataInputStream(new ByteArrayInputStream(data));
    } else {
        stream = new DataInputStream(getAssociatedInFileStream(context));
    }

    String type = stream.readUTF();
    if (type.equals("RCYTHR1")) {
        //Valid
        int count = stream.readInt();
        for (int i = 0; i < count; ++i) {
            String name = stream.readUTF();
            lookup.put(name, Key.readData(stream));
        }
    } else {
        throw new IOException("Bad Format");
    }

    storeLoaded = true;
}

From source file:org.prorefactor.refactor.PUB.java

private JPNode readTree(DataInputStream in) throws IOException {
    int nodeClass = in.readInt();
    if (nodeClass == -1)
        return null;
    JPNode node = com.joanju.proparse.NodeFactory.createByIndex(nodeClass);
    node.setFilenameList(fileIndexes);// w ww . ja va2s .com
    node.setNodeNum(++nodeCount);
    node.setType(in.readInt());
    node.setFileIndex(in.readShort());
    node.setLine(in.readInt());
    node.setColumn(in.readShort());
    node.setSourceNum(in.readInt());
    int key;
    int value;
    for (key = in.readInt(), value = in.readInt(); key != -1; key = in.readInt(), value = in.readInt()) {
        node.attrSet(key, value);
    }
    node.setFirstChild(readTree(in));
    node.setParentInChildren();
    node.setNextSiblingWithLinks(readTree(in));
    return node;
}

From source file:hd3gtv.embddb.network.DataBlock.java

/**
 * Import mode//from w  ww .  jav  a 2s  . co  m
 */
DataBlock(Protocol protocol, byte[] request_raw_datas) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("Get raw datas" + Hexview.LINESEPARATOR + Hexview.tracelog(request_raw_datas));
    }

    ByteArrayInputStream inputstream_client_request = new ByteArrayInputStream(request_raw_datas);

    DataInputStream dis = new DataInputStream(inputstream_client_request);

    byte[] app_socket_header_tag = new byte[Protocol.APP_SOCKET_HEADER_TAG.length];
    dis.readFully(app_socket_header_tag, 0, Protocol.APP_SOCKET_HEADER_TAG.length);

    if (Arrays.equals(Protocol.APP_SOCKET_HEADER_TAG, app_socket_header_tag) == false) {
        throw new IOException("Protocol error with app_socket_header_tag");
    }

    int version = dis.readInt();
    if (version != Protocol.VERSION) {
        throw new IOException(
                "Protocol error with version, this = " + Protocol.VERSION + " and dest = " + version);
    }

    byte tag = dis.readByte();
    if (tag != 0) {
        throw new IOException("Protocol error, can't found request_name raw datas");
    }

    int size = dis.readInt();
    if (size < 1) {
        throw new IOException(
                "Protocol error, can't found request_name raw datas size is too short (" + size + ")");
    }

    byte[] request_name_raw = new byte[size];
    dis.read(request_name_raw);
    request_name = new String(request_name_raw, Protocol.UTF8);

    tag = dis.readByte();
    if (tag != 1) {
        throw new IOException("Protocol error, can't found zip raw datas");
    }

    entries = new ArrayList<>(1);

    ZipInputStream request_zip = new ZipInputStream(dis);

    ZipEntry entry;
    while ((entry = request_zip.getNextEntry()) != null) {
        entries.add(new RequestEntry(entry, request_zip));
    }
    request_zip.close();
}

From source file:org.openmrs.module.odkconnector.serialization.processor.HttpProcessor.java

/**
 * Process any stream connection to this module
 *
 * @param inputStream  the input stream//from   www .  j  av a 2s. c  om
 * @param outputStream the output stream
 * @throws Exception when the stream processing failed
 */
@Override
public void process(final InputStream inputStream, final OutputStream outputStream) throws Exception {

    GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(inputStream));

    DataInputStream dataInputStream = new DataInputStream(gzipInputStream);
    String username = dataInputStream.readUTF();
    String password = dataInputStream.readUTF();
    Boolean savedSearch = dataInputStream.readBoolean();
    Integer cohortId = 0;
    Integer programId = 0;
    if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) {
        cohortId = dataInputStream.readInt();
        programId = dataInputStream.readInt();
    }
    dataInputStream.close();

    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new BufferedOutputStream(outputStream));
    DataOutputStream dataOutputStream = new DataOutputStream(gzipOutputStream);
    try {
        Context.openSession();
        Context.authenticate(username, password);

        dataOutputStream.writeInt(HttpURLConnection.HTTP_OK);
        dataOutputStream.flush();

        if (log.isDebugEnabled()) {
            log.debug("Saved Search Value: " + savedSearch);
            log.debug("Cohort ID: " + cohortId);
            log.debug("Program ID: " + programId);
        }

        Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class);
        if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) {
            ConnectorService connectorService = Context.getService(ConnectorService.class);

            Cohort cohort = new Cohort();
            if (savedSearch) {
                CohortSearchHistory history = new CohortSearchHistory();
                PatientSearchReportObject patientSearchReportObject = (PatientSearchReportObject) Context
                        .getReportObjectService().getReportObject(cohortId);
                if (patientSearchReportObject != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Object Class: " + patientSearchReportObject.getClass());
                        log.debug("Object Name: " + patientSearchReportObject.getName());
                        log.debug("Object Subtype: " + patientSearchReportObject.getSubType());
                        log.debug("Object Type: " + patientSearchReportObject.getType());
                    }
                    history.addSearchItem(PatientSearch.createSavedSearchReference(cohortId));
                    cohort = history.getPatientSet(0, null);
                }
            } else {
                cohort = Context.getCohortService().getCohort(cohortId);
            }

            if (log.isDebugEnabled())
                log.debug("Cohort data: " + cohort.getMemberIds());

            log.info("Streaming patients information!");
            serializer.write(dataOutputStream, connectorService.getCohortPatients(cohort));

            // check the concept list
            Collection<Concept> concepts = null;
            ConceptConfiguration conceptConfiguration = connectorService.getConceptConfiguration(programId);
            if (conceptConfiguration != null) {

                if (log.isDebugEnabled())
                    log.debug("Printing concept configuration information: " + conceptConfiguration);

                concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts());
            }
            log.info("Streaming observations information!");
            serializer.write(dataOutputStream, connectorService.getCohortObservations(cohort, concepts));

            // evaluate and get the applicable form for the patients
            CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class);
            ReportingConnectorService reportingService = Context.getService(ReportingConnectorService.class);
            List<ExtendedDefinition> definitions = reportingService.getAllExtendedDefinition();

            EvaluationContext context = new EvaluationContext();
            context.setBaseCohort(cohort);

            Collection intersectedMemberIds = Collections.emptyList();
            List<SerializedForm> serializedForms = new ArrayList<SerializedForm>();
            for (ExtendedDefinition definition : definitions) {
                if (definition.containsProperty(ExtendedDefinition.DEFINITION_PROPERTY_FORM)) {

                    if (log.isDebugEnabled())
                        log.debug("Evaluating: " + definition.getCohortDefinition().getName());

                    EvaluatedCohort evaluatedCohort = cohortDefinitionService
                            .evaluate(definition.getCohortDefinition(), context);
                    // the cohort could be null, so we don't want to get exception during the intersection process
                    if (cohort != null)
                        intersectedMemberIds = CollectionUtils.intersection(cohort.getMemberIds(),
                                evaluatedCohort.getMemberIds());

                    if (log.isDebugEnabled())
                        log.debug("Cohort data after intersection: " + intersectedMemberIds);

                    for (DefinitionProperty definitionProperty : definition.getProperties()) {
                        // skip retired definition property
                        if (definitionProperty.isRetired())
                            continue;

                        Integer formId = NumberUtils.toInt(definitionProperty.getPropertyValue());
                        for (Object patientId : intersectedMemberIds)
                            serializedForms.add(
                                    new SerializedForm(NumberUtils.toInt(String.valueOf(patientId)), formId));
                    }
                }
            }

            if (log.isDebugEnabled())
                log.debug("Serialized form informations:" + serializedForms);

            log.info("Streaming forms information!");
            serializer.write(dataOutputStream, serializedForms);

        } else {
            if (savedSearch) {
                List<SerializedCohort> serializedCohorts = new ArrayList<SerializedCohort>();
                List<AbstractReportObject> objects = Context.getReportObjectService()
                        .getReportObjectsByType(OpenmrsConstants.REPORT_OBJECT_TYPE_PATIENTSEARCH);
                for (AbstractReportObject object : objects) {
                    SerializedCohort serializedCohort = new SerializedCohort();
                    serializedCohort.setId(object.getReportObjectId());
                    serializedCohort.setName(object.getName());
                    serializedCohorts.add(serializedCohort);
                }
                serializer.write(dataOutputStream, serializedCohorts);

            } else {
                serializer.write(dataOutputStream, Context.getCohortService().getAllCohorts());
            }
        }

        dataOutputStream.close();
    } catch (Exception e) {
        log.error("Processing stream failed!", e);
        dataOutputStream.writeInt(HttpURLConnection.HTTP_UNAUTHORIZED);
        dataOutputStream.close();
    } finally {
        Context.closeSession();
    }
}

From source file:org.prorefactor.refactor.PUB.java

private SymbolRef readSymbol(DataInputStream in) throws IOException {
    SymbolRef symbolRef = new SymbolRef(in.readInt(), in.readUTF());
    if (symbolRef.progressType == -1)
        return null;
    symbolRef.dataType = in.readInt();/*ww w  . jav  a2  s. co m*/
    if (symbolRef.dataType == TokenTypes.CLASS)
        symbolRef.classSymbolRefName = in.readUTF();
    return symbolRef;
}