Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:ClassFile.java

/**
 * Read a class from InputStream <i>in</i>.
 *//*from   w  w  w.jav  a 2 s  .com*/
public boolean read(InputStream in) throws IOException {
    DataInputStream di = new DataInputStream(in);
    int count;

    magic = di.readInt();
    if (magic != (int) 0xCAFEBABE) {
        return (false);
    }

    majorVersion = di.readShort();
    minorVersion = di.readShort();
    count = di.readShort();
    constantPool = new ConstantPoolInfo[count];
    if (debug)
        System.out.println("read(): Read header...");
    constantPool[0] = new ConstantPoolInfo();
    for (int i = 1; i < constantPool.length; i++) {
        constantPool[i] = new ConstantPoolInfo();
        if (!constantPool[i].read(di)) {
            return (false);
        }
        // These two types take up "two" spots in the table
        if ((constantPool[i].type == ConstantPoolInfo.LONG)
                || (constantPool[i].type == ConstantPoolInfo.DOUBLE))
            i++;
    }

    /*
     * Update pointers in the constant table. This turns the
     * table into a real datastructure.
     *
     * TODO: Have it verify that the right arguments are present
     */
    for (int i = 1; i < constantPool.length; i++) {
        if (constantPool[i] == null)
            continue;
        if (constantPool[i].index1 > 0)
            constantPool[i].arg1 = constantPool[constantPool[i].index1];
        if (constantPool[i].index2 > 0)
            constantPool[i].arg2 = constantPool[constantPool[i].index2];
    }

    if (dumpConstants) {
        for (int i = 1; i < constantPool.length; i++) {
            System.out.println("C" + i + " - " + constantPool[i]);
        }
    }
    accessFlags = di.readShort();

    thisClass = constantPool[di.readShort()];
    superClass = constantPool[di.readShort()];
    if (debug)
        System.out.println("read(): Read class info...");

    /*
     * Identify all of the interfaces implemented by this class
     */
    count = di.readShort();
    if (count != 0) {
        if (debug)
            System.out.println("Class implements " + count + " interfaces.");
        interfaces = new ConstantPoolInfo[count];
        for (int i = 0; i < count; i++) {
            int iindex = di.readShort();
            if ((iindex < 1) || (iindex > constantPool.length - 1))
                return (false);
            interfaces[i] = constantPool[iindex];
            if (debug)
                System.out.println("I" + i + ": " + interfaces[i]);
        }
    }
    if (debug)
        System.out.println("read(): Read interface info...");

    /*
     * Identify all fields in this class.
     */
    count = di.readShort();
    if (debug)
        System.out.println("This class has " + count + " fields.");
    if (count != 0) {
        fields = new FieldInfo[count];
        for (int i = 0; i < count; i++) {
            fields[i] = new FieldInfo();
            if (!fields[i].read(di, constantPool)) {
                return (false);
            }
            if (debug)
                System.out.println("F" + i + ": " + fields[i].toString(constantPool));
        }
    }
    if (debug)
        System.out.println("read(): Read field info...");

    /*
       * Identify all the methods in this class.
     */
    count = di.readShort();
    if (count != 0) {
        methods = new MethodInfo[count];
        for (int i = 0; i < count; i++) {
            methods[i] = new MethodInfo();
            if (!methods[i].read(di, constantPool)) {
                return (false);
            }
            if (debug)
                System.out.println("M" + i + ": " + methods[i].toString());
        }
    }
    if (debug)
        System.out.println("read(): Read method info...");

    /*
     * Identify all of the attributes in this class
     */
    count = di.readShort();
    if (count != 0) {
        attributes = new AttributeInfo[count];
        for (int i = 0; i < count; i++) {
            attributes[i] = new AttributeInfo();
            if (!attributes[i].read(di, constantPool)) {
                return (false);
            }
        }
    }
    if (debug) {
        System.out.println("read(): Read attribute info...");
        System.out.println("done.");
    }
    isValidClass = true;
    return (true);
}

From source file:com.jivesoftware.os.amza.service.replication.http.HttpAvailableRowsTaker.java

@Override
public void availableRowsStream(RingMember localRingMember, TimestampedRingHost localTimestampedRingHost,
        RingMember remoteRingMember, RingHost remoteRingHost, boolean system, long takeSessionId,
        long takeSharedKey, long timeoutMillis, AvailableStream availableStream, PingStream pingStream)
        throws Exception {

    String endpoint = "/amza/rows/available" + "/" + localRingMember.getMember() + "/"
            + localTimestampedRingHost.ringHost.toCanonicalString() + "/" + system + "/"
            + localTimestampedRingHost.timestampId + "/" + takeSessionId + "/" + timeoutMillis;
    String sharedKeyJson = mapper.writeValueAsString(takeSharedKey); // lame
    HttpStreamResponse httpStreamResponse = ringClient.call("",
            new ConnectionDescriptorSelectiveStrategy(
                    new HostPort[] { new HostPort(remoteRingHost.getHost(), remoteRingHost.getPort()) }),
            "availableRowsStream", httpClient -> {
                HttpStreamResponse response = httpClient.streamingPost(endpoint, sharedKeyJson, null);
                if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                    throw new NonSuccessStatusCodeException(response.getStatusCode(),
                            response.getStatusReasonPhrase());
                }//www  .  j  ava 2  s. c  om
                return new ClientResponse<>(response, true);
            });
    try {
        BufferedInputStream bis = new BufferedInputStream(httpStreamResponse.getInputStream(), 8192); // TODO config??
        DataInputStream dis = new DataInputStream(new SnappyInputStream(bis));
        streamingTakesConsumer.consume(dis, availableStream, pingStream);
    } finally {
        httpStreamResponse.close();
    }
}

From source file:de.hybris.platform.jobs.RemovedItemPKProcessorTest.java

@Test
public void testAllIterated() {
    final PK one = PK.createFixedUUIDPK(102, 1);
    final PK two = PK.createFixedUUIDPK(102, 2);
    final PK three = PK.createFixedUUIDPK(102, 3);

    final MediaModel mediaPk = new MediaModel();
    final DataInputStream dis = new DataInputStream(buildUpStream(one, two, three));

    Mockito.when(model.getItemPKs()).thenReturn(mediaPk);
    Mockito.when(mediaService.getStreamFromMedia(mediaPk)).thenReturn(dis);

    iterator.init(model);/*  ww w.  ja  v  a  2 s .  co m*/

    Assert.assertTrue("Not all iterations should be skipped ", iterator.hasNext());
    Assert.assertEquals("Should  return first element ", one, iterator.next());
    Assert.assertTrue("Not all iterations should be skipped ", iterator.hasNext());
    Assert.assertEquals("Should  return second element ", two, iterator.next());
    Assert.assertTrue("Not all iterations should be skipped ", iterator.hasNext());
    Assert.assertEquals("Should  return third element ", three, iterator.next());
    Assert.assertFalse("Now all iterations should be skipped ", iterator.hasNext());
}

From source file:hudson.console.ConsoleAnnotationOutputStream.java

/**
 * Called after we read the whole line of plain text, which is stored in {@link #buf}.
 * This method performs annotations and send the result to {@link #out}.
 *//*from   www .j  a v a2s  . c o m*/
protected void eol(byte[] in, int sz) throws IOException {
    line.reset();
    final StringBuffer strBuf = line.getStringBuffer();

    int next = ConsoleNote.findPreamble(in, 0, sz);

    List<ConsoleAnnotator<T>> annotators = null;

    {// perform byte[]->char[] while figuring out the char positions of the BLOBs
        int written = 0;
        while (next >= 0) {
            if (next > written) {
                lineOut.write(in, written, next - written);
                lineOut.flush();
                written = next;
            } else {
                assert next == written;
            }

            // character position of this annotation in this line
            final int charPos = strBuf.length();

            int rest = sz - next;
            ByteArrayInputStream b = new ByteArrayInputStream(in, next, rest);

            try {
                final ConsoleNote a = ConsoleNote.readFrom(new DataInputStream(b));
                if (a != null) {
                    if (annotators == null)
                        annotators = new ArrayList<ConsoleAnnotator<T>>();
                    annotators.add(new ConsoleAnnotator<T>() {
                        public ConsoleAnnotator annotate(T context, MarkupText text) {
                            return a.annotate(context, text, charPos);
                        }
                    });
                }
            } catch (IOException e) {
                // if we failed to resurrect an annotation, ignore it.
                LOGGER.log(Level.FINE, "Failed to resurrect annotation", e);
            } catch (ClassNotFoundException e) {
                LOGGER.log(Level.FINE, "Failed to resurrect annotation", e);
            }

            int bytesUsed = rest - b.available(); // bytes consumed by annotations
            written += bytesUsed;

            next = ConsoleNote.findPreamble(in, written, sz - written);
        }
        // finish the remaining bytes->chars conversion
        lineOut.write(in, written, sz - written);

        if (annotators != null) {
            // aggregate newly retrieved ConsoleAnnotators into the current one.
            if (ann != null)
                annotators.add(ann);
            ann = ConsoleAnnotator.combine(annotators);
        }
    }

    lineOut.flush();
    MarkupText mt = new MarkupText(strBuf.toString());
    if (ann != null)
        ann = ann.annotate(context, mt);
    out.write(mt.toString(true)); // this perform escapes
}

From source file:jeeves.utils.EMail.java

/** Sends the message to the mail server
  *//*from  www  .  ja  v  a 2 s .  c  om*/

public boolean send() throws IOException {
    Socket socket = new Socket(sMailServer, iPort);
    try {
        in = new BufferedReader(new InputStreamReader(new DataInputStream(socket.getInputStream()),
                Charset.forName(Jeeves.ENCODING)));
        out = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()), "ISO-8859-1");

        if (lookMailServer())
            if (sendData("2", "HELO " + InetAddress.getLocalHost().getHostName() + "\r\n"))
                if (sendData("2", "MAIL FROM: <" + sFrom + ">\r\n"))
                    if (sendData("2", "RCPT TO: <" + sTo + ">\r\n"))
                        if (sendData("354", "DATA\r\n"))
                            if (sendData("2", buildContent()))
                                if (sendData("2", "QUIT\r\n"))
                                    return true;

        sendData("2", "QUIT\r\n");
    } finally {
        IOUtils.closeQuietly(socket);
    }
    return false;
}

From source file:es.logongas.util.seguridad.CodigoVerificacionSeguro.java

public int getKey() {
    try {//from  w w w. jav  a2s .  com
        Base32 base32 = new Base32();
        byte datos[] = base32.decode(valor);
        DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(datos));
        int key = dataInputStream.readInt();

        return key;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.sforce.cd.apexUnit.client.fileReader.ApexManifestFileReader.java

private String[] readInputStreamAndConstructClassArray(InputStream inStr) throws IOException {
    String[] testClassesAsArray = null;
    ArrayList<String> testClassList = new ArrayList<String>();

    LOG.debug("Input stream: " + inStr);
    DataInputStream dataIS = new DataInputStream(inStr);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataIS));
    String strLine = null;/* w  ww .j a va 2 s .  c o  m*/
    String newline = System.getProperty("line.separator");

    while ((strLine = bufferedReader.readLine()) != null) {
        if (!newline.equals(strLine) && !strLine.equals("") && strLine.length() > 0) {
            LOG.debug("The line says .... -  " + strLine);
            insertIntoTestClassesArray(strLine, testClassList);
        }
    }
    dataIS.close();

    Object[] apexClassesObjArr = testClassList.toArray();
    testClassesAsArray = (Arrays.copyOf(apexClassesObjArr, apexClassesObjArr.length, String[].class));
    if (LOG.isDebugEnabled()) {
        ApexClassFetcherUtils.logTheFetchedApexClasses(testClassesAsArray);
    }
    return testClassesAsArray;
}

From source file:CommPortThreaded.java

/**
 * This version of converse() just starts a Thread in each direction.
 *//*from  w ww. jav  a2  s. c  om*/
protected void converse() throws IOException {

    String resp; // the modem response.

    new DataThread(is, System.out).start();
    new DataThread(new DataInputStream(System.in), os).start();

}

From source file:RMSGameScores.java

public int compare(byte[] rec1, byte[] rec2) {

    // Construct DataInputStreams for extracting the scores from
    // the records.
    ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
    DataInputStream inputStream1 = new DataInputStream(bais1);
    ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
    DataInputStream inputStream2 = new DataInputStream(bais2);
    int score1 = 0;
    int score2 = 0;
    try {//from  w  w  w.  j  a v  a2  s  .  co  m
        // Extract the scores.
        score1 = inputStream1.readInt();
        score2 = inputStream2.readInt();
    } catch (EOFException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    } catch (IOException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    }

    // Sort by score
    if (score1 > score2) {
        return RecordComparator.FOLLOWS;
    } else if (score1 < score2) {
        return RecordComparator.PRECEDES;
    } else {
        return RecordComparator.EQUIVALENT;
    }
}

From source file:edu.cornell.med.icb.goby.compression.HybridChunkCodec2.java

@Override
public Message decode(final byte[] bytes) throws IOException {
    final DataInputStream completeChunkData = new DataInputStream(new ByteArrayInputStream(bytes));
    final int compressedSize = completeChunkData.readInt();
    final int storedChecksum = completeChunkData.readInt();

    final byte[] compressedBytes = new byte[compressedSize];
    final int read = completeChunkData.read(compressedBytes, 0, compressedSize);
    assert read == compressedSize : "read size must match recorded size.";
    crc32.reset();//www. ja va 2  s  .c o m

    crc32.update(compressedBytes);
    final int computedChecksum = (int) crc32.getValue();
    if (computedChecksum != storedChecksum) {
        throw new InvalidChecksumException();
    }
    final int bytesLeft = bytes.length - 4 - compressedSize - 4;
    final byte[] leftOver = new byte[bytesLeft];
    // 8 is the number of bytes to encode the length of the compressed chunk, plus
    // the number of bytes to encode the checksum.
    System.arraycopy(bytes, 8 + compressedSize, leftOver, 0, bytesLeft);
    final Message reducedProtoBuff = bzip2Codec.decode(leftOver);
    if (reducedProtoBuff == null) {
        return null;
    }
    return handler.decompressCollection(reducedProtoBuff, compressedBytes);
}