Example usage for org.springframework.core.io ResourceLoader getResource

List of usage examples for org.springframework.core.io ResourceLoader getResource

Introduction

In this page you can find the example usage for org.springframework.core.io ResourceLoader getResource.

Prototype

Resource getResource(String location);

Source Link

Document

Return a Resource handle for the specified resource location.

Usage

From source file:no.kantega.publishing.common.data.attributes.Attribute.java

public void setConfig(Element config, Map<String, String> model)
        throws InvalidTemplateException, SystemException {
    if (config != null) {
        name = config.getAttribute("name");
        if (name == null) {
            throw new InvalidTemplateException("name mangler i mal fil", null);
        }/*  w w  w  .  ja va  2 s  .c om*/

        if (name.contains("[") || name.contains("]")) {
            throw new InvalidTemplateException("[ og ] er ikke tillatt i navn p attributter", null);
        }

        editable = !(config.getAttribute("editable").equals("false"));
        regexp = config.getAttribute("regexp");
        String mapto = config.getAttribute("mapto");
        if (mapto == null || mapto.length() == 0) {
            mapto = config.getAttribute("field");
        }
        setField(mapto);
        title = config.getAttribute("title");
        if (title == null || title.length() == 0) {
            title = name.substring(0, 1).toUpperCase() + name.substring(1, name.length()).toLowerCase();
        }

        String isMandatory = config.getAttribute("mandatory");
        if ("true".equalsIgnoreCase(isMandatory)) {
            mandatory = true;
        }

        String doesInheritFromAncestors = config.getAttribute("inheritsfromancestors");
        if ("true".equalsIgnoreCase(doesInheritFromAncestors)) {
            inheritsFromAncestors = true;
        }

        String strMaxlength = config.getAttribute("maxlength");
        if (strMaxlength != null && strMaxlength.length() > 0) {
            this.maxLength = Integer.parseInt(strMaxlength);
        }

        String strEditableByRole = config.getAttribute("editablebyrole");
        if (strEditableByRole != null && strEditableByRole.length() > 0) {
            editableByRole = strEditableByRole.split(",");
            for (int i = 0; i < editableByRole.length; i++) {
                editableByRole[i] = editableByRole[i].trim();
            }
        } else {
            editableByRole = new String[] { Aksess.getEveryoneRole() };
        }

        String strShowInSites = config.getAttribute("showinsites");
        if (strShowInSites != null && strShowInSites.length() > 0) {
            showInSites = strShowInSites.split(",");
            for (int i = 0; i < showInSites.length; i++) {
                showInSites[i] = showInSites[i].trim();
            }
        }

        String strHideInSites = config.getAttribute("hideinsites");
        if (strHideInSites != null && strHideInSites.length() > 0) {
            hideInSites = strHideInSites.split(",");
            for (int i = 0; i < hideInSites.length; i++) {
                hideInSites[i] = hideInSites[i].trim();
            }
        }

        if ("true".equalsIgnoreCase(config.getAttribute("hideifempty"))) {
            hideIfEmpty = true;
        }

        String defaultValue = config.getAttribute("default");
        if (value == null || value.length() == 0 && defaultValue != null) {
            // Hent defaultverdi fra en fil
            if (defaultValue.contains(FILE_TOKEN)) {
                int inx = defaultValue.indexOf(FILE_TOKEN) + FILE_TOKEN.length();
                String file = defaultValue.substring(inx, defaultValue.length());

                ResourceLoader source = RootContext.getInstance().getBean("contentTemplateResourceLoader",
                        ResourceLoader.class);
                Resource resource = source.getResource("defaults/" + file);

                try (InputStream is = resource.getInputStream()) {
                    value = IOUtils.toString(is);
                } catch (IOException e) {
                    throw new SystemException("Feil ved lesing av default fil:" + file, e);
                }
            } else {
                if (model != null && model.size() > 0) {
                    for (Map.Entry<String, String> entry : model.entrySet()) {
                        String value = defaultString(entry.getValue());

                        String keyToken = "\\$\\{" + entry + "\\}";

                        String tmp = defaultValue.replaceAll(keyToken, value);
                        if (tmp.equals(defaultValue)) {
                            defaultValue = defaultValue.replaceAll(entry.getKey(), value);
                        } else {
                            defaultValue = tmp;
                        }

                    }

                    defaultValue = defaultValue.replaceAll("\\$\\{(.*)\\}", "");

                    value = defaultValue;
                }
            }
        }

        helpText = XPathHelper.getString(config, "helptext");
        script = XPathHelper.getString(config, "script");
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a string from a Velocity template.
 *
 * @param templateFile The name of the template file to use.
 * @param parameters   The values to merge into the template.
 * @return The result of the merge./*  www. ja  va 2  s.c  o  m*/
 * @throws SystemException if template handling fails.
 */
public static String createStringFromVelocityTemplate(String templateFile, Map<String, Object> parameters)
        throws SystemException {
    try {
        Velocity.init();

        ResourceLoader source = (ResourceLoader) RootContext.getInstance()
                .getBean("emailTemplateResourceLoader");
        Resource resource = source.getResource(templateFile);

        parameters.put("dateFormatter", new DateTool());

        Configuration config = Aksess.getConfiguration();

        String encoding = config.getString("mail.templates.encoding", "ISO-8859-1");
        try (InputStream is = resource.getInputStream()) {
            String templateText = IOUtils.toString(is, encoding);

            VelocityContext context = new VelocityContext(parameters);
            StringWriter textWriter = new StringWriter();
            Velocity.evaluate(context, textWriter, "body", templateText);

            return textWriter.toString();
        }
    } catch (Exception e) {
        throw new SystemException(
                "Feil ved generering av mailtekst basert p Velocity. TemplateFile: " + templateFile, e);
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailTextReader.java

public static String getContent(String filename, String[] replaceStrings) throws SystemException {

    try {/* ww  w. ja va  2  s . c  om*/
        ResourceLoader source = (ResourceLoader) RootContext.getInstance()
                .getBean("emailTemplateResourceLoader");
        Resource resource = source.getResource(filename);

        try (InputStream is = resource.getInputStream()) {
            String content = IOUtils.toString(is);

            StringBuilder result = new StringBuilder();
            int count = 0;
            char[] chars = content.toCharArray();
            for (char aChar : chars) {
                if (aChar == '%') {
                    if (count < replaceStrings.length) {
                        result.append(replaceStrings[count++]);
                    }
                } else {
                    result.append(aChar);
                }
            }

            return result.toString();
        }
    } catch (Exception e) {
        throw new SystemException("Feil ved lesing av " + filename, e);
    }
}

From source file:org.alfresco.repo.importer.ImporterBootstrap.java

/**
 * Get a Reader onto an XML view/*from  w ww .  j a va 2 s .c  o m*/
 * 
 * @param view  the view location
 * @param encoding  the encoding of the view
 * @return  the reader
 */
private Reader getReader(String view, String encoding) {
    // Get Input Stream
    ResourceLoader resourceLoader = new DefaultResourceLoader(getClass().getClassLoader());
    Resource viewResource = resourceLoader.getResource(view);
    if (viewResource == null) {
        throw new ImporterException("Could not find view file " + view);
    }

    // Wrap in buffered reader
    try {
        InputStream viewStream = viewResource.getInputStream();
        InputStreamReader inputReader = (encoding == null) ? new InputStreamReader(viewStream)
                : new InputStreamReader(viewStream, encoding);
        BufferedReader reader = new BufferedReader(inputReader);
        return reader;
    } catch (UnsupportedEncodingException e) {
        throw new ImporterException(
                "Could not create reader for view " + view + " as encoding " + encoding + " is not supported");
    } catch (IOException e) {
        throw new ImporterException("Could not open resource for view " + view);
    }
}

From source file:org.codehaus.groovy.grails.context.annotation.ClosureClassIgnoringComponentScanBeanDefinitionParser.java

@Override
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
    final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element);

    final ResourceLoader originalResourceLoader = parserContext.getReaderContext().getResourceLoader();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Scanning only this classloader:" + originalResourceLoader.getClassLoader());
    }//from   w  w  w  . j  a  v a2 s .co m

    ResourceLoader parentOnlyResourceLoader;
    try {
        parentOnlyResourceLoader = new ResourceLoader() {
            ClassLoader parentOnlyGetResourcesClassLoader = new ParentOnlyGetResourcesClassLoader(
                    originalResourceLoader.getClassLoader());

            public Resource getResource(String location) {
                return originalResourceLoader.getResource(location);
            }

            public ClassLoader getClassLoader() {
                return parentOnlyGetResourcesClassLoader;
            }
        };
    } catch (Throwable t) {
        // restrictive classloading environment, use the original
        parentOnlyResourceLoader = originalResourceLoader;
    }

    final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(
            parentOnlyResourceLoader) {
        @Override
        protected Resource[] findAllClassPathResources(String location) throws IOException {
            Set<Resource> result = new LinkedHashSet<Resource>(16);

            @SuppressWarnings("unused")
            URL classesDir = null;

            final boolean warDeployed = Metadata.getCurrent().isWarDeployed();
            if (!warDeployed) {
                BuildSettings buildSettings = BuildSettingsHolder.getSettings();
                if (buildSettings != null && buildSettings.getClassesDir() != null) {
                    classesDir = buildSettings.getClassesDir().toURI().toURL();
                }
            }

            // only scan classes from project classes directory
            String path = location;
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            Enumeration<URL> resourceUrls = getClassLoader().getResources(path);
            while (resourceUrls.hasMoreElements()) {
                URL url = resourceUrls.nextElement();
                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            "Scanning URL " + url.toExternalForm() + " while searching for '" + location + "'");
                }
                /*
                if (!warDeployed && classesDir!= null && url.equals(classesDir)) {
                result.add(convertClassLoaderURL(url));
                }
                else if (warDeployed) {
                result.add(convertClassLoaderURL(url));
                }
                */
                result.add(convertClassLoaderURL(url));
            }
            return result.toArray(new Resource[result.size()]);
        }
    };
    resourceResolver.setPathMatcher(new AntPathMatcher() {
        @Override
        public boolean match(String pattern, String path) {
            if (path.endsWith(".class")) {
                String filename = FilenameUtils.getBaseName(path);
                if (filename.indexOf("$") > -1)
                    return false;
            }
            return super.match(pattern, path);
        }
    });
    scanner.setResourceLoader(resourceResolver);
    return scanner;
}

From source file:org.codehaus.groovy.grails.web.pages.discovery.DefaultGroovyPageLocator.java

protected Resource findResource(List<String> searchPaths) {
    Resource foundResource = null;
    Resource resource;// www .  j av a  2 s  .c o m
    for (ResourceLoader loader : resourceLoaders) {
        for (String path : searchPaths) {
            resource = loader.getResource(path);
            if (resource != null && resource.exists()) {
                foundResource = resource;
                break;
            }
        }
        if (foundResource != null)
            break;
    }
    return foundResource;
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

@Override
public Decorator getNamedDecorator(HttpServletRequest request, String name) {
    if (StringUtils.isBlank(name))
        return null;

    if (Environment.getCurrent() != Environment.DEVELOPMENT && decoratorMap.containsKey(name)) {
        return decoratorMap.get(name);
    }// w  w w  .  j  a  va 2s.  co  m

    String decoratorName = name;
    if (!name.matches("(.+)(\\.)(\\w{2}|\\w{3})")) {
        name += DEFAULT_VIEW_TYPE;
    }
    String decoratorPage = DEFAULT_DECORATOR_PATH + '/' + name;

    ResourceLoader resourceLoader = establishResourceLoader();

    // lookup something like /WEB-INF/grails-app/views/layouts/[NAME].gsp
    Resource res = resourceLoader.getResource(decoratorPage);
    Decorator d = null;
    if (!res.exists()) {
        // lookup something like /WEB-INF/plugins/myplugin/grails-app/views/layouts/[NAME].gsp
        String pathToView = lookupPathToControllerView(request, name);
        res = pathToView != null ? resourceLoader.getResource(pathToView) : null;
        if (res != null && res.exists()) {
            decoratorPage = pathToView;
            d = useExistingDecorator(request, decoratorName, decoratorPage);
        } else {
            // scan /WEB-INF/plugins/*/grails-app/views/layouts/[NAME].gsp for first matching
            String pluginViewLocation = searchPluginViews(name, resourceLoader);
            if (pluginViewLocation == null) {
                pluginViewLocation = searchPluginViewsInBinaryPlugins(name);

            }

            if (pluginViewLocation != null) {
                decoratorPage = pluginViewLocation;
                d = useExistingDecorator(request, decoratorName, decoratorPage);
            }

        }
    } else {
        d = useExistingDecorator(request, decoratorName, decoratorPage);
    }
    return d;
}

From source file:org.codenergic.theskeleton.core.security.SecurityConfig.java

/**
* Token converter and enhancer/* w ww.  j a va2 s.co m*/
* @return
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter(@Value("${security.jwt.signing-key:}") String signingKey,
        ResourceLoader resourceLoader) throws IOException {
    DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
    accessTokenConverter.setUserTokenConverter(new UserAccessTokenAuthenticationConverter());
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setAccessTokenConverter(accessTokenConverter);
    if (StringUtils.isBlank(signingKey))
        return jwtAccessTokenConverter;
    if (ResourceUtils.isUrl(signingKey)) {
        Resource signingKeyResource = resourceLoader.getResource(signingKey);
        signingKey = IOUtils.toString(signingKeyResource.getURI(), StandardCharsets.UTF_8);
    }
    jwtAccessTokenConverter.setSigningKey(signingKey);
    jwtAccessTokenConverter.setVerifierKey(signingKey);
    return jwtAccessTokenConverter;
}

From source file:org.craftercms.core.store.impl.filesystem.FileSystemContentStoreAdapterTest.java

private void setUpTestStoreAdapter() throws IOException {
    ResourceLoader resourceLoader = mock(ResourceLoader.class);
    when(resourceLoader.getResource(CLASSPATH_STORE_ROOT_FOLDER_PATH))
            .thenReturn(new ClassPathResource(CLASSPATH_STORE_ROOT_FOLDER_PATH));

    storeAdapter = new FileSystemContentStoreAdapter();
    storeAdapter.setCacheTemplate(cacheTemplate);
    storeAdapter.setResourceLoader(resourceLoader);
    storeAdapter.setDescriptorFileExtension(DESCRIPTOR_FILE_EXTENSION);
    storeAdapter.setMetadataFileExtension(METADATA_FILE_EXTENSION);
    storeAdapter.setPathValidator(new SecurePathValidator("path"));
}

From source file:org.craftercms.engine.service.context.SiteContextFactory.java

protected ConfigurableApplicationContext getApplicationContext(SiteContext siteContext,
        URLClassLoader classLoader, HierarchicalConfiguration config, String[] applicationContextPaths,
        ResourceLoader resourceLoader) {
    try {/*from   w w  w. j av a2 s  .  c  o m*/
        List<Resource> resources = new ArrayList<>();

        for (String path : applicationContextPaths) {
            Resource resource = resourceLoader.getResource(path);
            if (resource.exists()) {
                resources.add(resource);
            }
        }

        if (CollectionUtils.isNotEmpty(resources)) {
            String siteName = siteContext.getSiteName();

            logger.info("--------------------------------------------------");
            logger.info("<Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);
            appContext.setClassLoader(classLoader);

            if (config != null) {
                MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
                propertySources.addFirst(new ApacheCommonsConfiguration2PropertySource("siteConfig", config));
            }

            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
            reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

            for (Resource resource : resources) {
                reader.loadBeanDefinitions(resource);
            }

            appContext.refresh();

            logger.info("--------------------------------------------------");
            logger.info("</Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            return appContext;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new SiteContextCreationException(
                "Unable to load application context for site '" + siteContext.getSiteName() + "'", e);
    }
}