Search in sources :

Example 91 with Closeable

use of java.io.Closeable in project wildfly by wildfly.

the class RaOperationUtil method installRaServicesAndDeployFromModule.

public static void installRaServicesAndDeployFromModule(OperationContext context, String name, ModifiableResourceAdapter resourceAdapter, String fullModuleName, final List<ServiceController<?>> newControllers) throws OperationFailedException {
    ServiceName raServiceName = installRaServices(context, name, resourceAdapter, newControllers);
    final boolean resolveProperties = true;
    final ServiceTarget serviceTarget = context.getServiceTarget();
    final String moduleName;
    //load module
    String slot = "main";
    if (fullModuleName.contains(":")) {
        slot = fullModuleName.substring(fullModuleName.indexOf(":") + 1);
        moduleName = fullModuleName.substring(0, fullModuleName.indexOf(":"));
    } else {
        moduleName = fullModuleName;
    }
    Module module;
    try {
        ModuleIdentifier moduleId = ModuleIdentifier.create(moduleName, slot);
        module = Module.getCallerModuleLoader().loadModule(moduleId);
    } catch (ModuleLoadException e) {
        throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToLoadModuleRA(moduleName), e);
    }
    URL path = module.getExportedResource("META-INF/ra.xml");
    Closeable closable = null;
    try {
        VirtualFile child;
        if (path.getPath().contains("!")) {
            throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.compressedRarNotSupportedInModuleRA(moduleName));
        } else {
            child = VFS.getChild(path.getPath().split("META-INF")[0]);
            closable = VFS.mountReal(new File(path.getPath().split("META-INF")[0]), child);
        }
        //final Closeable closable = VFS.mountZip((InputStream) new JarInputStream(new FileInputStream(path.getPath().split("!")[0].split(":")[1])), path.getPath().split("!")[0].split(":")[1], child, TempFileProviderService.provider());
        final MountHandle mountHandle = new MountHandle(closable);
        final ResourceRoot resourceRoot = new ResourceRoot(child, mountHandle);
        final VirtualFile deploymentRoot = resourceRoot.getRoot();
        if (deploymentRoot == null || !deploymentRoot.exists())
            return;
        ConnectorXmlDescriptor connectorXmlDescriptor = RaDeploymentParsingProcessor.process(resolveProperties, deploymentRoot, null, name);
        IronJacamarXmlDescriptor ironJacamarXmlDescriptor = IronJacamarDeploymentParsingProcessor.process(deploymentRoot, resolveProperties);
        RaNativeProcessor.process(deploymentRoot);
        Map<ResourceRoot, Index> annotationIndexes = new HashMap<ResourceRoot, Index>();
        ResourceRootIndexer.indexResourceRoot(resourceRoot);
        Index index = resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX);
        if (index != null) {
            annotationIndexes.put(resourceRoot, index);
        }
        if (ironJacamarXmlDescriptor != null) {
            ConnectorLogger.SUBSYSTEM_RA_LOGGER.forceIJToNull();
            ironJacamarXmlDescriptor = null;
        }
        final ServiceName deployerServiceName = ConnectorServices.RESOURCE_ADAPTER_DEPLOYER_SERVICE_PREFIX.append(connectorXmlDescriptor.getDeploymentName());
        final ServiceController<?> deployerService = context.getServiceRegistry(true).getService(deployerServiceName);
        if (deployerService == null) {
            ServiceBuilder builder = ParsedRaDeploymentProcessor.process(connectorXmlDescriptor, ironJacamarXmlDescriptor, module.getClassLoader(), serviceTarget, annotationIndexes, RAR_MODULE.append(name), null, null);
            newControllers.add(builder.addDependency(raServiceName).setInitialMode(ServiceController.Mode.ACTIVE).install());
        }
        String rarName = resourceAdapter.getArchive();
        if (fullModuleName.equals(rarName)) {
            ServiceName serviceName = ConnectorServices.INACTIVE_RESOURCE_ADAPTER_SERVICE.append(name);
            InactiveResourceAdapterDeploymentService service = new InactiveResourceAdapterDeploymentService(connectorXmlDescriptor, module, name, name, RAR_MODULE.append(name), null, serviceTarget, null);
            newControllers.add(serviceTarget.addService(serviceName, service).setInitialMode(ServiceController.Mode.ACTIVE).install());
        }
    } catch (Exception e) {
        throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToLoadModuleRA(moduleName), e);
    } finally {
        if (closable != null) {
            try {
                closable.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : ModuleLoadException(org.jboss.modules.ModuleLoadException) VirtualFile(org.jboss.vfs.VirtualFile) InactiveResourceAdapterDeploymentService(org.jboss.as.connector.services.resourceadapters.deployment.InactiveResourceAdapterDeploymentService) MountHandle(org.jboss.as.server.deployment.module.MountHandle) HashMap(java.util.HashMap) ServiceTarget(org.jboss.msc.service.ServiceTarget) Closeable(java.io.Closeable) OperationFailedException(org.jboss.as.controller.OperationFailedException) ConnectorXmlDescriptor(org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor) Index(org.jboss.jandex.Index) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) OperationFailedException(org.jboss.as.controller.OperationFailedException) ModuleLoadException(org.jboss.modules.ModuleLoadException) ValidateException(org.jboss.jca.common.api.validator.ValidateException) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) ResourceRoot(org.jboss.as.server.deployment.module.ResourceRoot) ServiceName(org.jboss.msc.service.ServiceName) ModuleIdentifier(org.jboss.modules.ModuleIdentifier) IronJacamarXmlDescriptor(org.jboss.as.connector.metadata.xmldescriptors.IronJacamarXmlDescriptor) Module(org.jboss.modules.Module) File(java.io.File) VirtualFile(org.jboss.vfs.VirtualFile)

Example 92 with Closeable

use of java.io.Closeable in project wildfly by wildfly.

the class JaxrsSpringProcessor method getResteasySpringVirtualFile.

/**
     * Lookup Seam integration resource loader.
     *
     * @return the Seam integration resource loader
     * @throws DeploymentUnitProcessingException
     *          for any error
     */
protected synchronized VirtualFile getResteasySpringVirtualFile() throws DeploymentUnitProcessingException {
    if (resourceRoot != null) {
        return resourceRoot;
    }
    try {
        Module module = Module.getBootModuleLoader().loadModule(MODULE);
        URL fileUrl = module.getClassLoader().getResource(JAR_LOCATION);
        if (fileUrl == null) {
            throw JaxrsLogger.JAXRS_LOGGER.noSpringIntegrationJar();
        }
        File dir = new File(fileUrl.toURI());
        File file = null;
        for (String jar : dir.list()) {
            if (jar.endsWith(".jar")) {
                file = new File(dir, jar);
                break;
            }
        }
        if (file == null) {
            throw JaxrsLogger.JAXRS_LOGGER.noSpringIntegrationJar();
        }
        VirtualFile vf = VFS.getChild(file.toURI());
        final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());
        Service<Closeable> mountHandleService = new Service<Closeable>() {

            public void start(StartContext startContext) throws StartException {
            }

            public void stop(StopContext stopContext) {
                VFSUtils.safeClose(mountHandle);
            }

            public Closeable getValue() throws IllegalStateException, IllegalArgumentException {
                return mountHandle;
            }
        };
        ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SERVICE_NAME), mountHandleService);
        builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
        resourceRoot = vf;
        return resourceRoot;
    } catch (Exception e) {
        throw new DeploymentUnitProcessingException(e);
    }
}
Also used : VirtualFile(org.jboss.vfs.VirtualFile) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) StopContext(org.jboss.msc.service.StopContext) Closeable(java.io.Closeable) Service(org.jboss.msc.service.Service) TempFileProviderService(org.jboss.as.server.deployment.module.TempFileProviderService) URL(java.net.URL) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) StartException(org.jboss.msc.service.StartException) StartContext(org.jboss.msc.service.StartContext) Module(org.jboss.modules.Module) VirtualFile(org.jboss.vfs.VirtualFile) File(java.io.File)

Example 93 with Closeable

use of java.io.Closeable in project eiger by wlloyd.

the class RowIteratorFactory method getIterator.

/**
     * Get a row iterator over the provided memtables and sstables, between the provided keys
     * and filtered by the queryfilter.
     * @param memtables Memtables pending flush.
     * @param sstables SStables to scan through.
     * @param startWith Start at this key
     * @param stopAt Stop and this key
     * @param filter Used to decide which columns to pull out
     * @param cfs
     * @return A row iterator following all the given restrictions
     */
public static CloseableIterator<Row> getIterator(final Iterable<Memtable> memtables, final Collection<SSTableReader> sstables, final RowPosition startWith, final RowPosition stopAt, final QueryFilter filter, final ColumnFamilyStore cfs) {
    // fetch data from current memtable, historical memtables, and SSTables in the correct order.
    final List<CloseableIterator<IColumnIterator>> iterators = new ArrayList<CloseableIterator<IColumnIterator>>();
    // memtables
    for (Memtable memtable : memtables) {
        iterators.add(new ConvertToColumnIterator(filter, memtable.getEntryIterator(startWith, stopAt)));
    }
    for (SSTableReader sstable : sstables) {
        final SSTableScanner scanner = sstable.getScanner(filter);
        scanner.seekTo(startWith);
        // otherwise we leak FDs
        assert scanner instanceof Closeable;
        iterators.add(scanner);
    }
    // reduce rows from all sources into a single row
    return MergeIterator.get(iterators, COMPARE_BY_KEY, new MergeIterator.Reducer<IColumnIterator, Row>() {

        private final int gcBefore = (int) (System.currentTimeMillis() / 1000) - cfs.metadata.getGcGraceSeconds();

        private final List<IColumnIterator> colIters = new ArrayList<IColumnIterator>();

        private DecoratedKey key;

        private ColumnFamily returnCF;

        @Override
        protected void onKeyChange() {
            this.returnCF = ColumnFamily.create(cfs.metadata);
        }

        public void reduce(IColumnIterator current) {
            this.colIters.add(current);
            this.key = current.getKey();
            this.returnCF.delete(current.getColumnFamily());
        }

        protected Row getReduced() {
            // First check if this row is in the rowCache. If it is we can skip the rest
            ColumnFamily cached = cfs.getRawCachedRow(key);
            if (cached == null)
                // not cached: collate
                filter.collateColumns(returnCF, colIters, gcBefore);
            else {
                QueryFilter keyFilter = new QueryFilter(key, filter.path, filter.filter);
                returnCF = cfs.filterColumnFamily(cached, keyFilter, gcBefore);
            }
            Row rv = new Row(key, returnCF);
            colIters.clear();
            key = null;
            return rv;
        }
    });
}
Also used : CloseableIterator(org.apache.cassandra.utils.CloseableIterator) Closeable(java.io.Closeable) IColumnIterator(org.apache.cassandra.db.columniterator.IColumnIterator) SSTableReader(org.apache.cassandra.io.sstable.SSTableReader) QueryFilter(org.apache.cassandra.db.filter.QueryFilter) SSTableScanner(org.apache.cassandra.io.sstable.SSTableScanner) MergeIterator(org.apache.cassandra.utils.MergeIterator)

Example 94 with Closeable

use of java.io.Closeable in project tika by apache.

the class TemporaryResources method close.

/**
     * Closes all tracked resources. The resources are closed in reverse order
     * from how they were added.
     * <p>
     * Any suppressed exceptions from managed resources are collected and
     * then added to the first thrown exception, which is re-thrown once
     * all the resources have been closed.
     *
     * @throws IOException if one or more of the tracked resources
     *                     could not be closed
     */
public void close() throws IOException {
    // Release all resources and keep track of any exceptions
    IOException exception = null;
    for (Closeable resource : resources) {
        try {
            resource.close();
        } catch (IOException e) {
            if (exception == null) {
                exception = e;
            } else {
                exception.addSuppressed(e);
            }
        }
    }
    resources.clear();
    // Throw any exceptions that were captured from above
    if (exception != null) {
        throw exception;
    }
}
Also used : Closeable(java.io.Closeable) IOException(java.io.IOException)

Example 95 with Closeable

use of java.io.Closeable in project tika by apache.

the class TemporaryResources method createTempFile.

/**
     * Creates a temporary file that will automatically be deleted when
     * the {@link #close()} method is called, returning its path.
     *
     * @return Path to created temporary file that will be deleted after closing
     * @throws IOException
     */
public Path createTempFile() throws IOException {
    final Path path = tempFileDir == null ? Files.createTempFile("apache-tika-", ".tmp") : Files.createTempFile(tempFileDir, "apache-tika-", ".tmp");
    addResource(new Closeable() {

        public void close() throws IOException {
            Files.delete(path);
        }
    });
    return path;
}
Also used : Path(java.nio.file.Path) Closeable(java.io.Closeable) IOException(java.io.IOException)

Aggregations

Closeable (java.io.Closeable)216 IOException (java.io.IOException)88 Test (org.junit.Test)56 ArrayList (java.util.ArrayList)29 File (java.io.File)26 HashMap (java.util.HashMap)12 VirtualFile (org.jboss.vfs.VirtualFile)12 URL (java.net.URL)9 Path (java.nio.file.Path)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 Map (java.util.Map)7 ISE (io.druid.java.util.common.ISE)6 InputStream (java.io.InputStream)6 MountHandle (org.jboss.as.server.deployment.module.MountHandle)6 ResourceRoot (org.jboss.as.server.deployment.module.ResourceRoot)6 ProgramController (co.cask.cdap.app.runtime.ProgramController)5 ProgramType (co.cask.cdap.proto.ProgramType)4 ProgramId (co.cask.cdap.proto.id.ProgramId)4 Pair (io.druid.java.util.common.Pair)4 FileOutputStream (java.io.FileOutputStream)4