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:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 *//* ww  w . ja  v  a2 s.  c  om*/
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();
    String urlToString = originalURL.toExternalForm();

    // 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);
    }

    else {
        // check META-INF folder
        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));
        return new URL(persistenceUnitRoot);
    }
}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

private void loadThemeFromXml(DesktopThemeImpl theme, Resource resource) throws IOException {
    log.info("Loading theme file " + resource.getURL());

    Document doc = readXmlDocument(resource);
    final Element rootElement = doc.getRootElement();

    for (Element element : (List<Element>) rootElement.elements()) {
        String elementName = element.getName();
        if ("lookAndFeel".equals(elementName)) {
            String lookAndFeel = element.getTextTrim();
            if (StringUtils.isNotEmpty(lookAndFeel)) {
                theme.setLookAndFeel(lookAndFeel);
            }/*from w ww  .  j  a  va2 s  .c o  m*/
        } else if ("ui-defaults".equals(elementName)) {
            loadUIDefaults(theme.getUiDefaults(), element);
        } else if ("layout".equals(elementName)) {
            loadLayoutSettings(theme, element);
        } else if ("style".equals(elementName)) {
            DesktopStyle style = loadStyle(element);
            theme.addStyle(style);
        } else if ("include".equals(elementName)) {
            includeThemeFile(theme, element, resource);
        } else if ("class".equals(elementName)) {
            // ignore it
        } else {
            log.error("Unknown tag: " + elementName);
        }
    }
}

From source file:com.remind.bpf.common.mybatis.MySqlSessionFactoryBean.java

private String convertToPackageFormat(Resource r) {
    String uri = "";
    try {//w w  w.  jav a2  s .  c  om
        uri = r.getURL().toString();
        int pos = uri.indexOf("/classes/");
        if (pos > 0)
            uri = uri.substring(pos + 9, uri.length() - 1).replaceAll("/", ".");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return uri;
}

From source file:com.panet.imeta.core.plugins.PluginLoader.java

private void fromXML(FileObject xml, FileObject parent)
        throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(KettleVFS.getInputStream(xml));
    Node plugin = XMLHandler.getSubNode(doc, Plugin.PLUGIN);
    String id = XMLHandler.getTagAttribute(plugin, Plugin.ID);
    String description = XMLHandler.getTagAttribute(plugin, Plugin.DESCRIPTION);
    String iconfile = XMLHandler.getTagAttribute(plugin, Plugin.ICONFILE);
    String tooltip = XMLHandler.getTagAttribute(plugin, Plugin.TOOLTIP);
    String classname = XMLHandler.getTagAttribute(plugin, Plugin.CLASSNAME);
    String category = XMLHandler.getTagAttribute(plugin, Plugin.CATEGORY);
    String errorHelpfile = XMLHandler.getTagAttribute(plugin, Plugin.ERRORHELPFILE);

    // Localized categories
    ///*w  ww  . j a  va  2  s.c  o m*/
    Node locCatsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_CATEGORY);
    int nrLocCats = XMLHandler.countNodes(locCatsNode, Plugin.CATEGORY);
    Map<String, String> localizedCategories = new Hashtable<String, String>();
    for (int j = 0; j < nrLocCats; j++) {
        Node locCatNode = XMLHandler.getSubNodeByNr(locCatsNode, Plugin.CATEGORY, j);
        String locale = XMLHandler.getTagAttribute(locCatNode, Plugin.LOCALE);
        String locCat = XMLHandler.getNodeValue(locCatNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locCat)) {
            localizedCategories.put(locale.toLowerCase(), locCat);
        }
    }

    // Localized descriptions
    //
    Node locDescsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_DESCRIPTION);
    int nrLocDescs = XMLHandler.countNodes(locDescsNode, Plugin.DESCRIPTION);
    Map<String, String> localizedDescriptions = new Hashtable<String, String>();
    for (int j = 0; j < nrLocDescs; j++) {
        Node locDescNode = XMLHandler.getSubNodeByNr(locDescsNode, Plugin.DESCRIPTION, j);
        String locale = XMLHandler.getTagAttribute(locDescNode, Plugin.LOCALE);
        String locDesc = XMLHandler.getNodeValue(locDescNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locDesc)) {
            localizedDescriptions.put(locale.toLowerCase(), locDesc);
        }
    }

    // Localized tooltips
    //
    Node locTipsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_TOOLTIP);
    int nrLocTips = XMLHandler.countNodes(locTipsNode, Plugin.TOOLTIP);
    Map<String, String> localizedTooltips = new Hashtable<String, String>();
    for (int j = 0; j < nrLocTips; j++) {
        Node locTipNode = XMLHandler.getSubNodeByNr(locTipsNode, Plugin.TOOLTIP, j);
        String locale = XMLHandler.getTagAttribute(locTipNode, Plugin.LOCALE);
        String locTip = XMLHandler.getNodeValue(locTipNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locTip)) {
            localizedTooltips.put(locale.toLowerCase(), locTip);
        }
    }

    Node libsnode = XMLHandler.getSubNode(plugin, Plugin.LIBRARIES);
    int nrlibs = XMLHandler.countNodes(libsnode, Plugin.LIBRARY);
    String jarfiles[] = new String[nrlibs];
    for (int j = 0; j < nrlibs; j++) {
        Node libnode = XMLHandler.getSubNodeByNr(libsnode, Plugin.LIBRARY, j);
        String jarfile = XMLHandler.getTagAttribute(libnode, Plugin.NAME);
        jarfiles[j] = parent.resolveFile(jarfile).getURL().getFile();
        // System.out.println("jar files=" + jarfiles[j]);
    }

    // convert to URL
    List<URL> classpath = new ArrayList<URL>();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());
    for (int i = 0; i < jarfiles.length; i++) {
        try {
            Resource[] paths = resolver.getResources(jarfiles[i]);
            for (Resource path : paths) {
                classpath.add(path.getURL());
            }
        } catch (IOException e) {
            e.printStackTrace();
            continue;
        }
    }

    URL urls[] = classpath.toArray(new URL[classpath.size()]);

    URLClassLoader cl = new PDIClassLoader(urls, Thread.currentThread().getContextClassLoader());

    String iconFilename = parent.resolveFile(iconfile).getURL().getFile();

    Class<?> pluginClass = cl.loadClass(classname);

    // here we'll have to use some reflection in order to decide
    // which object we should instantiate!
    if (JobEntryInterface.class.isAssignableFrom(pluginClass)) {
        Set<JobPlugin> jps = (Set<JobPlugin>) this.plugins.get(Job.class);

        JobPlugin plg = new JobPlugin(Plugin.TYPE_PLUGIN, id, description, tooltip, parent.getName().getURI(),
                jarfiles, iconFilename, classname, category);
        plg.setClassLoader(cl);

        // Add localized information too...
        plg.setLocalizedCategories(localizedCategories);
        plg.setLocalizedDescriptions(localizedDescriptions);
        plg.setLocalizedTooltips(localizedTooltips);

        jps.add(plg);
    } else {
        String errorHelpFileFull = errorHelpfile;
        String path = parent.getName().getURI();
        if (!Const.isEmpty(errorHelpfile))
            errorHelpFileFull = (path == null) ? errorHelpfile : path + Const.FILE_SEPARATOR + errorHelpfile;

        StepPlugin sp = new StepPlugin(Plugin.TYPE_PLUGIN, new String[] { id }, description, tooltip, path,
                jarfiles, iconFilename, classname, category, errorHelpFileFull);

        // Add localized information too...
        sp.setLocalizedCategories(localizedCategories);
        sp.setLocalizedDescriptions(localizedDescriptions);
        sp.setLocalizedTooltips(localizedTooltips);

        Set<StepPlugin> sps = (Set<StepPlugin>) this.plugins.get(Step.class);
        sps.add(sp);
    }

}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

private void includeThemeFile(DesktopThemeImpl theme, Element element, Resource resource) throws IOException {
    String fileName = element.attributeValue("file");
    if (StringUtils.isEmpty(fileName)) {
        log.error("Missing 'file' attribute to include");
        return;/*www .j  av a 2  s .  com*/
    }

    Resource relativeResource = resource.createRelative(fileName);
    if (relativeResource.exists()) {
        log.info("Including theme file " + relativeResource.getURL());
        loadThemeFromXml(theme, relativeResource);
    } else {
        log.error("Resource " + fileName + " not found, ignore it");
    }
}

From source file:org.cfr.capsicum.server.ServerRuntimeFactoryBean.java

/**
 * Builds Cayenne configuration object based on configured properties.
 *///from  w w w. j a v  a 2  s  . c om
@Override
public void afterPropertiesSet() throws Exception {
    // check datasource and transaction
    if (transactionManager == null && dataSource == null) {
        throw new IllegalArgumentException("Property 'transactionManager' or 'dataSource' is required");
    }

    // create default resource loader if no attached spring context.
    if (applicationContext == null) {
        this.resourceLoader = new DefaultResourceLoader();
    } else {
        this.resourceLoader = applicationContext;
    }
    SpringServerModule springModule = new SpringServerModule();
    List<String> configurationLocations = ImmutableList.of();
    if (dataDomainDefinitions != null && !dataDomainDefinitions.isEmpty()) {
        configurationLocations = Lists.newArrayListWithCapacity(dataDomainDefinitions.size());
        for (DataDomainDefinition dataDomainDefinition : dataDomainDefinitions) {
            Assert.notNull(dataDomainDefinition.getName(), "the name of DataDomain is required");
            Resource resource = Assert.notNull(dataDomainDefinition.getDomainResource(),
                    "the resource of DataDomain is required");
            URL url = null;
            try {
                url = resource.getURL();
            } catch (IOException ex) {
                throw new CayenneException(ex.getMessage(), ex);
            }
            configurationLocations.add(url.toString());
            // set default update strategy
            if (dataDomainDefinition.getSchemaUpdateStrategy() == null) {
                dataDomainDefinition.setSchemaUpdateStrategy(getDefaultSchemaUpdateStrategy());
            }
        }
    }
    // create specific datasource Factory
    if (dataSourceFactory == null) {
        dataSourceFactory = new SpringDataSourceFactory(this);
    }
    // create cayenne runtime instance with domain definitions
    cayenneRuntime = new ServerRuntime(Iterables.toArray(configurationLocations, String.class), springModule);

    // create default transaction manager
    if (transactionManager == null) {
        transactionManager = new CayenneTransactionManager(dataSource, cayenneRuntime);
    } else {
        this.transactionManager.setCayenneRuntime(cayenneRuntime);
    }

}

From source file:org.toobsframework.transformpipeline.domain.XSLUriResolverImpl.java

protected URL resolveContextResource(String xslFile, String string) throws IOException {
    Resource configFileURL = null;
    String systemId = null;//from  www. j ava  2s  .c  om
    for (int i = 0; i < this.contextBase.size(); i++) {
        systemId = this.contextBase.get(i) + xslFile;

        if (log.isDebugEnabled()) {
            log.debug("Checking for: " + systemId);
        }
        configFileURL = applicationContext.getResource(systemId);

        if (null != configFileURL) {
            break;
        }
    }
    if (configFileURL.exists()) {
        return configFileURL.getURL();
    }
    return null;
}

From source file:org.jruby.rack.mock.MockServletContext.java

public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }/*w ww .j a va  2s .c  o  m*/
    try {
        return resource.getURL();
    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        logger.log("WARN: Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:org.ireland.jnetty.webapp.ServletContextImpl.java

/**
 * Returns a resource for the given uri.
 * //from  w  w  w . j  a v a2  s  . c  om
 *
 * @see org.springframework.mock.web.MockServletContext
 */
@Override
public URL getResource(String path) throws java.net.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) {
        log.info("Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:com.jpoweredcart.common.mock.servlet.MockServletContext.java

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