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

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

Introduction

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

Prototype

@Override
public boolean exists() 

Source Link

Document

This implementation checks for the resolution of a resource URL.

Usage

From source file:fr.univlorraine.mondossierweb.config.SpringConfig.java

/**
 * Messages de l'application//from  www . j a v  a2 s  . co m
 * @return
 */
@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();

    List<String> filesToLoad = new LinkedList<String>();

    //Ajout du fichier de conf optionnel
    ClassPathResource res = new ClassPathResource("i18n/messages.properties");
    if (res.exists()) {
        filesToLoad.add("i18n/messages");
    }
    //Ajout du fichier de conf par dfaut
    filesToLoad.add("i18n/messages-default");

    //Ajout du fichier de conf optionnel
    ClassPathResource resv = new ClassPathResource("i18n/vaadin-messages.properties");
    if (resv.exists()) {
        filesToLoad.add("i18n/vaadin-messages");
    }
    //Ajout du fichier de conf par dfaut
    filesToLoad.add("i18n/vaadin-messages-default");

    resourceBundleMessageSource.setBasenames(filesToLoad.toArray(new String[filesToLoad.size()]));
    return resourceBundleMessageSource;
}

From source file:nl.surfnet.coin.db.AbstractInMemoryDatabaseTest.java

/**
 * We use an in-memory database - no need for Spring in this one - and
 * populate it with the sql statements in test-data-eb.sql
 * //from  w  w w . j  a  v a  2s .c o  m
 * @throws Exception
 *           unexpected
 */
@Before
public void before() throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setPassword("");
    dataSource.setUsername("sa");
    String url = getDataSourceUrl();
    dataSource.setUrl(url);
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");

    jdbcTemplate = new JdbcTemplate(dataSource);

    ClassPathResource resource = new ClassPathResource(getMockDataContentFilename());
    logger.debug("Loading database content from " + resource);
    if (resource.exists()) {
        final String sql = IOUtils.toString(resource.getInputStream());
        final String[] split = sql.split(";");
        for (String s : split) {
            if (!StringUtils.hasText(s)) {
                continue;
            }
            jdbcTemplate.execute(s + ';');
        }
    }
}

From source file:com.ephesoft.dcma.core.service.ServerHeartBeatMonitor.java

/**
 * Gets stream to read workflow properties for the server.
 * /*www  .j  a v  a  2 s . c o m*/
 * @return {@link BufferedInputStream}
 * @throws IOException
 */
private BufferedInputStream getHeartBeatPropertiesReaderStream() throws IOException {
    BufferedInputStream propertyInputStream = null;
    String filePath = ICommonConstants.DCMA_HEART_BEAT_PROPERTIES;
    ClassPathResource classPathResourse = new ClassPathResource(filePath);
    if (classPathResourse.exists()) {
        propertyInputStream = new BufferedInputStream(classPathResourse.getInputStream());
    }
    return propertyInputStream;
}

From source file:chronos.mbeans.QuartzSchedulerAdapter.java

/**
 * @param factory//from w  w  w. j a  v  a  2s . co m
 *        {@link StdSchedulerFactory}
 * @throws SchedulerException
 *         on exception
 */
private void createOwnScheduler(final StdSchedulerFactory factory) throws SchedulerException {
    logger.debug("Creating new Quartz scheduler...");
    final ClassPathResource resource = new ClassPathResource("quartz.properties");
    if (resource.exists() && resource.isReadable()) {
        logger.debug("Configuring Quartz from resource: " + resource.getPath());
        try {
            final InputStream is = resource.getInputStream();
            try {
                factory.initialize(is);
            } finally {
                is.close();
            }
        } catch (final IOException e) {
            logger.debug("Exception initializing from resource: " + e.getMessage(), e);
        }
    } else {
        logger.debug("Using minimal default properties");
        final Properties props = new Properties();
        props.put(PROP_SCHED_INSTANCE_NAME, schedulerInstanceName);
        props.put(PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());
        factory.initialize(props);
    }
}

From source file:org.alfresco.textgen.TextGenerator.java

public TextGenerator(String configPath) {
    ClassPathResource cpr = new ClassPathResource(configPath);
    if (!cpr.exists()) {
        throw new RuntimeException("No resource found: " + configPath);
    }//from w  w w .j  ava 2  s.  c  o  m
    InputStream is = null;
    InputStreamReader r = null;
    BufferedReader br = null;
    try {
        int lineNumber = 0;
        is = cpr.getInputStream();
        r = new InputStreamReader(is, "UTF-8");
        br = new BufferedReader(r);

        String line;
        while ((line = br.readLine()) != null) {
            lineNumber++;
            if (lineNumber == 1) {
                // skip header
                continue;
            }
            String[] split = line.split("\t");

            if (split.length != 7) {
                //System.out.println("Skipping "+lineNumber);
                continue;
            }

            String word = split[1].replaceAll("\\*", "");
            String mode = split[3].replaceAll("\\*", "");
            long frequency = Long.parseLong(split[4].replaceAll("#", "").trim());

            // Single varient
            if (mode.equals(":")) {
                if (!ignore(word)) {
                    wordGenerator.addWord(splitAlternates(word), frequency == 0 ? 1 : frequency);
                }
            } else {
                if (word.equals("@")) {
                    // varient
                    if (!ignore(mode)) {
                        wordGenerator.addWord(splitAlternates(mode), frequency == 0 ? 1 : frequency);
                    }
                } else {
                    //System.out.println("Skipping totla and using varients for " + word + " @ " + lineNumber);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to load resource " + configPath);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
            }
        }
        if (r != null) {
            try {
                r.close();
            } catch (Exception e) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:de.ingrid.admin.service.ElasticsearchNodeFactoryBean.java

private void internalCreateNode() {

    final NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder();

    // set inital configurations coming from the property file
    Properties p = new Properties();
    try {/*from   w w  w  .j  a v  a2 s . co  m*/
        ClassPathResource resource = new ClassPathResource("/elasticsearch.properties");
        if (resource.exists()) {
            p.load(resource.getInputStream());
            nodeBuilder.getSettings().put(p);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // other possibilities for configuration
    // TODO: remove those not needed!
    if (null != configLocation) {
        internalLoadSettings(nodeBuilder, configLocation);
    }

    if (null != configLocations) {
        for (final Resource location : configLocations) {
            internalLoadSettings(nodeBuilder, location);
        }
    }

    if (null != settings) {
        nodeBuilder.getSettings().put(settings);
    }
    if (null != properties) {
        nodeBuilder.getSettings().put(properties);
    }

    Node localNode = nodeBuilder.node();
    localNode.client().admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet();
    node = localNode;
}

From source file:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }//from w  w  w .ja  va 2s.  c  om

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

/**
 * Returns a {@link ClassLoaderOffer} containing the requested file in the classpath, if possible.<br/>
 * If the resource cannot be located, {@code null} is returned instead.
 * /*from   w ww.j  a  va  2 s .  co  m*/
 * @param fileName the name of the resource
 * @return the offer (can be {@code null})
 */
protected ClassLoaderOffer collectFile(String fileName) {
    try {
        ClassPathResource resource = new ClassPathResource(fileName);
        if (resource.exists()) {
            File file = resource.getFile();
            ClassLoaderFile classLoaderFile = new ClassLoaderFile(fileName, file.lastModified(),
                    ContentType.ROFILE, Files.toByteArray(file));
            return new ClassLoaderOffer(null, 0, new ClassLoaderFile[] { classLoaderFile });
        }
    } catch (IOException e) {
        // ignore
    }
    return null;
}

From source file:info.jtrac.config.JtracConfigurer.java

private void configureJtrac() throws Exception {

    String jtracHome = null;//w  ww  .j  a v  a  2 s . c  o m
    ClassPathResource jtracInitResource = new ClassPathResource("jtrac-init.properties");
    // jtrac-init.properties assumed to exist
    Properties props = loadProps(jtracInitResource.getFile());
    logger.info("found 'jtrac-init.properties' on classpath, processing...");
    jtracHome = props.getProperty("jtrac.home");
    if (jtracHome != null) {
        logger.info("'jtrac.home' property initialized from 'jtrac-init.properties' as '" + jtracHome + "'");
    }
    //======================================================================
    FilenameFilter ff = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("messages_") && name.endsWith(".properties");
        }
    };
    File[] messagePropsFiles = jtracInitResource.getFile().getParentFile().listFiles(ff);
    String locales = "en";
    for (File f : messagePropsFiles) {
        int endIndex = f.getName().indexOf('.');
        String localeCode = f.getName().substring(9, endIndex);
        locales += "," + localeCode;
    }
    logger.info("locales available configured are '" + locales + "'");
    props.setProperty("jtrac.locales", locales);
    //======================================================================
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in 'jtrac-init.properties', trying system properties.");
        jtracHome = System.getProperty("jtrac.home");
        if (jtracHome != null) {
            logger.info("'jtrac.home' property initialized from system properties as '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in system properties, trying servlet init paramters.");
        jtracHome = servletContext.getInitParameter("jtrac.home");
        if (jtracHome != null) {
            logger.info("Servlet init parameter 'jtrac.home' exists: '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        jtracHome = System.getProperty("user.home") + "/.jtrac";
        logger.warn("Servlet init paramter  'jtrac.home' does not exist.  Will use 'user.home' directory '"
                + jtracHome + "'");
    }
    //======================================================================
    File homeFile = new File(jtracHome);
    if (!homeFile.exists()) {
        homeFile.mkdir();
        logger.info("directory does not exist, created '" + homeFile.getPath() + "'");
        if (!homeFile.exists()) {
            String message = "invalid path '" + homeFile.getAbsolutePath()
                    + "', try creating this directory first.  Aborting.";
            logger.error(message);
            throw new Exception(message);
        }
    } else {
        logger.info("directory already exists: '" + homeFile.getPath() + "'");
    }
    props.setProperty("jtrac.home", homeFile.getAbsolutePath());
    //======================================================================
    File attachmentsFile = new File(jtracHome + "/attachments");
    if (!attachmentsFile.exists()) {
        attachmentsFile.mkdir();
        logger.info("directory does not exist, created '" + attachmentsFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + attachmentsFile.getPath() + "'");
    }
    File indexesFile = new File(jtracHome + "/indexes");
    if (!indexesFile.exists()) {
        indexesFile.mkdir();
        logger.info("directory does not exist, created '" + indexesFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + indexesFile.getPath() + "'");
    }
    //======================================================================
    File propsFile = new File(homeFile.getPath() + "/jtrac.properties");
    if (!propsFile.exists()) {
        propsFile.createNewFile();
        logger.info("properties file does not exist, created '" + propsFile.getPath() + "'");
        OutputStream os = new FileOutputStream(propsFile);
        Writer out = new PrintWriter(os);
        try {
            out.write("database.driver=org.hsqldb.jdbcDriver\n");
            out.write("database.url=jdbc:hsqldb:file:${jtrac.home}/db/jtrac\n");
            out.write("database.username=sa\n");
            out.write("database.password=\n");
            out.write("hibernate.dialect=org.hibernate.dialect.HSQLDialect\n");
            out.write("hibernate.show_sql=false\n");
        } finally {
            out.close();
            os.close();
        }
        logger.info("HSQLDB will be used.  Finished creating '" + propsFile.getPath() + "'");
    } else {
        logger.info("'jtrac.properties' file exists: '" + propsFile.getPath() + "'");
    }
    //======================================================================
    String version = "0.0.0";
    String timestamp = "0000";
    ClassPathResource versionResource = new ClassPathResource("jtrac-version.properties");
    if (versionResource.exists()) {
        logger.info("found 'jtrac-version.properties' on classpath, processing...");
        Properties versionProps = loadProps(versionResource.getFile());
        version = versionProps.getProperty("version");
        timestamp = versionProps.getProperty("timestamp");
    } else {
        logger.info("did not find 'jtrac-version.properties' on classpath");
    }
    logger.info("jtrac.version = '" + version + "'");
    logger.info("jtrac.timestamp = '" + timestamp + "'");
    props.setProperty("jtrac.version", version);
    props.setProperty("jtrac.timestamp", timestamp);
    props.setProperty("database.validationQuery", "SELECT 1");
    props.setProperty("ldap.url", "");
    props.setProperty("ldap.activeDirectoryDomain", "");
    props.setProperty("ldap.searchBase", "");
    props.setProperty("database.datasource.jndiname", "");
    // set default properties that can be overridden by user if required
    setProperties(props);
    // finally set the property that spring is expecting, manually
    FileSystemResource fsr = new FileSystemResource(propsFile);
    setLocation(fsr);
}