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

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

Introduction

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

Prototype

public AutoCloseInputStream(InputStream in) 

Source Link

Document

Creates an automatically closing proxy for the given input stream.

Usage

From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java

@Override
public SecurityComponents createSecurityComponents() {
    Binding binding = new Binding();
    binding.setVariable("instance", this);

    BeanBuilder builder = new BeanBuilder(Jenkins.getInstance().pluginManager.uberClassLoader);

    String fileName;//from   w ww  . j a v  a  2  s.c om
    if (getLDAPURL() != null) {
        fileName = "ReverseProxyLDAPSecurityRealm.groovy";
    } else {
        fileName = "ReverseProxySecurityRealm.groovy";
    }

    try {
        File override = new File(Jenkins.getInstance().getRootDir(), fileName);
        builder.parse(override.exists() ? new AutoCloseInputStream(new FileInputStream(override))
                : getClass().getResourceAsStream(fileName), binding);
    } catch (FileNotFoundException e) {
        throw new Error("Failed to load " + fileName, e);
    }
    WebApplicationContext appContext = builder.createApplicationContext();

    if (getLDAPURL() == null) {
        proxyTemplate = new ReverseProxySearchTemplate();

        return new SecurityComponents(findBean(AuthenticationManager.class, appContext),
                new ReverseProxyUserDetailsService(appContext));
    } else {
        ldapTemplate = new LdapTemplate(findBean(InitialDirContextFactory.class, appContext));

        if (groupMembershipFilter != null || groupNameAttribute != null) {
            ProxyLDAPAuthoritiesPopulator authoritiesPopulator = findBean(ProxyLDAPAuthoritiesPopulator.class,
                    appContext);
            if (groupMembershipFilter != null) {
                authoritiesPopulator.setGroupSearchFilter(groupMembershipFilter);
            }
            if (groupNameAttribute != null) {
                authoritiesPopulator.setGroupRoleAttribute(groupNameAttribute);
            }
        }

        return new SecurityComponents(findBean(AuthenticationManager.class, appContext),
                new ProxyLDAPUserDetailsService(this, appContext));
    }
}

From source file:org.metaeffekt.dcc.agent.AgentRouteBuilder.java

@Override
public void configure() throws Exception {

    DeploymentBasedEndpointUriBuilder deploymentBasedEndpointUriBuilder = new DeploymentBasedEndpointUriBuilder();
    UnitBasedEndpointUriBuilder unitBasedEndpointUriBuilder = new UnitBasedEndpointUriBuilder();
    HostBasedEndpointUriBuilder hostBasedEndpointUriBuilder = new HostBasedEndpointUriBuilder();

    // FIXME JKO does not fit into our URI pattern, resource for Browser usage, move to different RouteBuilder
    from("resource:" + DccAgentEndpoint.PATH_ROOT + "/logs/{logId}?restletMethod=GET").routeId("log")
            .routePolicy(getRoutePolicy()).process(new Processor() {
                // NOTE: the standard agent logs are deploymentId unspecific. To address the logs
                //   inside a deployment part an additional endpoint may be required.
                @Override//from w  ww  .  j ava2s.c o  m
                public void process(Exchange exchange) throws Exception {
                    String logId = notNull((String) exchange.getIn().getHeader("logId"), "logId");

                    // backward compatibility: wrapper.log renamed to dcc-agent-service.log
                    if (logId != null && logId.equals("wrapper.log")) {
                        logId = "dcc-agent-service.log";
                    }

                    if (logId.contains("..")) {
                        throw new IllegalStateException("Leaving log file context is not allowed: " + logId);
                    }

                    LOG.info("Received GET request for [logs] with id [{}].", logId);
                    File logFile = new File(System.getProperty(DccAgent.DCC_AGENT_HOME), "logs/" + logId);
                    if (logFile.exists()) {
                        exchange.getOut().setBody(new AutoCloseInputStream(new FileInputStream(logFile)));
                    }
                }
            });

    from(hostBasedEndpointUriBuilder.buildRestletResourceUri(LOGS)).routeId(LOGS.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received GET request for [logs].");
                    throw new UnsupportedOperationException("Non! Si! Ohhh!");
                }
            });

    from(hostBasedEndpointUriBuilder.buildRestletResourceUri(VERSION)).routeId(VERSION.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received GET request for [version].");
                    exchange.getOut().setBody(version);
                }
            });

    from(deploymentBasedEndpointUriBuilder.buildRestletResourceUri(STATE)).routeId(STATE.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received GET request for [state].");
                    Id<DeploymentId> deploymentId = extractDeploymentId(exchange);
                    exchange.getOut().setBody(remoteScriptExecutor.getExecutionStateHandler(deploymentId)
                            .consolidateState(deploymentId));
                }
            });

    from(deploymentBasedEndpointUriBuilder.buildRestletResourceUri(INITIALIZE)).routeId(INITIALIZE.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received PUT request for [initialize].");

                    Id<DeploymentId> deploymentId = extractDeploymentId(exchange);

                    // execute an implicit clean
                    remoteScriptExecutor.cleanFilesystemLocations(extractDeploymentId(exchange));

                    // ensure the file system is as required
                    remoteScriptExecutor.prepareFilesystemLocations(deploymentId);
                    prepareSolutionLocation(exchange);

                    // currently no properties are passed on from the shell. To persist a state
                    // we create one with the appropriate name.
                    File executionPropertiesFile = createInitializeExecutionProperties(exchange,
                            INITIALIZE.toString());
                    remoteScriptExecutor.getExecutionStateHandler(deploymentId)
                            .persistStateAfterSuccessfulExecution(deploymentId, INITIALIZE,
                                    executionPropertiesFile);
                }
            });

    from(deploymentBasedEndpointUriBuilder.buildRestletResourceUri(CLEAN)).routeId(CLEAN.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received PUT request for [clean].");
                    remoteScriptExecutor.cleanFilesystemLocations(extractDeploymentId(exchange));
                }
            });

    from(deploymentBasedEndpointUriBuilder.buildRestletResourceUri(PURGE)).routeId(PURGE.toString())
            .routePolicy(getRoutePolicy()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    LOG.info("Received PUT request for [purge].");
                    remoteScriptExecutor.purgeFilesystemLocations(extractDeploymentId(exchange));
                }
            });

    from(unitBasedEndpointUriBuilder.buildRestletResourceUri()).routeId("execute").routePolicy(getRoutePolicy())
            .process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    String commandString = notNull((String) exchange.getIn().getHeader(COMMAND), COMMAND);
                    Id<PackageId> packageId = extractPackageId(exchange);
                    Id<UnitId> unitId = extractUnitId(exchange);
                    Id<DeploymentId> deploymentId = extractDeploymentId(exchange);
                    final Map<String, File> properties = dropOffProperties(exchange);
                    File executionPropertiesFile = properties.get(DccConstants.COMMAND_PROPERTIES);
                    File prerequisitesPropertiesFile = properties.get(DccConstants.PREREQUISITES_PROPERTIES);

                    remoteScriptExecutor.executeScript(deploymentId, packageId, unitId, commandString,
                            executionPropertiesFile, prerequisitesPropertiesFile);
                }
            });
}

From source file:org.metaeffekt.dcc.commons.execution.ExecutionStateHandler.java

/**
 * Collect all execution properties files in the ${dcc.solution.dir}/config directory into a zip
 * file and return it as an InputStream/*from w  w  w .j a va  2  s.com*/
 *
 * @return An InputStream
 */
public InputStream consolidateState(Id<DeploymentId> deploymentId) {
    Validate.notNull(deploymentId);
    Validate.notNull(deploymentId.getValue());

    LOG.debug("Collecting all execution properties to create consolidated state.");

    // FIXME: this collects also properties in the tmp structures
    Collection<File> allExecutionProperties = Collections.emptyList();
    if (configurationDirectory.exists()) {
        allExecutionProperties = FileUtils.listFiles(configurationDirectory, new String[] { "properties" },
                true);
    }

    if (allExecutionProperties.size() > 0) {
        final URI configurationFolderURI = configurationDirectory.toURI();
        try {
            final File targetFile = new File(configurationDirectory, ZIP_FILE_NAME);
            deleteFile(targetFile);
            try (OutputStream out = new FileOutputStream(targetFile);
                    ZipOutputStream zos = new ZipOutputStream(out)) {
                for (File file : allExecutionProperties) {
                    String name = configurationFolderURI.relativize(file.toURI()).getPath();
                    LOG.debug("Found [{}]", name);
                    if (name.contains("/tmp/") || name.contains("\\tmp\\")) {
                        // FIXME: we should move the tmp folder out of the config folder
                        LOG.debug("Skipping [{}] as it is included in a tmp folder", name);
                    } else {
                        zos.putNextEntry(new ZipEntry(name));
                        try (FileInputStream fis = new FileInputStream(file)) {
                            IOUtils.copy(fis, zos);
                        }
                    }
                }
                zos.finish();
            }
            if (targetFile.exists()) {
                AutoCloseInputStream autoCloseStream = new AutoCloseInputStream(
                        new FileInputStream(targetFile)) {
                    @Override
                    public void close() throws IOException {
                        super.close();
                        targetFile.delete();
                    }
                };
                return autoCloseStream;
            }

            // no state produced
            return null;
        } catch (IOException e) {
            throw new IllegalStateException("Error while updating execution status:", e);
        }
    }
    return null;
}

From source file:org.n52.oxf.adapter.OperationResult.java

public InputStream getIncomingResultAsAutoCloseStream() {
    return new AutoCloseInputStream(new ByteArrayInputStream(incomingResult));
}

From source file:org.n52.sps.control.admin.AdminControl.java

private XmlObject parseIncomingXmlObject(InputStream payload) throws XmlException, IOException {
    // fixes https://issues.apache.org/jira/browse/XMLBEANS-226
    // @see http://commons.apache.org/io/api-release/org/apache/commons/io/input/AutoCloseInputStream.html
    XmlObject request = XmlObject.Factory.parse(new AutoCloseInputStream(payload));
    return request;
}

From source file:org.n52.sps.control.xml.XmlController.java

private XmlObject parseIncomingXmlObject(InputStream payload) throws XmlException, IOException {
    // @see https://issues.apache.org/jira/browse/XMLBEANS-226
    // @see http://commons.apache.org/io/api-release/org/apache/commons/io/input/AutoCloseInputStream.html
    return XmlObject.Factory.parse(new AutoCloseInputStream(payload));
}

From source file:org.obm.sync.login.LDAPLoginIntegrationTest.java

private void loadLdifBootstrap(String file) throws Exception {
    Entry entry;//from ww  w  .  j  av a  2 s  .  co m
    LDIFReader reader = new LDIFReader(new LDIFImportConfig(
            new AutoCloseInputStream(ClassLoader.getSystemClassLoader().getResourceAsStream(file))));

    while ((entry = reader.readEntry()) != null) {
        addEntry(entry);
    }
}

From source file:org.owasp.dependencycheck.analyzer.PythonDistributionAnalyzer.java

/**
 * Reads the manifest entries from the provided file.
 *
 * @param manifest the manifest//from   w  w  w .ja v a 2s .  c  o  m
 * @return the manifest entries
 */
private static InternetHeaders getManifestProperties(File manifest) {
    final InternetHeaders result = new InternetHeaders();
    if (null == manifest) {
        LOGGER.debug("Manifest file not found.");
    } else {
        try {
            result.load(new AutoCloseInputStream(new BufferedInputStream(new FileInputStream(manifest))));
        } catch (MessagingException e) {
            LOGGER.warn(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.wso2.carbon.connector.util.ResultPayloadCreate.java

/**
 * @param file        Read file//from  ww  w .  jav a2  s  . c  o m
 * @param msgCtx      Message Context
 * @param contentType content type
 * @param streaming   streaming mode (true/false)
 * @return return the status
 * @throws SynapseException
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType)
        throws SynapseException {
    ManagedDataSource dataSource = null;
    try {
        if (StringUtils.isEmpty(contentType) || StringUtils.isEmpty(contentType.trim())) {
            if (file.getName().getExtension().toLowerCase().endsWith("xml")) {
                contentType = "application/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                charSetEnc = new ContentType(contentType).getParameter("charset");
            } catch (ParseException ex) {
                log.warn("Invalid encoding type.", ex);
            }
            msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (StringUtils.isEmpty(contentType)) {
            log.debug("No content type specified. Using RELAY builder.");
            builder = new BinaryRelayBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back " + "to"
                            + " RELAY builder.");
                }
                builder = new BinaryRelayBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in = null;
        in = new AutoCloseInputStream(file.getContent().getInputStream());
        dataSource = null;

        // Inject the message to the sequence.
        OMElement documentElement;
        if (in != null) {
            documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
        } else {
            documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                    axis2MsgCtx);
        }
        //We need this to build the complete message before closing the stream
        //noinspection ResultOfMethodCallIgnored
        documentElement.toString();
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
    } catch (SynapseException se) {
        throw se;
    } catch (Exception e) {
        log.error("Error while processing the file/folder", e);
        throw new SynapseException("Error while processing the file/folder", e);
    } finally {
        if (dataSource != null) {
            dataSource.destroy();
        }
    }
    return true;
}

From source file:org.wso2.carbon.connector.util.ResultPayloadCreater.java

public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType, String streaming)
        throws SynapseException {
    ManagedDataSource dataSource = null;
    try {/*w w  w.  j  a v  a 2 s.  c  o m*/
        if (contentType == null || contentType.trim().equals("")) {
            if (file.getName().getExtension().toLowerCase().endsWith("xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                log.warn("Invalid encoding type.", ex);
            }
            msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using RELAY builder.");
            builder = new BinaryRelayBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "No message builder found for type '" + type + "'. Falling back to RELAY builder.");
                }
                builder = new BinaryRelayBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        if (builder instanceof DataSourceMessageBuilder && "true".equals(streaming)) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(file.getContent().getInputStream());
            dataSource = null;
        }

        // Inject the message to the sequence.

        OMElement documentElement;
        if (in != null) {
            documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
        } else {
            documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                    axis2MsgCtx);
        }

        //We need this to build the complete message before closing the stream
        documentElement.toString();

        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

    } catch (SynapseException se) {
        throw se;
    } catch (Exception e) {
        log.error("Error while processing the file/folder", e);
        throw new SynapseException("Error while processing the file/folder", e);
    } finally {
        if (dataSource != null) {
            dataSource.destroy();
        }
    }
    return true;
}