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:com.scottieknows.test.autoconfigure.PostgresAutoConfiguration.java

private Collection<String> getSqls(String file, ApplicationContext ctx) throws IOException {
    StringBuilder builder = new StringBuilder();
    Resource resource = ctx.getResource(file);
    if (!resource.exists()) {
        return Collections.emptyList();
    }/*  www. j  a  v a 2s.  c  o m*/
    try (BufferedReader reader = new BufferedReader(new FileReader(resource.getFile()))) {
        String line;
        while (null != (line = reader.readLine())) {
            if (!line.startsWith("--")) {
                builder.append(line);
            }
        }
    }
    return Arrays.asList(builder.toString().split(";"));
}

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

protected boolean isDirectory(Resource sResource) throws IOException {
    if (sResource.exists()) {
        return sResource.getFile().isDirectory();
    } else {/*  w  ww.j  a  va 2  s.c om*/
        // Dirty trick to tell if the resource is a directory or not when it does not exist yet
        return sResource.createRelative(SAME_RELATIVE_PATH).getFile().getCanonicalPath()
                .equals(sResource.getFile().getCanonicalPath());
    }
}

From source file:com.khs.test.jdbc.datasource.DSInitializer.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;/* ww  w .  j  a  v  a  2 s.com*/
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback() {

        @SuppressWarnings("unchecked")
        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.works.common.data.layer.datasource.InitializingDataSourceFactoryBean.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;/* www. j  a  v  a2  s  . co m*/
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.mitre.jose.TestJWKSetKeyStore.java

@Test(expected = IllegalArgumentException.class)
public void ksBadJWKinput() throws IOException {

    byte jwtbyte[] = RSAjwk.toString().getBytes();
    FileOutputStream out = new FileOutputStream(ks_file_badJWK);
    out.write(jwtbyte);/*from   w w w .  j a v a 2s. com*/
    out.close();

    JWKSetKeyStore ks_badJWK = new JWKSetKeyStore();
    Resource loc = new FileSystemResource(ks_file_badJWK);
    assertTrue(loc.exists());

    ks_badJWK.setLocation(loc);
    assertEquals(loc.getFilename(), ks_file_badJWK);

    ks_badJWK = new JWKSetKeyStore(null);
}

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

@Test
public void testGetStudioWebAppRootFile() throws Exception {
    GridFSStudioFileSystem sf = new GridFSStudioFileSystem(this.mongoFactory);
    sf.setServletContext(this.servletContext);
    Resource studioWebAppRootFile = sf.getStudioWebAppRoot();
    assertTrue(studioWebAppRootFile.exists());
    Resource studioWebInfFile = studioWebAppRootFile.createRelative("WEB-INF/");
    assertTrue(studioWebInfFile.exists());
    Resource webXmlFile = studioWebInfFile.createRelative(ProjectConstants.WEB_XML);
    assertTrue(webXmlFile.exists());// ww  w  . j  a va  2  s  . c  o m
}

From source file:org.dataconservancy.access.connector.SimpleConnectorIT.java

@Test
public void testGetStreamOk() throws IOException, DcsConnectorFault, SAXException, InvalidXmlException {
    final Resource entitiesDir = rl.getResource("/entities");
    assertTrue(entitiesDir.exists() && entitiesDir.getFile().canRead());

    final InputStream entityIn = underTest.getStream(String.format(ENTITY_ID, "test1"));
    assertNotNull(entityIn);//from w  w w. j a  va2  s  .  c om
    final File test1Entity = new File(entitiesDir.getFile(), "test1.xml");
    final String entityString = IOUtils.toString(entityIn);
    XMLAssert.assertXMLEqual(IOUtils.toString(new FileInputStream(test1Entity)), entityString);
    assertEquals(mb.buildSip(new FileInputStream(test1Entity)),
            mb.buildSip(IOUtils.toInputStream(entityString)));
}

From source file:com.haulmont.cuba.restapi.RestServicePermissions.java

protected void init() {
    String configName = AppContext.getProperty(CUBA_REST_SERVICES_CONFIG_PROP_NAME);
    StrTokenizer tokenizer = new StrTokenizer(configName);
    for (String location : tokenizer.getTokenArray()) {
        Resource resource = resources.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                loadConfig(Dom4j.readDocument(stream).getRootElement());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }//w ww  .  jav  a  2s  .  c  o m
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }
}

From source file:ar.com.zauber.commons.spring.web.controllers.InformationController.java

/**
 * @see AbstractController#handleRequest(HttpServletRequest,
 *      HttpServletResponse)/*from w w w  .jav  a2  s . com*/
 */
@Override
protected final ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final String uri = request.getRequestURI().substring(request.getContextPath().length());

    if (uri.contains("..")) {
        throw new IllegalArgumentException("..");
    }
    final int i = uri.lastIndexOf('.');
    String view = (i == -1) ? uri : uri.substring(1, i);
    while (view.startsWith("/")) {
        view = view.substring(1);
    }
    while (view.endsWith("/")) {
        view = view.substring(0, view.length() - 1);
    }

    final Resource r = getApplicationContext()
            .getResource("/WEB-INF/templates/jsp/" + baseView + view + ".jsp");
    final ModelAndView ret;
    if (r.exists()) {
        ret = new ModelAndView(baseView + view);
    } else {
        response.sendError(404);
        ret = null;
    }
    return ret;
}

From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java

@Override
protected URL findResource(String name) {

    URL ret = null;/*from  w  w  w .j ava 2  s.c  o  m*/
    JarFile jarFile = null;

    try {
        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(name);
                jarFile.close();

                if (ze != null) {
                    ret = new URL("jar:" + entry.getURL() + "!/" + name);
                    break;
                }
            } else {
                Resource file = entry.createRelative(name);
                if (file.exists()) {
                    ret = file.getURL();
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }

    return ret;
}