Example usage for org.springframework.core.io Resource getFile

List of usage examples for org.springframework.core.io Resource getFile

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getFile.

Prototype

File getFile() throws IOException;

Source Link

Document

Return a File handle for this resource.

Usage

From source file:org.jahia.modules.modulemanager.rest.ModuleManagerResource.java

/**
 * Install the given bundle on the specified group of nodes. If nodes parameter is empty then deploy to default group.
 *
 * @param bundleInputStream the bundle to deploy file input stream
 * @param target the group of cluster nodes targeted by the install operation
 * @param start whether the installed bundle should be started right away
 * @return the operation result// w  w  w .j a v  a 2s.  c  om
 * @throws WebApplicationException when the operation fails
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response install(@FormDataParam("bundle") InputStream bundleInputStream,
        @FormDataParam("bundle") FormDataContentDisposition fileDisposition,
        @FormDataParam("target") String target, @FormDataParam("start") boolean start)
        throws WebApplicationException {

    if (bundleInputStream == null) {
        throw new ClientErrorException("The bundle file could not be null", Response.Status.BAD_REQUEST);
    }

    long startTime = System.currentTimeMillis();
    log.info("Received request to install bundle {} on target {}. Should start the bundle after: {}",
            new Object[] { fileDisposition.getFileName(), target, start });

    Resource bundleResource = null;

    try {
        bundleResource = getUploadedFileAsResource(bundleInputStream, fileDisposition.getFileName());
        OperationResult result = getModuleManager().install(bundleResource, target, start);
        return Response.ok(result).build();
    } catch (ModuleManagementInvalidArgumentException e) {
        log.error("Unable to install module. Cause: " + e.getMessage());
        throw new ClientErrorException("Unable to install module. Cause: " + e.getMessage(),
                Response.Status.BAD_REQUEST, e);
    } catch (Exception e) {
        log.error("Module management exception when installing module", e);
        throw new InternalServerErrorException("Error while installing bundle", e);
    } finally {
        IOUtils.closeQuietly(bundleInputStream);
        log.info("Operation completed in {} ms", System.currentTimeMillis() - startTime);
        if (bundleResource != null) {
            try {
                File bundleFile = bundleResource.getFile();
                FileUtils.deleteQuietly(bundleFile);
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.warn("Unable to clean installed bundle file. Cause: " + e.getMessage(), e);
                } else {
                    log.warn("Unable to clean installed bundle file (details in DEBUG logging level). Cause: "
                            + e.getMessage());
                }
            }
        }
    }
}

From source file:com.baomidou.mybatisplus.spring.MybatisMapperRefresh.java

public void run() {
    final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration);
    /*// w w  w. j  a  v a  2  s  .  c om
     * ? XML 
     */
    if (enabled) {
        beforeTime = SystemClock.now();
        final MybatisMapperRefresh runnable = this;
        new Thread(new Runnable() {

            public void run() {
                if (fileSet == null) {
                    fileSet = new HashSet<String>();
                    for (Resource mapperLocation : mapperLocations) {
                        try {
                            if (ResourceUtils.isJarURL(mapperLocation.getURL())) {
                                String key = new UrlResource(
                                        ResourceUtils.extractJarFileURL(mapperLocation.getURL())).getFile()
                                                .getPath();
                                fileSet.add(key);
                                if (jarMapper.get(key) != null) {
                                    jarMapper.get(key).add(mapperLocation);
                                } else {
                                    List<Resource> resourcesList = new ArrayList<Resource>();
                                    resourcesList.add(mapperLocation);
                                    jarMapper.put(key, resourcesList);
                                }
                            } else {
                                fileSet.add(mapperLocation.getFile().getPath());
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }
                try {
                    Thread.sleep(delaySeconds * 1000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                while (true) {
                    try {
                        for (String filePath : fileSet) {
                            File file = new File(filePath);
                            if (file != null && file.isFile() && file.lastModified() > beforeTime) {
                                mybatisGlobalCache.setRefresh(true);
                                List<Resource> removeList = jarMapper.get(filePath);
                                if (removeList != null && !removeList.isEmpty()) {// jarxmljarxml??jar?xml
                                    for (Resource resource : removeList) {
                                        runnable.refresh(resource);
                                    }
                                } else {
                                    runnable.refresh(new FileSystemResource(file));
                                }
                            }
                        }
                        if (mybatisGlobalCache.isRefresh()) {
                            beforeTime = SystemClock.now();
                        }
                        mybatisGlobalCache.setRefresh(true);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                    try {
                        Thread.sleep(sleepSeconds * 1000);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }

                }
            }
        }, "mybatis-plus MapperRefresh").start();
    }
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * Constructor.//from   w  ww  .j a va  2s.  c o m
 *
 * @param jobsDir The job directory resource
 * @throws IOException When the job directory can't be created or isn't a directory
 */
public DiskJobFileServiceImpl(final Resource jobsDir) throws IOException {
    /*
       TODO: Note there is a @Bean for jobs dir but it's currently returned as a Spring Resource interface
         This abstracts the actual underlying implementation and we can't guarantee it's on disk in that case
         as it could be on S3 or some other storage medium and the Resource masks those details (correctly).
         We can revisit this going forward but we may want to centralize the logic here. For now just keeping
         local reference to the path on disk of the root of the jobs directory as specified by the property.
     */

    /*
    TODO: Fix using jobDir as a resource reference at some point... but integration tests swap out the
    reference and don't rely on properties. Too much to fix right now with other priorities.
    This should probably be based off the property.
     */

    // TODO: This throws an InvalidPathException ... Should we catch or just propagate as this will be called
    //       at startup and the system won't even start
    this.jobsDirRoot = jobsDir.getFile().toPath();

    // Make sure the root exists and is a directory
    this.createOrCheckDirectory(this.jobsDirRoot);
}

From source file:it.publisys.ims.discovery.job.EntityTasks.java

private EntitiesDescriptorDocument storeEntitiesFile(List<File> files) {
    Resource resource = new ClassPathResource(METADATA_DIR + "/" + PROTECTEDAPP_GUARD_XML);

    EntitiesDescriptorDocument entities = EntitiesDescriptorDocument.Factory.newInstance();

    EntityDescriptorType[] arrayEntities = new EntityDescriptorType[files.size()];

    for (int i = 0; i < files.size(); i++) {
        File f = files.get(i);// w ww.j a  v a  2s.c om

        log.debug(String.format("Metadata: %s", f.getAbsolutePath()));

        try {
            EntityDescriptorDocument singolo = EntityDescriptorDocument.Factory.parse(f);
            arrayEntities[i] = singolo.getEntityDescriptor();
        } catch (IOException ioe) {
            log.error(String.format("Errore di lettura del file %s", f.getAbsolutePath()), ioe);
        } catch (XmlException xmle) {
            log.error(String.format("Errore durante il parsing del file %s", f.getAbsolutePath()), xmle);
        }

    }

    entities.addNewEntitiesDescriptor().setEntityDescriptorArray(arrayEntities);

    // scrivo il nuovo file corrispondente alle entity ottenute
    try {
        Utils.writeSAML2MetadataToDisk(entities, resource.getFile().getAbsolutePath());
    } catch (Exception ex) {
        log.error(String.format("Errore durante la scrittura del file '%s' su disco", PROTECTEDAPP_GUARD_XML),
                ex);
    }

    return entities;

}

From source file:com.netflix.genie.web.tasks.job.JobCompletionService.java

/**
 * Constructor.//from ww  w.ja v a  2s .co m
 *
 * @param jobSearchService         An implementation of the job search service.
 * @param jobPersistenceService    An implementation of the job persistence service.
 * @param genieFileTransferService An implementation of the Genie File Transfer service.
 * @param genieWorkingDir          The working directory where all job directories are created.
 * @param mailServiceImpl          An implementation of the mail service.
 * @param registry                 The metrics registry to use
 * @param jobsProperties           The properties relating to running jobs
 * @param retryTemplate            Retry template for retrying remote calls
 * @throws GenieException if there is a problem
 */
@Autowired
public JobCompletionService(final JobPersistenceService jobPersistenceService,
        final JobSearchService jobSearchService, final GenieFileTransferService genieFileTransferService,
        final Resource genieWorkingDir, final MailService mailServiceImpl, final Registry registry,
        final JobsProperties jobsProperties,
        @Qualifier("genieRetryTemplate") @NotNull final RetryTemplate retryTemplate) throws GenieException {
    this.jobPersistenceService = jobPersistenceService;
    this.jobSearchService = jobSearchService;
    this.genieFileTransferService = genieFileTransferService;
    this.mailServiceImpl = mailServiceImpl;
    this.deleteArchiveFile = jobsProperties.getCleanup().isDeleteArchiveFile();
    this.deleteDependencies = jobsProperties.getCleanup().isDeleteDependencies();
    this.runAsUserEnabled = jobsProperties.getUsers().isRunAsUserEnabled();

    this.executor = new DefaultExecutor();
    this.executor.setStreamHandler(new PumpStreamHandler(null, null));

    try {
        this.baseWorkingDir = genieWorkingDir.getFile();
    } catch (IOException gse) {
        throw new GenieServerException("Could not load the base path from resource");
    }

    // Set up the metrics
    this.registry = registry;
    this.jobCompletionId = registry.createId("genie.jobs.completion.timer");
    this.emailSuccessRate = registry.counter("genie.jobs.email.success.rate");
    this.emailFailureRate = registry.counter("genie.jobs.email.failure.rate");
    this.archivalFailureRate = registry.counter("genie.jobs.archivalFailure.rate");
    this.doneFileProcessingFailureRate = registry.counter("genie.jobs.doneFileProcessingFailure.rate");
    this.finalStatusUpdateFailureRate = registry.counter("genie.jobs.finalStatusUpdateFailure.rate");
    this.processGroupCleanupFailureRate = registry.counter("genie.jobs.processGroupCleanupFailure.rate");
    this.archiveFileDeletionFailure = registry.counter("genie.jobs.archiveFileDeletionFailure.rate");
    this.deleteDependenciesFailure = registry.counter("genie.jobs.deleteDependenciesFailure.rate");
    // Retry template
    this.retryTemplate = retryTemplate;
}

From source file:org.apache.uima.ruta.resource.MultiTreeWordList.java

/**
 * @param lists//from w ww.j  a  v  a  2  s  .  c  om
 *          Resources to load.
 * @throws IOException
 *           When there is a problem reading a resource.
 */
public MultiTreeWordList(Resource... lists) throws IOException {
    this.root = new MultiTextNode();
    this.costMap = new EditDistanceCostMap();

    for (Resource list : lists) {
        // check if the resource is a directory
        File directory = null;
        try {
            directory = list.getFile();
        } catch (IOException e) {
            // resource is not on the file system
            directory = null;
        }

        if (directory != null && directory.isDirectory()) {
            // resource is a directory, load its content
            for (File data : directory.listFiles()) {
                load(new FileSystemResource(data));
            }
        } else {
            // resource is not a directory, load it normally
            load(list);
        }
    }
}

From source file:com.epam.catgenome.manager.FeatureIndexManagerTest.java

@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testNoIndexGene() throws IOException {
    FeatureIndexedFileRegistrationRequest geneRequest = new FeatureIndexedFileRegistrationRequest();
    Resource resource = context.getResource(CLASSPATH_TEMPLATES_GENES_SORTED);
    geneRequest.setReferenceId(referenceId);
    geneRequest.setPath(resource.getFile().getAbsolutePath());
    geneRequest.setDoIndex(false);// w  w  w .j a  v a  2  s. c om
    geneRequest.setName(UUID.randomUUID().toString());

    GeneFile geneFile = gffManager.registerGeneFile(geneRequest);
    Assert.assertNotNull(geneFile);

    TestUtils.assertFail(
            () -> featureIndexDao.searchFeatures(TEST_GENE_PREFIX.toLowerCase(),
                    Collections.singletonList(geneFile), 10),
            Collections.singletonList(IllegalArgumentException.class));
}

From source file:com.epam.catgenome.manager.FeatureIndexManagerTest.java

@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testReindexGene() throws IOException {
    FeatureIndexedFileRegistrationRequest geneRequest = new FeatureIndexedFileRegistrationRequest();
    Resource resource = context.getResource(CLASSPATH_TEMPLATES_GENES_SORTED);
    geneRequest.setReferenceId(referenceId);
    geneRequest.setPath(resource.getFile().getAbsolutePath());
    geneRequest.setName(UUID.randomUUID().toString());

    GeneFile geneFile = gffManager.registerGeneFile(geneRequest);

    IndexSearchResult searchResult = featureIndexDao.searchFeatures(TEST_GENE_PREFIX.toLowerCase(),
            Collections.singletonList(geneFile), 10);
    Assert.assertFalse(searchResult.getEntries().isEmpty());
    Assert.assertTrue(searchResult.getEntries().size() <= 10);
    Assert.assertTrue(searchResult.isExceedsLimit());

    fileManager.deleteFileFeatureIndex(geneFile);
    TestUtils.assertFail(/* w w  w .  j  a  va  2 s.  c  om*/
            () -> featureIndexDao.searchFeatures(TEST_GENE_PREFIX.toLowerCase(),
                    Collections.singletonList(geneFile), 10),
            Collections.singletonList(IllegalArgumentException.class));

    gffManager.reindexGeneFile(geneFile.getId(), false);
    searchResult = featureIndexDao.searchFeatures("ens", Collections.singletonList(geneFile), 10);
    Assert.assertFalse(searchResult.getEntries().isEmpty());
    Assert.assertTrue(searchResult.getEntries().size() <= 10);
    Assert.assertTrue(searchResult.isExceedsLimit());
}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/**
 * Create a PrefabGraphTypeDao from the properties file in sourceResource
 * If reloadable is true, add the type's reload call back to each graph,
 * otherwise don't If sourceResource is not a file-based resource, then
 * reloadable should be false NB: I didn't want to get into checking for
 * what the implementation class of Resource is, because that could break
 * in future with new classes and types that do have a File underneath
 * them. This way, it's up to the caller, who *should* be able to make a
 * sensible choice as to whether the resource is reloadable or not.
 *
 * @param type//from  w ww .  ja v a2  s .  c  o m
 * @param sourceResource
 * @param reloadable
 * @return
 */
private PrefabGraphTypeDao createPrefabGraphType(String type, Resource sourceResource, boolean reloadable) {
    InputStream in = null;
    try {
        in = sourceResource.getInputStream();
        Properties properties = new Properties();
        properties.load(in);
        PrefabGraphTypeDao t = new PrefabGraphTypeDao();
        t.setName(type);

        t.setCommandPrefix(getProperty(properties, "command.prefix"));
        t.setOutputMimeType(getProperty(properties, "output.mime"));

        t.setDefaultReport(properties.getProperty("default.report", "none"));

        String includeDirectoryString = properties.getProperty("include.directory");
        t.setIncludeDirectory(includeDirectoryString);

        if (includeDirectoryString != null) {
            Resource includeDirectoryResource;

            File includeDirectoryFile = new File(includeDirectoryString);
            if (includeDirectoryFile.isAbsolute()) {
                includeDirectoryResource = new FileSystemResource(includeDirectoryString);
            } else {
                includeDirectoryResource = sourceResource.createRelative(includeDirectoryString);
            }

            File includeDirectory = includeDirectoryResource.getFile();

            if (includeDirectory.isDirectory()) {
                t.setIncludeDirectoryResource(includeDirectoryResource);
            } else {
                // Just warn; no need to throw a hissy fit or otherwise fail to load
                LOG.warn("includeDirectory '{}' specified in '{}' is not a directory",
                        includeDirectoryFile.getAbsolutePath(), sourceResource.getFilename());
            }
        }

        // Default to 5 minutes; it's up to users to specify a shorter
        // time if they don't mind OpenNMS spamming on that directory
        int interval;
        try {
            interval = Integer.parseInt(properties.getProperty("include.directory.rescan", "300000"));
        } catch (NumberFormatException e) {
            // Default value if one was specified but it wasn't an integer
            interval = 300000;
            LOG.warn(
                    "The property 'include.directory.rescan' in {} was not able to be parsed as an integer.  Defaulting to {}ms",
                    sourceResource, interval, e);
        }

        t.setIncludeDirectoryRescanInterval(interval);

        List<PrefabGraph> graphs = loadPrefabGraphDefinitions(t, properties);

        for (PrefabGraph graph : graphs) {
            //The graphs list may contain nulls; see loadPrefabGraphDefinitions for reasons
            if (graph != null) {
                FileReloadContainer<PrefabGraph> container;
                if (reloadable) {
                    container = new FileReloadContainer<PrefabGraph>(graph, sourceResource, t.getCallback());
                } else {
                    container = new FileReloadContainer<PrefabGraph>(graph);
                }

                t.addPrefabGraph(container);
            }
        }

        //This *must* come after loading the main graph file, to ensure overrides are correct
        this.scanIncludeDirectory(t);
        return t;

    } catch (IOException e) {
        LOG.error("Failed to load prefab graph configuration of type {} from {}", type, sourceResource, e);
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:grails.plugins.DefaultGrailsPluginManager.java

private Class<?> loadPluginClass(ClassLoader cl, Resource r) {
    Class<?> pluginClass;/*from  ww  w . j  a  va 2  s.  c o  m*/
    if (cl instanceof GroovyClassLoader) {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("Parsing & compiling " + r.getFilename());
            }
            pluginClass = ((GroovyClassLoader) cl)
                    .parseClass(IOGroovyMethods.getText(r.getInputStream(), "UTF-8"));
        } catch (CompilationFailedException e) {
            throw new PluginException("Error compiling plugin [" + r.getFilename() + "] " + e.getMessage(), e);
        } catch (IOException e) {
            throw new PluginException("Error reading plugin [" + r.getFilename() + "] " + e.getMessage(), e);
        }
    } else {
        String className = null;
        try {
            className = GrailsResourceUtils.getClassName(r.getFile().getAbsolutePath());
        } catch (IOException e) {
            throw new PluginException(
                    "Cannot find plugin class [" + className + "] resource: [" + r.getFilename() + "]", e);
        }
        try {
            pluginClass = Class.forName(className, true, cl);
        } catch (ClassNotFoundException e) {
            throw new PluginException(
                    "Cannot find plugin class [" + className + "] resource: [" + r.getFilename() + "]", e);
        }
    }
    return pluginClass;
}