Example usage for java.io FilterInputStream FilterInputStream

List of usage examples for java.io FilterInputStream FilterInputStream

Introduction

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

Prototype

protected FilterInputStream(InputStream in) 

Source Link

Document

Creates a FilterInputStream by assigning the argument in to the field this.in so as to remember it for later use.

Usage

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/*from  w  w  w.  ja  va 2  s . c  o  m*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:Main.java

public static Document createDocument(InputStream input) {
    DOMParser parser = null;/*from  www .j a v a  2s.co  m*/
    try {
        parser = getLargeParser(input.available());
        parser.parse(new InputSource(new FilterInputStream(input) {
            public void close() {
                // disable close. Because createDocument calls close, but it shoudn't do it.
            }
        }));
        return parser.getDocument();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.oneandone.sushi.fs.webdav.methods.Get.java

@Override
public InputStream processResponse(final WebdavConnection connection, final HttpResponse response)
        throws IOException {
    int status;/*  w w  w  . j  a va2s . c  o m*/

    status = response.getStatusLine().getStatusCode();
    switch (status) {
    case HttpStatus.SC_OK:
        return new FilterInputStream(response.getEntity().getContent()) {
            private boolean freed = false;

            @Override
            public void close() throws IOException {
                if (!freed) {
                    freed = true;
                    resource.getRoot().free(response, connection);
                }
                super.close();
            }
        };
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_MOVED_PERMANENTLY:
        resource.getRoot().free(response, connection);
        throw new FileNotFoundException(resource);
    default:
        resource.getRoot().free(response, connection);
        throw new StatusException(response.getStatusLine());
    }
}

From source file:org.apache.activemq.blob.FTPBlobDownloadStrategy.java

public InputStream getInputStream(ActiveMQBlobMessage message) throws IOException, JMSException {
    url = message.getURL();//from  www . ja  va 2s  .  com
    final FTPClient ftp = createFTP();
    String path = url.getPath();
    String workingDir = path.substring(0, path.lastIndexOf("/"));
    String file = path.substring(path.lastIndexOf("/") + 1);
    ftp.changeWorkingDirectory(workingDir);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

    InputStream input = new FilterInputStream(ftp.retrieveFileStream(file)) {

        public void close() throws IOException {
            in.close();
            ftp.quit();
            ftp.disconnect();
        }
    };

    return input;
}

From source file:org.codehaus.mojo.minijar.resource.LicenseHandler.java

public InputStream onResource(Jar jar, String oldName, String newName, Version[] versions,
        InputStream inputStream) throws IOException {
    final String s = oldName.toLowerCase();

    if ("meta-inf/license.txt".equals(s) || "meta-inf/license".equals(s) || "meta-inf/notice.txt".equals(s)
            || "meta-inf/notice".equals(s)) {
        System.out.println(this + " found resource " + oldName);

        if (licensesFile == null) {
            licensesFile = File.createTempFile("minijar", "license");
            licensesFile.deleteOnExit();
        }//  w ww  .  ja  va 2 s  .c o m

        if (licensesOutputStream == null) {
            licensesOutputStream = new FileOutputStream(licensesFile);
        }

        return new FilterInputStream(inputStream) {

            public int read() throws IOException {
                int r = super.read();
                if (r > 0) {
                    licensesOutputStream.write(r);
                }
                return r;
            }

            public int read(byte[] b, int off, int len) throws IOException {
                int r = super.read(b, off, len);
                if (r > 0) {
                    licensesOutputStream.write(b, off, r);
                }
                return r;
            }

            public int read(byte[] b) throws IOException {
                int r = super.read(b);
                if (r > 0) {
                    licensesOutputStream.write(b, 0, r);
                }
                return r;
            }
        };
    }

    return inputStream;
}

From source file:org.jclouds.vfs.provider.blobstore.BlobStoreRandomAccessContent.java

protected DataInputStream getDataInputStream() throws IOException {
    if (dis != null) {
        return dis;
    }//from  w w w .jav  a 2s .c om

    dis = new DataInputStream(
            new FilterInputStream((InputStream) fileObject.getBlobStore().getBlob(fileObject.getContainer(),
                    fileObject.getNameTrimLeadingSlashes(), new GetOptions().startAt(filePointer)).getPayload()
                    .getInput()) {
                public int read() throws IOException {
                    int ret = super.read();
                    if (ret > -1) {
                        filePointer++;
                    }
                    return ret;
                }

                public int read(byte b[]) throws IOException {
                    int ret = super.read(b);
                    if (ret > -1) {
                        filePointer += ret;
                    }
                    return ret;
                }

                public int read(byte b[], int off, int len) throws IOException {
                    int ret = super.read(b, off, len);
                    if (ret > -1) {
                        filePointer += ret;
                    }
                    return ret;
                }
            });

    return dis;
}

From source file:org.mycore.common.content.MCRVFSContent.java

@Override
public InputStream getInputStream() throws IOException {
    final FileContent content = fo.getContent();
    LOGGER.debug(() -> getDebugMessage("{}: returning InputStream of {}"));
    return new FilterInputStream(content.getInputStream()) {
        @Override//from   w  w w .  j  a va  2  s  .c o m
        public void close() throws IOException {
            LOGGER.debug(() -> getDebugMessage("{}: closing InputStream of {}"));
            super.close();
            content.close();
        }
    };
}

From source file:net.solarnetwork.node.backup.ZipStreamBackupResource.java

@Override
public InputStream getInputStream() throws IOException {
    // to support calling getInputStream() more than once, tee the input to a temp file
    // the first time, and subsequent times 
    if (tempFile != null) {
        return new BufferedInputStream(new FileInputStream(tempFile));
    }//ww  w .java 2 s  . c om
    tempFile = File.createTempFile(entry.getName(), ".tmp");
    final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
    return new TeeInputStream(new FilterInputStream(stream) {

        @Override
        public void close() throws IOException {
            out.flush();
            out.close();
        }
    }, out, false);
}

From source file:org.apache.james.blob.objectstorage.AESPayloadCodecTest.java

@Test
void aesCodecShouldRaiseExceptionWhenUnderliyingInputStreamFails() throws Exception {
    Payload payload = Payloads//  ww  w . jav  a2  s  .  c  o  m
            .newInputStreamPayload(new FilterInputStream(new ByteArrayInputStream(ENCRYPTED_BYTES)) {
                private int readCount = 0;

                @Override
                public int read(@NotNull byte[] b, int off, int len) throws IOException {
                    if (readCount >= ENCRYPTED_BYTES.length / 2) {
                        throw new IOException();
                    } else {
                        readCount += len;
                        return super.read(b, off, len);
                    }
                }
            });
    int i = ENCRYPTED_BYTES.length / 2;
    byte[] bytes = new byte[i];
    InputStream is = codec().read(payload);
    assertThatThrownBy(() -> is.read(bytes, 0, i)).isInstanceOf(IOException.class);

}

From source file:org.openehealth.ipf.platform.camel.ihe.xds.iti17.Iti17Producer.java

private InputStream createWrappedStream(final GetMethod get) throws IOException {
    return new FilterInputStream(get.getResponseBodyAsStream()) {
        @Override/*from  w  w  w .jav a  2s.  co m*/
        public void close() throws IOException {
            super.close();
            get.releaseConnection();
        }
    };
}