Example usage for org.springframework.core.io UrlResource UrlResource

List of usage examples for org.springframework.core.io UrlResource UrlResource

Introduction

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

Prototype

public UrlResource(String path) throws MalformedURLException 

Source Link

Document

Create a new UrlResource based on a URL path.

Usage

From source file:org.jboss.spring.facade.KernelControllerListableBeanFactoryTestCase.java

@Test(expected = BeanCreationException.class)
public void testConfigurationFailsIfParentBeanMissing() throws Throwable {
    BasicBootstrap bootstrap = new BasicBootstrap();
    bootstrap.run();//from ww  w .j av  a 2 s  . c o  m
    BasicXMLDeployer deployer = new BasicXMLDeployer(bootstrap.getKernel());
    BeanFactory parentBeanFactory = new KernelControllerListableBeanFactory(
            bootstrap.getKernel().getController());
    deployer.deploy(KernelControllerListableBeanFactory.class.getResource("microcontainer-beans-2.xml"));
    BeanFactory beanFactory = new XmlBeanFactory(
            new UrlResource(KernelControllerListableBeanFactory.class.getResource("spring-beans.xml")),
            parentBeanFactory);
    ComplexService service = (ComplexService) beanFactory.getBean("service");
    Assert.assertEquals("Result is: 2", service.processNumbers(1, 1));
    deployer.shutdown();
}

From source file:ch.astina.hesperid.web.services.dbmigration.impl.ClasspathMigrationResolver.java

public Set<Migration> resolve() {
    Set<Migration> migrations = new HashSet<Migration>();

    try {/*from  ww w  .j a va2 s  . co m*/
        Enumeration<URL> enumeration = getClass().getClassLoader().getResources(classPath);

        while (enumeration.hasMoreElements()) {

            URL url = enumeration.nextElement();

            if (url.toExternalForm().startsWith("jar:")) {
                String file = url.getFile();

                file = file.substring(0, file.indexOf("!"));
                file = file.substring(file.indexOf(":") + 1);

                InputStream is = new FileInputStream(file);

                ZipInputStream zip = new ZipInputStream(is);

                ZipEntry ze;

                while ((ze = zip.getNextEntry()) != null) {
                    if (!ze.isDirectory() && ze.getName().startsWith(classPath)
                            && ze.getName().endsWith(".sql")) {

                        Resource r = new UrlResource(getClass().getClassLoader().getResource(ze.getName()));

                        String version = versionExtractor.extractVersion(r.getFilename());
                        migrations.add(migrationFactory.create(version, r));
                    }
                }
            } else {
                File file = new File(url.getFile());

                for (String s : file.list()) {
                    Resource r = new UrlResource(getClass().getClassLoader().getResource(classPath + "/" + s));

                    String version = versionExtractor.extractVersion(r.getFilename());
                    migrations.add(migrationFactory.create(version, r));
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error while resolving migrations", e);
    }

    return migrations;
}

From source file:inti.ws.spring.resource.WebResource.java

public WebResource(ServletContext ctx, String location, String route, Minifier minifier, boolean minify)
        throws URISyntaxException, MalformedURLException {
    this.route = route;
    this.minifier = minifier;
    this.minify = minify;

    LOGGER.debug("WebResource - try to load {}", location);

    if (location != null) {
        if (location.startsWith("classpath:")) {
            resource = new ClassPathResource(location.substring(10));
        } else if (location.startsWith("/")) {
            resource = new ServletContextResource(ctx, location);
        } else {/*from  w w w.  j  a v a2 s  .c o  m*/
            resource = new UrlResource(location);
        }
    }
}

From source file:org.pac4j.saml.metadata.SAML2IdentityProviderMetadataResolver.java

@Override
public final MetadataResolver resolve() {

    try {/*from w  ww  .java  2s.  co m*/
        Resource resource = null;
        if (this.idpMetadataPath.startsWith(CommonHelper.RESOURCE_PREFIX)) {
            String path = this.idpMetadataPath.substring(CommonHelper.RESOURCE_PREFIX.length());
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            resource = ResourceHelper.of(new ClassPathResource(path));
        } else if (this.idpMetadataPath.startsWith("file:")) {
            resource = ResourceHelper.of(new FileSystemResource(this.idpMetadataPath));
        } else if (this.idpMetadataPath.startsWith("http")) {
            resource = ResourceHelper.of(new UrlResource(this.idpMetadataPath));
        }

        if (resource == null) {
            throw new XMLParserException("idp metadata cannot be resolved from " + this.idpMetadataPath);
        }

        final InputStream in = resource.getInputStream();
        final Document inCommonMDDoc = Configuration.getParserPool().parse(in);
        final Element metadataRoot = inCommonMDDoc.getDocumentElement();
        idpMetadataProvider = new DOMMetadataResolver(metadataRoot);

        idpMetadataProvider.setParserPool(Configuration.getParserPool());
        idpMetadataProvider.setFailFastInitialization(true);
        idpMetadataProvider.setRequireValidMetadata(true);
        idpMetadataProvider.setId(idpMetadataProvider.getClass().getCanonicalName());
        idpMetadataProvider.initialize();

        // If no idpEntityId declared, select first EntityDescriptor entityId as our IDP entityId
        if (this.idpEntityId == null) {
            final Iterator<EntityDescriptor> it = idpMetadataProvider.iterator();

            while (it.hasNext()) {
                final EntityDescriptor entityDescriptor = it.next();
                if (SAML2IdentityProviderMetadataResolver.this.idpEntityId == null) {
                    SAML2IdentityProviderMetadataResolver.this.idpEntityId = entityDescriptor.getEntityID();
                }
            }
        }

        if (this.idpEntityId == null) {
            throw new SAMLException("No idp entityId found");
        }

    } catch (final ComponentInitializationException e) {
        throw new SAMLException("Error initializing idpMetadataProvider", e);
    } catch (final XMLParserException e) {
        throw new TechnicalException("Error parsing idp Metadata", e);
    } catch (final IOException e) {
        throw new TechnicalException("Error getting idp Metadata resource", e);
    }
    return idpMetadataProvider;
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private Resource openConnection(String urlStr) throws IOException {
    final String[] urlParts = StringUtils.split(urlStr, "|");

    if (urlStr.startsWith("file:")) {
        String path = urlParts[0].substring(7);
        if (path.startsWith("~" + File.separator)) {
            path = System.getProperty("user.home") + path.substring(1);
        }/*w w w.  ja  va2s.  c  om*/
        final File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
        return new FileSystemResource(file);
    } else if (urlStr.startsWith("classpath:")) {
        return new ClassPathResource(urlParts[0].substring(10));
    }

    return new UrlResource(urlParts[0]);
}

From source file:com.liferay.portal.configuration.ExtletConfigurationImpl.java

/**
 * Find all extlet-portal.properties in all jars and override actual content
 *///from   w w w . j  a v  a2s  .c  o m
public void addExtletProperties() {
    ClassLoader classLoader = getClass().getClassLoader();
    String resourceName = EXTLET_PORTAL_PROPERTIES;

    try {
        // load all resource file from the classpath (all jars).
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            try {
                if (_log.isDebugEnabled()) {
                    _log.debug("Loading extlet-portal.properties from: " + resource);
                }
                InputStream is = new UrlResource(resource).getInputStream();

                if (is != null) {
                    addPropertiesToLiferay(is);
                }
                if (_log.isDebugEnabled()) {
                    _log.debug("Loading OK: " + resource);
                }
            } catch (Exception e2) {
                if (_log.isWarnEnabled()) {
                    _log.warn("Problem while loading " + resource, e2);
                }
            }
        }
    } catch (Exception e2) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem while loading classLoader resources: " + resourceName, e2);
        }
    }
}

From source file:spring.osgi.utils.OsgiResourceUtils.java

public static Resource[] convertURLEnumerationToResourceArray(Enumeration enm) {
    Set<Resource> resources = new LinkedHashSet<>(4);
    while (enm != null && enm.hasMoreElements()) {
        resources.add(new UrlResource((URL) enm.nextElement()));
    }/*from   ww w  . ja v  a2 s.c  o m*/
    return resources.toArray(new Resource[resources.size()]);
}

From source file:com.liferay.portal.model.ModelHintsImpl.java

public void afterPropertiesSet() {
    _hintCollections = new HashMap<String, Map<String, String>>();
    _defaultHints = new HashMap<String, Map<String, String>>();
    _modelFields = new HashMap<String, Object>();
    _models = new TreeSet<String>();

    try {/*from   w  ww .  j  av a2s  . c om*/
        ClassLoader classLoader = getClass().getClassLoader();

        String[] configs = StringUtil.split(PropsUtil.get(PropsKeys.MODEL_HINTS_CONFIGS));

        for (int i = 0; i < configs.length; i++) {
            if (!configs[i].startsWith("classpath*:")) {
                read(classLoader, configs[i]);
            } else {
                String configName = configs[i].substring("classpath*:".length());
                Enumeration<URL> resources = classLoader.getResources(configName);
                if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
                    _log.debug("No " + configName + " has been found");
                }
                while (resources.hasMoreElements()) {
                    URL resource = resources.nextElement();
                    if (_log.isDebugEnabled()) {
                        _log.debug("Loading " + configName + " from: " + resource);
                    }
                    InputStream is = new UrlResource(resource).getInputStream();

                    if (is != null) {
                        read(classLoader, resource.toString(), is);
                    }
                }
            }
        }

    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:org.echocat.jomon.spring.application.XmlBasedApplicationContextRequirement.java

@Nonnull
public XmlBasedApplicationContextRequirement withConfigurations(@Nonnull URL... files) {
    for (final URL file : files) {
        _configurationFiles.add(new UrlResource(file));
    }//  w w  w  .  j  av  a 2s . c om
    return this;
}

From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.CRLDistributionPointRevocationChecker.java

/**
 * @see AbstractCRLRevocationChecker#getCRL(X509Certificate)
 */// w  w  w  .  j a  va2 s .  c o m
protected X509CRL getCRL(final X509Certificate cert) {
    final URL[] urls = getDistributionPoints(cert);
    if (log.isDebugEnabled()) {
        log.debug(String.format("Distribution points for %s: %s.", CertUtils.toString(cert),
                Arrays.asList(urls)));
    }

    Element item;
    for (URL url : urls) {
        item = this.crlCache.get(url);
        if (item != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found CRL in cache for " + CertUtils.toString(cert));
            }
            return (X509CRL) item.getObjectValue();
        }
    }

    // Try all distribution points and stop at first fetch that succeeds
    X509CRL crl = null;
    for (int i = 0; i < urls.length && crl == null; i++) {
        this.log.info("Attempting to fetch CRL at " + urls[i]);
        try {
            crl = CertUtils.fetchCRL(new UrlResource(urls[i]));
            this.log.info("Success. Caching fetched CRL.");
            this.crlCache.put(new Element(urls[i], crl));
        } catch (Exception e) {
            this.log.error("Error fetching CRL at " + urls[i], e);
        }
    }

    return crl;
}