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:org.sonatype.nexus.proxy.SimplePullTest.java

/**
 * NXCM-4582: When Local storage is about to store something, but during "store" operation source stream EOFs, the
 * new LocalStorage exception should be thrown, to differentiate from other "fatal" (like disk full or what not)
 * error.//from   w  w  w.j  ava 2  s  .  co  m
 */
@Test
public void testNXCM4852() throws Exception {
    final Repository repository = getRepositoryRegistry().getRepository("inhouse");
    final ResourceStoreRequest request = new ResourceStoreRequest(
            "/activemq/activemq-core/1.2/activemq-core-1.2.jar", true);

    try {
        repository.storeItem(request,
                new FilterInputStream(new ByteArrayInputStream("123456789012345678901234567890".getBytes())) {
                    @Override
                    public int read() throws IOException {
                        int result = super.read();
                        if (result == -1) {
                            throw new EOFException("Foo");
                        } else {
                            return result;
                        }
                    }

                    @Override
                    public int read(final byte[] b, final int off, final int len) throws IOException {
                        int result = super.read(b, off, len);
                        if (result == -1) {
                            throw new EOFException("Foo");
                        }
                        return result;
                    }
                }, null);

        fail("We expected a LocalStorageEofException to be thrown");
    } catch (LocalStorageEOFException e) {
        // good, we expected this
    } finally {
        // now we have to ensure no remnant files exists
        assertThat(repository.getLocalStorage().containsItem(repository, request), is(false));
        // no tmp files should exists either
        assertThat(repository.getLocalStorage().listItems(repository, new ResourceStoreRequest("/.nexus/tmp")),
                is(empty()));
    }
}

From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java

/**
 * {@inheritDoc}/*from w w w . j a va  2s  .c  o  m*/
 */
public InputStream getInputStream(String filePath) throws FileSystemException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    FileSystemPathUtil.checkFormat(filePath);

    String parentDir = FileSystemPathUtil.getParentDir(filePath);
    String name = FileSystemPathUtil.getName(filePath);

    synchronized (selectDataSQL) {
        try {
            Statement stmt = executeStmt(selectDataSQL, new Object[] { parentDir, name });

            final ResultSet rs = stmt.getResultSet();
            if (!rs.next()) {
                throw new FileSystemException("no such file: " + filePath);
            }
            InputStream in = rs.getBinaryStream(1);
            /**
             * return an InputStream wrapper in order to
             * close the ResultSet when the stream is closed
             */
            return new FilterInputStream(in) {
                public void close() throws IOException {
                    super.close();
                    // close ResultSet
                    closeResultSet(rs);
                }
            };
        } catch (SQLException e) {
            String msg = "failed to retrieve data of file: " + filePath;
            log.error(msg, e);
            throw new FileSystemException(msg, e);
        }
    }
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException {

    final InputStream inputStream;

    if (response.getEntity() == null) {
        inputStream = new ByteArrayInputStream(new byte[0]);
    } else {//from  www  . j av  a  2  s  . c  om
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported()) {
            inputStream = i;
        } else {
            inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
        }
    }

    return new FilterInputStream(inputStream) {
        @Override
        public void close() throws IOException {
            response.close();
            super.close();
        }
    };
}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * Opens a input stream for the indicated file. A read lock is requested at the method call and
 * released on close./*from  w  ww. j  a va2 s .  c  o m*/
 * 
 * @param type
 *           the type of file to open the stream to.
 * @param requestor
 *           the object requesting the stream
 * @return an input stream
 * 
 * @throws IOException
 *            if a problem occurred opening the stream.
 */
public InputStream getInputStream(ShpFileType type, final FileReader requestor) throws IOException {
    final URL url = acquireRead(type, requestor);

    try {
        FilterInputStream input = new FilterInputStream(url.openStream()) {

            private volatile boolean closed = false;

            @Override
            public void close() throws IOException {
                try {
                    super.close();
                } finally {
                    if (!closed) {
                        closed = true;
                        unlockRead(url, requestor);
                    }
                }
            }

        };
        return input;
    } catch (Throwable e) {
        unlockRead(url, requestor);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof Error) {
            throw (Error) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException {

    final InputStream inputStream;

    // DK_CLD: do not forward the entity stream to Jersey if the connection has been upgraded. This prevent any
    // component of trying to reading it, which likely result in unexpected result or even deadlock.
    if (response.getEntity() == null) {
        inputStream = new ByteArrayInputStream(new byte[0]);
    } else {/*from ww  w.  j av  a  2  s .  c o m*/
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported()) {
            inputStream = i;
        } else {
            inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
        }
    }

    return new FilterInputStream(inputStream) {
        @Override
        public void close() throws IOException {
            response.close();
            super.close();
        }
    };
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

private InputStream createConnectionReleasingInputStream(final HttpMethodBase method) throws IOException {
    return new FilterInputStream(method.getResponseBodyAsStream()) {
        @Override//from   w  w  w .j  av  a 2 s.  c  om
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                method.releaseConnection();
            }
        }
    };
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SPDocument.java

/**
 * For downloading the contents of the documents using its URL. Used with
 * content feeds only./* www . j a  v a 2  s  .c  om*/
 *
 * @return {@link SPContent} containing the status, content type and
 *    content stream.
 * @throws RepositoryException
 */
@VisibleForTesting
SPContent downloadContents() throws RepositoryException {
    InputStream docContentStream = null;
    String docContentType = null;

    if (null == sharepointClientContext) {
        LOGGER.log(Level.SEVERE,
                "Failed to download document content because the connector context is not found!");
        return new SPContent(SPConstants.CONNECTIVITY_FAIL, docContentType, docContentStream);
    }
    LOGGER.config("Document URL [ " + contentDwnldURL + " is getting processed for contents");
    if (isEmptyDocument()) {
        LOGGER.config("Document URL [" + contentDwnldURL + "] is empty document");
        return new SPContent("empty", docContentType, docContentStream);
    }
    int responseCode = 0;
    boolean downloadContent = true;
    if (getFileSize() > 0 && sharepointClientContext.getTraversalContext() != null) {
        if (getFileSize() > sharepointClientContext.getTraversalContext().maxDocumentSize()) {
            // Set the flag to download content to be false so that no
            // content is downloaded as the CM itself will drop it.
            downloadContent = false;
            LOGGER.log(Level.WARNING,
                    "Dropping content of document : " + getUrl() + " with docId : " + docId + " of size "
                            + getFileSize() + " as it exceeds the allowed max document size "
                            + sharepointClientContext.getTraversalContext().maxDocumentSize());
        }
    }
    if (downloadContent) {
        final String docURL = Util.encodeURL(contentDwnldURL);
        final HttpMethodBase method;
        try {
            method = new GetMethod(docURL);
            responseCode = sharepointClientContext.checkConnectivity(docURL, method);
            if (responseCode != 200) {
                LOGGER.warning("Unable to get contents for document '" + getUrl()
                        + "'. Received the response code: " + responseCode);
                return new SPContent(Integer.toString(responseCode), responseCode, docContentType,
                        docContentStream);
            }

            InputStream contentStream = method.getResponseBodyAsStream();
            if (contentStream != null) {
                docContentStream = new FilterInputStream(contentStream) {
                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                        } finally {
                            method.releaseConnection();
                        }
                    }
                };
            }
        } catch (Throwable t) {
            String msg = new StringBuffer("Unable to fetch contents from URL: ").append(url).toString();
            LOGGER.log(Level.WARNING, "Unable to fetch contents from URL: " + url, t);
            throw new RepositoryDocumentException(msg, t);
        }
        // checks if the give URL is for .msg file if true set the mimetype
        // directly to application/vnd.ms-outlook as mimetype returned by the
        // header is incorrect for .msg files
        if (!contentDwnldURL.endsWith(MSG_FILE_EXTENSION)) {
            final Header contentType = method.getResponseHeader(SPConstants.CONTENT_TYPE_HEADER);
            if (contentType != null) {
                docContentType = contentType.getValue();
            } else {
                LOGGER.info("The content type returned for doc : " + toString() + " is : null ");
            }
        } else {
            docContentType = MSG_FILE_MIMETYPE;
        }

        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.fine("The content type for doc : " + toString() + " is : " + docContentType);
        }

        if (sharepointClientContext.getTraversalContext() != null && docContentType != null) {
            // TODO : This is to be revisited later where a better
            // approach to skip documents or only content is
            // available
            int mimeTypeSupport = sharepointClientContext.getTraversalContext()
                    .mimeTypeSupportLevel(docContentType);
            if (mimeTypeSupport == 0) {
                docContentStream = null;
                LOGGER.log(Level.WARNING, "Dropping content of document : " + getUrl() + " with docId : "
                        + docId + " as the mimetype : " + docContentType + " is not supported");
            } else if (mimeTypeSupport < 0) {
                // Since the mimetype is in list of 'ignored' mimetype
                // list, mark it to be skipped from sending
                String msg = new StringBuffer("Skipping the document with docId : ").append(getDocId())
                        .append(" doc URL: ").append(getUrl())
                        .append(" as the mimetype is in the 'ignored' mimetypes list ").toString();
                // Log it to the excluded_url log
                sharepointClientContext.logExcludedURL(msg);
                throw new SkippedDocumentException(msg);
            }
        }
    }

    return new SPContent(SPConstants.CONNECTIVITY_SUCCESS, responseCode, docContentType, docContentStream);
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

private InputStream createConnectionReleasingInputStream(final HttpMethodBase method) throws IOException {
    return new FilterInputStream(method.getResponseBodyAsStream()) {
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                method.releaseConnection();
            }/*from   ww w  .ja  v a 2 s  .  c om*/
        }
    };
}

From source file:davmail.exchange.ews.EWSMethod.java

protected void processResponseStream(InputStream inputStream) {
    responseItems = new ArrayList<Item>();
    XMLStreamReader reader = null;
    try {//from  w ww . j  a v a  2s. c  o m
        inputStream = new FilterInputStream(inputStream) {
            int totalCount;
            int lastLogCount;

            @Override
            public int read(byte[] buffer, int offset, int length) throws IOException {
                int count = super.read(buffer, offset, length);
                totalCount += count;
                if (totalCount - lastLogCount > 1024 * 128) {
                    DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS",
                            String.valueOf(totalCount / 1024), EWSMethod.this.getURI()));
                    DavGatewayTray.switchIcon();
                    lastLogCount = totalCount;
                }
                return count;
            }
        };
        reader = XMLStreamUtil.createXMLStreamReader(inputStream);
        while (reader.hasNext()) {
            reader.next();
            handleErrors(reader);
            if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) {
                String majorVersion = getAttributeValue(reader, "MajorVersion");
                if ("14".equals(majorVersion)) {
                    String minorVersion = getAttributeValue(reader, "MinorVersion");
                    if ("0".equals(minorVersion)) {
                        serverVersion = "Exchange2010";
                    } else {
                        serverVersion = "Exchange2010_SP1";
                    }
                } else {
                    serverVersion = "Exchange2007_SP1";
                }
            } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) {
                includesLastItemInRange = "true"
                        .equals(reader.getAttributeValue(null, "IncludesLastItemInRange"));
            } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) {
                handleItems(reader);
            } else {
                handleCustom(reader);
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error("Error while parsing soap response: " + e, e);
        if (reader != null) {
            try {
                LOGGER.error("Current text: " + reader.getText());
            } catch (IllegalStateException ise) {
                LOGGER.error(e + " " + e.getMessage());
            }
        }
    }
    if (errorDetail != null) {
        LOGGER.debug(errorDetail);
    }
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

@Override
public void generateEsbFiles() throws ProcessorException {
    List<? extends INode> graphicalNodes = process.getGraphicalNodes(); // process.getGeneratingNodes();

    try {/*from   w w  w.  ja  v  a2s  . c o  m*/
        IPath jobPackagePath = getSrcCodePath().removeLastSegments(1);
        IFolder jobPackageFolder = this.getCodeProject().getFolder(jobPackagePath);
        IFolder wsdlsPackageFolder = jobPackageFolder.getFolder("wsdl"); //$NON-NLS-1$
        if (wsdlsPackageFolder.exists()) {
            wsdlsPackageFolder.delete(true, null);
        }

        for (INode node : graphicalNodes) {
            if ("tESBConsumer".equals(node.getComponent().getName()) && node.isActivate()) { //$NON-NLS-1$
                // retrieve WSDL content (compressed-n-encoded) -> zip-content.-> wsdls.(first named main.wsdl)
                String wsdlContent = (String) node.getPropertyValue("WSDL_CONTENT"); //$NON-NLS-1$
                String uniqueName = node.getUniqueName();
                if (null != uniqueName && null != wsdlContent && !wsdlContent.trim().isEmpty()) {

                    // configure decoding and uncompressing
                    InputStream wsdlStream = new BufferedInputStream(new InflaterInputStream(
                            new Base64InputStream(new ByteArrayInputStream(wsdlContent.getBytes()))));

                    if (!wsdlsPackageFolder.exists()) {
                        wsdlsPackageFolder.create(true, true, null);
                    }
                    // generate WSDL file
                    if (checkIsZipStream(wsdlStream)) {

                        ZipInputStream zipIn = new ZipInputStream(wsdlStream);
                        ZipEntry zipEntry = null;

                        while ((zipEntry = zipIn.getNextEntry()) != null) {
                            String outputName = zipEntry.getName();
                            if ("main.wsdl".equals(outputName)) { //$NON-NLS-1$
                                outputName = uniqueName + ".wsdl"; //$NON-NLS-1$
                            }
                            IFile wsdlFile = wsdlsPackageFolder.getFile(outputName);
                            if (!wsdlFile.exists()) {
                                // cause create file will do a close. add a warp to ignore close.
                                InputStream unCloseIn = new FilterInputStream(zipIn) {

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

                                wsdlFile.create(unCloseIn, true, null);
                            }
                            zipIn.closeEntry();
                        }
                        zipIn.close();
                    } else {
                        IFile wsdlFile = wsdlsPackageFolder.getFile(uniqueName + ".wsdl"); //$NON-NLS-1$
                        wsdlFile.create(wsdlStream, true, null);
                    }
                }
            }
        }
    } catch (CoreException e) {
        if (e.getStatus() != null && e.getStatus().getException() != null) {
            ExceptionHandler.process(e.getStatus().getException());
        }
        throw new ProcessorException(Messages.getString("Processor.tempFailed"), e); //$NON-NLS-1$
    } catch (IOException e) {
        throw new ProcessorException(Messages.getString("Processor.tempFailed"), e); //$NON-NLS-1$
    }

    boolean samEnabled = false;
    boolean slEnabled = false;
    for (INode node : graphicalNodes) {
        if (node.isActivate()) {
            final String nodeName = node.getComponent().getName();
            Object slValue = null, samValue = null;
            if ("tESBConsumer".equals(nodeName) //$NON-NLS-1$
                    || "tRESTClient".equals(nodeName) //$NON-NLS-1$
                    || "tRESTRequest".equals(nodeName) //$NON-NLS-1$
                    || "cCXFRS".equals(nodeName)) { //$NON-NLS-1$
                if (!slEnabled) {
                    slValue = node.getPropertyValue("SERVICE_LOCATOR"); //$NON-NLS-1$
                }
                if (!samEnabled) {
                    samValue = node.getPropertyValue("SERVICE_ACTIVITY_MONITOR"); //$NON-NLS-1$
                }
            } else if ("cCXF".equals(nodeName)) { //$NON-NLS-1$
                if (!slEnabled) {
                    slValue = node.getPropertyValue("ENABLE_SL"); //$NON-NLS-1$
                }
                if (!samEnabled) {
                    samValue = node.getPropertyValue("ENABLE_SAM"); //$NON-NLS-1$
                }
            }
            if (null != slValue) {
                slEnabled = (Boolean) slValue;
            }
            if (null != samValue) {
                samEnabled = (Boolean) samValue;
            }
            if (samEnabled && slEnabled) {
                break;
            }
        }
    }

    if (samEnabled || slEnabled) {
        File esbConfigsSourceFolder = EsbConfigUtils.getEclipseEsbFolder();
        if (!esbConfigsSourceFolder.exists()) {
            RunProcessPlugin.getDefault().getLog()
                    .log(new Status(IStatus.WARNING,
                            RunProcessPlugin.getDefault().getBundle().getSymbolicName(),
                            "ESB configuration folder does not exists - " + esbConfigsSourceFolder.toURI())); //$NON-NLS-1$
            return;
        }
        ITalendProcessJavaProject tProcessJvaProject = this.getTalendJavaProject();
        if (tProcessJvaProject == null) {
            return;
        }
        IFolder esbConfigsTargetFolder = tProcessJvaProject.getResourcesFolder();

        // add SAM config file to classpath
        if (samEnabled) {
            copyEsbConfigFile(esbConfigsSourceFolder, esbConfigsTargetFolder, "agent.properties"); //$NON-NLS-1$
        }

        // add SL config file to classpath
        if (slEnabled) {
            copyEsbConfigFile(esbConfigsSourceFolder, esbConfigsTargetFolder, "locator.properties"); //$NON-NLS-1$
        }
    }
}