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:com.netflix.genie.web.tasks.node.DiskCleanupTaskUnitTests.java

/**
 * Make sure we can run successfully when runAsUser is false for the system.
 *
 * @throws IOException    on error/*from   w w  w .j a  va  2s .c  o m*/
 * @throws GenieException on error
 */
@Test
public void canRunWithoutSudo() throws IOException, GenieException {
    final JobsProperties jobsProperties = new JobsProperties();
    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 Calendar cal = TaskUtils.getMidnightUTC();
    TaskUtils.subtractDaysFromDate(cal, properties.getRetention());
    final Date threshold = cal.getTime();

    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(new Date(threshold.getTime() - 1)));
    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);
    final Registry registry = Mockito.mock(Registry.class);
    final AtomicLong numberOfDeletedJobDirs = new AtomicLong();
    Mockito.when(registry.gauge(Mockito.eq("genie.tasks.diskCleanup.numberDeletedJobDirs.gauge"),
            Mockito.any(AtomicLong.class))).thenReturn(numberOfDeletedJobDirs);
    final AtomicLong numberOfDirsUnableToDelete = new AtomicLong();
    Mockito.when(registry.gauge(Mockito.eq("genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge"),
            Mockito.any(AtomicLong.class))).thenReturn(numberOfDirsUnableToDelete);
    final Counter unableToGetJobCounter = Mockito.mock(Counter.class);
    Mockito.when(registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate"))
            .thenReturn(unableToGetJobCounter);
    final Counter unabledToDeleteJobsDir = Mockito.mock(Counter.class);
    Mockito.when(registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate"))
            .thenReturn(unabledToDeleteJobsDir);

    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), registry);
    Assert.assertThat(numberOfDeletedJobDirs.get(), Matchers.is(0L));
    Assert.assertThat(numberOfDirsUnableToDelete.get(), Matchers.is(0L));
    task.run();
    Assert.assertThat(numberOfDeletedJobDirs.get(), Matchers.is(1L));
    Assert.assertThat(numberOfDirsUnableToDelete.get(), Matchers.is(1L));
    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:com.careerly.common.support.ReloadablePropertySourcesPlaceholderConfigurer.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notEmpty(locations, "properties reload, locations not given");
    // ??//from w  w  w .  j  a  v a2  s .  c  om
    for (Resource resource : locations) {
        long modified = resource.lastModified();
        String modifiedTime = new DateTime(modified).toString("yyyy-MM-dd HH:mm:ss");
        logger.info("properties monitor, file: {}, modified: {}", resource.getFile().getPath(), modifiedTime);
        lastModifiedResources.put(resource, modified);
    }
    // ??Constant?
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        if (beanName.endsWith("Constant")) {
            logger.info("properties monitor, bean: {}", beanName);
            beanNames.add(beanName);
        }
    }
    // ??10??JDK7?nio2 Watch Service
    scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("properties-reload"));
    scheduler.scheduleWithFixedDelay(this, 120L, 10L, TimeUnit.SECONDS);
}

From source file:jp.go.aist.six.util.core.config.spring.SpringContext.java

private Properties _getConfigProperties() {
    if (_configProperties == null) {
        _configProperties = new Properties();
        if (_configPropertyLocations != null) {
            for (String location : _configPropertyLocations) {
                try {
                    Resource resource = _getContext().getResource(location);
                    _LOG_.info("property resource: " + (resource.exists() ? "exist - " : "inexist - ")
                            + resource.getFile());
                    if (resource.exists()) {
                        _configProperties.load(resource.getInputStream());
                    }//from   www.  j av  a 2  s  . c  o  m
                } catch (IOException ex) {
                    _LOG_.warn("property resource ERROR (skip): " + ex);
                }

                //                _configProperties.list( System.out );
            }
        }
    }

    return _configProperties;
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java

@Override
public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception {

    // 1. Destination exists
    //    a. Overwrite => default behaviour
    //    b. Update => copy to temporary file, open, read entries, merge with new entries, write merged entries and stream
    // 2. New destination => default behaviour

    Map<String, Object> aSourceParams = new HashMap<String, Object>();
    aSourceParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC,
            ((sChunkContext != null) && (sChunkContext.getStepContext() != null))
                    ? sChunkContext.getStepContext().getStepExecution()
                    : null);//  w ww . j  a v  a2 s  . co  m
    aSourceParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory);
    Resource[] aSourceResources = sourceFactory.getResources(aSourceParams);
    Map<String, Object> aDestinationParams = new HashMap<String, Object>();

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} file(s) to zip", aSourceResources.length);
    }

    if (aSourceResources.length > 0) {

        aDestinationParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory);
        aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC,
                ((sChunkContext != null) && (sChunkContext.getStepContext() != null))
                        ? sChunkContext.getStepContext().getStepExecution()
                        : null);
        Resource aDestination = destinationFactory.getResource(aDestinationParams);

        ZipArchiveOutputStream aZipArchiveOutputStream = null;
        try {
            aZipArchiveOutputStream = new ZipArchiveOutputStream(aDestination.getFile());

            sourceBaseDirectoryPath = sourceBaseDirectory.getFile().getCanonicalPath();

            for (Resource aSourceResource : aSourceResources) {
                zipResource(aSourceResource, aZipArchiveOutputStream, sContribution, sChunkContext);
            }
        } finally {
            if (aZipArchiveOutputStream != null) {
                aZipArchiveOutputStream.finish();
                aZipArchiveOutputStream.close();
            }
        }
    }

    return RepeatStatus.FINISHED;
}

From source file:spring.osgi.io.OsgiBundleResourceTest.java

private void testFileVsOsgiFileResolution(Resource fileRes, Resource otherRes) throws Exception {
    assertNotNull(fileRes.getURL());/*w  w  w .  j  a  v  a2  s .  co m*/
    assertNotNull(fileRes.getFile());
    assertTrue(fileRes.getFile().exists());

    assertNotNull(otherRes.getURL());
    assertNotNull(otherRes.getFile());
    assertTrue(
            StringUtils.pathEquals(fileRes.getFile().getAbsolutePath(), otherRes.getFile().getAbsolutePath()));
}

From source file:edu.jhuapl.openessence.i18n.InspectableResourceBundleMessageSource.java

public Collection<Locale> getLocales() throws IOException {
    String basename = basenames[0];
    Resource resource = resourceLoader.getResource(basename + ".properties");
    if (!resource.exists()) {
        return Collections.emptyList();
    }//from  www  .j a va 2 s  .  c om

    File baseFile = resource.getFile();
    final String bundleName = FilenameUtils.getBaseName(baseFile.getPath());
    File[] files = resource.getFile().getParentFile().listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(bundleName + "_") && name.endsWith(".properties");
        }
    });

    List<Locale> locales = new ArrayList<Locale>();
    for (File f : files) {
        String prefix = bundleName + "_";
        String code = f.getName().substring(prefix.length()).replace(".properties", "");

        locales.add(StringUtils.parseLocaleString(code));
    }

    return locales;
}

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

/**
 * Setup for the tests.//from   w  w  w  .jav a  2 s .  c om
 *
 * @throws IOException on error
 */
@Before
public void setup() throws IOException {
    final Calendar cal = Calendar.getInstance(JobConstants.UTC);
    cal.add(Calendar.DAY_OF_YEAR, 1);
    this.tomorrow = cal.getTime();
    this.jobSearchService = Mockito.mock(JobSearchService.class);
    this.jobSubmitterService = Mockito.mock(JobSubmitterService.class);
    final Executor executor = Mockito.mock(Executor.class);
    this.scheduler = Mockito.mock(TaskScheduler.class);
    this.eventMulticaster = Mockito.mock(ApplicationEventMulticaster.class);
    final Registry registry = Mockito.mock(Registry.class);
    this.unableToCancel = Mockito.mock(Counter.class);
    Mockito.when(registry.counter(Mockito.anyString())).thenReturn(this.unableToCancel);

    final File jobsFile = this.folder.newFolder();
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.getFile()).thenReturn(jobsFile);

    this.coordinator = new JobMonitoringCoordinator(HOSTNAME, this.jobSearchService,
            Mockito.mock(ApplicationEventPublisher.class), this.eventMulticaster, this.scheduler, executor,
            registry, jobsDir, new JobsProperties(), jobSubmitterService);
}