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:mvctest.web.TestController.java

@RequestMapping(value = "/appCtxGetResources")
public void appCtxGetResources(HttpServletRequest request, HttpServletResponse response) throws Exception {

    final String path = getRequiredStringParameter(request, "path");
    final String title = "From ApplicationContext/ResourceLoader's getResources()";
    StringBuilder builder = new StringBuilder();
    builder.append("<html>\n<head>\n<title>").append(title).append("</title>\n</head>\n<body>\n");
    builder.append("<h1>").append(title).append("</h1>\n");
    builder.append("path: ").append(path).append("<br />\n");
    builder.append("<hr />\n");

    if (this.resourceLoader instanceof ResourcePatternResolver) {
        ResourcePatternResolver resourcePatternResolver = (ResourcePatternResolver) this.resourceLoader;
        Resource[] resources = resourcePatternResolver.getResources(path);
        for (Resource resource : resources) {
            builder.append("<h3>Resource: ").append(resource.getURL()).append("</h3>\n");
            InputStream inputStream = null;
            try {
                inputStream = resource.getInputStream();
                builder.append("<p>")
                        .append(FileCopyUtils
                                .copyToString(new BufferedReader(new InputStreamReader(inputStream))))
                        .append("</p>\n");
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }//from w  ww  . j a  v  a 2  s. c om
            }
            builder.append("<hr />\n");
        }
    }

    builder.append("</body>\n</html>\n");
    response.getWriter().write(builder.toString());
}

From source file:com.iterranux.droolsjbpmCore.runtime.build.impl.KieModuleBuilder.java

public void buildKmoduleForGrailsModule(String moduleName, Resource kmoduleXml) throws IOException {

    //ReleaseId for this kmodule
    ReleaseId releaseId = droolsjbpmCoreUtils.getReleaseIdForGrailsModule(moduleName);

    //Only build kmodule for modules that exist
    if (releaseId != null) {
        log.debug("Found KieModule for: " + moduleName);

        org.springframework.core.io.Resource[] moduleResources = getGrailsModuleResources(moduleName);

        KieFileSystem kfs = kieServices.newKieFileSystem();

        for (org.springframework.core.io.Resource moduleResource : moduleResources) {
            URL moduleResourceURL = moduleResource.getURL();

            if (!isTestResource(moduleResourceURL) && !isFolder(moduleResourceURL)) {

                if (log.isDebugEnabled())
                    log.debug("Resources found for '" + moduleName + "': " + moduleResourceURL);

                org.kie.api.io.Resource kieResource = kieResources.newUrlResource(moduleResourceURL);
                kfs.write(getKmodulePathForResourceUrlAndModuleName(moduleResourceURL.toString(), moduleName),
                        kieResource);/*  w w w.ja v a 2 s  .  co m*/

            }
        }

        //Generate Basic POM
        kfs.generateAndWritePomXML(releaseId);

        //Add Kmodule.xml
        kfs.writeKModuleXML(IOUtils.toByteArray(kmoduleXml.getInputStream()));

        //Builder for the KieModule from the kfs, also possible from folder
        KieBuilder kbuilder = kieServices.newKieBuilder(kfs);

        //Build KieModule and automatically deploy to kieRepo if successful
        kbuilder.buildAll();

        //Throw RuntimeException if build failed
        if (kbuilder.getResults().hasMessages(Message.Level.ERROR)) {
            throw new RuntimeException("Error: \n" + kbuilder.getResults().toString());
        }
    } else {
        log.error("Error: There was an attempt to build a KieModule for a plugin or application named '"
                + moduleName + "' which doesn't exist.\n"
                + "       Please check that your KieModule directory structure is setup as intended:\n\n"
                + "          1) Save any resources you might have in the 'grails-app/conf/droolsjbpm' to a secure location\n"
                + "          2) Delete anything in the 'grails-app/conf/droolsjbpm' folder except the 'data' directory\n"
                + "          3) Use the grails command 'droolsjbpm --init-kmodule' to set up a correct folder structure\n\n"
                + "       If the error still persists please file a bug report.");
    }
}

From source file:mvctest.web.TestController.java

@RequestMapping(value = "/appCtxGetResourcesLikeSwfFlowDefinitionResourceFactory")
public void appCtxGetResourcesLikeSwfFlowDefinitionResourceFactory(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final String pattern = getRequiredStringParameter(request, "pattern");
    final String basePath = getStringParameter(request, "basePath", null);
    final String title = "From ApplicationContext/ResourceLoader's getResources() like SWF's FlowDefinitionResourceFactory";
    StringBuilder builder = new StringBuilder();
    builder.append("<html>\n<head>\n<title>").append(title).append("</title>\n</head>\n<body>\n");
    builder.append("<h1>").append(title).append("</h1>\n");
    builder.append("base path: ").append(basePath).append("<br />\n");
    builder.append("pattern: ").append(pattern).append("<br />\n");
    builder.append("<hr />\n");

    if (this.resourceLoader instanceof ResourcePatternResolver) {
        ResourcePatternResolver resolver = (ResourcePatternResolver) this.resourceLoader;
        Resource[] resources;//from   w  ww .  j  a va  2  s. co  m
        if (basePath == null) {
            resources = resolver.getResources(pattern);
        } else {
            if (basePath.endsWith(SLASH) || pattern.startsWith(SLASH)) {
                resources = resolver.getResources(basePath + pattern);
            } else {
                resources = resolver.getResources(basePath + SLASH + pattern);
            }
        }

        for (Resource resource : resources) {
            builder.append("<h3>Resource: ").append(resource.getURL()).append("</h3>\n");
            if (resource instanceof ContextResource) {
                ContextResource contextResource = (ContextResource) resource;
                builder.append("<p>PathWithinContext: ").append(contextResource.getPathWithinContext())
                        .append("</p>\n");
            } else {
                builder.append("<p>Resource is not a ContextResource but rather a [")
                        .append(resource.getClass().getName()).append("].</p>\n");
            }
            builder.append("<p>Flow ID: ").append(getFlowId(basePath, resource)).append("</p>\n");
            builder.append("<hr />\n");
        }
    }

    builder.append("</body>\n</html>\n");
    response.getWriter().write(builder.toString());
}

From source file:spring.osgi.io.OsgiBundleResourceTest.java

private void testFileVsOsgiFileResolution(Resource fileRes, Resource otherRes) throws Exception {
    assertNotNull(fileRes.getURL());
    assertNotNull(fileRes.getFile());/*  ww w  .j a  v  a  2 s  .  c o  m*/
    assertTrue(fileRes.getFile().exists());

    assertNotNull(otherRes.getURL());
    assertNotNull(otherRes.getFile());
    assertTrue(
            StringUtils.pathEquals(fileRes.getFile().getAbsolutePath(), otherRes.getFile().getAbsolutePath()));
}

From source file:org.mitre.stix.STIXSchema.java

/**
 * Private constructor to permit a single STIXSchema to exists.
 *//* w w  w  . j  a v  a 2 s  .  c  o m*/
private STIXSchema() {

    this.version = ((Version) this.getClass().getPackage().getAnnotation(Version.class)).schema();

    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(
            this.getClass().getClassLoader());
    Resource[] schemaResources;

    try {
        schemaResources = patternResolver.getResources("classpath:schemas/v" + version + "/**/*.xsd");

        prefixSchemaBindings = new HashMap<String, String>();

        String url, prefix, targetNamespace;
        Document schemaDocument;
        NamedNodeMap attributes;
        Node attribute;

        for (Resource resource : schemaResources) {

            url = resource.getURL().toString();

            schemaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(resource.getInputStream());

            schemaDocument.getDocumentElement().normalize();

            attributes = schemaDocument.getDocumentElement().getAttributes();

            for (int i = 0; i < attributes.getLength(); i++) {

                attribute = attributes.item(i);

                targetNamespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");

                if (attribute.getNodeName().startsWith("xmlns:")
                        && attribute.getNodeValue().equals(targetNamespace)) {

                    prefix = attributes.item(i).getNodeName().split(":")[1];

                    if ((prefixSchemaBindings.containsKey(prefix))
                            && (prefixSchemaBindings.get(prefix).split("schemas/v" + version + "/")[1]
                                    .startsWith("external"))) {

                        continue;

                    }

                    LOGGER.fine("     adding: " + prefix + " :: " + url);

                    prefixSchemaBindings.put(prefix, url);
                }
            }
        }

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Source[] schemas = new Source[prefixSchemaBindings.values().size()];

        int i = 0;
        for (String schemaLocation : prefixSchemaBindings.values()) {
            schemas[i++] = new StreamSource(schemaLocation);
        }

        schema = factory.newSchema(schemas);

        validator = schema.newValidator();
        validator.setErrorHandler(new ValidationErrorHandler());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarCreator.java

/**
 * Small utility method used for determining the file name by striping the
 * root path from the file full path./*  w w  w .  j av  a  2s. co  m*/
 * 
 * @param rootPath
 * @param resource
 * @return
 */
private String determineRelativeName(String rootPath, Resource resource) {
    try {
        String path = StringUtils.cleanPath(resource.getURL().toExternalForm());
        return path.substring(path.indexOf(rootPath) + rootPath.length());
    } catch (IOException ex) {
        throw (RuntimeException) new IllegalArgumentException("illegal resource " + resource.toString())
                .initCause(ex);
    }
}

From source file:at.gv.egiz.bku.spring.ConfigurationFactoryBean.java

protected Configuration getDefaultConfiguration() throws ConfigurationException, IOException {
    Resource resource = resourceLoader.getResource(DEFAULT_CONFIG);
    XMLConfiguration xmlConfiguration = new XMLConfiguration();
    xmlConfiguration.load(resource.getInputStream());
    xmlConfiguration.setURL(resource.getURL());
    return xmlConfiguration;
}

From source file:com.gfactor.jpa.core.MyPersistenceUnitReader.java

/**
 * Parse the <code>jar-file</code> XML elements.
 *///from   www  .j  a  va 2 s. c  o  m
@SuppressWarnings("unchecked")
protected void parseJarFiles(Element persistenceUnit, MySpringPersistenceUnitInfo 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);
            for (Resource resource : resources) {
                unitInfo.addJarFileUrl(resource.getURL());
            }
        }
    }
}

From source file:com.sinosoft.one.mvc.scanning.MvcScanner.java

/**
 * ???jar?/* w  w w  . j  a v  a  2s. co  m*/
 * @return
 * @throws IOException
 */
public List<ResourceRef> getJarResources() throws IOException {
    if (jarResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] start to found available jar files for mvc to scanning...");
        }
        List<ResourceRef> jarResources = new LinkedList<ResourceRef>();
        Resource[] metaInfResources = resourcePatternResolver.getResources("classpath*:/META-INF/");
        for (Resource metaInfResource : metaInfResources) {
            URL urlObject = metaInfResource.getURL();
            if (ResourceUtils.isJarURL(urlObject)) {
                try {
                    String path = URLDecoder.decode(urlObject.getPath(), "UTF-8"); // fix 20%
                    if (path.startsWith("file:")) {
                        path = path.substring("file:".length(), path.lastIndexOf('!'));
                    } else {
                        path = path.substring(0, path.lastIndexOf('!'));
                    }
                    Resource resource = new FileSystemResource(path);
                    if (jarResources.contains(resource)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("[jarFile] skip replicated jar resource: " + path);//  linux ???,fix it!
                        }
                    } else {
                        ResourceRef ref = ResourceRef.toResourceRef(resource);
                        if (ref.getModifiers() != null) {
                            jarResources.add(ref);
                            if (logger.isInfoEnabled()) {
                                logger.info("[jarFile] add jar resource: " + ref);
                            }
                        } else {
                            if (logger.isDebugEnabled()) {
                                logger.debug("[jarFile] not mvc jar resource: " + path);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(urlObject, e);
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("[jarFile] not mvc type(not a jar) " + urlObject);
                }
            }
        }
        this.jarResources = jarResources;
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found " + jarResources.size() + " jar files: " + jarResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found cached " + jarResources.size() + " jar files: " + jarResources);
        }
    }
    return Collections.unmodifiableList(jarResources);
}

From source file:com.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.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 java.io.IOException if the checking failed
 *///from   w  w  w  . ja  v  a2 s  .  c o m
protected 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);
}