Example usage for org.springframework.core.io Resource getURL

List of usage examples for org.springframework.core.io Resource getURL

Introduction

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

Prototype

URL getURL() throws IOException;

Source Link

Document

Return a URL handle for this resource.

Usage

From source file:org.springframework.extensions.webscripts.ClassPathStore.java

/**
 * Matches the given path to the full class path that is comprised of class files and resources located
 * inside of JAR files that are on the class path.
 * /* w  ww.  j  av  a  2  s  . c o  m*/
 * @param pattern The pattern to match
 * 
 * @return List<String> of matching paths
 */
private List<String> matchDocumentPaths(String pattern) throws IOException {
    Resource[] resources = getDocumentResources(pattern);
    List<String> documentPaths = new ArrayList<String>(resources.length);
    for (Resource resource : resources) {
        String documentPath = toDocumentPath(resource.getURL().toExternalForm());
        documentPaths.add(documentPath);
    }
    return documentPaths;
}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

/**
 * Dispatches to the resource with the given path
 * //from  ww  w .  j a  va2s. co  m
 * @param path the path
 * @param request the request
 * @param response the response
 */
public boolean dispatchResource(final String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final boolean debug = logger.isDebugEnabled();
    if (debug)
        logger.debug("Attemping to dispatch resource: " + path);

    boolean resolved = false;
    {
        // check JAR files
        URL resourceUrl = ClassUtils.getDefaultClassLoader().getResource("META-INF/" + path);
        if (resourceUrl != null) {
            if (debug)
                logger.debug("...dispatching resource from JAR location: " + resourceUrl);

            // attempt to stream back
            try {
                commitResponse(path, resourceUrl, response);
                resolved = true;
            } catch (IOException ioe) {
                logger.info(ioe.getMessage());
                if (debug)
                    ioe.printStackTrace();
            }
        }
    }

    if (!resolved) {
        // look up the resource in the resource provider
        // (application context resources / classpath)

        // check the classpath
        Resource r = getApplicationContext().getResource("classpath*:" + path);
        if (r != null && r.exists()) {
            URL resourceUrl = r.getURL();

            if (debug)
                logger.debug("...dispatching resource from classpath location: " + resourceUrl);

            // stream back resource
            try {
                commitResponse(path, resourceUrl, response);
                resolved = true;
            } catch (IOException ioe) {
                logger.info(ioe.getMessage());
                if (debug)
                    ioe.printStackTrace();
            }
        }
    }

    if (!resolved) {
        // serve back the resource from the web application (if it exists)
        ServletContextResource resource = new ServletContextResource(getServletContext(), "/" + path);
        if (resource.exists()) {
            // dispatch to resource
            if (debug)
                logger.debug("...dispatching resource from web application ServletContext.");
            commitResponse(path, resource, request, response);
            resolved = true;
        }
    }

    if (!resolved && defaultUrl != null) {
        if (debug)
            logger.debug("...handing off to Spring resource servlet: " + defaultUrl + "/" + path);

        // try to hand off to a default servlet context (compatibility with Spring JS resource servlet)
        // use a forward here because the new servlet context may be different than the current servlet context
        RequestDispatcher rd = this.getServletContext().getRequestDispatcher(defaultUrl + "/" + path);
        rd.forward(request, response);
        resolved = true;
    }

    return resolved;
}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

public void commitResponse(final String path, final Resource resource, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // determine properties of the resource being served back
    final URLConnection resourceConn = resource.getURL().openConnection();
    applyHeaders(path, response, resourceConn.getContentLength(), resourceConn.getLastModified());

    // stream back to response
    RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/" + path);
    rd.include(request, response);/* w w w .j a v  a 2  s.c o  m*/
}

From source file:org.springframework.integration.xquery.support.XQueryUtils.java

/**
 * Reads the XQuery string from the resource file specified
 *
 * @param resource the {@link Resource} instance of the file that contains the XQuery
 *          currently only classpath and file resources are supported
 *
 * @return the XQuery string from the resource specified
 *//*from w w  w.  java 2 s .c om*/
public static String readXQueryFromResource(Resource resource) {
    Assert.notNull(resource, "null resource provided");
    Assert.isTrue(resource.exists(), "Provided XQuery resource does not exist");
    Assert.isTrue(resource.isReadable(), "Provided XQuery resource is not readable");
    BufferedReader reader = null;
    try {
        URL url = resource.getURL();
        InputStream inStream = url.openStream();
        reader = new BufferedReader(new InputStreamReader(inStream));
        String line = reader.readLine();
        StringBuilder builder = new StringBuilder();
        while (line != null) {
            builder.append(line).append("\n");
            line = reader.readLine();
        }
        String xQuery = builder.toString();
        reader.close();
        return xQuery;
    } catch (IOException e) {
        throw new MessagingException("Error while reading the xQuery resource", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error("Exception while closing reader", e);
            }
        }
    }
}

From source file:org.springframework.mock.web.MockServletContext.java

@Override
@Nullable/*w w  w  .  j a v a 2  s  . c  om*/
public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }
    try {
        return resource.getURL();
    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        logger.warn("Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:org.springframework.mock.web.portlet.MockPortletContext.java

@Override
public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    try {/*from   ww w  . j a va2 s .c o m*/
        return resource.getURL();
    } catch (IOException ex) {
        logger.info("Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

/**
 * Populate the underlying {@code Configuration} instance with the various
 * properties of this builder. Customization may be performed through
 * {@code pre*} and {@code post*} methods.
 * @see #preBuildSessionFactory()//  ww w. ja v  a 2  s . c om
 * @see #postProcessMappings()
 * @see #postBuildSessionFactory()
 * @see #postBuildSessionFactory()
 */
protected final SessionFactory doBuildSessionFactory() throws Exception {
    initializeConfigurationIfNecessary();

    if (this.dataSource != null) {
        // Make given DataSource available for SessionFactory configuration.
        configTimeDataSourceHolder.set(this.dataSource);
    }
    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
    }
    if (this.cacheRegionFactory != null) {
        // Make Spring-provided Hibernate RegionFactory available.
        configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
    }
    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        configTimeLobHandlerHolder.set(this.lobHandler);
    }

    try {
        if (isExposeTransactionAwareSessionFactory()) {
            // Set Hibernate 3.1+ CurrentSessionContext implementation,
            // providing the Spring-managed Session as current Session.
            // Can be overridden by a custom value for the corresponding Hibernate property.
            this.configuration.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,
                    SpringSessionContext.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            this.configuration.setProperty(Environment.TRANSACTION_STRATEGY,
                    JTATransactionFactory.class.getName());
            this.configuration.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        } else {
            // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
            // Also sets connection release mode to ON_CLOSE by default.
            this.configuration.setProperty(Environment.TRANSACTION_STRATEGY,
                    SpringTransactionFactory.class.getName());
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            this.configuration.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            this.configuration.setNamingStrategy(this.namingStrategy);
        }

        if (this.typeDefinitions != null) {
            // Register specified Hibernate type definitions.
            // Use reflection for compatibility with both Hibernate 3.3 and 3.5:
            // the returned Mappings object changed from a class to an interface.
            Method createMappings = Configuration.class.getMethod("createMappings");
            Method addTypeDef = createMappings.getReturnType().getMethod("addTypeDef", String.class,
                    String.class, Properties.class);
            Object mappings = ReflectionUtils.invokeMethod(createMappings, this.configuration);
            for (TypeDefinitionBean typeDef : this.typeDefinitions) {
                ReflectionUtils.invokeMethod(addTypeDef, mappings, typeDef.getTypeName(),
                        typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (FilterDefinition filterDef : this.filterDefinitions) {
                this.configuration.addFilterDefinition(filterDef);
            }
        }

        if (this.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                this.configuration.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            this.configuration.addProperties(this.hibernateProperties);
        }

        if (dataSource != null) {
            Class<?> providerClass = LocalDataSourceConnectionProvider.class;
            if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) {
                providerClass = TransactionAwareDataSourceConnectionProvider.class;
            } else if (this.configuration.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
                providerClass = LocalJtaDataSourceConnectionProvider.class;
            }
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            this.configuration.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.cacheRegionFactory != null) {
            // Expose Spring-provided Hibernate RegionFactory.
            this.configuration.setProperty(Environment.CACHE_REGION_FACTORY,
                    "org.springframework.orm.hibernate3.LocalRegionFactoryProxy");
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                this.configuration.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                this.configuration.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                this.configuration.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                this.configuration.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                this.configuration.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings();
        this.configuration.buildMappings();

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements();) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    // method signature declares return type as Configuration on Hibernate 3.6
                    // but as void on Hibernate 3.3 and 3.5
                    Method setCacheConcurrencyStrategy = Configuration.class
                            .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class);
                    ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, this.configuration, className,
                            strategyAndRegion[0], strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    this.configuration.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements();) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    this.configuration.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    this.configuration.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<?> listeners = (Collection<?>) listenerObject;
                    EventListeners listenerRegistry = this.configuration.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    this.configuration.setListeners(listenerType, listenerArray);
                } else {
                    this.configuration.setListener(listenerType, listenerObject);
                }
            }
        }

        preBuildSessionFactory();

        // Perform custom post-processing in subclasses.
        postProcessConfiguration();

        // Build SessionFactory instance.
        logger.info("Building new Hibernate SessionFactory");

        return this.sessionFactory = newSessionFactory();
    } finally {
        if (dataSource != null) {
            SessionFactoryBuilderSupport.configTimeDataSourceHolder.remove();
        }
        if (this.jtaTransactionManager != null) {
            SessionFactoryBuilderSupport.configTimeTransactionManagerHolder.remove();
        }
        if (this.cacheRegionFactory != null) {
            SessionFactoryBuilderSupport.configTimeRegionFactoryHolder.remove();
        }
        if (this.lobHandler != null) {
            SessionFactoryBuilderSupport.configTimeLobHandlerHolder.remove();
        }

        postBuildSessionFactory();
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates/*  w  w  w .j av a 2 s .com*/
                    .addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }

    try {
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getURL();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(
                            className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader.java

/**
 * Parse the {@code jar-file} XML elements.
 *///from   www .ja  va  2 s  .com
protected void parseJarFiles(Element persistenceUnit, SpringPersistenceUnitInfo unitInfo) throws IOException {
    List<Element> jars = DomUtils.getChildElementsByTagName(persistenceUnit, JAR_FILE_URL);
    for (Element element : jars) {
        String value = DomUtils.getTextValue(element).trim();
        if (StringUtils.hasText(value)) {
            Resource[] resources = this.resourcePatternResolver.getResources(value);
            boolean found = false;
            for (Resource resource : resources) {
                if (resource.exists()) {
                    found = true;
                    unitInfo.addJarFileUrl(resource.getURL());
                }
            }
            if (!found) {
                // relative to the persistence unit root, according to the JPA spec
                URL rootUrl = unitInfo.getPersistenceUnitRootUrl();
                if (rootUrl != null) {
                    unitInfo.addJarFileUrl(new URL(rootUrl, value));
                } else {
                    logger.warn("Cannot resolve jar-file entry [" + value + "] in persistence unit '"
                            + unitInfo.getPersistenceUnitName() + "' without root URL");
                }
            }
        }
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the {@code persistence.xml} file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 */// w ww  . j av  a2s.  c  o m
@Nullable
static URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    // Check META-INF folder
    String urlToString = originalURL.toExternalForm();
    if (!urlToString.contains(META_INF)) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }
    if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }

    String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
    if (persistenceUnitRoot.endsWith("/")) {
        persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
    }
    return new URL(persistenceUnitRoot);
}