List of usage examples for java.io DataInputStream readByte
public final byte readByte() throws IOException
readByte
method of DataInput
. From source file:org.openmrs.module.odkconnector.serialization.serializer.ListSerializerTest.java
@Test public void serialize_shouldSerializePatientInformation() throws Exception { File file = File.createTempFile("PatientSerialization", "Example"); GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file))); log.info("Writing to: " + file.getAbsolutePath()); Cohort cohort = new Cohort(); cohort.addMember(6);//from www . j a va 2 s. com cohort.addMember(7); cohort.addMember(8); List<Patient> patients = new ArrayList<Patient>(); List<Obs> observations = new ArrayList<Obs>(); List<Form> forms = new ArrayList<Form>(); for (Integer patientId : cohort.getMemberIds()) { Patient patient = Context.getPatientService().getPatient(patientId); observations.addAll(Context.getObsService().getObservationsByPerson(patient)); patients.add(patient); } Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class); serializer.write(outputStream, patients); serializer.write(outputStream, observations); serializer.write(outputStream, forms); outputStream.close(); GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); DataInputStream dataInputStream = new DataInputStream(inputStream); // total number of patients Integer patientCounter = dataInputStream.readInt(); System.out.println("Patient Counter: " + patientCounter); for (int i = 0; i < patientCounter; i++) { System.out.println("=================Patient====================="); System.out.println("Patient Id: " + dataInputStream.readInt()); System.out.println("Family Name: " + dataInputStream.readUTF()); System.out.println("Middle Name: " + dataInputStream.readUTF()); System.out.println("Last Name: " + dataInputStream.readUTF()); System.out.println("Gender: " + dataInputStream.readUTF()); System.out.println("Birth Date: " + dataInputStream.readLong()); System.out.println("Identifier" + dataInputStream.readUTF()); } Integer obsCounter = dataInputStream.readInt(); for (int j = 0; j < obsCounter; j++) { System.out.println("==================Observation================="); System.out.println("Patient Id: " + dataInputStream.readInt()); System.out.println("Concept Name: " + dataInputStream.readUTF()); byte type = dataInputStream.readByte(); if (type == ObsSerializer.TYPE_STRING) System.out.println("Value: " + dataInputStream.readUTF()); else if (type == ObsSerializer.TYPE_INT) System.out.println("Value: " + dataInputStream.readInt()); else if (type == ObsSerializer.TYPE_DOUBLE) System.out.println("Value: " + dataInputStream.readDouble()); else if (type == ObsSerializer.TYPE_DATE) System.out.println("Value: " + dataInputStream.readLong()); System.out.println("Time: " + dataInputStream.readLong()); } Integer formCounter = dataInputStream.readInt(); for (int j = 0; j < formCounter; j++) { System.out.println("==================Form================="); System.out.println("Form Id: " + dataInputStream.readInt()); } System.out.println(); inputStream.close(); }
From source file:ubic.gemma.analysis.preprocess.batcheffects.AffyScanDateExtractor.java
@Override public Date extract(InputStream is) { DataInputStream str = new DataInputStream(is); BufferedReader reader = null; Date date = null;//from w w w.j a va 2s. co m try { int magic = readByteLittleEndian(str); if (magic == 64) { int version = readIntLittleEndian(str); if (version != 4) { // it's always supposed to be. throw new IllegalStateException("Affymetrix CEL format not recognized: " + version); } log.debug(readShortLittleEndian(str)); // numrows log.debug(readShortLittleEndian(str)); // numcols log.debug(readIntLittleEndian(str)); // numcells int headerLen = readShortLittleEndian(str); if (headerLen == 0) { // throw new IllegalStateException( "Zero header length read" ); headerLen = 800; } log.debug(headerLen); StringBuilder buf = new StringBuilder(); for (int i = 0; i < headerLen; i++) { buf.append(new String(new byte[] { str.readByte() }, "US-ASCII")); } String[] headerLines = StringUtils.split(buf.toString(), "\n"); for (String string : headerLines) { if (string.startsWith("DatHeader")) { date = parseStandardFormat(string); break; } } } else if (magic == 59) { // Command Console format int version = readUnsignedByteLittleEndian(str); if (version != 1) { throw new IllegalStateException("Affymetrix CEL format not recognized: " + version); } log.debug(readIntLittleEndian(str)); // number of data groups log.debug(readIntLittleEndian(str)); // file position of first group String datatypeIdentifier = readGCOSString(str); log.debug(datatypeIdentifier); String guid = readGCOSString(str); log.debug(guid); reader = new BufferedReader(new InputStreamReader(is, "UTF-16BE")); String line = null; int count = 0; while ((line = reader.readLine()) != null) { log.debug(line); if (line.contains("affymetrix-scan-date")) { date = parseISO8601(line); } if (date != null || ++count > 100) { reader.close(); break; } } log.debug(date); } else { /* * assume version 3 plain text. */ reader = new BufferedReader(new InputStreamReader(is)); String line = null; int count = 0; while ((line = reader.readLine()) != null) { // log.info( line ); if (line.startsWith("DatHeader")) { date = parseStandardFormat(line); } if (date != null || ++count > 100) { reader.close(); break; } } } if (date == null) { throw new IllegalStateException("Failed to find date"); } log.debug(date); return date; } catch (IOException e) { throw new RuntimeException(e); } finally { try { str.close(); if (reader != null) { reader.close(); } } catch (IOException e) { log.error("Failed to close open file handle: " + e.getMessage()); } } }
From source file:org.openmrs.module.odkconnector.serialization.serializer.openmrs.PatientSerializerTest.java
@Test public void serialize_shouldSerializePatientInformation() throws Exception { File file = File.createTempFile("PatientSerialization", "Example"); GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file))); log.info("Writing to: " + file.getAbsolutePath()); Cohort cohort = new Cohort(); cohort.addMember(6);//w ww .j a v a 2 s . c o m cohort.addMember(7); cohort.addMember(8); List<Patient> patients = new ArrayList<Patient>(); List<Obs> observations = new ArrayList<Obs>(); List<Form> forms = new ArrayList<Form>(); for (Integer patientId : cohort.getMemberIds()) { Patient patient = Context.getPatientService().getPatient(patientId); observations.addAll(Context.getObsService().getObservationsByPerson(patient)); patients.add(patient); } Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class); serializer.write(outputStream, patients); serializer.write(outputStream, observations); serializer.write(outputStream, forms); outputStream.close(); GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); DataInputStream dataInputStream = new DataInputStream(inputStream); // total number of patients Integer patientCounter = dataInputStream.readInt(); System.out.println("Patient Counter: " + patientCounter); for (int i = 0; i < patientCounter; i++) { System.out.println("=================Patient====================="); System.out.println("Patient Id: " + dataInputStream.readInt()); System.out.println("Family Name: " + dataInputStream.readUTF()); System.out.println("Middle Name: " + dataInputStream.readUTF()); System.out.println("Last Name: " + dataInputStream.readUTF()); System.out.println("Gender: " + dataInputStream.readUTF()); System.out.println("Birth Date: " + dataInputStream.readUTF()); System.out.println("Identifier" + dataInputStream.readUTF()); } Integer obsCounter = dataInputStream.readInt(); for (int j = 0; j < obsCounter; j++) { System.out.println("==================Observation================="); System.out.println("Patient Id: " + dataInputStream.readInt()); System.out.println("Concept Name: " + dataInputStream.readUTF()); byte type = dataInputStream.readByte(); if (type == ObsSerializer.TYPE_STRING) System.out.println("Value: " + dataInputStream.readUTF()); else if (type == ObsSerializer.TYPE_INT) System.out.println("Value: " + dataInputStream.readInt()); else if (type == ObsSerializer.TYPE_DOUBLE) System.out.println("Value: " + dataInputStream.readDouble()); else if (type == ObsSerializer.TYPE_DATE) System.out.println("Value: " + dataInputStream.readUTF()); System.out.println("Time: " + dataInputStream.readUTF()); } Integer formCounter = dataInputStream.readInt(); for (int j = 0; j < formCounter; j++) { System.out.println("==================Form================="); System.out.println("Form Id: " + dataInputStream.readInt()); } System.out.println(); inputStream.close(); }
From source file:VASSAL.launch.TilingHandler.java
protected void runSlicer(List<String> multi, final int tcount, int maxheap) throws CancellationException, IOException { final InetAddress lo = InetAddress.getByName(null); final ServerSocket ssock = new ServerSocket(0, 0, lo); final int port = ssock.getLocalPort(); final List<String> args = new ArrayList<String>(); args.addAll(Arrays.asList(new String[] { Info.javaBinPath, "-classpath", System.getProperty("java.class.path"), "-Xmx" + maxheap + "M", "-DVASSAL.id=" + pid, "-Duser.home=" + System.getProperty("user.home"), "-DVASSAL.port=" + port, "VASSAL.tools.image.tilecache.ZipFileImageTiler", aname, cdir.getAbsolutePath(), String.valueOf(tdim.width), String.valueOf(tdim.height) })); // get the progress dialog final ProgressDialog pd = ProgressDialog.createOnEDT(ModuleManagerWindow.getInstance(), "Processing Image Tiles", " "); // set up the process final InputStreamPump outP = new InputOutputStreamPump(null, System.out); final InputStreamPump errP = new InputOutputStreamPump(null, System.err); final ProcessWrapper proc = new ProcessLauncher().launch(null, outP, errP, args.toArray(new String[args.size()])); // write the image paths to child's stdin, one per line PrintWriter stdin = null;// w w w . j a va 2 s . com try { stdin = new PrintWriter(proc.stdin); for (String m : multi) { stdin.println(m); } } finally { IOUtils.closeQuietly(stdin); } Socket csock = null; DataInputStream in = null; try { csock = ssock.accept(); csock.shutdownOutput(); in = new DataInputStream(csock.getInputStream()); final Progressor progressor = new Progressor(0, tcount) { @Override protected void run(Pair<Integer, Integer> prog) { pd.setProgress((100 * prog.second) / max); } }; // setup the cancel button in the progress dialog EDT.execute(new Runnable() { public void run() { pd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pd.setVisible(false); proc.future.cancel(true); } }); } }); boolean done = false; byte type; while (!done) { type = in.readByte(); switch (type) { case STARTING_IMAGE: final String ipath = in.readUTF(); EDT.execute(new Runnable() { public void run() { pd.setLabel("Tiling " + ipath); if (!pd.isVisible()) pd.setVisible(true); } }); break; case TILE_WRITTEN: progressor.increment(); if (progressor.get() >= tcount) { pd.setVisible(false); } break; case TILING_FINISHED: done = true; break; default: throw new IllegalStateException("bad type: " + type); } } in.close(); csock.close(); ssock.close(); } catch (IOException e) { } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(csock); IOUtils.closeQuietly(ssock); } // wait for the tiling process to end try { final int retval = proc.future.get(); if (retval != 0) { throw new IOException("return value == " + retval); } } catch (ExecutionException e) { // should never happen throw new IllegalStateException(e); } catch (InterruptedException e) { // should never happen throw new IllegalStateException(e); } }
From source file:com.isecpartners.gizmo.HttpRequest.java
private StringBuffer readMessage(InputStream input) { StringBuffer contents = new StringBuffer(); String CONTENT_LENGTH = "CONTENT-LENGTH"; DataInputStream dinput = new DataInputStream(input); readerToStringBuffer(dinput, contents); int ii = 0;// www . j a v a 2s . com String uContents = contents.toString().toUpperCase(); if (uContents.contains(CONTENT_LENGTH)) { int contentLengthIndex = uContents.indexOf(CONTENT_LENGTH) + CONTENT_LENGTH.length() + 2; String value = uContents.substring(uContents.indexOf(CONTENT_LENGTH) + CONTENT_LENGTH.length() + 2, uContents.indexOf('\r', contentLengthIndex)); int contentLength = Integer.parseInt(value.trim()); StringBuffer body = new StringBuffer(); try { for (; body.length() < contentLength; ii++) { byte ch_n = dinput.readByte(); while (ch_n == -1) { Thread.sleep(20); ch_n = dinput.readByte(); } body.append((char) ch_n); } } catch (InterruptedException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } contents.append(body); } return contents; }
From source file:ClassFile.java
public boolean read(DataInputStream dis) throws IOException { int len;/* www .j a v a 2 s.c o m*/ char c; type = dis.readByte(); switch (type) { case CLASS: name = "Class"; index1 = dis.readShort(); index2 = -1; break; case FIELDREF: name = "Field Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case METHODREF: name = "Method Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case INTERFACE: name = "Interface Method Reference"; index1 = dis.readShort(); index2 = dis.readShort(); break; case NAMEANDTYPE: name = "Name and Type"; index1 = dis.readShort(); index2 = dis.readShort(); break; case STRING: name = "String"; index1 = dis.readShort(); index2 = -1; break; case INTEGER: name = "Integer"; intValue = dis.readInt(); break; case FLOAT: name = "Float"; floatValue = dis.readFloat(); break; case LONG: name = "Long"; longValue = dis.readLong(); break; case DOUBLE: name = "Double"; doubleValue = dis.readDouble(); break; case ASCIZ: case UNICODE: if (type == ASCIZ) name = "ASCIZ"; else name = "UNICODE"; StringBuffer xxBuf = new StringBuffer(); len = dis.readShort(); while (len > 0) { c = (char) (dis.readByte()); xxBuf.append(c); len--; } strValue = xxBuf.toString(); break; default: System.out.println("Warning bad type."); } return (true); }
From source file:org.structr.core.graph.SyncCommand.java
private static void importDatabase(final GraphDatabaseService graphDb, final SecurityContext securityContext, final ZipInputStream zis, boolean doValidation, final Long batchSize) throws FrameworkException, IOException { final App app = StructrApp.getInstance(); final DataInputStream dis = new DataInputStream(new BufferedInputStream(zis)); final RelationshipFactory relFactory = new RelationshipFactory(securityContext); final long internalBatchSize = batchSize != null ? batchSize : 200; final NodeFactory nodeFactory = new NodeFactory(securityContext); final String uuidPropertyName = GraphObject.id.dbName(); final Map<String, Node> uuidMap = new LinkedHashMap<>(); final Set<Long> deletedNodes = new HashSet<>(); final Set<Long> deletedRels = new HashSet<>(); final SuperUser superUser = new SuperUser(); double t0 = System.nanoTime(); PropertyContainer currentObject = null; String currentKey = null;/*from w ww .j a va 2 s .com*/ boolean finished = false; long totalNodeCount = 0; long totalRelCount = 0; do { try (final Tx tx = app.tx(doValidation)) { final List<Relationship> rels = new LinkedList<>(); final List<Node> nodes = new LinkedList<>(); long nodeCount = 0; long relCount = 0; do { try { // store current position dis.mark(4); // read one byte byte objectType = dis.readByte(); // skip newlines if (objectType == '\n') { continue; } if (objectType == 'N') { // break loop after 200 objects, commit and restart afterwards if (nodeCount + relCount >= internalBatchSize) { dis.reset(); break; } currentObject = graphDb.createNode(); nodeCount++; // store for later use nodes.add((Node) currentObject); } else if (objectType == 'R') { // break look after 200 objects, commit and restart afterwards if (nodeCount + relCount >= internalBatchSize) { dis.reset(); break; } String startId = (String) deserialize(dis); String endId = (String) deserialize(dis); String relTypeName = (String) deserialize(dis); Node endNode = uuidMap.get(endId); Node startNode = uuidMap.get(startId); if (startNode != null && endNode != null) { if (deletedNodes.contains(startNode.getId()) || deletedNodes.contains(endNode.getId())) { System.out.println("NOT creating relationship between deleted nodes.."); } else { RelationshipType relType = DynamicRelationshipType.withName(relTypeName); currentObject = startNode.createRelationshipTo(endNode, relType); // store for later use rels.add((Relationship) currentObject); relCount++; } } else { System.out.println("NOT creating relationship of type " + relTypeName + ", start: " + startId + ", end: " + endId); } } else { // reset if not at the beginning of a line dis.reset(); if (currentKey == null) { currentKey = (String) deserialize(dis); } else { if (currentObject != null) { Object obj = deserialize(dis); if (uuidPropertyName.equals(currentKey) && currentObject instanceof Node) { String uuid = (String) obj; uuidMap.put(uuid, (Node) currentObject); } if (currentKey.length() != 0) { // store object in DB currentObject.setProperty(currentKey, obj); // set type label if (currentObject instanceof Node && NodeInterface.type.dbName().equals(currentKey)) { ((Node) currentObject).addLabel(DynamicLabel.label((String) obj)); } } else { logger.log(Level.SEVERE, "Invalid property key for value {0}, ignoring", obj); } currentKey = null; } else { logger.log(Level.WARNING, "No current object to store property in."); } } } } catch (EOFException eofex) { finished = true; } } while (!finished); totalNodeCount += nodeCount; totalRelCount += relCount; for (Node node : nodes) { if (!deletedNodes.contains(node.getId())) { NodeInterface entity = nodeFactory.instantiate(node); // check for existing schema node and merge if (entity instanceof AbstractSchemaNode) { checkAndMerge(entity, deletedNodes, deletedRels); } if (!deletedNodes.contains(node.getId())) { TransactionCommand.nodeCreated(superUser, entity); entity.addToIndex(); } } } for (Relationship rel : rels) { if (!deletedRels.contains(rel.getId())) { RelationshipInterface entity = relFactory.instantiate(rel); TransactionCommand.relationshipCreated(superUser, entity); entity.addToIndex(); } } logger.log(Level.INFO, "Imported {0} nodes and {1} rels, committing transaction..", new Object[] { totalNodeCount, totalRelCount }); tx.success(); } } while (!finished); double t1 = System.nanoTime(); double time = ((t1 - t0) / 1000000000.0); DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); logger.log(Level.INFO, "Import done in {0} s", decimalFormat.format(time)); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
/** * //from w w w . j av a 2s . c o m * @param message * @param type set to 5 when sending a PKI request, 3 when sending a PKIConf * @return * @throws IOException * @throws NoSuchProviderException */ protected byte[] sendCmpTcp(byte[] message, int type) throws IOException, NoSuchProviderException { final String host = getProperty("tcpCmpProxyIP", this.CMP_HOST); final int port = getProperty("tcpCmpProxyPort", PORT_NUMBER); try { final Socket socket = new Socket(host, port); final byte[] msg = createTcpMessage(message); try { final BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); os.write(msg); os.flush(); DataInputStream dis = new DataInputStream(socket.getInputStream()); // Read the length, 32 bits final int len = dis.readInt(); log.info("Got a message claiming to be of length: " + len); // Read the version, 8 bits. Version should be 10 (protocol draft nr // 5) final int ver = dis.readByte(); log.info("Got a message with version: " + ver); assertEquals(ver, 10); // Read flags, 8 bits for version 10 final byte flags = dis.readByte(); log.info("Got a message with flags (1 means close): " + flags); // Check if the client wants us to close the connection (LSB is 1 in // that case according to spec) // Read message type, 8 bits final int msgType = dis.readByte(); log.info("Got a message of type: " + msgType); assertEquals(msgType, type); // Read message final ByteArrayOutputStream baos = new ByteArrayOutputStream(3072); while (dis.available() > 0) { baos.write(dis.read()); } log.info("Read " + baos.size() + " bytes"); final byte[] respBytes = baos.toByteArray(); assertNotNull(respBytes); assertTrue(respBytes.length > 0); return respBytes; } finally { socket.close(); } } catch (ConnectException e) { assertTrue("This test requires a CMP TCP listener to be configured on " + host + ":" + port + ". Edit conf/cmptcp.properties and redeploy.", false); } catch (EOFException e) { assertTrue("Response was malformed.", false); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } return null; }
From source file:net.timewalker.ffmq4.storage.data.impl.AbstractBlockBasedDataStore.java
private final void loadAllocationTable() throws DataStoreException { log.debug(/*from ww w . j av a2 s . c om*/ "[" + descriptor.getName() + "] Loading allocation table " + allocationTableFile.getAbsolutePath()); DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new FileInputStream(allocationTableFile), 16384)); this.blockCount = in.readInt(); this.blockSize = in.readInt(); this.firstBlock = in.readInt(); this.flags = new byte[blockCount]; this.allocatedSize = new int[blockCount]; this.previousBlock = new int[blockCount]; this.nextBlock = new int[blockCount]; this.blocksInUse = 0; int msgCount = 0; for (int n = 0; n < blockCount; n++) { flags[n] = in.readByte(); allocatedSize[n] = in.readInt(); previousBlock[n] = in.readInt(); nextBlock[n] = in.readInt(); if (allocatedSize[n] != -1) { blocksInUse++; if ((flags[n] & FLAG_START_BLOCK) > 0) msgCount++; } } this.locks = new FastBitSet(blockCount); this.size = msgCount; log.debug("[" + descriptor.getName() + "] " + msgCount + " entries found"); } catch (EOFException e) { throw new DataStoreException("Allocation table is truncated : " + allocationTableFile.getAbsolutePath(), e); } catch (IOException e) { throw new DataStoreException( "Cannot initialize allocation table : " + allocationTableFile.getAbsolutePath(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("[" + descriptor.getName() + "] Could not close file input stream", e); } } } }
From source file:org.deeplearning4j.models.embeddings.loader.WordVectorSerializer.java
/** * Read a string from a data input stream Credit to: * https://github.com/NLPchina/Word2VEC_java/blob/master/src/com/ansj/vec/Word2VEC.java * * @param dis/* ww w . ja v a 2s. com*/ * @return * @throws IOException */ public static String readString(DataInputStream dis) throws IOException { byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes, "UTF-8")); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1, "UTF-8")); return sb.toString(); }