List of usage examples for org.springframework.core.io Resource getFile
File getFile() throws IOException;
From source file:org.obiba.onyx.spring.context.OnyxMessageSourceFactoryBean.java
protected String resolveBasename(String pathPrefix, Resource bundleResource) { // Resource#getFilename() does not return the full path. As such, we must get the underlying File instance. // Since all Resource instances are not File instances, this will only work with resources on the filesystem. File bundleFile;/* w w w. j a va2 s . co m*/ try { bundleFile = bundleResource.getFile(); } catch (IOException e) { log.info("Cannot add resource {} to MessageSource because it is not on the filesystem.", bundleResource.getDescription()); return null; } String filename = bundleFile.getAbsolutePath(); // Make file pathname compatible with Spring's pathnames (if necessary) if (File.separatorChar != '/') { filename = filename.replace(File.separatorChar, '/'); } StringBuilder basename = new StringBuilder(filename); int rootDirIndex = basename.lastIndexOf(pathPrefix); // Remove everything before pathPrefix if (rootDirIndex > 0) { basename.delete(0, rootDirIndex); } // Find the last part that fits the bundle's name int basenameIndex = basename.lastIndexOf(MESSAGES_BUNDLENAME); int length = basename.length(); // Delete anything appearing after the bundle's name basename.delete(basenameIndex + MESSAGES_BUNDLENAME.length(), length); return basename.toString(); }
From source file:com.iflytek.edu.cloud.frame.support.jdbc.CustomSQL.java
/** * /*w w w . j a v a 2s . c o m*/ */ private void reloadConfig() throws IOException { Resource[] newConfigs = this.loadConfigs(); for (Resource newConfig : newConfigs) { boolean flag = true; for (Entry<String, Long> entry : configMap.entrySet()) { if (newConfig.getURL().getPath().equals(entry.getKey())) { flag = false; if (newConfig.getFile().lastModified() != entry.getValue().longValue()) { configMap.put(entry.getKey(), newConfig.getFile().lastModified()); read(newConfig.getInputStream()); logger.info("Reloading " + entry.getKey()); break; } } } if (flag) { configMap.put(newConfig.getURL().getPath(), newConfig.getFile().lastModified()); read(newConfig.getInputStream()); logger.info("Reloading " + newConfig.getURL().getPath()); } } }
From source file:org.apereo.lap.services.ConfigurationService.java
/** * @return the directory which is the application home *///from ww w . j a v a 2s .c om File appHome() { if (applicationHomeDirectory == null) { try { // first see if the app home is set String lapHome = (String) System.getProperties().get("LAP_HOME"); if (lapHome == null) { lapHome = System.getenv("LAP_HOME"); } if (lapHome != null) { // check if the directory is valid File lapHomeDir = new File(lapHome); if (lapHomeDir.exists() && lapHomeDir.canRead() && lapHomeDir.isDirectory()) { applicationHomeDirectory = lapHomeDir; } else { logger.warn("Unable to read the configured LAP_HOME dir: " + lapHomeDir.getAbsolutePath() + ", it is probably not readable or not a directory, using the default instead (the classpath)"); } } if (applicationHomeDirectory == null) { // failed to find or successfully load the LAP_HOME Resource appCP = resourceLoader.getResource("classpath:"); // default to using the classpath (usually where the webapp is running) logger.debug("AppCP: " + appCP.getFile().getAbsolutePath()); File appRoot = appCP.getFile().getParentFile(); logger.debug("Parent: " + appRoot.getAbsolutePath()); File appHome = new File(appRoot, "lap"); if (!appHome.exists()) { try { //noinspection ResultOfMethodCallIgnored appHome.mkdir(); } catch (Exception e) { logger.warn("Could not create app home at: " + appHome.getAbsolutePath() + ", using root instead: " + appRoot.getAbsolutePath()); appHome = appRoot; } } applicationHomeDirectory = appHome; } } catch (IOException e) { logger.error("IO failure (getting app home): " + e, e); } } return applicationHomeDirectory; }
From source file:com.netflix.genie.web.services.impl.LocalJobKillServiceImpl.java
/** * Constructor./*from w ww .j a v a2 s . co m*/ * * @param hostname The name of the host this Genie node is running on * @param jobSearchService The job search service to use to locate job information * @param executor The executor to use to run system processes * @param runAsUser True if jobs are run as the user who submitted the job * @param genieEventBus The system event bus to use * @param genieWorkingDir The working directory where all job directories are created. * @param objectMapper The Jackson ObjectMapper used to serialize from/to JSON */ public LocalJobKillServiceImpl(@NotBlank final String hostname, @NotNull final JobSearchService jobSearchService, @NotNull final Executor executor, final boolean runAsUser, @NotNull final GenieEventBus genieEventBus, @NotNull final Resource genieWorkingDir, @NotNull final ObjectMapper objectMapper) { this.hostname = hostname; this.jobSearchService = jobSearchService; this.executor = executor; this.runAsUser = runAsUser; this.genieEventBus = genieEventBus; this.objectMapper = objectMapper; try { this.baseWorkingDir = genieWorkingDir.getFile(); } catch (IOException gse) { throw new RuntimeException("Could not load the base path from resource", gse); } }
From source file:org.apereo.lap.services.ConfigurationService.java
@PostConstruct public void init() throws IOException { logger.info("INIT started"); logger.info("App Home: " + appHome().getAbsolutePath()); CompositeConfiguration config = new CompositeConfiguration(); // load internal config defaults first config.setProperty("app.name", "LAP"); File dbDefaults = resourceLoader.getResource("classpath:db.properties").getFile(); try {//from ww w . j a v a2s. c om config.addConfiguration(new PropertiesConfiguration(dbDefaults)); } catch (ConfigurationException e) { logger.error("Unable to load default db.properties file"); } File appDefaults = resourceLoader.getResource("classpath:app.properties").getFile(); try { config.addConfiguration(new PropertiesConfiguration(appDefaults)); logger.info("Default app configuration loaded from: " + appDefaults.getAbsolutePath()); } catch (ConfigurationException e) { logger.error("Unable to load default app.properties file"); } // now try to load external config settings config.addConfiguration(new SystemConfiguration()); File lapConfigProps = new File(appHome(), "lap.properties"); if (lapConfigProps.exists() && lapConfigProps.canRead()) { try { config.addConfiguration(new PropertiesConfiguration(lapConfigProps)); } catch (ConfigurationException e) { logger.warn("Unable to load lap.properties file"); } } else { IOUtils.copy( SampleCSVInputHandlerService.class.getClassLoader() .getResourceAsStream("config" + SLASH + "lap.properties"), new FileOutputStream(new File(appHome(), "lap.properties"))); logger.info("No external LAP config found: " + lapConfigProps.getAbsolutePath() + ", copied default sample lap.properties"); } this.config = config; // verify the existence of the various dirs pipelinesDirectory = verifyDir("dir.pipelines", "piplines"); inputDirectory = verifyDir("dir.inputs", "inputs"); outputDirectory = verifyDir("dir.outputs", "outputs"); pipelineConfigs = new ConcurrentHashMap<>(); // first load the internal ones (must be listed explicitly for now) Resource pipelineSample = resourceLoader.getResource("classpath:pipelines" + SLASH + "sample.xml"); PipelineConfig plcfg = processPipelineConfigFile(pipelineSample.getFile()); if (plcfg != null) { pipelineConfigs.put(plcfg.getType(), plcfg); } // then try to load the external ones File[] pipelineFiles = pipelinesDirectory.listFiles(); if (pipelineFiles != null && pipelineFiles.length > 0) { for (final File fileEntry : pipelineFiles) { if (fileEntry.isFile()) { PipelineConfig filePLC = processPipelineConfigFile(pipelineSample.getFile()); if (filePLC != null) { pipelineConfigs.put(filePLC.getType(), filePLC); } } } } logger.info("INIT complete: " + config.getString("app.name") + ", home=" + applicationHomeDirectory.getAbsolutePath()); }
From source file:org.obiba.onyx.spring.AnnotatedBeanFinderFactoryBean.java
/** * @param res/*from ww w . j a v a 2s. c om*/ * @throws Exception */ private void dealWithJars(Resource res) throws Exception { // Enumerate all entries in this JAR file. Enumeration<JarEntry> jarEntries = new JarFile(res.getFile()).entries(); while (jarEntries.hasMoreElements()) { String name = jarEntries.nextElement().getName(); // If the entry is a class, deal with it. if (name.endsWith(".class") && !name.equals("")) { // Format the path first. name = pathToQualifiedClassName(name); // Apply the qualified class name pattern to improve the // searching performance. if (matchQualifiedClassNamePatterns(name)) // This is the qualified class name, so add it. addPossibleClasses(name); } } }
From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java
@Override public Resource getParent(Resource resource) { File f;//from w w w .j av a 2 s.co m try { f = resource.getFile().getParentFile(); } catch (IOException ex) { throw new WMRuntimeException(ex); } Resource parent = null; if (f != null) { String path = f.getAbsolutePath() + "/"; parent = new FileSystemResource(path); } return parent; }
From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java
/** * Make sure if the resource isn't a directory it's sent to super. * <p>/* w w w . j a v a 2s . c o m*/ * Note: This doesn't actually test returning a file as we leverage Spring's implementation * which we assume is working. * * @throws ServletException On any error * @throws IOException On any error */ @Test public void canHandleRequestForFile() throws ServletException, IOException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final String path = UUID.randomUUID().toString(); Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path); final Resource resource = Mockito.mock(Resource.class); Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource); Mockito.when(resource.exists()).thenReturn(true); final File file = Mockito.mock(File.class); Mockito.when(resource.getFile()).thenReturn(file); Mockito.when(file.isDirectory()).thenReturn(false); this.handler.handleRequest(request, response); Mockito.verify(response, Mockito.times(1)).sendError(HttpStatus.NOT_FOUND.value()); }
From source file:it.publisys.ims.discovery.job.EntityTasks.java
@Scheduled(fixedRate = 600000, initialDelay = 5000) public void reloadEntities() { log.debug("Reload Entities"); log.debug("ServletContext: " + servletContext); try {/*w w w .jav a2 s. co m*/ Resource resourceDir = new ClassPathResource(METADATA_DIR + "/" + GUARDS_DIR); if (!resourceDir.exists()) { throw new FileNotFoundException( String.format("Directory dei Medatada non presente. [%s]", resourceDir)); } List<File> files = loadMetadataXml(resourceDir.getFile()); EntitiesDescriptorDocument entitiesDescriptorDocument = storeEntitiesFile(files); EntityDescriptorType[] entityDescriptorTypes = loadAndCacheEntities(entitiesDescriptorDocument); loadEntities(entityDescriptorTypes); } catch (FileNotFoundException fnfe) { log.warn(fnfe.getMessage(), fnfe); } catch (IOException ioe) { log.warn("Caricamento Metadata non riuscito.", ioe); } }
From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java
/** * Make sure if the resource is a directory it's handled properly until exception thrown. * * @throws Exception On any error// w w w . j av a2 s . c om */ @Test(expected = ServletException.class) public void cantHandleRequestForDirectoryWhenException() throws Exception { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final String path = UUID.randomUUID().toString(); Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path); Mockito.when(request.getAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY)) .thenReturn(false); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); final Resource resource = Mockito.mock(Resource.class); Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource); Mockito.when(resource.exists()).thenReturn(true); final File file = Mockito.mock(File.class); Mockito.when(resource.getFile()).thenReturn(file); Mockito.when(file.isDirectory()).thenReturn(true); Mockito.when(this.directoryWriter.toHtml(Mockito.eq(file), Mockito.eq(requestUrl), Mockito.eq(true))) .thenThrow(new Exception()); final ServletOutputStream os = Mockito.mock(ServletOutputStream.class); Mockito.when(response.getOutputStream()).thenReturn(os); this.handler.handleRequest(request, response); }