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.universAAL.itests.IntegrationTest.java

/**
 * Adds additionall dependencies which are needed for launching uAAL
 * Integration Test./*from  ww  w  . j  a v  a  2  s  . co  m*/
 *
 * @return Returns array of resources.
 */
private Resource[] insertNeededDeps(final List<Resource> bundles) throws Exception {
    String itestsVersion = MavenUtils.getArtifactVersion("org.universAAL.support", "itests");
    bundles.add(0, new UrlResource("mvn:org.apache.commons/com.springsource.org.apache.commons.io/1.4.0"));
    bundles.add(0, new UrlResource("mvn:org.universAAL.support/itests/" + itestsVersion));
    bundles.add(0, new UrlResource("mvn:org.ops4j.pax.url/pax-url-wrap/1.3.5"));
    bundles.add(0, new UrlResource("mvn:org.ops4j.pax.url/pax-url-mvn/1.3.5"));
    bundles.add(0, new UrlResource("mvn:org.ops4j.pax.url/pax-url-mvn/1.3.5"));
    if (ignoreLastBundle) {
        Resource last = bundles.get(bundles.size() - 1);
        log("Ignoring Last Bundle: " + last.getDescription());
        bundles.remove(bundles.size() - 1);
    }
    return bundles.toArray(new Resource[bundles.size()]);
}

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

/**
 * Find a local maven artifact. First tries to find the resource as a
 * packaged artifact produced by a local maven build, and if that fails will
 * search the local maven repository.//  w w  w.j  a va2 s  . c o  m
 * 
 * @param groupId - the groupId of the organization supplying the bundle
 * @param artifactId - the artifact id of the bundle
 * @param version - the version of the bundle
 * @param type - the extension type of the artifact
 * @return
 */
public Resource locateArtifact(final String groupId, final String artifactId, final String version,
        final String type) {
    init();

    return (Resource) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            try {

                return localMavenBuildArtifact(groupId, artifactId, version, type);
            } catch (IllegalStateException illStateEx) {
                Resource localMavenBundle = localMavenBundle(groupId, artifactId, version, type);
                if (log.isDebugEnabled()) {
                    StringBuilder buf = new StringBuilder();
                    buf.append("[");
                    buf.append(groupId);
                    buf.append("|");
                    buf.append(artifactId);
                    buf.append("|");
                    buf.append(version);
                    buf.append("]");
                    log.debug(buf
                            + " local maven build artifact detection failed, falling back to local maven bundle "
                            + localMavenBundle.getDescription());
                }
                return localMavenBundle;
            }
        }
    });
}

From source file:org.obiba.onyx.print.impl.AbstractPrintableReport.java

public void afterPropertiesSet() {
    activeInterviewService = (ActiveInterviewService) applicationContext.getBean("activeInterviewService");

    XStream xstream = new XStream(new InjectingReflectionProviderWrapper(
            (new XStream()).getReflectionProvider(), applicationContext));
    xstream.alias("variableDataSource", VariableDataSource.class);
    xstream.alias("comparingDataSource", ComparingDataSource.class);
    xstream.useAttributeFor(ComparingDataSource.class, "comparisonOperator");
    xstream.alias("participantPropertyDataSource", ParticipantPropertyDataSource.class);
    xstream.useAttributeFor(AbstractBeanPropertyDataSource.class, "property");
    xstream.alias("fixedDataSource", FixedDataSource.class);
    xstream.useAttributeFor("type", DataType.class);
    xstream.useAttributeFor("dataType", DataType.class);
    xstream.alias("computingDataSource", ComputingDataSource.class);

    if (readyConditionConfigPath != null) {
        Resource readyConditionFile = null;
        InputStream readyConditionStream = null;
        try {/*from  ww w  .j  a v  a 2 s . c o  m*/
            readyConditionFile = resourceLoader
                    .getResource(readyConditionConfigPath + File.separator + getName() + "-condition.xml");
            readyConditionStream = readyConditionFile.getInputStream();

            try {
                readyCondition = (IDataSource) xstream.fromXML(readyConditionStream);
            } finally {
                try {
                    readyConditionStream.close();
                } catch (IOException e) {
                }
            }

            log.info("Loaded the report condition for the following report: {} ({})", getName(),
                    readyConditionFile.getDescription());
        } catch (IOException e) {
            log.warn("Cannot find the report condition file for the following report: {} ({})", getName(),
                    readyConditionFile.getDescription());
        }
    }

}

From source file:org.data.support.beans.factory.xml.XmlQueryDefinitionReader.java

/**
 * Actually load query definitions from the specified XML file.
 * @param inputSource the SAX InputSource to read from
 * @param resource the resource descriptor for the XML file
 * @return the number of query definitions found
 * @throws QueryDefinitionStoreException in case of loading or parsing errors
 *//* w w w  .j  a v  a 2  s .  c  om*/
protected int doLoadQueryDefinitions(InputSource inputSource, Resource resource)
        throws QueryDefinitionStoreException {
    try {
        int validationMode = getValidationModeForResource(resource);
        Document doc = this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
                validationMode, isNamespaceAware());
        return registerQueryDefinitions(doc, resource);
    } catch (QueryDefinitionStoreException ex) {
        throw ex;
    } catch (SAXParseException ex) {
        throw new XmlQueryDefinitionStoreException(resource.getDescription(),
                "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
    } catch (SAXException ex) {
        throw new XmlQueryDefinitionStoreException(resource.getDescription(),
                "XML document from " + resource + " is invalid", ex);
    } catch (ParserConfigurationException ex) {
        throw new QueryDefinitionStoreException(resource.getDescription(),
                "Parser configuration exception parsing XML from " + resource, ex);
    } catch (IOException ex) {
        throw new QueryDefinitionStoreException(resource.getDescription(),
                "IOException parsing XML document from " + resource, ex);
    } catch (Throwable ex) {
        throw new QueryDefinitionStoreException(resource.getDescription(),
                "Unexpected exception parsing XML document from " + resource, ex);
    }
}

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

/**
 * Returns the <tt>groupId</tt> setting in a <tt>pom.xml</tt> file.
 * /*  w w w  .j  a  v  a 2 s .  com*/
 * @return a <tt>pom.xml</tt> <tt>groupId</tt>.
 */
String getGroupIdFromPom(Resource pomXml) {
    try {
        DocumentLoader docLoader = new DefaultDocumentLoader();
        Document document = docLoader.loadDocument(new InputSource(pomXml.getInputStream()), null, null,
                XmlValidationModeDetector.VALIDATION_NONE, false);

        String groupId = DomUtils.getChildElementValueByTagName(document.getDocumentElement(), GROUP_ID_ELEM);
        // no groupId specified, try the parent definition
        if (groupId == null) {
            if (log.isTraceEnabled())
                log.trace("No groupId defined; checking for the parent definition");
            Element parent = DomUtils.getChildElementByTagName(document.getDocumentElement(), "parent");
            if (parent != null)
                return DomUtils.getChildElementValueByTagName(parent, GROUP_ID_ELEM);
        } else {
            return groupId;
        }
    } catch (Exception ex) {
        throw (RuntimeException) new RuntimeException(
                new ParserConfigurationException("error parsing resource=" + pomXml).initCause(ex));
    }

    throw new IllegalArgumentException(
            "no groupId or parent/groupId defined by resource [" + pomXml.getDescription() + "]");

}

From source file:org.ow2.authzforce.pap.dao.flatfile.FlatFileBasedDomainsDAO.java

/**
 * Creates instance// w w w  .j a v a2 s. com
 * 
 * @param domainsRoot
 *            root directory of the configuration data of security domains,
 *            one subdirectory per domain
 * @param domainTmpl
 *            domain template directory; directories of new domains are
 *            created from this template
 * @param domainsSyncIntervalSec
 *            how often (in seconds) the synchronization of managed domains
 *            (in memory) with the domain subdirectories in the
 *            <code>domainsRoot</code> directory (on disk) is done. If
 *            <code>domainSyncInterval</code> > 0, every
 *            <code>domainSyncInterval</code>, the managed domains (loaded
 *            in memory) are updated if any change has been detected in the
 *            <code>domainsRoot</code> directory in this interval (since
 *            last sync). To be more specific, <i>any change</i> here means
 *            any creation/deletion/modification of a domain folder
 *            (modification means: any file changed within the folder). If
 *            <code>domainSyncInterval</code> &lt;= 0, synchronization is
 *            disabled.
 * @param pdpModelHandler
 *            PDP configuration model handler
 * @param useRandomAddressBasedUUID
 *            true iff a random multicast address must be used as node field
 *            of generated UUIDs (Version 1), else the MAC address of one of
 *            the network interfaces is used. Setting this to 'true' is NOT
 *            recommended unless the host is disconnected from the network.
 *            These generated UUIDs are used for domain IDs.
 * @param domainDAOClientFactory
 *            domain DAO client factory
 * @throws IOException
 *             I/O error occurred scanning existing domain folders in
 *             {@code domainsRoot} for loading.
 */
@ConstructorProperties({ "domainsRoot", "domainTmpl", "domainsSyncIntervalSec", "pdpModelHandler",
        "useRandomAddressBasedUUID", "domainDAOClientFactory" })
public FlatFileBasedDomainsDAO(final Resource domainsRoot, final Resource domainTmpl,
        final int domainsSyncIntervalSec, final PdpModelHandler pdpModelHandler,
        final boolean useRandomAddressBasedUUID,
        final DomainDAOClient.Factory<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT, FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT>, DOMAIN_DAO_CLIENT> domainDAOClientFactory)
        throws IOException {
    if (domainsRoot == null || domainTmpl == null || pdpModelHandler == null
            || domainDAOClientFactory == null) {
        throw ILLEGAL_CONSTRUCTOR_ARGS_EXCEPTION;
    }

    this.domainDAOClientFactory = domainDAOClientFactory;
    this.policyDAOClientFactory = domainDAOClientFactory.getPolicyDAOClientFactory();
    this.policyVersionDAOClientFactory = policyDAOClientFactory.getVersionDAOClientFactory();

    this.uuidGen = initUUIDGenerator(useRandomAddressBasedUUID);
    this.pdpModelHandler = pdpModelHandler;

    // Validate domainsRoot arg
    if (!domainsRoot.exists()) {
        throw new IllegalArgumentException(
                "'domainsRoot' resource does not exist: " + domainsRoot.getDescription());
    }

    final String ioExMsg = "Cannot resolve 'domainsRoot' resource '" + domainsRoot.getDescription()
            + "' as a file on the file system";
    File domainsRootFile = null;
    try {
        domainsRootFile = domainsRoot.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg, e);
    }

    this.domainsRootDir = domainsRootFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainsRoot'", domainsRootDir,
            true, true);

    // Validate domainTmpl directory arg
    if (!domainTmpl.exists()) {
        throw new IllegalArgumentException(
                "'domainTmpl' resource does not exist: " + domainTmpl.getDescription());
    }

    final String ioExMsg2 = "Cannot resolve 'domainTmpl' resource '" + domainTmpl.getDescription()
            + "' as a file on the file system";
    File domainTmplFile = null;
    try {
        domainTmplFile = domainTmpl.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg2, e);
    }

    this.domainTmplDirPath = domainTmplFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainTmpl'",
            domainTmplDirPath, true, false);

    LOGGER.debug("Looking for domain sub-directories in directory {}", domainsRootDir);
    try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(domainsRootDir)) {
        for (final Path domainPath : dirStream) {
            LOGGER.debug("Checking domain in file {}", domainPath);
            if (!Files.isDirectory(domainPath)) {
                LOGGER.warn("Ignoring invalid domain file {} (not a directory)", domainPath);
                continue;
            }

            // domain folder name is the domain ID
            final Path lastPathSegment = domainPath.getFileName();
            if (lastPathSegment == null) {
                throw new RuntimeException("Invalid Domain folder path '" + domainPath + "': no filename");
            }

            final String domainId = lastPathSegment.toString();
            FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT> domainDAO = null;
            try {
                domainDAO = new FileBasedDomainDAOImpl(domainPath, null);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException("Invalid domain data for domain '" + domainId + "'", e);
            }

            final DOMAIN_DAO_CLIENT domain = domainDAOClientFactory.getInstance(domainId, domainDAO);
            domainMap.put(domainId, domain);
        }
    } catch (final IOException e) {
        throw new IOException("Failed to scan files in the domains root directory '" + domainsRootDir
                + "' looking for domain directories", e);
    }

    this.domainDirToMemSyncIntervalSec = Integer.valueOf(domainsSyncIntervalSec).longValue();
}

From source file:org.activiti.dmn.spring.autodeployment.AbstractAutoDeploymentStrategy.java

/**
 * Determines the name to be used for the provided resource.
 * //from  w w w  . ja va  2 s  .co m
 * @param resource
 *          the resource to get the name for
 * @return the name of the resource
 */
protected String determineResourceName(final Resource resource) {
    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();
        }
    }
    return resourceName;
}

From source file:org.alfresco.filesys.alfresco.DesktopAction.java

/**
 * Initialize the desktop action/*www  .  j ava2 s .  c  o m*/
 * 
 * @exception DesktopActionException
 */
public void initializeAction(ServiceRegistry serviceRegistry, AlfrescoContext filesysContext)
        throws DesktopActionException {
    this.serviceRegistry = serviceRegistry;

    // Save the filesystem device and I/O handler
    m_filesysContext = filesysContext;

    // Check for standard config values

    if (m_name == null || m_name.length() == 0)
        throw new DesktopActionException("Desktop action name not specified");

    // Get the pseudo file name
    if (m_pseudoFile == null) {
        if (m_filename == null || m_filename.length() == 0)
            throw new DesktopActionException("Desktop action pseudo name not specified");

        // Get the local path to the executable
        if (m_path == null || m_path.length() == 0) {
            m_path = m_filesysContext.getGlobalDesktopActionConfig().getPath();
        }
        if (m_path == null || m_path.length() == 0)
            throw new DesktopActionException("Desktop action executable path not specified");

        // Check that the application exists on the local filesystem

        Resource resource = new ResourceFinder().getResource(m_path);
        if (!resource.exists()) {
            throw new DesktopActionException("Failed to find drag and drop application, " + m_path);
        }

        PseudoFile pseudoFile = null;
        try {
            pseudoFile = new MemoryPseudoFile(m_filename, IOUtils.toByteArray(resource.getInputStream()));
        } catch (IOException e) {
            throw new DesktopActionException(
                    "Drag and drop application resource is invalid, " + resource.getDescription());
        }

        setPseudoFile(pseudoFile);
    }

    // Check if confirmations should be switched off for the action

    if (m_filesysContext.getGlobalDesktopActionConfig().getNoConfirm() && hasPreProcessAction(PreConfirmAction))
        setPreProcessActions(getPreProcessActions() - PreConfirmAction);

    // Check if the webapp URL has been specified

    SysAdminParams sysAdminParams = m_filesysContext.getSysAdminParams();
    if (m_webappURL == null || m_webappURL.length() == 0) {
        m_webappURL = m_filesysContext.getShareUrlPrefix();
    } else {
        // Check if the path name contains the local name token
        m_webappURL = sysAdminParams.subsituteHost(m_webappURL);

        if (!m_webappURL.endsWith("/")) {
            m_webappURL = m_webappURL + "/";
        }
    }

    // Check if debug output is enabled for the action

    if (m_filesysContext.getGlobalDesktopActionConfig().getDebug())
        setDebug(true);

    // DEBUG

    if (logger.isDebugEnabled() && hasDebug())
        logger.debug("Initialized desktop action " + getName() + ", pseudo name " + m_pseudoFile.getFileName());
}

From source file:org.alfresco.util.ResourceFinderConfigSource.java

@Override
public List<ConfigDeployment> getConfigDeployments() {
    List<ConfigDeployment> configs = new ArrayList<ConfigDeployment>();

    String[] locs = locations.toArray(new String[locations.size()]);

    Resource[] resources;//  w  ww.j  a  v a2s.co  m
    try {
        resources = resourceFinder.getResources(locs);
    } catch (IOException e) {
        throw new AlfrescoRuntimeException("Unable to find resources", e);
    }

    for (Resource resource : resources) {
        try {
            configs.add(new ConfigDeployment(resource.getDescription(), resource.getInputStream()));

            if (logger.isDebugEnabled()) {
                logger.debug("Loaded resource " + resource);
            }
        } catch (IOException e) {
            logger.warn("Skipping unreadable resource " + resource, e);
        }
    }

    return configs;
}

From source file:org.apache.geode.management.internal.web.util.ConvertUtils.java

/**
 * Converts the array of Resources into a 2-dimensional byte array containing content from each
 * Resource. The 2-dimensional byte array format is used by Gfsh and the GemFire Manager to
 * transmit file data.// w ww  .  j  a v  a 2s  .c om
 * <p/>
 * 
 * @param resources an array of Spring Resource objects to convert into the 2-dimensional byte
 *        array format.
 * @return a 2-dimensional byte array containing the content of each Resource.
 * @throws IllegalArgumentException if the filename of a Resource was not specified.
 * @throws IOException if an I/O error occurs reading the contents of a Resource!
 * @see org.springframework.core.io.Resource
 */
public static byte[][] convert(final Resource... resources) throws IOException {
    if (resources == null) {
        return new byte[0][];
    }

    final List<byte[]> fileData = new ArrayList<byte[]>(resources.length * 2);

    for (final Resource resource : resources) {
        if (StringUtils.isBlank(resource.getFilename())) {
            throw new IllegalArgumentException(String
                    .format("The filename of Resource (%1$s) must be specified!", resource.getDescription()));
        }

        fileData.add(resource.getFilename().getBytes());
        fileData.add(IOUtils.toByteArray(resource.getInputStream()));
    }

    return fileData.toArray(new byte[fileData.size()][]);
}