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

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

Introduction

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

Prototype

String getDescription();

Source Link

Document

Return a description for this resource, to be used for error output when working with the resource.

Usage

From source file:org.eclipse.gemini.blueprint.test.provisioning.internal.LocalFileSystemMavenRepository.java

/**
 * Find a local maven artifact in the current build tree. This searches for
 * resources produced by the package phase of a maven build.
 * //from ww  w.j  a v  a 2  s.  c o m
 * @param artifactId
 * @param version
 * @param type
 * @return
 */
protected Resource localMavenBuildArtifact(String groupId, String artifactId, String version, String type) {
    try {
        File found = new MavenPackagedArtifactFinder(groupId, artifactId, version, type)
                .findPackagedArtifact(new File("."));
        Resource res = new FileSystemResource(found);
        if (log.isDebugEnabled()) {
            log.debug("[" + artifactId + "|" + version + "] resolved to " + res.getDescription()
                    + " as a local maven artifact");
        }
        return res;
    } catch (IOException ioEx) {
        throw (RuntimeException) new IllegalStateException(
                "Artifact " + artifactId + "-" + version + "." + type + " could not be found").initCause(ioEx);
    }
}

From source file:org.finra.jtaf.core.parsing.CommandLibraryParser.java

private List<InvocationTarget> handleCoreLibrarySource(MessageCollector mc) throws NameFormatException,
        NameCollisionException, SAXException, IOException, ParsingException, URISyntaxException {
    List<InvocationTarget> retval = new ArrayList<InvocationTarget>();

    Resource[] resources = getResources();

    for (Resource resource : resources) {
        logger.debug("Parsing library " + resource.getDescription());
        List<InvocationTarget> library = readLibrary(mc, resource.getInputStream(), resource.getDescription());
        if ((library != null) && (library.size() > 0)) {
            // try to read jars (maven or ant setup)
            retval.addAll(library);//from  ww w .jav  a  2s . c o  m
        } else {
            logger.debug("Found no commands");
        }
    }
    return retval;
}

From source file:org.activiti.engine.impl.cfg.spring.ProcessEngineFactoryBean.java

private String getResourceName(Resource resource) {
    String name;// ww w .j a v  a  2s .  c  o  m
    if (resource instanceof ContextResource) {
        name = ((ContextResource) resource).getPathWithinContext();
    } else if (resource instanceof ByteArrayResource) {
        name = resource.getDescription();
    } else {
        try {
            name = resource.getFile().getAbsolutePath();
        } catch (IOException e) {
            name = resource.getFilename();
        }
    }
    return name;
}

From source file:org.finra.jtaf.core.parsing.CommandLibraryParser.java

/**
 * for all elements of java.class.path get a Collection of resources under
 * testlibrary/*from  w w w .j  av a  2s.  com*/
 * 
 * @return the resources in the order they are found
 */

private Resource[] getResources() throws IOException, URISyntaxException {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    ArrayList<Resource> result = new ArrayList<Resource>();

    // We want all commands.xml files in testlibrary folder anywhere in the
    // hierarchy in the classpath
    // There is no single regex to address our requirement. Hence we have
    // two regex.
    // The first one gets all entries where testLibrary is under root.
    // The second gets all
    Resource[] firstResultSet = resolver.getResources("classpath*:/testlibrary/**/*commands.xml");
    if (firstResultSet != null) {
        Collections.addAll(result, firstResultSet);
    }
    // This path does not address testlibrary being directly under the root.
    resolver = new PathMatchingResourcePatternResolver();
    Resource[] secondResultSet = resolver.getResources("classpath*:/**/testlibrary/**/*commands.xml");

    if (secondResultSet != null) {
        if (firstResultSet != null) {
            for (Resource secondResource : secondResultSet) {
                // check to see if it was already found.
                boolean found = false;
                for (Resource firstResource : firstResultSet) {
                    if (firstResource.getDescription().equals(secondResource.getDescription())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    result.add(secondResource);
                }
            }
        } else {
            Collections.addAll(result, secondResultSet);
        }
    }

    return result.toArray(new Resource[] {});
}

From source file:org.springmodules.validation.bean.conf.loader.xml.AbstractXmlBeanValidationConfigurationLoader.java

/**
 * todo: document/*  ww  w .j a  v  a  2 s.co  m*/
 *
 * @see org.springmodules.validation.bean.conf.loader.xml.AbstractResourceBasedBeanValidationConfigurationLoader#loadConfigurations(org.springframework.core.io.Resource)
 */
protected final Map loadConfigurations(Resource resource) {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resource.getInputStream());
        return loadConfigurations(document, resource.getDescription());
    } catch (IOException ioe) {
        logger.error("Could not read resource '" + resource.getDescription() + "'", ioe);
        throw new ResourceConfigurationLoadingException(resource, ioe);
    } catch (ParserConfigurationException pce) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", pce);
        throw new ResourceConfigurationLoadingException(resource, pce);
    } catch (SAXException se) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", se);
        throw new ResourceConfigurationLoadingException(resource, se);
    } catch (Throwable t) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", t);
        throw new ResourceConfigurationLoadingException(resource, t);
    }
}

From source file:cat.albirar.framework.sets.registry.impl.SetRegistryDefaultImpl.java

/**
 * {@inheritDoc}//from   ww  w.  j a va  2 s .com
 */
@Override
public int loadFromResource(Resource resource) throws ClassNotFoundException {
    Properties prop;
    int n;

    Assert.notNull(resource, "The resource argument are required!");
    if (logger.isTraceEnabled()) {
        logger.trace("Processing set registry from resource '" + resource.getDescription() + "'...");
    }
    prop = new Properties();
    try {
        prop.load(resource.getInputStream());
        if (logger.isTraceEnabled()) {
            logger.trace("Resource '" + resource.getDescription() + "' file loaded.");
        }
        n = loadFromProperties(prop);
        if (logger.isTraceEnabled()) {
            logger.trace(
                    String.format("End processing resource '%s', %d sets read", resource.getDescription(), n));
        }
        return n;
    } catch (IOException e) {
        logger.error("Cannot load from resource '" + resource.getDescription() + "'", e);
        throw new IllegalArgumentException("Cannot load from the resource '" + resource.getDescription() + "'",
                e);
    }
}

From source file:org.activiti.spring.SpringProcessEngineConfiguration.java

protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();

        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering()
                .name(deploymentName);//from   w w w  . j  ava2  s . c o  m

        for (Resource resource : deploymentResources) {
            String resourceName = null;

            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();

            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();

            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }

            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip")
                        || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException(
                        "couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }

        deploymentBuilder.deploy();
    }
}

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use./*from w  w w.ja v a  2 s.  c  om*/
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:net.happyonroad.component.container.support.DefaultComponentResolver.java

@Override
public Component resolveComponent(final Dependency dependency, Resource resource)
        throws InvalidComponentNameException, DependencyNotMeetException {
    logger.debug("Resolving {} from {}", dependency, resource);
    String originName = resource.getFilename();
    if (originName == null)
        originName = resource.getDescription();
    String fileName = FilenameUtils.getName(originName);
    Dependency basic = Dependency.parse(fileName);
    if (!dependency.accept(basic)) {
        throw new InvalidComponentNameException(
                "The component file name: " + fileName + " does not satisfy the dependency: " + dependency);
    }/*ww w. ja  va  2  s  .  c o  m*/
    DefaultComponent comp;
    InputStream stream = null;
    if (fileName.endsWith(".pom")) {
        try {
            stream = resource.getInputStream();
            comp = (DefaultComponent) resolveComponent(dependency, stream);
            comp.setUnderlyingResource(resource);
            if (!comp.isAggregating()) {
                File jarFile = digJarFilePath(fileName);
                if (jarFile != null) {
                    ComponentJarResource jarResource = new ComponentJarResource(dependency, jarFile.getName());
                    comp.setResource(jarResource);
                } else {
                    logger.warn("Can't find jar file for {}", comp);
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("The pom file does not exist: " + fileName);
        } finally {
            try {
                if (stream != null)
                    stream.close();
            } catch (IOException ex) {
                /**/}
        }
    } else {
        if (dependency.getVersion() == null) {
            dependency.setVersion(basic.getVersion());
        }
        ComponentJarResource jarResource = new ComponentJarResource(dependency, fileName);
        try {
            stream = jarResource.getPomStream();
            comp = (DefaultComponent) resolveComponent(dependency, stream);
            comp.setUnderlyingResource(resource);
            comp.setResource(jarResource);
        } catch (IOException e) {
            throw new InvalidComponentException(dependency.getGroupId(), dependency.getArtifactId(),
                    dependency.getVersion(), "jar", "Can't resolve pom.xml: " + e.getMessage());
        } finally {
            try {
                if (stream != null)
                    stream.close();
            } catch (IOException ex) {
                /**/}
        }
    }
    if (comp.getType() == null)
        comp.setType(dependency.getType());

    if (!dependency.accept(comp))
        throw new InvalidComponentNameException(
                "The component file name: " + fileName + " conflict with its inner pom: " + comp.toString());
    comp.setClassLoader(new ComponentClassLoader(comp));
    return comp;
}

From source file:de.ingrid.admin.service.ElasticsearchNodeFactoryBean.java

private void internalLoadSettings(final NodeBuilder nodeBuilder, final Resource configLocation) {

    try {//from   w  w  w .j  av a  2 s.  co  m
        final String filename = configLocation.getFilename();
        if (logger.isInfoEnabled()) {
            logger.info("Loading configuration file from: " + filename);
        }
        nodeBuilder.getSettings().loadFromStream(filename, configLocation.getInputStream());
    } catch (final Exception e) {
        throw new IllegalArgumentException(
                "Could not load settings from configLocation: " + configLocation.getDescription(), e);
    }
}