Example usage for java.io SequenceInputStream SequenceInputStream

List of usage examples for java.io SequenceInputStream SequenceInputStream

Introduction

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

Prototype

public SequenceInputStream(Enumeration<? extends InputStream> e) 

Source Link

Document

Initializes a newly created SequenceInputStream by remembering the argument, which must be an Enumeration that produces objects whose run-time type is InputStream.

Usage

From source file:org.dspace.discovery.FullTextContentStreams.java

@Override
public InputStream getStream() throws IOException {
    try {//from  w  ww  . ja  v a2s .  co  m
        return new SequenceInputStream(new FullTextEnumeration(fullTextStreams.iterator()));
    } catch (Exception e) {
        log.error("Unable to add full text bitstreams to SOLR for item " + sourceInfo + ": " + e.getMessage(),
                e);
        return new ByteArrayInputStream(
                (e.getClass() + ": " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
    }
}

From source file:pt.webdetails.cpf.Util.java

public static InputStream joinStreams(final InputStream... streams) {
    return new SequenceInputStream(toEnumeration(streams));
}

From source file:randori.plugin.compiled.RblFileDecompiler.java

/**
 * Extract the library for each declared bundle in the RBL.
 * It doesn't extract it from the rblFile itself but from its content.
 *
 * @param rblFile The RBL file./* w w w .ja  v  a 2  s.  com*/
 * @param content The content of the RBL file.
 * @return An InputStream sequence of the extracted libraries.
 * @throws IOException
 * @throws XMLStreamException
 */
public static InputStream extractLibraries(VirtualFile rblFile, byte[] content)
        throws IOException, XMLStreamException {
    final List<InputStream> libraries = new ArrayList<InputStream>();
    SequenceInputStream librariesInputStream = null;
    InputStream swcInputStream;
    byte[] swcBytes;
    ZipFile swc;
    InputStream library;
    ZipEntry entry;

    final Bundle bundle = new Bundle(new File(rblFile.getPath()));
    final ByteArrayReadOnlyFile rof = new ByteArrayReadOnlyFile(content);
    final ZipFile rbl = new ZipFile(rof);

    readCatalog(rbl, bundle);

    for (IBundleLibrary iBundleLibrary : bundle.getLibraries()) {
        entry = rbl.getEntry(iBundleLibrary.getName() + "/bin/swc/" + iBundleLibrary.getName() + ".swc");
        swcInputStream = rbl.getInputStream(entry);

        if (swcInputStream != null) {
            swcBytes = IOUtils.toByteArray(swcInputStream);

            if (swcBytes != null && swcBytes.length > 0) {
                swc = new ZipFile(new ByteArrayReadOnlyFile(swcBytes));
                library = swc.getInputStream("library.swf");
                libraries.add(library);
                libraries.add(new ByteArrayInputStream(libSeparator.getBytes()));
            }
        }
    }

    if (libraries.size() > 0)
        librariesInputStream = new SequenceInputStream(Collections.enumeration(libraries));

    return librariesInputStream;
}

From source file:org.apache.xmlgraphics.image.loader.impl.PNGFile.java

public ImageRawPNG getImageRawPNG(final ImageInfo info) throws ImageException, IOException {
    try (final InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec))) {
        switch (this.colorType) {
        case PNG_COLOR_GRAY:
            if (this.hasPalette) {
                throw new ImageException("Corrupt PNG: color palette is not allowed!");
            }//  w w w.ja  v a 2s  .c  o m
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
                    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_RGB:
            // actually a check of the sRGB chunk would be necessary to
            // confirm
            // if it's really sRGB
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false,
                    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_PALETTE:
            if (this.hasAlphaPalette) {
                this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                        this.greenPalette, this.bluePalette, this.alphaPalette);
            } else {
                this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                        this.greenPalette, this.bluePalette);
            }
            break;
        case PNG_COLOR_GRAY_ALPHA:
            if (this.hasPalette) {
                throw new ImageException("Corrupt PNG: color palette is not allowed!");
            }
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false,
                    Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_RGB_ALPHA:
            // actually a check of the sRGB chunk would be necessary to
            // confirm
            // if it's really sRGB
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false,
                    Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
            break;
        default:
            throw new ImageException("Unsupported color type: " + this.colorType);
        }
        // the iccProfile is still null for now
        final ImageRawPNG rawImage = new ImageRawPNG(info, seqStream, this.colorModel, this.bitDepth,
                this.iccProfile);
        if (this.isTransparent) {
            if (this.colorType == PNG_COLOR_GRAY) {
                rawImage.setGrayTransparentAlpha(this.grayTransparentAlpha);
            } else if (this.colorType == PNG_COLOR_RGB) {
                rawImage.setRGBTransparentAlpha(this.redTransparentAlpha, this.greenTransparentAlpha,
                        this.blueTransparentAlpha);
            } else if (this.colorType == PNG_COLOR_PALETTE) {
                rawImage.setTransparent();
            } else {
                //
            }
        }
        return rawImage;
    }
}

From source file:com.metamolecular.pubcouch.pubchem.Snapshot.java

private InputStream getStream(int beginAfter) throws IOException {
    //    Compound_00000001_00025000.sdf.gz
    Pattern pattern = Pattern.compile("^(Substance|Compound)_(\\d{8})_(\\d{8})\\.sdf\\.gz");
    List<String> filenames = getFilenames();
    List<String> keep = new ArrayList();
    boolean check = true;

    for (String name : filenames) {
        Matcher matcher = pattern.matcher(name);

        if (matcher.matches()) {
            if (check) {
                int start = Integer.parseInt(matcher.group(2));
                int end = Integer.parseInt(matcher.group(3));

                if (beginAfter >= start && beginAfter <= end) {
                    keep.add(name);/*from  ww w.  j a  v  a2  s  . co m*/
                    check = false;
                }
            } else {
                keep.add(name);
            }
        }
    }

    return new SequenceInputStream(new StreamEnumerator(keep));
}

From source file:org.apache.pdfbox.pdmodel.PDPage.java

@Override
public InputStream getContents() throws IOException {
    COSBase base = page.getDictionaryObject(COSName.CONTENTS);
    if (base instanceof COSStream) {
        return ((COSStream) base).createInputStream();
    } else if (base instanceof COSArray && ((COSArray) base).size() > 0) {
        COSArray streams = (COSArray) base;
        byte[] delimiter = new byte[] { '\n' };
        List<InputStream> inputStreams = new ArrayList<InputStream>();
        for (int i = 0; i < streams.size(); i++) {
            COSStream stream = (COSStream) streams.getObject(i);
            inputStreams.add(stream.createInputStream());
            inputStreams.add(new ByteArrayInputStream(delimiter));
        }//  ww  w  .j  a  v  a2s  . c  o  m
        return new SequenceInputStream(Collections.enumeration(inputStreams));
    }
    return null;
}

From source file:it.anyplace.sync.bep.BlockPuller.java

public FileDownloadObserver pullBlocks(FileBlocks fileBlocks) throws InterruptedException {
    logger.info("pulling file = {}", fileBlocks);
    checkArgument(connectionHandler.hasFolder(fileBlocks.getFolder()),
            "supplied connection handler %s will not share folder %s", connectionHandler,
            fileBlocks.getFolder());/*from   w  w  w  . j  av a 2  s . c o  m*/
    final Object lock = new Object();
    final AtomicReference<Exception> error = new AtomicReference<>();
    final Object listener = new Object() {
        @Subscribe
        public void handleResponseMessageReceivedEvent(ResponseMessageReceivedEvent event) {
            synchronized (lock) {
                try {
                    if (!requestIds.contains(event.getMessage().getId())) {
                        return;
                    }
                    checkArgument(equal(event.getMessage().getCode(), ErrorCode.NO_ERROR),
                            "received error response, code = %s", event.getMessage().getCode());
                    byte[] data = event.getMessage().getData().toByteArray();
                    String hash = BaseEncoding.base16().encode(Hashing.sha256().hashBytes(data).asBytes());
                    blockCache.pushBlock(data);
                    if (missingHashes.remove(hash)) {
                        blocksByHash.put(hash, data);
                        logger.debug("aquired block, hash = {}", hash);
                        lock.notify();
                    } else {
                        logger.warn("received not-needed block, hash = {}", hash);
                    }
                } catch (Exception ex) {
                    error.set(ex);
                    lock.notify();
                }
            }
        }
    };
    FileDownloadObserver fileDownloadObserver = new FileDownloadObserver() {

        private long getReceivedData() {
            return blocksByHash.size() * BLOCK_SIZE;
        }

        private long getTotalData() {
            return (blocksByHash.size() + missingHashes.size()) * BLOCK_SIZE;
        }

        @Override
        public double getProgress() {
            return isCompleted() ? 1d : getReceivedData() / ((double) getTotalData());
        }

        @Override
        public String getProgressMessage() {
            return (Math.round(getProgress() * 1000d) / 10d) + "% "
                    + FileUtils.byteCountToDisplaySize(getReceivedData()) + " / "
                    + FileUtils.byteCountToDisplaySize(getTotalData());
        }

        @Override
        public boolean isCompleted() {
            return missingHashes.isEmpty();
        }

        @Override
        public void checkError() {
            if (error.get() != null) {
                throw new RuntimeException(error.get());
            }
        }

        @Override
        public double waitForProgressUpdate() throws InterruptedException {
            if (!isCompleted()) {
                synchronized (lock) {
                    checkError();
                    lock.wait();
                    checkError();
                }
            }
            return getProgress();
        }

        @Override
        public InputStream getInputStream() {
            checkArgument(missingHashes.isEmpty(), "pull failed, some blocks are still missing");
            List<byte[]> blockList = Lists
                    .newArrayList(Lists.transform(hashList, Functions.forMap(blocksByHash)));
            return new SequenceInputStream(Collections
                    .enumeration(Lists.transform(blockList, new Function<byte[], ByteArrayInputStream>() {
                        @Override
                        public ByteArrayInputStream apply(byte[] data) {
                            return new ByteArrayInputStream(data);
                        }
                    })));
        }

        @Override
        public void close() {
            missingHashes.clear();
            hashList.clear();
            blocksByHash.clear();
            try {
                connectionHandler.getEventBus().unregister(listener);
            } catch (Exception ex) {
            }
            if (closeConnection) {
                connectionHandler.close();
            }
        }
    };
    try {
        synchronized (lock) {
            hashList.addAll(Lists.transform(fileBlocks.getBlocks(), new Function<BlockInfo, String>() {
                @Override
                public String apply(BlockInfo block) {
                    return block.getHash();
                }
            }));
            missingHashes.addAll(hashList);
            for (String hash : missingHashes) {
                byte[] block = blockCache.pullBlock(hash);
                if (block != null) {
                    blocksByHash.put(hash, block);
                    missingHashes.remove(hash);
                }
            }
            connectionHandler.getEventBus().register(listener);
            for (BlockInfo block : fileBlocks.getBlocks()) {
                if (missingHashes.contains(block.getHash())) {
                    int requestId = Math.abs(new Random().nextInt());
                    requestIds.add(requestId);
                    connectionHandler.sendMessage(Request.newBuilder().setId(requestId)
                            .setFolder(fileBlocks.getFolder()).setName(fileBlocks.getPath())
                            .setOffset(block.getOffset()).setSize(block.getSize())
                            .setHash(ByteString.copyFrom(BaseEncoding.base16().decode(block.getHash())))
                            .build());
                    logger.debug("sent request for block, hash = {}", block.getHash());
                }
            }
            return fileDownloadObserver;
        }
    } catch (Exception ex) {
        fileDownloadObserver.close();
        throw ex;
    }
}

From source file:eu.crowdrec.contest.sender.RequestSenderORP.java

/**
 * read logFile then sends line by line to server.
 * //from   ww  w  .  jav a2s  . c o m
 * @param inLogFileName
 *            path to log file. That can be a zip file or text file.
 * @param outLogFile
 *            path to outLog file. The outLog file should be analyzed by the evaluator.
 *            if the filename is null; no output will be generated
 * @param serverURL
 *            URL of the server
 */
public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) {

    // handle the log file
    // check type of file

    // try to read the defined logFile
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // if outLogFile name is not null, create an output file
        if (outLogFile != null && outLogFile.length() > 0) {
            bw = new BufferedWriter(new FileWriter(new File(outLogFile), false));
        }

        // support a list of files in a directory
        File inLogFile = new File(inLogFileName);
        InputStream is;
        if (inLogFile.isFile()) {
            is = new FileInputStream(inLogFileName);
            // support gZip files
            if (inLogFile.getName().toLowerCase().endsWith(".gz")) {
                is = new GZIPInputStream(is);
            }
        } else {
            // if the input is a directory, consider all files based on a pattern
            File[] childs = inLogFile.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    final String fileName = name.toLowerCase();
                    return fileName.startsWith("contest.log");
                }
            });
            if (childs == null || childs.length == 0) {
                throw new IOException("invalid inLogFileName or empty directory");
            }
            Arrays.sort(childs, new Comparator<File>() {

                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            Vector<InputStream> isChilds = new Vector<InputStream>();
            for (int i = 0; i < childs.length; i++) {
                InputStream tmpIS = new FileInputStream(childs[i]);
                // support gZip files
                if (childs[i].getName().toLowerCase().endsWith(".gz")) {
                    tmpIS = new GZIPInputStream(tmpIS);
                }
                isChilds.add(tmpIS);
            }
            is = new SequenceInputStream(isChilds.elements());
        }

        // read the log file line by line
        br = new BufferedReader(new InputStreamReader(is));
        try {
            for (String line = br.readLine(); line != null; line = br.readLine()) {

                // ignore invalid lines and header
                if (line.startsWith("null") || line.startsWith("#")) {
                    continue;
                }

                String[] token = parseLogLine(line);
                if (token == null) {
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(line);
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    continue;
                }

                // use a threadPool
                RequestSenderThread t = new RequestSenderThread(token[0], token[1], token[2], serverURL, bw);
                try {
                    // try to limit the speed of sending requests
                    if (Thread.activeCount() > 1000) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Thread.activeCount() = " + Thread.activeCount());
                        }
                        Thread.sleep(200);
                    }
                } catch (Exception e) {
                    logger.info(e.toString());
                }
                t.start();
            }

        } catch (IOException e) {
            logger.warn(e.toString(), e);
        }
    } catch (FileNotFoundException e) {
        logger.error("logFile not found e:" + e.toString());
    } catch (IOException e) {
        logger.error("reading the logFile failed e:" + e.toString());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                logger.debug("close read-log file failed");
            }
        }
        if (bw != null) {
            try {
                // wait for ensuring that all request are finished
                // this simplifies the management of thread and worked fine for all test machines
                Thread.sleep(5000);
                bw.flush();
            } catch (Exception e) {
                logger.debug("close write-log file failed");
            }
        }
    }
}

From source file:gov.nih.nci.caarray.domain.MultiPartBlob.java

/**
 * Returns an input stream to access the contents of this MultiPartBlob.
 * //w w w . j  a v a  2s .c  om
 * @param uncompress true if the data should be uncompressed when read, false otherwise
 * @return the input stream to read.
 * @throws IOException if the contents couldn't be accessed.
 */
private InputStream readContents(boolean uncompress) throws IOException {
    try {
        final Vector<InputStream> isVector = new Vector<InputStream>(); // NOPMD
        for (final BlobHolder currentBlobHolder : getBlobParts()) {
            isVector.add(currentBlobHolder.getContents().getBinaryStream());
        }
        final SequenceInputStream sequenceInputStream = new SequenceInputStream(isVector.elements());
        if (uncompress) {
            return new GZIPInputStream(sequenceInputStream);
        } else {
            return sequenceInputStream;
        }
    } catch (final SQLException e) {
        throw new IllegalStateException("Couldn't access file contents", e);
    }
}

From source file:com.zextras.zimbradrive.UploadFileHttpHandler.java

private HttpEntity createUploadFileRequest(HttpServletRequest httpServletRequest, String formBoundary,
        Account userAccount) throws IOException {
    InputStream userRequestInputStream = httpServletRequest.getInputStream();
    String userInfoPartsString = createUserInfoInFormStyle(userAccount, formBoundary);
    String internalFormPartsBoundary = getInternalBodyBoundary(formBoundary);
    List<InputStream> payloadStreamToSendToDrive = Arrays.asList(
            new ByteArrayInputStream(userInfoPartsString.getBytes()),
            new ByteArrayInputStream(internalFormPartsBoundary.getBytes()), userRequestInputStream // TODO: This inputStreams will be closed?
    );//  w  w w.j a v  a  2  s  . c o  m

    SequenceInputStream payloadToSendToDriveInputStream = new SequenceInputStream(
            Collections.enumeration(payloadStreamToSendToDrive));

    int contentLength = httpServletRequest.getIntHeader(HTTP.CONTENT_LEN);
    int diffInternalFormPartsBoundaryAndFirstBodyBoundary = 2; // getFirstBodyBoundary(boundaryOfParts) - getInternalBodyBoundary(formBoundary)
    contentLength = contentLength + userInfoPartsString.length()
            + diffInternalFormPartsBoundaryAndFirstBodyBoundary;
    return new InputStreamEntity(payloadToSendToDriveInputStream, contentLength);
}