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:fr.acxio.tools.agia.io.FilesOperationProcessorTest.java

@Test
public void testExecuteCopy() throws Exception {
    FilesOperationProcessor aProcessor = new FilesOperationProcessor();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/input.csv"));
    when(aFileResource1.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-input.csv"));
    when(aDestResource.exists()).thenReturn(false);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    assertFalse(aDestResource.getFile().exists());

    aProcessor.setSourceFactory(aSourceFactory);
    aProcessor.setDestinationFactory(aDestinationFactory);
    aProcessor.setOperation(Operation.COPY);
    aProcessor.setKey("outputFiles");
    aProcessor.afterPropertiesSet();//  w  ww.j a v a2 s  .com

    Map<String, Object> aData = new HashMap<String, Object>();
    aData.put("k1", "v1");

    Map<String, Object> aResult = aProcessor.process(aData);
    assertNotNull(aResult);
    assertNotNull(aResult.get("outputFiles"));

    String aOutputFilePath = ((List<String>) aResult.get("outputFiles")).get(0);
    assertEquals(new File("target/CP-input.csv").getCanonicalPath(), aOutputFilePath);

    assertTrue(aDestResource.getFile().exists());
    assertTrue(new File(aOutputFilePath).exists());
}

From source file:fr.acxio.tools.agia.io.IdentityResourceAwareItemReaderItemStreamTest.java

@Test
public void testRead() throws Exception {
    IdentityResourceAwareItemReaderItemStream aReader = new IdentityResourceAwareItemReaderItemStream();
    aReader.setName("testReader");

    Resource aResource = mock(Resource.class);
    when(aResource.getFilename()).thenReturn("file1");
    when(aResource.getDescription()).thenReturn("file1");
    when(aResource.exists()).thenReturn(true);

    aReader.setResource(aResource);/*from w w w.ja va  2 s .  c  om*/

    aReader.open(new ExecutionContext());
    assertEquals(aResource, aReader.read());
    assertNull(aReader.read());
    aReader.close();
}

From source file:fr.acxio.tools.agia.io.IdentityResourceAwareItemReaderItemStreamTest.java

@Test
public void testReadNotExists() throws Exception {
    IdentityResourceAwareItemReaderItemStream aReader = new IdentityResourceAwareItemReaderItemStream();
    aReader.setName("testReader");
    aReader.setStrict(false);//www  . j a  v a2s . com

    Resource aResource = mock(Resource.class);
    when(aResource.getFilename()).thenReturn("file1");
    when(aResource.getDescription()).thenReturn("file1");
    when(aResource.exists()).thenReturn(false);

    aReader.setResource(aResource);

    aReader.open(new ExecutionContext());
    assertNull(aReader.read());
    aReader.close();
}

From source file:com.wavemaker.tools.project.CloudFoundryStudioConfigurationTest.java

@Test
public void testDefaultStudioHome() throws Exception {
    StudioFileSystem sf = new GridFSStudioFileSystem(this.mongoFactory);
    Resource home = sf.getWaveMakerHome();
    assertTrue("we expected the home to exist; home: " + home, home.exists());
}

From source file:fr.acxio.tools.agia.io.IdentityResourceAwareItemReaderItemStreamTest.java

@Test
public void testReadNotExistsStrict() throws Exception {
    exception.expect(ItemStreamException.class);
    IdentityResourceAwareItemReaderItemStream aReader = new IdentityResourceAwareItemReaderItemStream();
    aReader.setName("testReader");
    aReader.setStrict(true);/*from www .j a  va 2s .  co m*/

    Resource aResource = mock(Resource.class);
    when(aResource.getFilename()).thenReturn("file1");
    when(aResource.getDescription()).thenReturn("file1");
    when(aResource.exists()).thenReturn(false);

    aReader.setResource(aResource);

    aReader.open(new ExecutionContext());
    assertNull(aReader.read());
    aReader.close();
}

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

private boolean uploadSurvey(final Properties properties, final MifosRestResource restResource,
        final String countryCode) {
    final Resource surveyResource = this.resourceLoader
            .getResource("classpath:template/" + countryCode.toUpperCase() + "/survey.json");

    if (surveyResource.exists()) {
        try {/*  w ww  .  ja  va2 s. c o  m*/
            final JsonReader reader = new JsonReader(new InputStreamReader(surveyResource.getInputStream()));
            final Survey survey = this.gson.fromJson(reader, Survey.class);
            restResource.createSurvey(this.authToken(properties), properties.getProperty("tenant"),
                    PPIUploaderConstant.CONTENT_TYPE, survey);
            return true;
        } 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 + "!");
    }
    return false;
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {

    Resource resource = null;//w w w  . j  a  v a 2  s  . c  o m
    ServletContext servletContext = applicationContext.getServletContext();
    WebApplicationContextUtils.initServletPropertySources(
            applicationContext.getEnvironment().getPropertySources(), servletContext,
            applicationContext.getServletConfig());

    ServletConfig servletConfig = applicationContext.getServletConfig();
    String locations = servletConfig == null ? null
            : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
    resource = getResource(servletContext, applicationContext, locations);

    if (resource == null) {
        servletContext.log("No YAML environment properties from servlet.  Defaulting to servlet context.");
        locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
        resource = getResource(servletContext, applicationContext, locations);
    }

    try {
        servletContext.log("Loading YAML environment properties from location: " + resource);
        YamlMapFactoryBean factory = new YamlMapFactoryBean();
        factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);

        List<Resource> resources = new ArrayList<Resource>();

        String defaultLocation = servletConfig == null ? null
                : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT);
        if (defaultLocation != null) {
            Resource defaultResource = new ClassPathResource(defaultLocation);
            if (defaultResource.exists()) {
                resources.add(defaultResource);
            }
        }

        resources.add(resource);
        factory.setResources(resources.toArray(new Resource[resources.size()]));

        Map<String, Object> map = factory.getObject();
        String yamlStr = (new Yaml()).dump(map);
        map.put(rawYamlKey, yamlStr);
        NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map);
        applicationContext.getEnvironment().getPropertySources().addLast(properties);
        applySpringProfiles(applicationContext.getEnvironment(), servletContext);
        applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext);

    } catch (Exception e) {
        servletContext.log("Error loading YAML environment properties from location: " + resource, e);
    }

}

From source file:com.github.eddumelendez.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration.java

private void populateDirectoryServer() throws LDAPException {
    String location = this.embeddedProperties.getLdif();
    if (StringUtils.hasText(location)) {
        try {//from   ww  w . java 2 s.  co  m
            Resource resource = this.applicationContext.getResource(this.embeddedProperties.getLdif());
            if (resource.exists()) {
                File tempFile = File.createTempFile("ldap_test_data", ".ldif");
                try {
                    InputStream inputStream = resource.getInputStream();
                    FileCopyUtils.copy(inputStream, new FileOutputStream(tempFile));
                    this.server.importFromLDIF(true, new LDIFReader(tempFile));
                } catch (LDAPException e) {
                    e.printStackTrace();
                } finally {
                    tempFile.delete();
                }
            }
        } catch (IOException ex) {
            throw new IllegalStateException("Unable to load resource from " + location, ex);
        }
    }
}

From source file:de.hybris.platform.acceleratorservices.process.strategies.impl.DefaultEmailTemplateTranslationStrategy.java

protected Map loadPropertyfile(final String path) {
    final Properties properties = new Properties();
    Reader reader = null;/* w  ww  . ja va2  s . c  om*/
    try {
        final Resource propertyResource = getApplicationContext().getResource(path);
        if (propertyResource != null && (propertyResource.exists()) && (propertyResource.isReadable())) {
            reader = new InputStreamReader(new BOMInputStream(propertyResource.getInputStream()), "UTF-8");
            properties.load(reader);
        }
    } catch (final IOException e) {
        throw new RendererException("Problem during rendering", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return properties;
}

From source file:grails.plugin.freemarker.GrailsTemplateLoader.java

public Object findTemplateSource(String templateName) throws IOException {
    //debugInfo(templateName);
    if (log.isDebugEnabled()) {
        log.debug("GrailsTemplateLoader Looking for template with name [" + templateName + "]");
    }/*  w w  w .j  ava  2 s . c om*/

    //add the slash back on
    //templateName = "/"+templateName;

    Resource resource = viewResourceLocator.getResource(templateName);
    if (resource != null && resource.exists()) {
        if (log.isDebugEnabled()) {
            log.debug("viewResourceLocator found [" + templateName + "] ");
        }
        return resource;
    }

    return null;
}