List of usage examples for org.springframework.core.io Resource getFile
File getFile() throws IOException;
From source file:com.netflix.genie.web.configs.MvcConfig.java
/** * Get the jobs dir as a Spring Resource. Will create if it doesn't exist. * * @param resourceLoader The resource loader to use * @param jobsProperties The jobs properties to use * @return The job dir as a resource/* w w w . j a v a2s . c om*/ * @throws IOException on error reading or creating the directory */ @Bean @ConditionalOnMissingBean public Resource jobsDir(final ResourceLoader resourceLoader, final JobsProperties jobsProperties) throws IOException { final String jobsDirLocation = jobsProperties.getLocations().getJobs(); final Resource tmpJobsDirResource = resourceLoader.getResource(jobsDirLocation); if (tmpJobsDirResource.exists() && !tmpJobsDirResource.getFile().isDirectory()) { throw new IllegalStateException(jobsDirLocation + " exists but isn't a directory. Unable to continue"); } // We want the resource to end in a slash for use later in the generation of URL's final String slash = "/"; String localJobsDir = jobsDirLocation; if (!jobsDirLocation.endsWith(slash)) { localJobsDir = localJobsDir + slash; } final Resource jobsDirResource = resourceLoader.getResource(localJobsDir); if (!jobsDirResource.exists()) { final File file = jobsDirResource.getFile(); if (!file.mkdirs()) { throw new IllegalStateException( "Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist."); } } return jobsDirResource; }
From source file:nl.surfnet.coin.teams.control.AbstractControllerTest.java
/** * Creates Freemarker {@link Configuration} that loads the template from the classpath folder {@literal ftl} * * @return Freemarker Configuration/*from w ww .j av a 2s .c om*/ * @throws IOException when this folder cannot be found */ protected Configuration getFreemarkerConfig() throws IOException { Configuration freemarkerConfiguration = new Configuration(); Resource templateDir = new ClassPathResource("/ftl/"); freemarkerConfiguration.setDirectoryForTemplateLoading(templateDir.getFile()); freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper()); return freemarkerConfiguration; }
From source file:fr.acxio.tools.agia.file.pdf.SplitPDFTasklet.java
@Override public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception { Map<String, Object> aSourceParams = new HashMap<String, Object>(); aSourceParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, ((sChunkContext != null) && (sChunkContext.getStepContext() != null)) ? sChunkContext.getStepContext().getStepExecution() : null);//from www . j av a 2 s. c o m Resource[] aSourceResources = sourceFactory.getResources(aSourceParams); if (LOGGER.isInfoEnabled()) { LOGGER.info("{} file(s) to split", aSourceResources.length); } for (Resource aSourceResource : aSourceResources) { if (sContribution != null) { sContribution.incrementReadCount(); } File aOriginFile = aSourceResource.getFile(); if (aOriginFile.exists()) { int aOutputCount = splitFile(aSourceResource, sChunkContext); if (sContribution != null) { sContribution.incrementWriteCount(aOutputCount); } } else { throw new SplitPDFException("File not found: " + aOriginFile); } } return RepeatStatus.FINISHED; }
From source file:net.paoding.rose.jade.context.spring.JadeBeanFactoryPostProcessor.java
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String postProcessor = System.getProperty("jade.spring.postProcessor"); if ("disable".equals(postProcessor)) { logger.info("jade.spring.postProcessor: disable"); return;// w ww . j a va 2 s. c om } else if (postProcessor == null || "enable".equals(postProcessor)) { logger.info("jade.spring.postProcessor: enable"); } else { throw new IllegalArgumentException(// "illegal property of 'jade.spring.postProcessor': " + postProcessor); } if (logger.isInfoEnabled()) { logger.info("[jade] starting ..."); } final List<ResourceRef> resources; try { // scope resources = RoseScanner.getInstance().getJarOrClassesFolderResources(); } catch (IOException e) { throw new ApplicationContextException("error on getJarResources/getClassesFolderResources", e); } List<String> urls = new LinkedList<String>(); for (ResourceRef ref : resources) { if (ref.hasModifier("dao") || ref.hasModifier("DAO")) { try { Resource resource = ref.getResource(); File resourceFile = resource.getFile(); if (resourceFile.isFile()) { urls.add("jar:file:" + resourceFile.toURI().getPath() + ResourceUtils.JAR_URL_SEPARATOR); } else if (resourceFile.isDirectory()) { urls.add(resourceFile.toURI().toString()); } } catch (IOException e) { throw new ApplicationContextException("error on resource.getFile", e); } } } if (logger.isInfoEnabled()) { logger.info("[jade] found " + urls.size() + " jade urls: " + urls); } if (urls.size() > 0) { DAOComponentProvider provider = new DAOComponentProvider(true); if (filters != null) { for (TypeFilter excludeFilter : filters) { provider.addExcludeFilter(excludeFilter); } } Set<String> daoClassNames = new HashSet<String>(); for (String url : urls) { if (logger.isInfoEnabled()) { logger.info("[jade] call 'jade/find'"); } Set<BeanDefinition> dfs = provider.findCandidateComponents(url); if (logger.isInfoEnabled()) { logger.info("[jade] found " + dfs.size() + " beanDefinition from '" + url + "'"); } for (BeanDefinition beanDefinition : dfs) { String daoClassName = beanDefinition.getBeanClassName(); if (isDisable(daoClassName)) { if (logger.isDebugEnabled()) { logger.debug( "[jade] ignored disabled jade dao class: " + daoClassName + " [" + url + "]"); } continue; } if (daoClassNames.contains(daoClassName)) { if (logger.isDebugEnabled()) { logger.debug("[jade] ignored replicated jade dao class: " + daoClassName + " [" + url + "]"); } continue; } daoClassNames.add(daoClassName); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); propertyValues.addPropertyValue("DAOClass", daoClassName); ScannedGenericBeanDefinition scannedBeanDefinition = (ScannedGenericBeanDefinition) beanDefinition; scannedBeanDefinition.setPropertyValues(propertyValues); scannedBeanDefinition.setBeanClass(DAOFactoryBean.class); DefaultListableBeanFactory defaultBeanFactory = (DefaultListableBeanFactory) beanFactory; defaultBeanFactory.registerBeanDefinition(daoClassName, beanDefinition); if (logger.isDebugEnabled()) { logger.debug("[jade] register DAO: " + daoClassName); } } } } if (logger.isInfoEnabled()) { logger.info("[jade] exits"); } }
From source file:br.eb.ime.labprog3.tam.MenorCaminhoController.java
@RequestMapping(value = "menorcaminho") public String menorCaminho(ModelMap map, HttpServletRequest request) { String fileNameTrechos = "../../resources/xml/rotas.xml"; String fileNameAeroportos = "../../resources/xml/aeroportos.xml"; Resource resource = null; TrechoDAO daoTrecho = null;/*ww w. ja v a2 s. com*/ AeroportoDAO daoAeroporto = null; resource = new ClassPathResource(fileNameTrechos); try { daoTrecho = new TrechoDAO(resource.getFile()); } catch (IOException ex) { Logger.getLogger(MenorCaminhoController.class.getName()).log(Level.SEVERE, null, ex); } resource = new ClassPathResource(fileNameAeroportos); try { daoAeroporto = new AeroportoDAO(resource.getFile()); } catch (IOException ex) { Logger.getLogger(MenorCaminhoController.class.getName()).log(Level.SEVERE, null, ex); } List<Aeroporto> listaDeAeroportos = daoAeroporto.listarAeroportos(); List<Trecho> listaDeTrechos = daoTrecho.listarTrechos(); GeradorGrafoDijkstra geradorDeGrafo = new GeradorGrafoDijkstra(daoAeroporto.listarAeroportos(), daoTrecho.listarTrechos()); int origem = -1; int destino = -1; try { origem = Integer.parseInt(request.getParameter("origem")); destino = Integer.parseInt(request.getParameter("destino")); } catch (Exception e) { return "erro"; } if (origem < 0 || destino < 0) return "erro"; List<Aeroporto> listaDeAeroportosDestino = geradorDeGrafo.geraMenorCaminho(origem, destino); List<Trecho> listaDeTrechosDestino = new ArrayList<>(); map.addAttribute("aeroportoOrigem", listaDeAeroportos.get(origem - 1)); map.addAttribute("aeroportoDestino", listaDeAeroportos.get(destino - 1)); if (listaDeAeroportosDestino.size() == 1) { map.addAttribute("visibility", 0); if (listaDeAeroportos.get(origem - 1).getId() == listaDeAeroportos.get(destino - 1).getId()) map.addAttribute("visibility", 1); } else { for (int i = 0; i < listaDeAeroportosDestino.size() - 1; i++) { Aeroporto aeroportoOrigem = listaDeAeroportosDestino.get(i); for (int j = 0; j < listaDeTrechos.size(); j++) { Trecho trecho = listaDeTrechos.get(j); if (trecho.getIdAeroportoOrigem() == aeroportoOrigem.getId()) { Aeroporto aeroportoDestino = listaDeAeroportosDestino.get(i + 1); trecho.setAeroportoOrigemNome(aeroportoOrigem.getNome()); if (trecho.getIdAeroportoDestino() == aeroportoDestino.getId()) { trecho.setAeroportoDestinoNome(aeroportoDestino.getNome()); listaDeTrechosDestino.add(trecho); } } } } map.addAttribute("visibility", 2); } map.addAttribute("listaDeAeroportos", listaDeAeroportos); map.addAttribute("listaDeTrechos", listaDeTrechosDestino); return "menorcaminho"; }
From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskTest.java
/** * Make sure we can run successfully when runAsUser is false for the system. * * @throws IOException on error/*from w ww .ja v a 2 s.co m*/ * @throws GenieException on error */ @Test public void canRunWithoutSudo() throws IOException, GenieException { final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults(); jobsProperties.getUsers().setRunAsUserEnabled(false); // Create some random junk file that should be ignored this.tmpJobDir.newFile(UUID.randomUUID().toString()); final DiskCleanupProperties properties = new DiskCleanupProperties(); final Instant threshold = TaskUtils.getMidnightUTC().minus(properties.getRetention(), ChronoUnit.DAYS); final String job1Id = UUID.randomUUID().toString(); final String job2Id = UUID.randomUUID().toString(); final String job3Id = UUID.randomUUID().toString(); final String job4Id = UUID.randomUUID().toString(); final String job5Id = UUID.randomUUID().toString(); final Job job1 = Mockito.mock(Job.class); Mockito.when(job1.getStatus()).thenReturn(JobStatus.INIT); final Job job2 = Mockito.mock(Job.class); Mockito.when(job2.getStatus()).thenReturn(JobStatus.RUNNING); final Job job3 = Mockito.mock(Job.class); Mockito.when(job3.getStatus()).thenReturn(JobStatus.SUCCEEDED); Mockito.when(job3.getFinished()).thenReturn(Optional.of(threshold.minus(1, ChronoUnit.MILLIS))); final Job job4 = Mockito.mock(Job.class); Mockito.when(job4.getStatus()).thenReturn(JobStatus.FAILED); Mockito.when(job4.getFinished()).thenReturn(Optional.of(threshold)); this.createJobDir(job1Id); this.createJobDir(job2Id); this.createJobDir(job3Id); this.createJobDir(job4Id); this.createJobDir(job5Id); final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class); final Resource jobDir = Mockito.mock(Resource.class); Mockito.when(jobDir.exists()).thenReturn(true); Mockito.when(jobDir.getFile()).thenReturn(this.tmpJobDir.getRoot()); final JobSearchService jobSearchService = Mockito.mock(JobSearchService.class); Mockito.when(jobSearchService.getJob(job1Id)).thenReturn(job1); Mockito.when(jobSearchService.getJob(job2Id)).thenReturn(job2); Mockito.when(jobSearchService.getJob(job3Id)).thenReturn(job3); Mockito.when(jobSearchService.getJob(job4Id)).thenReturn(job4); Mockito.when(jobSearchService.getJob(job5Id)).thenThrow(new GenieServerException("blah")); final DiskCleanupTask task = new DiskCleanupTask(properties, scheduler, jobDir, jobSearchService, jobsProperties, Mockito.mock(Executor.class), new SimpleMeterRegistry()); task.run(); Assert.assertTrue(new File(jobDir.getFile(), job1Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job2Id).exists()); Assert.assertFalse(new File(jobDir.getFile(), job3Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job4Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job5Id).exists()); }
From source file:de.iew.services.impl.MessageBundleServiceImpl.java
public void loadMessageBundle(String source) throws IOException { Resource resource = this.resourceLoader.getResource(source); String basename = resource.getFile().getName(); if (basename.endsWith(".properties")) { basename = basename.substring(0, basename.length() - ".properties".length()); }/* w w w. j a v a 2 s . c o m*/ if (log.isDebugEnabled()) { log.debug("Basisname der zu importierenden Datei " + basename + "."); } Properties properties = new Properties(); properties.load(resource.getInputStream()); loadMessageBundle(properties, basename); }
From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (this.classPath == null) { throw new ClassNotFoundException("invalid search root: " + this.classPath); } else if (name == null) { throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage()); }// w w w . j a v a 2 s. c o m String classNamePath = name.replace('.', '/') + ".class"; byte[] fileBytes = null; try { InputStream is = null; JarFile jarFile = null; for (Resource entry : this.classPath) { if (entry.getFilename().toLowerCase().endsWith(".jar")) { jarFile = new JarFile(entry.getFile()); ZipEntry ze = jarFile.getEntry(classNamePath); if (ze != null) { is = jarFile.getInputStream(ze); break; } else { jarFile.close(); } } else { Resource classFile = entry.createRelative(classNamePath); if (classFile.exists()) { is = classFile.getInputStream(); break; } } } if (is != null) { try { fileBytes = IOUtils.toByteArray(is); is.close(); } finally { if (jarFile != null) { jarFile.close(); } } } } catch (IOException e) { throw new ClassNotFoundException(e.getMessage(), e); } if (name.contains(".")) { String packageName = name.substring(0, name.lastIndexOf('.')); if (getPackage(packageName) == null) { definePackage(packageName, "", "", "", "", "", "", null); } } Class<?> ret; if (fileBytes == null) { ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader); } else { ret = defineClass(name, fileBytes, 0, fileBytes.length); } if (ret == null) { throw new ClassNotFoundException( "Couldn't find class " + name + " in expected classpath: " + this.classPath); } return ret; }
From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (this.classPath == null) { throw new ClassNotFoundException("invalid search root: " + this.classPath); } else if (name == null) { throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage()); }// w w w .ja v a 2 s . c o m String classNamePath = name.replace('.', '/') + ".class"; byte[] fileBytes = null; try { InputStream is = null; JarFile jarFile = null; for (Resource entry : this.classPath) { if (entry.getFilename().toLowerCase().endsWith(".jar")) { jarFile = new JarFile(entry.getFile()); ZipEntry ze = jarFile.getEntry(classNamePath); if (ze != null) { is = jarFile.getInputStream(ze); break; } else { jarFile.close(); } } else { Resource classFile = entry.createRelative(classNamePath); if (classFile.exists()) { is = classFile.getInputStream(); break; } } } if (is != null) { try { fileBytes = IOUtils.toByteArray(is); is.close(); } finally { if (jarFile != null) { jarFile.close(); } } } } catch (IOException e) { throw new ClassNotFoundException(e.getMessage(), e); } if (name.contains(".")) { String packageName = name.substring(0, name.lastIndexOf('.')); if (getPackage(packageName) == null) { definePackage(packageName, "", "", "", "", "", "", null); } } Class<?> ret; if (fileBytes == null) { ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader); } else { ret = defineClass(name, fileBytes, 0, fileBytes.length); } if (ret == null) { throw new ClassNotFoundException( "Couldn't find class " + name + " in expected classpath: " + this.classPath); } return ret; }