Example usage for org.apache.commons.io.input CountingInputStream getCount

List of usage examples for org.apache.commons.io.input CountingInputStream getCount

Introduction

In this page you can find the example usage for org.apache.commons.io.input CountingInputStream getCount.

Prototype

public synchronized int getCount() 

Source Link

Document

The number of bytes that have passed through this stream.

Usage

From source file:com.playonlinux.win32.pe.PEReader.java

private static RsrcSection readResourceSection(CountingInputStream executableInputStream,
        SectionHeader[] sectionHeaders) throws IOException {
    SectionHeader rsrcSectionHeader = null;
    for (SectionHeader sectionHeader : sectionHeaders) {
        if (".rsrc\u0000\u0000\u0000".equals(new String(sectionHeader.name))) {
            rsrcSectionHeader = sectionHeader;
        }//w  w w  .j a va 2s  .  co m
    }

    if (rsrcSectionHeader == null) {
        return null;
    }

    long numberToSkip = rsrcSectionHeader.pointerToRawData.getUnsignedValue()
            - executableInputStream.getCount();
    executableInputStream.skip(numberToSkip);
    byte[] rsrcSection = new byte[(int) rsrcSectionHeader.sizeOfRawData.getUnsignedValue()];
    executableInputStream.read(rsrcSection);

    return new RsrcSection(rsrcSection);
}

From source file:com.google.code.jahath.common.io.SwappableInputStreamTest.java

@Test
public void test() throws Throwable {
    final SwappableInputStream swappableInputStream = new SwappableInputStream("test");
    final CRC actualCRC = new CRC();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                actualCRC.update(swappableInputStream);
            } catch (Throwable ex) {
                thrown.set(ex);/*from   ww w.j a va2  s.c om*/
            }
        }
    });
    thread.start();
    Random random = new Random();
    CRC expectedCRC = new CRC();
    for (int i = 0; i < 100; i++) {
        int len = 2048 + random.nextInt(4096);
        byte[] data = new byte[len];
        random.nextBytes(data);
        expectedCRC.update(data);
        CountingInputStream in = new CountingInputStream(new ByteArrayInputStream(data));
        swappableInputStream.swap(in);
        // Check that the stream has been consumed entirely
        Assert.assertEquals(len, in.getCount());
    }
    swappableInputStream.sendEndOfStream();
    thread.join();
    if (thrown.get() != null) {
        throw thrown.get();
    }
    Assert.assertEquals(expectedCRC.getValue(), actualCRC.getValue());
}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkListDecrypter.java

void streamChunks(List<ChunkInfo> chunkInfos, CountingInputStream inputStream, ChunkStore store) {
    logger.debug("-- streamChunks() - chunk count: {}", chunkInfos.size());
    chunkInfos.stream().peek(ci -> logger.debug("-- streamChunks() - chunk info: {}", ci))
            .filter(u -> isChunkMissing(u, store))
            .forEach(u -> streamChunk(inputStream, inputStream.getCount(), u, store));
}

From source file:acmi.l2.clientmod.xdat.Controller.java

@FXML
private void open() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open interface.xdat");
    fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XDAT (*.xdat)", "*.xdat"),
            new FileChooser.ExtensionFilter("All files", "*.*"));

    if (initialDirectory.getValue() != null && initialDirectory.getValue().exists()
            && initialDirectory.getValue().isDirectory())
        fileChooser.setInitialDirectory(initialDirectory.getValue());

    File selected = fileChooser.showOpenDialog(editor.getStage());
    if (selected == null)
        return;/*from   w w  w  . ja  va2 s .  c  o  m*/

    xdatFile.setValue(selected);
    initialDirectory.setValue(selected.getParentFile());

    try {
        IOEntity xdat = editor.getXdatClass().getConstructor().newInstance();

        editor.execute(() -> {
            CountingInputStream cis = new CountingInputStream(
                    new BufferedInputStream(new FileInputStream(selected)));
            try (InputStream is = cis) {
                xdat.read(is);

                Platform.runLater(() -> editor.setXdatObject(xdat));
            } catch (Exception e) {
                log.log(Level.WARNING, String.format("Read error before offset 0x%x", cis.getCount()), e);
                throw e;
            }
            return null;
        }, e -> Platform.runLater(() -> Dialogs.show(Alert.AlertType.ERROR, "Read error", null,
                "Try to choose another version")));
    } catch (ReflectiveOperationException e) {
        log.log(Level.WARNING, "XDAT class should have empty public constructor", e);
        Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                "XDAT class should have empty public constructor");
    }
}

From source file:org.apache.axiom.om.OMDocumentTestBase.java

public void testBuild() throws Exception {
    CountingInputStream in = new CountingInputStream(getTestResource(TestConstants.REALLY_BIG_MESSAGE));
    OMDocument doc = OMXMLBuilderFactory.createOMBuilder(omMetaFactory.getOMFactory(), in).getDocument();
    assertFalse(doc.isComplete());/* ww  w. j a  v  a2 s .  c o m*/
    int countBeforeBuild = in.getCount();
    doc.build();
    assertTrue(doc.isComplete());
    int countAfterBuild = in.getCount();
    assertTrue(countAfterBuild > countBeforeBuild);
    OMNode node = doc.getFirstOMChild();
    while (node != null) {
        node = node.getNextOMSibling();
    }
    assertEquals(countAfterBuild, in.getCount());
}

From source file:org.jcodec.codecs.mjpeg.JpegParser.java

public CodedImage parse(PushbackInputStream is, CountingInputStream counter) throws IOException {
    CodedImage image = new CodedImage();
    int curQTable = 0;
    while (true) {
        int marker = is.read();
        if (marker == -1)
            return image;
        if (marker == 0)
            continue;
        if (marker != 0xFF)
            throw new RuntimeException("@" + Long.toHexString(counter.getByteCount()) + " Marker expected: 0x"
                    + Integer.toHexString(marker));

        int b = is.read();
        Debug.trace("%s", Markers.toString(b));
        switch (b) {
        case Markers.SOF0:
            image.frame = FrameHeader.read(is);
            Debug.trace("    %s", image.frame);
            break;
        case Markers.DHT:
            int len1 = readShort(is);
            CountingInputStream cis = new CountingInputStream(is);
            while (cis.getCount() < len1 - 2) {
                readHuffmanTable(cis, image);
            }/* w  w  w  . j  a  va2 s. co m*/
            break;
        case Markers.DQT:
            int len4 = readShort(is);
            CountingInputStream cis1 = new CountingInputStream(is);
            while (cis1.getCount() < len4 - 2) {
                QuantTable quantTable = readQuantTable(cis1);
                if (curQTable == 0)
                    image.setQuantLum(quantTable);
                else
                    image.setQuantChrom(quantTable);
                curQTable++;
            }
            break;
        case Markers.SOS:
            if (image.scan != null) {
                throw new IllegalStateException("unhandled - more than one scan header");
            }
            image.scan = ScanHeader.read(is);
            Debug.trace("    %s", image.scan);
            image.setData(readData(is));
            break;
        case Markers.SOI:
            break;
        case Markers.EOI:
            return image;
        case Markers.APP0:
            // int len10 = readShort(is);
            // byte[] id = new byte[4];
            // is.read(id);
            // if (!Arrays.equals(JFIF, id))
            // throw new RuntimeException("Not a JFIF file");
            // is.skip(1);
            //
            // is.skip(2);
            // int units = is.read();
            // int dx = readShort(is);
            // int dy = readShort(is);
            // int tx = is.read();
            // int ty = is.read();
            // is.skip(tx * ty * 3);
            // break;
        case Markers.APP1:
        case Markers.APP2:
        case Markers.APP3:
        case Markers.APP4:
        case Markers.APP5:
        case Markers.APP6:
        case Markers.APP7:
        case Markers.APP8:
        case Markers.APP9:
        case Markers.APPA:
        case Markers.APPB:
        case Markers.APPC:
        case Markers.APPD:
        case Markers.APPE:
        case Markers.APPF:
            int len3 = readShort(is);
            StringReader.sureSkip(is, len3 - 2);
            break;
        case Markers.DRI:
            /*
             * Lr: Define restart interval segment length  Specifies the
             * length of the parameters in the DRI segment shown in Figure
             * B.9 (see B.1.1.4).
             */
            int lr = readShort(is);
            // Ri: Restart interval  Specifies the number of MCU in the
            // restart interval.
            int ri = readShort(is);
            Debug.trace("DRI Lr: %d Ri: %d", lr, ri);
            // A DRI marker segment with Ri equal to zero shall disable
            // restart intervals for the following scans.
            Asserts.assertEquals(0, ri);
            break;
        default: {
            throw new IllegalStateException("unhandled marker " + Markers.toString(b));
        }
        }
    }
}

From source file:org.jcodec.codecs.wav.WavHeader.java

public static WavHeader read(InputStream in) throws IOException {
    CountingInputStream cin = new CountingInputStream(in);
    String chunkId = readString(cin, 4);
    int chunkSize = readInt(cin);
    String format = readString(cin, 4);
    FmtChunk fmt = null;/* w  w w. j a v  a2 s  .  co m*/

    if (!"RIFF".equals(chunkId) || !"WAVE".equals(format)) {
        return null;
    }
    String fourcc;
    int size = 0;
    do {
        fourcc = readString(cin, 4);
        size = ReaderLE.readInt(cin);
        if ("fmt ".equals(fourcc) && size >= 14 && size <= 1024 * 1024) {
            switch (size) {
            case 16:
            case 18:
                fmt = FmtChunk.read(cin);
                StringReader.sureSkip(cin, 2);
                break;
            case 40:
                fmt = FmtChunkExtended.read(cin);
                StringReader.sureSkip(cin, 12);
                break;
            case 28:
                fmt = FmtChunkExtended.read(cin);
                break;
            default:
                throw new IllegalStateException("Don't know how to handle fmt size: " + size);
            }
        } else if (!"data".equals(fourcc)) {
            StringReader.sureRead(cin, size);
        }
    } while (!"data".equals(fourcc));

    return new WavHeader(chunkId, chunkSize, format, fmt, cin.getCount(), size);
}

From source file:org.phoenicis.win32.pe.PEReader.java

private RsrcSection readResourceSection(CountingInputStream executableInputStream,
        SectionHeader[] sectionHeaders) throws IOException {
    SectionHeader rsrcSectionHeader = null;
    for (SectionHeader sectionHeader : sectionHeaders) {
        if (".rsrc\u0000\u0000\u0000".equals(new String(sectionHeader.name))) {
            rsrcSectionHeader = sectionHeader;
        }/*from www .  j  av  a  2 s . c o m*/
    }

    if (rsrcSectionHeader == null) {
        return null;
    }

    long numberToSkip = rsrcSectionHeader.pointerToRawData.getUnsignedValue()
            - executableInputStream.getCount();
    executableInputStream.skip(numberToSkip);
    byte[] rsrcSection = new byte[(int) rsrcSectionHeader.sizeOfRawData.getUnsignedValue()];
    executableInputStream.read(rsrcSection);

    return new RsrcSection(rsrcSection);
}

From source file:org.springframework.ws.transport.http.AbstractHttpSenderConnectionTest.java

/**
 * Tests that {@link AbstractHttpSenderConnection} doesn't consume the response stream before
 * passing it to the message factory. This is a regression test for SWS-707.
 *
 * @param chunking//  w w w .j  a va2s . c o  m
 *            Specifies whether the test should simulate a response with chunking enabled.
 * @throws Exception
 */
private void testSupportsStreaming(boolean chunking) throws Exception {
    byte[] content = new byte[16 * 1024];
    new Random().nextBytes(content);
    CountingInputStream rawInputStream = new CountingInputStream(new ByteArrayInputStream(content));

    AbstractHttpSenderConnection connection = createNiceMock(AbstractHttpSenderConnection.class);
    expect(connection.getResponseCode()).andReturn(200);
    // Simulate response with chunking enabled
    expect(connection.getResponseContentLength()).andReturn(chunking ? -1L : content.length);
    expect(connection.getRawResponseInputStream()).andReturn(rawInputStream);
    expect(connection.getResponseHeaders(anyObject())).andReturn(Collections.emptyIterator());

    // Create a mock message factory to capture the InputStream passed to it
    WebServiceMessageFactory messageFactory = createNiceMock(WebServiceMessageFactory.class);
    WebServiceMessage message = createNiceMock(WebServiceMessage.class);
    Capture<InputStream> inputStreamCapture = new Capture<>();
    expect(messageFactory.createWebServiceMessage(capture(inputStreamCapture))).andReturn(message);

    replay(connection, messageFactory, message);

    connection.receive(messageFactory);

    assertTrue("The raw input stream has been completely consumed", rawInputStream.getCount() < content.length);
    assertArrayEquals("Unexpected content received by the message factory", content,
            IOUtils.toByteArray(inputStreamCapture.getValue()));
}