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.geomajas.gwt.server.mvc.ResourceSerializationPolicyLocator.java

@Override
public SerializationPolicy loadPolicy(HttpServletRequest request, String moduleBaseURL, String strongName) {

    SerializationPolicy serializationPolicy = null;
    String serializationPolicyFilePath = SerializationPolicyLoader.getSerializationPolicyFileName(strongName);

    for (Resource directory : policyRoots) {
        Resource policy;
        try {//  www  . jav  a2s.c o m
            policy = directory.createRelative(serializationPolicyFilePath);
            if (policy.exists()) {
                // Open the RPC resource file and read its contents.
                InputStream is = policy.getInputStream();
                try {
                    if (is != null) {
                        try {
                            serializationPolicy = SerializationPolicyLoader.loadFromStream(is, null);
                            break;
                        } catch (ParseException e) {
                            log.error("Failed to parse the policy file '" + policy + "'", e);
                        } catch (IOException e) {
                            log.error("Could not read the policy file '" + policy + "'", e);
                        }
                    } else {
                        // existing spring resources should not return null, log anyways
                        log.error("Unexpected null stream from the policy file resource '" + policy + "'");
                    }
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            // Ignore this error
                        }
                    }
                }
            }
        } catch (IOException e1) {
            log.debug("Could not create the policy resource '" + serializationPolicyFilePath
                    + "' from parent resource " + directory, e1);
        }
    }
    if (serializationPolicy == null) {
        String message = "The serialization policy file '" + serializationPolicyFilePath
                + "' was not found; did you forget to include it in this deployment?";
        log.error(message);
    }
    return serializationPolicy;
}

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

/**
 * Test the constructor on error case.// w  w w . j  a va 2s  .  co  m
 *
 * @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), JobsProperties.getJobsPropertiesDefaults(),
            Mockito.mock(Executor.class), new SimpleMeterRegistry()));
    Mockito.verify(scheduler, Mockito.never()).schedule(Mockito.any(Runnable.class),
            Mockito.any(Trigger.class));
}

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

/**
 * Test the constructor.//from  w w  w . ja  va 2 s .  co m
 *
 * @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), JobsProperties.getJobsPropertiesDefaults(),
            Mockito.mock(Executor.class), new SimpleMeterRegistry()));
    Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class),
            Mockito.any(Trigger.class));
}

From source file:net.rrm.ehour.persistence.dbvalidator.DerbyDbValidator.java

private void insertData(Platform platform, Database model, String filename) throws IOException {
    Resource resource = new ClassPathResource(filename);

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

    DatabaseDataIO dataIO = new DatabaseDataIO();

    DataReader dataReader = dataIO.getConfiguredDataReader(platform, model);

    dataReader.getSink().start();

    dataIO.writeDataToDatabase(dataReader, new InputStreamReader(resource.getInputStream(), "UTF-8"));
}

From source file:org.springbyexample.jdbc.core.SqlScriptProcessor.java

/**
 * Initializes SQL scripts.//from   www.  j  a  v a  2s. com
 * @throws IOException
 */
public void process() throws IOException {
    if (lSqlScripts != null) {
        for (String sqlScript : lSqlScripts) {
            String sql = null;

            Resource resource = resourceLoader.getResource(sqlScript);

            if (!resource.exists()) {
                sql = sqlScript;
            } else {
                BufferedReader br = null;

                try {
                    if (charset == null) {
                        br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                    } else {
                        br = new BufferedReader(new InputStreamReader(resource.getInputStream(), charset));
                    }

                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                        sb.append("\n");
                    }

                    sql = sb.toString();
                } finally {
                    try {
                        br.close();
                    } catch (Exception e) {
                    }
                }
            }

            if (StringUtils.hasLength(sql)) {
                logger.debug("Initializing db with given sql");
                // execute sql
                template.execute(sql);
            }
        }
    }
}

From source file:com.github.mrstampy.gameboot.GameBootDependencyWriter.java

private void writeResource(Resource resource) throws IOException {
    String desc = resource.getDescription();
    log.debug("Creating file from {}", desc);

    if (!resource.exists()) {
        log.warn("No resource for {}", desc);
        return;/*ww w  . jav  a  2s  .  c om*/
    }

    int first = desc.indexOf("[");
    int last = desc.indexOf("]");

    desc = desc.substring(first + 1, last);

    File f = new File(".", desc);

    try (BufferedOutputStream bis = new BufferedOutputStream(new FileOutputStream(f))) {
        InputStream in = resource.getInputStream();
        byte[] b = new byte[in.available()];
        in.read(b);

        bis.write(b);
        bis.flush();
    }
}

From source file:org.carewebframework.api.alias.AliasTypeRegistry.java

/**
 * Load aliases from a property file./*from   w  ww .  java  2  s .c o m*/
 * 
 * @param applicationContext The application context.
 * @param propertyFile A property file.
 */
private void loadAliases(ApplicationContext applicationContext, String propertyFile) {
    if (propertyFile.isEmpty()) {
        return;
    }

    Resource[] resources;

    try {
        resources = applicationContext.getResources(propertyFile);
    } catch (IOException e) {
        log.error("Failed to locate alias property file: " + propertyFile, e);
        return;
    }

    for (Resource resource : resources) {
        if (!resource.exists()) {
            log.info("Did not find alias property file: " + resource.getFilename());
            continue;
        }

        InputStream is = null;

        try {
            is = resource.getInputStream();
            Properties props = new Properties();
            props.load(is);

            for (Entry<Object, Object> entry : props.entrySet()) {
                try {
                    register((String) entry.getKey(), (String) entry.getValue());
                    entryCount++;
                } catch (Exception e) {
                    log.error("Error registering alias for '" + entry.getKey() + "'.", e);
                }
            }

            fileCount++;
        } catch (IOException e) {
            log.error("Failed to load alias property file: " + resource.getFilename(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

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

/**
 * Test the constructor./*from w  w  w .j a v a2s  . c o m*/
 *
 * @throws IOException on error
 */
@Test
public void willScheduleOnUnixWithoutSudo() throws IOException {
    final JobsProperties properties = JobsProperties.getJobsPropertiesDefaults();
    properties.getUsers().setRunAsUserEnabled(false);
    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), properties, Mockito.mock(Executor.class),
            new SimpleMeterRegistry()));
    Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class),
            Mockito.any(Trigger.class));
}

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

@Override
public void afterPropertiesSet() throws Exception {
    for (String licenseFile : licenseFiles) {
        Resource res = resourceLoader.getResource(licenseFile);
        if (res != null && res.exists()) {
            try {
                log.info("Loading License Summary file {} of Project ", licenseFile);
                String fileName = StringUtils.lowerCase(res.getFilename());
                if (StringUtils.endsWith(fileName, ".json")) {
                    storeForType(DependencyType.NPM, loadFromJSON(res));
                } else if (StringUtils.endsWith(fileName, ".xml")) {
                    storeForType(DependencyType.MAVEN, loadFromXML(res));
                } else {
                    log.warn("Could not identify file ");
                }/*from  w ww.  ja  va  2 s .com*/
            } catch (Exception e) {
                log.warn("Could not load license file {}", licenseFile);
                if (log.isDebugEnabled()) {
                    log.error("Exception on loading license file", e);
                }
            }
        }
    }
    freeze();
}