Example usage for org.apache.commons.io.input CloseShieldInputStream CloseShieldInputStream

List of usage examples for org.apache.commons.io.input CloseShieldInputStream CloseShieldInputStream

Introduction

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

Prototype

public CloseShieldInputStream(InputStream in) 

Source Link

Document

Creates a proxy that shields the given input stream from being closed.

Usage

From source file:com.cloudera.sqoop.io.FixedLengthInputStream.java

public FixedLengthInputStream(InputStream stream, long maxLen) {
    super(new CountingInputStream(new CloseShieldInputStream(stream)));

    // Save a correctly-typed reference to the underlying stream.
    this.countingIn = (CountingInputStream) this.in;
    this.maxBytes = maxLen;
}

From source file:com.liferay.blade.cli.util.Prompter.java

private static Optional<Boolean> _getBooleanAnswer(String questionWithPrompt, InputStream inputStream,
        PrintStream printStream, Optional<Boolean> defaultAnswer) {

    Optional<Boolean> answer = null;

    try (CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(inputStream);
            Scanner scanner = new Scanner(closeShieldInputStream)) {

        while ((answer == null) || !answer.isPresent()) {
            printStream.println(questionWithPrompt);

            String readLine = null;

            while (((answer == null) || !answer.isPresent()) && !Objects.equals(answer, defaultAnswer)
                    && scanner.hasNextLine()) {

                readLine = scanner.nextLine();

                if (readLine != null) {
                    readLine = readLine.toLowerCase();

                    switch (readLine.trim()) {
                    case "y":
                    case "yes":
                        answer = Optional.of(true);

                        break;
                    case "n":
                    case "no":
                        answer = Optional.of(false);

                        break;
                    default:
                        if (defaultAnswer.isPresent()) {
                            answer = defaultAnswer;
                        } else {
                            printStream.println("Unrecognized input: " + readLine);

                            continue;
                        }//from w w w  . j  a v a 2s.  com

                        break;
                    }
                } else {
                    answer = defaultAnswer;
                }
            }
        }
    } catch (IllegalStateException ise) {
        throw new RuntimeException(ise);
    } catch (Exception exception) {
        if (defaultAnswer.isPresent()) {
            answer = defaultAnswer;
        }
    }

    return answer;
}

From source file:de.fhg.iais.cortex.services.ingest.ZipStreamAipBinaries.java

public INamedBinaryStream takeBinary() throws IOException {
    ZipEntry zipEntry;//  w  ww .j  a v  a  2 s  .c om
    do {
        zipEntry = this.zipInputStream.getNextEntry();

        if (zipEntry == null) {
            return null;
        }
    } while (zipEntry.isDirectory());

    InputStream stream = new CloseShieldInputStream(this.zipInputStream);
    return new NamedBinaryStream(zipEntry.getName(), stream);
}

From source file:io.github.houbin217jz.tech14.w31.PokerGame.java

/**
 * ?????????/* w  w w.  ja va  2s .c  o  m*/
 * 
 * @return ???????
 */
private List<Integer> inputChangeCardNumbers(PokerPlayer pokerPlayer) {
    List<Integer> result = new ArrayList<>();

    try (Scanner scanner = new Scanner(new CloseShieldInputStream(System.in))) {
        /*
         * System.in?close???????????????eclipse???
         * CloseShieldInputStream???
         */

        while (result.size() <= 1) { // ???????????

            String inputString = scanner.nextLine();
            // 0???????
            if ("0".equals(inputString)) {
                return Arrays.asList(0);
            }

            // ?
            String errorMsg = validInput(inputString, pokerPlayer.getCardsInHand());

            if (errorMsg != null && !"".equals(errorMsg)) {
                // ???
                System.out.println(errorMsg);
                continue;
            } else {
                // ????
                for (char c : inputString.toCharArray()) {
                    result.add(Integer.parseInt("" + c));
                }
                break;
            }
        }
    }
    return result;
}

From source file:com.liferay.sync.engine.document.library.handler.DownloadFilesHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    long syncAccountId = getSyncAccountId();

    final Session session = SessionManager.getSession(syncAccountId);

    Header header = httpResponse.getFirstHeader("Sync-JWT");

    if (header != null) {
        session.addHeader("Sync-JWT", header.getValue());
    }//  w  ww . j  a v  a  2 s  . c om

    Map<String, DownloadFileHandler> handlers = (Map<String, DownloadFileHandler>) getParameterValue(
            "handlers");

    InputStream inputStream = null;

    try {
        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = new CountingInputStream(httpEntity.getContent()) {

            @Override
            protected synchronized void afterRead(int n) {
                session.incrementDownloadedBytes(n);

                super.afterRead(n);
            }

        };

        inputStream = new RateLimitedInputStream(inputStream, syncAccountId);

        ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        ZipEntry zipEntry = null;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();

            if (zipEntryName.equals("errors.json")) {
                JsonNode rootJsonNode = JSONUtil.readTree(new CloseShieldInputStream(zipInputStream));

                Iterator<Map.Entry<String, JsonNode>> fields = rootJsonNode.fields();

                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> field = fields.next();

                    Handler<Void> handler = handlers.remove(field.getKey());

                    JsonNode valueJsonNode = field.getValue();

                    JsonNode exceptionJsonNode = valueJsonNode.get("exception");

                    handler.handlePortalException(exceptionJsonNode.textValue());
                }

                break;
            }

            DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName);

            if (downloadFileHandler == null) {
                continue;
            }

            SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile");

            if (downloadFileHandler.isUnsynced(syncFile)) {
                handlers.remove(zipEntryName);

                continue;
            }

            if (_logger.isTraceEnabled()) {
                _logger.trace("Handling response {} file path {}", DownloadFileHandler.class.getSimpleName(),
                        syncFile.getFilePathName());
            }

            try {
                downloadFileHandler.copyFile(syncFile, Paths.get(syncFile.getFilePathName()),
                        new CloseShieldInputStream(zipInputStream), false);
            } catch (Exception e) {
                if (!isEventCancelled()) {
                    _logger.error(e.getMessage(), e);

                    downloadFileHandler.removeEvent();

                    FileEventUtil.downloadFile(getSyncAccountId(), syncFile, false);
                }
            } finally {
                handlers.remove(zipEntryName);

                downloadFileHandler.removeEvent();
            }
        }
    } catch (Exception e) {
        if (!isEventCancelled()) {
            _logger.error(e.getMessage(), e);

            retryEvent();
        }
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

@Override
public Suite parsePath(Path path) {
    List<Test> testsList = new ArrayList<>();
    try (ArchiveInputStream in = streamPath(path)) {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        ArchiveEntry entry;/*w w w.ja v  a2  s. c  o  m*/
        while ((entry = in.getNextEntry()) != null) {
            String entryName = entry.getName();
            if (entryName == null || !entryName.endsWith(".jtr.xml")) {
                continue;
            }
            try {
                XMLStreamReader reader = inputFactory.createXMLStreamReader(new CloseShieldInputStream(in),
                        "UTF-8");
                testsList.addAll(parseTestsuites(reader));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (testsList.isEmpty()) {
        return null;
    }
    List<String> testNames = testsList.stream().sequential().map(t -> t.getName()).sorted()
            .collect(Collectors.toList());
    List<Test> testProblems = testsList.stream().sequential()
            .filter(t -> t.getStatus() == TestStatus.ERROR || t.getStatus() == TestStatus.FAILED).sorted()
            .collect(Collectors.toList());
    ReportFull fullReport = new ReportFull(
            (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.PASSED).count(),
            (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.NOT_RUN).count(),
            (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.FAILED).count(),
            (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.ERROR).count(),
            testsList.size(), testProblems, testNames);
    return new Suite(suiteName(path), fullReport);
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileDecrypter.java

@Override
public InputStream decrypt(InputStream inputStream)
        throws InvalidCipherTextException, IOException, DecoderException {
    final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(inputStream, FileEncrypter.ENCODING);

    final BufferedBlockCipher cipher = createCipher(tarInputStream);

    //Advance to the next entry in the tar file
    tarInputStream.getNextTarEntry();// ww w .ja  v  a2 s  . c  o m

    //Protect the underlying TAR stream from being closed by the cipher stream
    final CloseShieldInputStream is = new CloseShieldInputStream(tarInputStream);

    //Setup the decrypting cipher stream
    final CipherInputStream stream = new CipherInputStream(is, cipher);

    //Generate a digest of the decrypted data
    final GeneralDigest digest = this.createDigester();
    final DigestInputStream digestInputStream = new DigestInputStream(stream, digest);

    return new DecryptingInputStream(digestInputStream, tarInputStream, digest);
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java

private void extract(File aArchive, ArchiveInputStream aArchiveStream, File aTarget) throws IOException {
    ArchiveEntry entry = null;/*from ww w  . ja v  a  2  s .c om*/
    while ((entry = aArchiveStream.getNextEntry()) != null) {
        String name = entry.getName();

        // Ensure that the filename will not break the manifest
        if (name.contains("\n")) {
            throw new IllegalStateException("Filename must not contain line break");
        }

        File out = new File(aTarget, name);
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(out);
        } else {
            FileUtils.copyInputStreamToFile(new CloseShieldInputStream(aArchiveStream), out);
        }
    }
}

From source file:com.adobe.communities.ugc.migration.importer.ImportFileUploadServlet.java

private void saveExplodedFiles(final ResourceResolver resolver, final Resource folder, final JSONWriter writer,
        final ZipInputStream zipInputStream, final String basePath) throws ServletException {

    // we need the closeShieldInputStream to prevent the zipInputStream from being closed during resolver.create()
    final CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(zipInputStream);

    // fileResourceProperties and folderProperties will be reused inside the while loop
    final Map<String, Object> fileResourceProperties = new HashMap<String, Object>();
    fileResourceProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);

    final Map<String, Object> folderProperties = new HashMap<String, Object>();
    folderProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder");

    ZipEntry zipEntry;//from  w w  w  .ja v a 2s. c  o m
    try {
        zipEntry = zipInputStream.getNextEntry();
    } catch (final IOException e) {
        throw new ServletException("Unable to read entries from uploaded zip archive", e);
    }
    final List<Resource> toDelete = new ArrayList<Resource>();
    while (zipEntry != null) {
        // store files under the provided folder
        try {
            final String name = ResourceUtil.normalize("/" + zipEntry.getName());
            if (null == name) {
                // normalize filename and if they aren't inside upload path, don't store them
                continue;
            }
            Resource parent = folder;
            Resource subFolder = null;
            for (final String subFolderName : name.split("/")) {
                // check if the sub-folder already exists
                subFolder = resolver.getResource(parent, subFolderName);
                if (null == subFolder || subFolder instanceof NonExistingResource) {
                    // create the sub-folder
                    subFolder = resolver.create(parent, subFolderName, folderProperties);
                }
                parent = subFolder;
            }
            if (!zipEntry.isDirectory()) {
                // first represent the file as a resource
                final Resource file = resolver.create(subFolder, "file", fileResourceProperties);
                // now store its data as a jcr:content node
                final Map<String, Object> fileProperties = new HashMap<String, Object>();
                byte[] bytes = IOUtils.toByteArray(closeShieldInputStream);
                fileProperties.put(JcrConstants.JCR_DATA, new String(bytes, "UTF8"));
                fileProperties.put(JcrConstants.JCR_PRIMARYTYPE, "nt:resource");
                resolver.create(file, JcrConstants.JCR_CONTENT, fileProperties);

                // if provided a basePath, import immediately
                if (StringUtils.isNotBlank(basePath) && null != file
                        && !(file instanceof NonExistingResource)) {
                    Resource fileContent = file.getChild(JcrConstants.JCR_CONTENT);
                    if (null != fileContent && !(fileContent instanceof NonExistingResource)) {
                        final ValueMap contentVM = fileContent.getValueMap();
                        InputStream inputStream = (InputStream) contentVM.get(JcrConstants.JCR_DATA);
                        if (inputStream != null) {
                            final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
                            jsonParser.nextToken(); // get the first token
                            String resName = basePath + name.substring(0, name.lastIndexOf(".json"));
                            Resource resource = resolver.getResource(resName);
                            if (resource == null) {
                                // voting does not have a node under articles
                                resource = resolver.getResource(resName.substring(0, resName.lastIndexOf("/")));
                            }
                            try {
                                importFile(jsonParser, resource, resolver);
                                toDelete.add(file);
                            } catch (final Exception e) {
                                // add the file name to our response ONLY if we failed to import it
                                writer.value(name);
                                // we want to log the reason we weren't able to import, but don't stop importing
                                LOG.error(e.getMessage());
                            }
                        }
                    }
                } else if (StringUtils.isBlank(basePath) && null != file
                        && !(file instanceof NonExistingResource)) {
                    // add the file name to our response
                    writer.value(name);
                }
            }
            resolver.commit();
            zipEntry = zipInputStream.getNextEntry();
        } catch (final IOException e) {
            // convert any IOExceptions into ServletExceptions
            throw new ServletException(e.getMessage(), e);
        } catch (final JSONException e) {
            // convert any JSONExceptions into ServletExceptions
            throw new ServletException(e.getMessage(), e);
        }
    }
    closeShieldInputStream.close();
    // delete any files that were successfully imported
    if (!toDelete.isEmpty()) {
        for (final Resource deleteResource : toDelete) {
            deleteResource(deleteResource);
        }
    }
}

From source file:com.xpn.xwiki.plugin.packaging.Package.java

/**
 * Load this package in memory from an InputStream. It may be installed later using {@link #install(XWikiContext)}.
 * //  w  w w.  java  2s. c  o m
 * @param file an InputStream of a zipped package file
 * @param context current XWikiContext
 * @return an empty string, useless.
 * @throws IOException while reading the ZipFile
 * @throws XWikiException when package content is broken
 * @since 2.3M2
 */
public String Import(InputStream file, XWikiContext context) throws IOException, XWikiException {
    ZipInputStream zis = new ZipInputStream(file);
    ZipEntry entry;
    Document description = null;

    try {
        zis = new ZipInputStream(file);

        List<XWikiDocument> docsToLoad = new LinkedList<XWikiDocument>();
        /*
         * Loop 1: Cycle through the zip input stream and load out all of the documents, when we find the
         * package.xml file we put it aside to so that we only include documents which are in the file.
         */
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory() || (entry.getName().indexOf("META-INF") != -1)) {
                // The entry is either a directory or is something inside of the META-INF dir.
                // (we use that directory to put meta data such as LICENSE/NOTICE files.)
                continue;
            } else if (entry.getName().compareTo(DefaultPackageFileName) == 0) {
                // The entry is the manifest (package.xml). Read this differently.
                description = fromXml(new CloseShieldInputStream(zis));
            } else {
                XWikiDocument doc = null;
                try {
                    doc = readFromXML(new CloseShieldInputStream(zis));
                } catch (Throwable ex) {
                    LOGGER.warn("Failed to parse document [" + entry.getName()
                            + "] from XML during import, thus it will not be installed. " + "The error was: "
                            + ex.getMessage());
                    // It will be listed in the "failed documents" section after the import.
                    addToErrors(entry.getName().replaceAll("/", "."), context);

                    continue;
                }

                // Run all of the registered DocumentFilters on this document and
                // if no filters throw exceptions, add it to the list to import.
                try {
                    this.filter(doc, context);
                    docsToLoad.add(doc);
                } catch (ExcludeDocumentException e) {
                    LOGGER.info("Skip the document '" + doc.getDocumentReference() + "'");
                }
            }
        }
        // Make sure a manifest was included in the package...
        if (description == null) {
            throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN,
                    "Could not find the package definition");
        }
        /*
         * Loop 2: Cycle through the list of documents and if they are in the manifest then add them, otherwise log
         * a warning and add them to the skipped list.
         */
        for (XWikiDocument doc : docsToLoad) {
            if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) {
                this.add(doc, context);
            } else {
                LOGGER.warn("document " + doc.getDocumentReference() + " does not exist in package definition."
                        + " It will not be installed.");
                // It will be listed in the "skipped documents" section after the
                // import.
                addToSkipped(doc.getFullName(), context);
            }
        }

        updateFileInfos(description);
    } catch (DocumentException e) {
        throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Error when reading the XML");
    }

    return "";
}