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:de.ingrid.ibus.comm.registry.Registry.java

/**
 * Creates a registry with a given lifetime for IPlugs, a given auto activation value for new IPlugs and a IPlug
 * factory.//from   ww  w.jav  a2s  .  c  o  m
 *
 * @param lifeTimeOfPlugs     Life time of IPlugs. If the last life sign of a IPlug is longer than this value the IPlug is removed.
 * @param iplugAutoActivation The auto activation feature. If this is true all new IPlugs are activated by default otherwise not.
 * @param factory             The factory that creates IPlugs.
 */
public Registry(long lifeTimeOfPlugs, boolean iplugAutoActivation, IPlugProxyFactory factory) {

    ClassPathResource ibusSettings = new ClassPathResource("/activatedIplugs.properties");

    try {
        if (ibusSettings.exists()) {
            this.fFile = ibusSettings.getFile();
        } else {
            File dir = new File("conf");
            if (!dir.exists()) {
                dir.mkdir();
            }
            this.fFile = new File(dir, "activatedIplugs.properties");
            if (!this.fFile.exists()) {
                this.fFile.createNewFile();
            }

        }
    } catch (Exception e) {
        if (fLogger.isErrorEnabled()) {
            fLogger.error("Cannot open the file for saving the activation state of the iplugs.", e);
        }
    }

    loadProperties();
    this.fLifeTime = lifeTimeOfPlugs;
    this.fIplugAutoActivation = iplugAutoActivation;
    this.fProxyFactory = factory;

    // start iplug timeout scanner
    PooledThreadExecutor.getInstance().execute(new RegistryIPlugTimeoutScanner());
}

From source file:nl.surfnet.spring.security.opensaml.controller.AuthnRequestController.java

@RequestMapping(value = { "/OpenSAML.sso/Metadata" }, method = RequestMethod.GET)
public void metaData(HttpServletResponse response) throws IOException {
    /*/*from w  ww .  ja  va  2s. c o  m*/
     * see https://rnd.feide.no/2010/01/05/
     * metadata_aggregation_requirements_specification/#section_5_5_3
     */
    response.setHeader("Content-Type", "application/xml");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    String result = IOUtils.toString(new ClassPathResource("metadata-template-sp.xml").getInputStream());

    result = result.replace("%VALID_UNTIL%",
            df.format(new DateTime().toDateMidnight().toDateTime().plusDays(1).toDate()));
    result = result.replace("%ENTITY_ID%", entityID);
    result = result.replace("%ASSERTION_CONSUMER_SERVICE_URL%", assertionConsumerServiceURL);

    Properties props = new Properties();
    props.load(new ClassPathResource("metadata.defaults.properties").getInputStream());

    if (StringUtils.hasText(metaDataProperties)) {
        ClassPathResource classPathResource = new ClassPathResource(metaDataProperties);
        if (classPathResource.exists()) {
            props.load(classPathResource.getInputStream());
        }
    }

    result = result.replace("%NAMEID_FORMAT%", props.getProperty("nameid-format"));

    result = result.replace("%SERVICE_NAME_EN%", props.getProperty("service-name-en"));
    result = result.replace("%SERVICE_NAME_NL%", props.getProperty("service-name-nl"));
    result = result.replace("%SERVICE_DESCRIPTION_EN%", props.getProperty("service-description-en"));
    result = result.replace("%SERVICE_DESCRIPTION_NL%", props.getProperty("service-description-nl"));

    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_GIVEN_NAME%",
            props.getProperty("contact-person-administrative-given-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_SUR_NAME%",
            props.getProperty("contact-person-administrative-sur-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_EMAIL%",
            props.getProperty("contact-person-administrative-email"));

    result = result.replace("%CONTACT_PERSON_TECHNICAL_GIVEN_NAME%",
            props.getProperty("contact-person-technical-given-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_SUR_NAME%",
            props.getProperty("contact-person-technical-sur-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_EMAIL%",
            props.getProperty("contact-person-technical-email"));

    result = result.replace("%CONTACT_PERSON_SUPPORT_GIVEN_NAME%",
            props.getProperty("contact-person-support-given-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_SUR_NAME%",
            props.getProperty("contact-person-support-sur-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_EMAIL%",
            props.getProperty("contact-person-support-email"));

    response.getOutputStream().write(result.getBytes());
    response.flushBuffer();

}

From source file:org.aon.esolutions.appconfig.client.web.SystemPropertiesListener.java

private void loadPropsFromClasspath(ServletContext sc) {
    String propertiesLocationProp = sc.getInitParameter("classpath.file.location");

    Properties systemProps = System.getProperties();
    Properties loadedProps = new Properties();
    ClassPathResource appConfigResource = new ClassPathResource(propertiesLocationProp);
    if (appConfigResource.exists()) {

        try {/*from   w w w .j  a  va 2 s  . co  m*/
            loadedProps.load(appConfigResource.getInputStream());

            for (Map.Entry<Object, Object> e : loadedProps.entrySet()) {
                if (systemProps.containsKey(e.getKey()) == false)
                    systemProps.put(e.getKey(), e.getValue());
            }
        } catch (Exception e) {
            logger.error("Error loading properties", e);
        }
    }
}

From source file:org.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java

@Override
public boolean checkForResourceOnClassPath(String name) {
    ClassPathResource resource = lookupResourceOnClassPath(name);
    return (resource != null && resource.exists());
}

From source file:org.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java

protected ClassPathResource lookupResourceOnClassPath(String name) {
    if (fileServiceClasspathDirectory != null && !"".equals(fileServiceClasspathDirectory)) {
        try {// w  w w .j av a2 s. co m
            String resourceName = FilenameUtils
                    .separatorsToUnix(FilenameUtils.normalize(fileServiceClasspathDirectory + '/' + name));
            ClassPathResource resource = new ClassPathResource(resourceName);
            if (resource.exists()) {
                return resource;
            }
        } catch (Exception e) {
            LOG.error("Error getting resource from classpath", e);
        }
    }
    return null;
}

From source file:org.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java

@Override
public InputStream getClasspathResource(String name) {
    try {/*from w w w  .  j  a  v  a2  s . c o m*/
        ClassPathResource resource = lookupResourceOnClassPath(name);
        if (resource != null && resource.exists()) {
            InputStream assetFile = resource.getInputStream();
            BufferedInputStream bufferedStream = new BufferedInputStream(assetFile);

            // Wrapping the buffered input stream with a globally shared stream allows us to 
            // vary the way the file names are generated on the file system.    
            // This benefits us (mainly in our demo site but their could be other uses) when we
            // have assets that are shared across sites that we also need to resize. 
            GloballySharedInputStream globallySharedStream = new GloballySharedInputStream(bufferedStream);
            globallySharedStream.mark(0);
            return globallySharedStream;
        } else {
            return null;
        }
    } catch (Exception e) {
        LOG.error("Error getting resource from classpath", e);
    }
    return null;
}

From source file:org.easycloud.las.core.util.Resources.java

/**
 * Provide a means to determine if a file name passed exists.
 * Good idea to call this before calling the loadProperties()
 * method with the file name if you dont want to throw a file
 * not found exception. If the file name passed contains directory
 * information ( a File.separator character ) then we look to
 * see if the file exists with the passed name as is.
 * If the file name contains no separator character, then it is
 * assumed to be the name of a resource, and we will look to see
 * if a resource of the name exists on the classpath. We do this
 * by trying to create a ClassPathResource with the passed name and
 * see if it exists./*from  w  w  w.ja  va  2s  . c o m*/
 *
 * @param fileName the name of the file to be checked
 * @return true if the file exists.
 */
public static boolean resourceExists(String fileName) {
    boolean rc = false;
    if (fileName.contains(File.separator)) {
        File resource = new File(fileName);
        if (resource.exists()) {
            rc = true;
        }
    } else {
        ClassPathResource res = new ClassPathResource(fileName);
        if (res.exists()) {
            rc = true;
        }
    }
    return rc;
}

From source file:org.kuali.kfs.sys.service.impl.ReportGenerationServiceImpl.java

/**
 * The dataSource can be an instance of JRDataSource, java.util.Collection or object array.
 * //from  w w  w.  j a v a  2  s  . c o m
 * @see org.kuali.kfs.sys.batch.service.ReportGenerationService#generateReportToPdfFile(java.util.Map, java.lang.Object, java.lang.String,
 *      java.lang.String)
 */
public void generateReportToPdfFile(Map<String, Object> reportData, Object dataSource, String template,
        String reportFileName) {
    ClassPathResource resource = getReportTemplateClassPathResource(
            template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    if (resource == null || !resource.exists()) {
        throw new IllegalArgumentException(
                "Cannot find the template file: " + template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    }

    try {
        if (reportData != null
                && reportData.containsKey(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME)) {
            Map<String, String> subReports = (Map<String, String>) reportData
                    .get(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME);
            String subReportDirectory = (String) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR);
            compileSubReports(subReports, subReportDirectory);
        }

        String designTemplateName = template.concat(ReportGeneration.DESIGN_FILE_EXTENSION);
        InputStream jasperReport = new FileInputStream(compileReportTemplate(designTemplateName));

        JRDataSource jrDataSource = JasperReportsUtils.convertReportData(dataSource);

        reportFileName = reportFileName + ReportGeneration.PDF_FILE_EXTENSION;
        File reportDirectory = new File(StringUtils.substringBeforeLast(reportFileName, File.separator));
        if (!reportDirectory.exists()) {
            reportDirectory.mkdir();
        }

        JasperRunManager.runReportToPdfStream(jasperReport, new FileOutputStream(reportFileName),
                decorateReportData(reportData), jrDataSource);
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException("Fail to generate report.", e);
    }
}

From source file:org.kuali.kfs.sys.service.impl.ReportGenerationServiceImpl.java

/**
 * @see org.kuali.kfs.sys.batch.service.ReportGenerationService#generateReportToOutputStream(java.util.Map, java.lang.Object,
 *      java.lang.String, java.io.ByteArrayOutputStream)
 *///from w  w  w . jav  a 2s  .com
public void generateReportToOutputStream(Map<String, Object> reportData, Object dataSource, String template,
        ByteArrayOutputStream baos) {
    ClassPathResource resource = getReportTemplateClassPathResource(
            template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    if (resource == null || !resource.exists()) {
        throw new IllegalArgumentException(
                "Cannot find the template file: " + template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    }

    try {
        if (reportData != null
                && reportData.containsKey(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME)) {
            Map<String, String> subReports = (Map<String, String>) reportData
                    .get(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME);
            String subReportDirectory = (String) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR);
            compileSubReports(subReports, subReportDirectory);
        }

        String designTemplateName = template.concat(ReportGeneration.DESIGN_FILE_EXTENSION);
        InputStream jasperReport = new FileInputStream(compileReportTemplate(designTemplateName));

        JRDataSource jrDataSource = JasperReportsUtils.convertReportData(dataSource);

        JasperRunManager.runReportToPdfStream(jasperReport, baos, decorateReportData(reportData), jrDataSource);
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException("Fail to generate report.", e);
    }
}