Example usage for java.io InputStream InputStream

List of usage examples for java.io InputStream InputStream

Introduction

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

Prototype

InputStream

Source Link

Usage

From source file:org.thelq.stackexchange.dbimport.analyze.ColumnAnalyzer.java

public static void main(String[] args) throws IOException, XMLStreamException {
    String archivePath = "C:\\Users\\Leon\\Downloads\\Stack Exchange Data Dump - Jun 2013\\Content\\android.stackexchange.com.7z";
    final SevenZFile archive = new SevenZFile(new File(archivePath));
    InputStream archiveWrappedInputStream = new InputStream() {
        @Override/*w ww  . jav  a  2s.c om*/
        public int read() throws IOException {
            return archive.read();
        }

        @Override
        public int read(byte[] b) throws IOException {
            return archive.read(b);
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            return archive.read(b, off, len);
        }
    };
    for (SevenZArchiveEntry curEntry = archive.getNextEntry(); (curEntry = archive.getNextEntry()) != null;)
        if (curEntry.getName().endsWith(".xml"))
            analyze(archivePath + "\\" + curEntry.getName(), archiveWrappedInputStream);
}

From source file:neembuu.httpserver.VFileEntity.java

@Override
public InputStream getContent() throws IOException, IllegalStateException {
    return new InputStream() {
        long pos = startingOffset;

        @Override/*from   w w w  .j a va  2 s  .  c  o m*/
        public int read() throws IOException {
            throw new IllegalStateException("This is not used.");
        }

        @Override
        public int read(byte[] b) throws IOException {
            return read(b, 0, b.length); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            ByteBuffer bb = ByteBuffer.wrap(b, 0, len);
            BlockingReadRequest brr = new BlockingReadRequest(bb, pos);
            try {
                af.read(new SimpleReadRequest(bb, pos));
            } catch (Exception a) {
                IOException ioe = new IOException();
                ioe.addSuppressed(a);
            }
            int read = brr.read();
            pos += read;
            return read;
        }

    };
}

From source file:onl.area51.httpd.util.EmptyEntity.java

@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
    return new InputStream() {
        @Override// w  w w.j a  v a 2  s.  co  m
        public int read() throws IOException {
            return -1;
        }
    };
}

From source file:com.btoddb.trellis.common.serialization.JavaSerializer.java

@Override
public Serializable deserialize(final ByteBuffer bb) {
    try {/*from www . ja  v a 2s . c om*/
        ObjectInputStream ois;
        ois = new ObjectInputStream(new InputStream() {
            @Override
            public int read() throws IOException {
                return bb.get();
            }
        });
        Object obj = ois.readObject();
        return (Serializable) obj;
    } catch (IOException e) {
        throw new TrellisException("exception while deserializing Java Serializable object", e);
    } catch (ClassNotFoundException e) {
        throw new TrellisException("exception while deserializing Java Serializable object", e);
    }
}

From source file:bobs.is.compress.sevenzip.AES256SHA256Decoder.java

@Override
InputStream decode(final String archiveName, final InputStream in, final long uncompressedLength,
        final Coder coder, final byte[] passwordBytes) throws IOException {
    return new InputStream() {
        private boolean isInitialized = false;
        private CipherInputStream cipherInputStream = null;

        private CipherInputStream init() throws IOException {
            if (isInitialized) {
                return cipherInputStream;
            }/*from  w  w w. j  a v  a  2 s  . com*/
            final int byte0 = 0xff & coder.properties[0];
            final int numCyclesPower = byte0 & 0x3f;
            final int byte1 = 0xff & coder.properties[1];
            final int ivSize = ((byte0 >> 6) & 1) + (byte1 & 0x0f);
            final int saltSize = ((byte0 >> 7) & 1) + (byte1 >> 4);
            if (2 + saltSize + ivSize > coder.properties.length) {
                throw new IOException("Salt size + IV size too long in " + archiveName);
            }
            final byte[] salt = new byte[saltSize];
            System.arraycopy(coder.properties, 2, salt, 0, saltSize);
            final byte[] iv = new byte[16];
            System.arraycopy(coder.properties, 2 + saltSize, iv, 0, ivSize);

            if (passwordBytes == null) {
                throw new PasswordRequiredException(archiveName);
            }
            final byte[] aesKeyBytes;
            if (numCyclesPower == 0x3f) {
                aesKeyBytes = new byte[32];
                System.arraycopy(salt, 0, aesKeyBytes, 0, saltSize);
                System.arraycopy(passwordBytes, 0, aesKeyBytes, saltSize,
                        Math.min(passwordBytes.length, aesKeyBytes.length - saltSize));
            } else {
                final MessageDigest digest;
                try {
                    digest = MessageDigest.getInstance("SHA-256");
                } catch (final NoSuchAlgorithmException noSuchAlgorithmException) {
                    throw new IOException("SHA-256 is unsupported by your Java implementation",
                            noSuchAlgorithmException);
                }
                final byte[] extra = new byte[8];
                for (long j = 0; j < (1L << numCyclesPower); j++) {
                    digest.update(salt);
                    digest.update(passwordBytes);
                    digest.update(extra);
                    for (int k = 0; k < extra.length; k++) {
                        ++extra[k];
                        if (extra[k] != 0) {
                            break;
                        }
                    }
                }
                aesKeyBytes = digest.digest();
            }

            final SecretKey aesKey = new SecretKeySpec(aesKeyBytes, "AES");
            try {
                final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
                cipherInputStream = new CipherInputStream(in, cipher);
                isInitialized = true;
                return cipherInputStream;
            } catch (final GeneralSecurityException generalSecurityException) {
                throw new IOException("Decryption error "
                        + "(do you have the JCE Unlimited Strength Jurisdiction Policy Files installed?)",
                        generalSecurityException);
            }
        }

        @Override
        public int read() throws IOException {
            return init().read();
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            return init().read(b, off, len);
        }

        @Override
        public void close() {
        }
    };
}

From source file:com.microsoft.alm.plugin.external.commands.CommandTest.java

/**
 * This test makes sure that output from a command is flushed before the completion event is fired.
 *
 * @throws Exception//ww  w.ja  v  a 2s. c o m
 */
@Test
public void testRaceCondition() throws Exception {
    // Fake the tool location so this works on any machine
    PowerMockito.mockStatic(TfTool.class);
    when(TfTool.getValidLocation()).thenReturn("/path/tf_home");

    Process proc = Mockito.mock(Process.class);
    PowerMockito.mockStatic(ProcessHelper.class);
    when(ProcessHelper.startProcess(anyString(), anyList())).thenReturn(proc);
    when(proc.getErrorStream()).thenReturn(new InputStream() {
        @Override
        public int read() throws IOException {
            return -1;
        }
    });
    when(proc.getInputStream()).thenReturn(new InputStream() {
        private String result = "12345";
        private int index = 0;

        @Override
        public int read() throws IOException {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (index < result.length()) {
                return result.charAt(index++);
            } else {
                return -1;
            }
        }
    });
    when(proc.waitFor()).thenAnswer(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            return 0;
        }
    });
    when(proc.exitValue()).thenReturn(0);

    final MyCommand cmd = new MyCommand(null);
    final String output = cmd.runSynchronously();
    Assert.assertEquals("12345", StringUtils.strip(output));
}

From source file:com.github.songsheng.vfs2.provider.nfs.NfsFileRandomAccessContent.java

public NfsFileRandomAccessContent(final XFile NfsFile, final RandomAccessMode mode) throws FileSystemException {
    super(mode);//  w w  w  . j av a 2 s.c om

    try {
        raf = new XRandomAccessFile(NfsFile, mode.getModeString());
        rafis = new InputStream() {
            @Override
            public int available() throws IOException {
                final long available = raf.length() - raf.getFilePointer();
                if (available > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }

                return (int) available;
            }

            @Override
            public void close() throws IOException {
                raf.close();
            }

            @Override
            public int read() throws IOException {
                return raf.readByte();
            }

            @Override
            public int read(final byte[] b) throws IOException {
                return raf.read(b);
            }

            @Override
            public int read(final byte[] b, final int off, final int len) throws IOException {
                return raf.read(b, off, len);
            }

            @Override
            public long skip(final long n) throws IOException {
                raf.seek(raf.getFilePointer() + n);
                return n;
            }
        };
    } catch (final MalformedURLException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", NfsFile, e);
    } catch (final UnknownHostException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", NfsFile, e);
    } catch (IOException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", NfsFile, e);
    }
}

From source file:com.adito.networkplaces.vfs2.provider.smb.SmbFileRandomAccessContent.java

SmbFileRandomAccessContent(final SmbFile smbFile, final RandomAccessMode mode) throws FileSystemException {
    super(mode);// w w w.j a va  2s . c  om

    final StringBuilder modes = new StringBuilder(2);
    if (mode.requestRead()) {
        modes.append('r');
    }
    if (mode.requestWrite()) {
        modes.append('w');
    }

    try {
        raf = new SmbRandomAccessFile(smbFile, modes.toString());
        rafis = new InputStream() {
            @Override
            public int read() throws IOException {
                return raf.readByte();
            }

            @Override
            public long skip(long n) throws IOException {
                raf.seek(raf.getFilePointer() + n);
                return n;
            }

            @Override
            public void close() throws IOException {
                raf.close();
            }

            @Override
            public int read(byte b[]) throws IOException {
                return raf.read(b);
            }

            @Override
            public int read(byte b[], int off, int len) throws IOException {
                return raf.read(b, off, len);
            }

            @Override
            public int available() throws IOException {
                long available = raf.length() - raf.getFilePointer();
                if (available > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }

                return (int) available;
            }
        };
    } catch (MalformedURLException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
    } catch (SmbException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
    } catch (UnknownHostException e) {
        throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
    }
}

From source file:org.thelq.stackexchange.dbimport.sources.ArchiveDumpEntry.java

public InputStream getInput() {
    if (input != null)
        throw new RuntimeException("Already generated an InputStream");

    try {//ww w.j a v  a2  s  . c o m
        final SevenZFile file7 = new SevenZFile(file);
        //Advance archive until we find the correct ArchiveEntry
        SevenZArchiveEntry curEntry;
        while ((curEntry = file7.getNextEntry()) != null) {
            if (!curEntry.getName().equals(name))
                continue;
            //Found, return a wrapped InputStream
            return new InputStream() {
                @Override
                public int read() throws IOException {
                    return file7.read();
                }
            };
        }
    } catch (IOException ex) {
        throw new RuntimeException("Cannot open archive entry", ex);
    }
    //Didn't find anything
    throw new RuntimeException("Could not find file " + name + " in archive " + file.getAbsolutePath());
}

From source file:org.apache.ant.compress.taskdefs.Un7z.java

protected void expandFile(FileUtils fileUtils, File srcF, File dir) {
    if (!srcF.exists()) {
        throw new BuildException("Unable to expand " + srcF + " as the file does not exist", getLocation());
    }/*from  w ww . j av a  2  s  .com*/
    log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO);
    FileNameMapper mapper = getMapper();
    SevenZFile outer = null;
    try {
        final SevenZFile zf = outer = new SevenZFile(srcF);
        boolean empty = true;
        SevenZArchiveEntry ze = zf.getNextEntry();
        while (ze != null) {
            empty = false;
            /* TODO implement canReadEntryData in CC
            if (getSkipUnreadableEntries() && !zf.canReadEntryData(ze)) {
            log(Messages.skippedIsUnreadable(ze));
            continue;
            }
            */
            log("extracting " + ze.getName(), Project.MSG_DEBUG);
            InputStream is = null;
            try {
                extractFile(fileUtils, srcF, dir, is = new InputStream() {
                    public int read() throws IOException {
                        return zf.read();
                    }

                    public int read(byte[] b) throws IOException {
                        return zf.read(b);
                    }
                }, ze.getName(), ze.getLastModifiedDate(), ze.isDirectory(), mapper);
            } finally {
                FileUtils.close(is);
            }
            ze = zf.getNextEntry();
        }
        if (empty && getFailOnEmptyArchive()) {
            throw new BuildException("archive '" + srcF + "' is empty");
        }
        log("expand complete", Project.MSG_VERBOSE);
    } catch (IOException ioe) {
        throw new BuildException("Error while expanding " + srcF.getPath() + "\n" + ioe.toString(), ioe);
    } finally {
        if (outer != null) {
            try {
                outer.close();
            } catch (IOException ex) {
                // swallow
            }
        }
    }
}