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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

private Resource readResource(final Media media, final int width, final int height, final Media.ResizeMode mode)
        throws IOException {
    //      Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    //      final Resource prefix = resourceLoader.getResource(blog.getMediaPath());
    final Resource prefix = resourceLoader.getResource(wallRideProperties.getMediaLocation());
    final Resource resource = prefix.createRelative(media.getId());

    if (!resource.exists()) {
        return null;
    }/*from  www.j a  va 2 s  .  co  m*/

    Resource resized = resource;
    boolean doResize = (width > 0 || height > 0);
    if (doResize && "image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        resized = prefix.createRelative(
                String.format("%s.resized/%dx%d-%d", media.getId(), width, height, mode.ordinal()));
        if (!resized.exists() || resource.lastModified() > resized.lastModified()) {
            File temp = File.createTempFile(getClass().getCanonicalName() + ".resized-",
                    "." + MediaType.parseMediaType(media.getMimeType()).getSubtype());
            temp.deleteOnExit();
            resizeImage(resource, temp, width, height, mode);

            //            AmazonS3ResourceUtils.writeFile(temp, resized);
            ExtendedResourceUtils.write(resized, temp);
            FileUtils.deleteQuietly(temp);
        }
    }
    return resized;
}

From source file:org.wso2.msf4j.spring.property.YamlFileApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Resource resource = applicationContext.getResource("classpath:" + YAML_CONFIG_FILE_NAME);
    if (!resource.exists()) {
        resource = applicationContext.getResource("file:" + YAML_CONFIG_FILE_NAME);
    }/*from ww w.  j  av  a  2 s  .  co m*/

    if (resource.exists()) {
        List<Properties> applicationYmlProperties = new ArrayList<>();
        String[] activeProfileNames = null;
        try (InputStream input = resource.getInputStream()) {
            Yaml yml = new Yaml(new SafeConstructor());
            Iterable<Object> objects = yml.loadAll(input);
            for (Object obj : objects) {
                Map<String, Object> flattenedMap = getFlattenedMap(asMap(obj));
                Properties properties = new Properties();
                properties.putAll(flattenedMap);
                Object activeProfile = properties.get("spring.profiles.active");
                if (activeProfile != null) {
                    activeProfileNames = activeProfile.toString().split(",");
                }
                applicationYmlProperties.add(properties);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Couldn't find " + YAML_CONFIG_FILE_NAME, e);
        } catch (IOException e) {
            throw new RuntimeException("Error while reading " + YAML_CONFIG_FILE_NAME, e);
        }

        if (activeProfileNames == null) {
            activeProfileNames = applicationContext.getEnvironment().getActiveProfiles();
        }

        for (Properties properties : applicationYmlProperties) {
            String profile = properties.getProperty("spring.profiles");
            PropertySource<?> propertySource;
            if (profile == null) {
                propertySource = new MapPropertySource(YAML_CONFIG_FILE_NAME, new HashMap(properties));
                applicationContext.getEnvironment().getPropertySources().addLast(propertySource);
            } else if (activeProfileNames != null && ("default".equals(profile)
                    || (activeProfileNames.length == 1 && activeProfileNames[0].equals(profile)))) {
                propertySource = new MapPropertySource(YAML_CONFIG_FILE_NAME + "[" + profile + "]",
                        new HashMap(properties));
                applicationContext.getEnvironment().getPropertySources().addAfter("systemEnvironment",
                        propertySource);
            }
            activeProfileNames = applicationContext.getEnvironment().getActiveProfiles();
        }
    }
    applicationContext.getEnvironment().getActiveProfiles();
}

From source file:org.mifos.tools.service.PPIUploaderService.java

private void uploadLookupTable(final Properties properties, final MifosRestResource restResource,
        final String countryCode, final Long surveyId) {
    final Resource lookupTableResource = this.resourceLoader
            .getResource("classpath:template/" + countryCode.toUpperCase() + "/lookuptable.json");

    if (lookupTableResource.exists()) {
        try {//from  www  .  j  a  v  a  2  s . c om
            final JsonReader reader = new JsonReader(
                    new InputStreamReader(lookupTableResource.getInputStream()));
            final List<LookupTable> lookupTables = this.gson.fromJson(reader,
                    new TypeToken<List<LookupTable>>() {
                    }.getType());
            if (lookupTables != null && !lookupTables.isEmpty()) {
                for (final LookupTable lookupTable : lookupTables) {
                    restResource.createLookupTable(this.authToken(properties), properties.getProperty("tenant"),
                            PPIUploaderConstant.CONTENT_TYPE, surveyId, lookupTable);
                }
            }
        } catch (Throwable th) {
            this.logger.error("Error while uploading survey!", th);
            System.out.println("Could not upload survey! See logfile for more information.");
        }
    } else {
        System.out.println("Unknown country code " + countryCode + "!");
    }
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskUnitTests.java

/**
 * Test the constructor on error case.//from   www  . jav  a  2  s. c  om
 *
 * @throws IOException on error
 */
@Test(expected = IOException.class)
public void cantConstruct() throws IOException {
    final JobsProperties properties = new JobsProperties();
    properties.getUsers().setRunAsUserEnabled(false);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(false);
    Assert.assertNotNull(new DiskCleanupTask(new DiskCleanupProperties(), Mockito.mock(TaskScheduler.class),
            jobsDir, Mockito.mock(JobSearchService.class), properties, Mockito.mock(Executor.class),
            Mockito.mock(Registry.class)));
}

From source file:com.github.mrstampy.gameboot.messages.context.GameBootContextLoader.java

/**
 * Gets the for locale./*from   w  w w  .  j  a v  a 2  s .c o  m*/
 *
 * @param suffix
 *          the suffix
 * @return the for locale
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public Map<Integer, ResponseContext> getForLocale(String suffix) throws IOException {
    Resource r = getOverridableErrorResource(suffix);

    if (r == null || !r.exists()) {
        log.trace("No error.properties for {}", suffix);
        return null;
    }

    Properties p = new Properties();
    p.load(r.getInputStream());

    List<String> codes = getCodes(p);

    Map<Integer, ResponseContext> map = new ConcurrentHashMap<>();

    codes.forEach(c -> createError(c, p, map));
    return map;
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskUnitTests.java

/**
 * Test the constructor on error case./* w w  w.  j  a va2s  .com*/
 *
 * @throws IOException on error
 */
@Test
public void wontScheduleOnNonUnixWithSudo() throws IOException {
    Assume.assumeTrue(!SystemUtils.IS_OS_UNIX);
    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(true);
    Assert.assertNotNull(new DiskCleanupTask(new DiskCleanupProperties(), scheduler, jobsDir,
            Mockito.mock(JobSearchService.class), new JobsProperties(), Mockito.mock(Executor.class),
            Mockito.mock(Registry.class)));
    Mockito.verify(scheduler, Mockito.never()).schedule(Mockito.any(Runnable.class),
            Mockito.any(Trigger.class));
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskUnitTests.java

/**
 * Test the constructor./*from ww  w .j  ava  2 s .c  om*/
 *
 * @throws IOException on error
 */
@Test
public void willScheduleOnUnixWithSudo() throws IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(true);
    Assert.assertNotNull(new DiskCleanupTask(new DiskCleanupProperties(), scheduler, jobsDir,
            Mockito.mock(JobSearchService.class), new JobsProperties(), Mockito.mock(Executor.class),
            Mockito.mock(Registry.class)));
    Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class),
            Mockito.any(Trigger.class));
}

From source file:org.eclipse.gemini.blueprint.test.AbstractConfigurableBundleCreatorTests.java

/**
 * Returns the settings used for creating this jar. This method tries to
 * locate and load the settings from the location indicated by
 * {@link #getSettingsLocation()}. If no file is found, the default
 * settings will be used./* w w  w  .  ja va2s. co m*/
 * 
 * <p/> A non-null properties object will always be returned.
 * 
 * @return settings for creating the on the fly jar
 * @throws Exception if loading the settings file fails
 */
protected Properties getSettings() throws Exception {
    Properties settings = new Properties(getDefaultSettings());
    // settings.setProperty(ROOT_DIR, getRootPath());
    Resource resource = new ClassPathResource(getSettingsLocation());

    if (resource.exists()) {
        InputStream stream = resource.getInputStream();
        try {
            if (stream != null) {
                settings.load(stream);
                logger.debug("Loaded jar settings from " + getSettingsLocation());
            }
        } finally {
            IOUtils.closeStream(stream);
        }
    } else
        logger.info(getSettingsLocation() + " was not found; using defaults");

    return settings;
}

From source file:org.jnap.core.assets.StaticAssetsHandler.java

protected void resetResource(Resource resource) throws IOException {
    File file = null;/* ww  w . j  a v  a 2  s . c om*/
    if (!resource.exists()) {
        ServletContextResource servletResource = (ServletContextResource) resource;
        file = new File(WebUtils.getRealPath(servletContext, "/") + servletResource.getPath());
    } else {
        file = resource.getFile();
    }
    if (file.exists()) {
        file.delete();
    }
    file.createNewFile();
}

From source file:org.brekka.stillingar.spring.snapshot.ResourceSnapshotManager.java

/**
 * Perform the load operation that will convert a resource into a snapshot.
 * @param resourceToLoad the resouce to load into a snapshot
 * @return the snapshot loaded from the specified resource
 * @throws ConfigurationException if something goes wrong such as an IO error.
 *///  w w w .j  a  va 2 s.  c o  m
protected Snapshot performLoad(Resource resourceToLoad) {
    Snapshot snapshot = null;
    if (resourceToLoad != null && resourceToLoad.exists() && resourceToLoad.isReadable()) {
        InputStream sourceStream = null;
        try {
            sourceStream = resourceToLoad.getInputStream();
            long timestamp = resourceToLoad.lastModified();
            ConfigurationSource configurationSource = configurationSourceLoader.parse(sourceStream, null);
            snapshot = new ResourceSnapshot(configurationSource, new Date(timestamp), resourceToLoad);
        } catch (IOException e) {
            throw new ConfigurationException(format("Resouce '%s'", resourceToLoad), e);
        } catch (RuntimeException e) {
            // Wrap to include location details
            throw new ConfigurationException(format("Resouce '%s' processing problem", resourceToLoad), e);
        } finally {
            closeQuietly(sourceStream);
        }
    }
    return snapshot;
}