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

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

Introduction

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

Prototype

@Nullable
String getFilename();

Source Link

Document

Determine a filename for this resource, i.e.

Usage

From source file:org.akaza.openclinica.dao.QueryStore.java

public void init() {
    String dbFolder = resolveDbFolder();
    PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(
            resourceLoader);//from   w ww  .  j  av  a 2 s  .  c o  m
    try {
        Resource resources[] = resourceResolver
                .getResources("classpath:queries/" + dbFolder + "/**/*.properties");
        for (Resource r : resources) {
            Properties p = new Properties();
            p.load(r.getInputStream());
            fileByName.put(StringUtils.substringBeforeLast(r.getFilename(), "."), p);
        }
    } catch (IOException e) {
        throw new BeanInitializationException(
                "Unable to read files from directory 'classpath:queries/" + dbFolder + "'", e);
    }
}

From source file:org.alfresco.repo.admin.RepoAdminServiceImpl.java

public String deployMessageBundle(String resourceClasspath) {
    // Check that all the passed values are not null        
    ParameterCheck.mandatory("ResourceClasspath", resourceClasspath);

    String bundleBaseName = resourceClasspath;

    // note: resource path should be in form path1/path2/path3/bundlebasename
    int idx = resourceClasspath.lastIndexOf("/");

    if (idx != -1) {
        if (idx < (resourceClasspath.length() - 1)) {
            bundleBaseName = resourceClasspath.substring(idx + 1);
        } else {/*from   w w w . j a  va2  s.  co m*/
            bundleBaseName = null;
        }
    }

    checkBundleBaseName(bundleBaseName);

    String pattern = "classpath*:" + resourceClasspath + "*" + MessageServiceImpl.PROPERTIES_FILE_SUFFIX;

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    try {
        Resource[] resources = resolver.getResources(pattern);

        if ((resources != null) && (resources.length > 0)) {
            ArrayList<String> names = new ArrayList<String>();
            ArrayList<Resource> filteredResources = new ArrayList<Resource>();

            for (int i = 0; i < resources.length; i++) {
                String filename = resources[i].getFilename();
                if (!names.contains(filename)) {
                    names.add(filename);
                    filteredResources.add(resources[i]);
                }
            }

            for (Resource resource : filteredResources) {
                InputStream fileStream = resource.getInputStream();
                String filename = resource.getFilename();
                deployMessageResourceFile(resourceClasspath, filename, fileStream, false);
            }

            // register bundle

            StoreRef storeRef = repoMessagesLocation.getStoreRef();
            String repoBundlePath = storeRef.toString() + repoMessagesLocation.getPath() + "/cm:"
                    + bundleBaseName;
            messageService.registerResourceBundle(repoBundlePath);

            logger.info("Message resource bundle deployed: " + bundleBaseName);
        } else {
            logger.warn("No message resources found: " + resourceClasspath);
            throw new AlfrescoRuntimeException(MSG_RESOURCES_NOT_FOUND, new Object[] { resourceClasspath });
        }
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException(MSG_RESOURCES_DEPLOYMENT_FAILED, new Object[] { resourceClasspath },
                e);
    }

    return bundleBaseName;
}

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.// www  .  j  a v  a  2s. co  m
 * <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()][]);
}

From source file:org.apache.servicecomb.core.definition.loader.SchemaLoader.java

public SchemaMeta registerSchema(String microserviceName, Resource resource) {
    try {//w  w w. ja v  a 2s . co  m
        String schemaId = FilenameUtils.getBaseName(resource.getFilename());

        String swaggerContent = IOUtils.toString(resource.getURL());
        SchemaMeta schemaMeta = registerSchema(microserviceName, schemaId, swaggerContent);

        return schemaMeta;
    } catch (Throwable e) {
        throw new Error(e);
    }
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

protected void importDataArchive(Resource archive, InputStream resourceStream, BatchImportOptions options) {
    BufferedInputStream bufferedResourceStream = null;
    try {/*from ww  w  . j  ava  2  s.  c o m*/
        //Make sure the stream is buffered
        if (resourceStream instanceof BufferedInputStream) {
            bufferedResourceStream = (BufferedInputStream) resourceStream;
        } else {
            bufferedResourceStream = new BufferedInputStream(resourceStream);
        }

        //Buffer up to 100MB, bad things will happen if we bust this buffer.
        //TODO see if there is a buffered stream that will write to a file once the buffer fills up
        bufferedResourceStream.mark(100 * 1024 * 1024);
        final MediaType type = getMediaType(bufferedResourceStream, archive.getFilename());

        if (MT_JAVA_ARCHIVE.equals(type)) {
            final ArchiveInputStream archiveStream = new JarArchiveInputStream(bufferedResourceStream);
            importDataArchive(archive, archiveStream, options);
        } else if (MediaType.APPLICATION_ZIP.equals(type)) {
            final ArchiveInputStream archiveStream = new ZipArchiveInputStream(bufferedResourceStream);
            importDataArchive(archive, archiveStream, options);
        } else if (MT_CPIO.equals(type)) {
            final ArchiveInputStream archiveStream = new CpioArchiveInputStream(bufferedResourceStream);
            importDataArchive(archive, archiveStream, options);
        } else if (MT_AR.equals(type)) {
            final ArchiveInputStream archiveStream = new ArArchiveInputStream(bufferedResourceStream);
            importDataArchive(archive, archiveStream, options);
        } else if (MT_TAR.equals(type)) {
            final ArchiveInputStream archiveStream = new TarArchiveInputStream(bufferedResourceStream);
            importDataArchive(archive, archiveStream, options);
        } else if (MT_BZIP2.equals(type)) {
            final CompressorInputStream compressedStream = new BZip2CompressorInputStream(
                    bufferedResourceStream);
            importDataArchive(archive, compressedStream, options);
        } else if (MT_GZIP.equals(type)) {
            final CompressorInputStream compressedStream = new GzipCompressorInputStream(
                    bufferedResourceStream);
            importDataArchive(archive, compressedStream, options);
        } else if (MT_PACK200.equals(type)) {
            final CompressorInputStream compressedStream = new Pack200CompressorInputStream(
                    bufferedResourceStream);
            importDataArchive(archive, compressedStream, options);
        } else if (MT_XZ.equals(type)) {
            final CompressorInputStream compressedStream = new XZCompressorInputStream(bufferedResourceStream);
            importDataArchive(archive, compressedStream, options);
        } else {
            throw new RuntimeException("Unrecognized archive media type: " + type);
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not load InputStream for resource: " + archive, e);
    } finally {
        IOUtils.closeQuietly(bufferedResourceStream);
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.identitystore.jackrabbit.JackrabbitIdentityStoreDao.java

private ContentObject importRole(Resource roleXmlResource, String systemUserId, String cmsRepositoryId,
        String idOfTheRepositoryWhichRepresentsTheIdentityStore) throws Exception {

    if (roleXmlResource == null || !roleXmlResource.exists()) {
        throw new CmsException("No roles xml file found");
    } else {/*from   w  w w .j a  v  a2 s  .  c o m*/

        String roleName = StringUtils.substringBeforeLast(roleXmlResource.getFilename(),
                CmsConstants.PERIOD_DELIM);

        String roleAffilitation = CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(CmsRole.valueOf(roleName), cmsRepositoryId);

        CmsOutcome<ContentObject> outcome = findRole(roleAffilitation);

        if (outcome != null && outcome.getCount() > 0) {

            if (outcome.getCount() > 1) {
                logger.warn("Found more than one roles with system name " + roleAffilitation
                        + " Will use first role available");
            }

            return outcome.getResults().get(0);
        }

        logger.info("Role {} for identity store not found. Creating one", roleAffilitation);

        InputStream inputStream = null;

        try {
            inputStream = roleXmlResource.getInputStream();

            String roleXml = IOUtils.toString(inputStream, "UTF-8");

            //Replace ids
            roleXml = StringUtils.replace(roleXml, SYSTEM_USER_ID, systemUserId);
            roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
            roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID,
                    idOfTheRepositoryWhichRepresentsTheIdentityStore);

            /*
             * Currently, the identifier of the repository which represents the identity store
             * is used in accessibility.canBeUpdated / accessibility.canBeDeleted properties
             * whose value follows the pattern ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID. 
             * In the case of the ROLE_CMS_IDENTITY_STORE_EDITOR.xml template, 
             * the replacements above will generate the outcome 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             * 
             * That is happening because the role name ROLE_CMS_IDENTITY_STORE_EDITOR is replaced once
             * by the roleAffiliation (roleName + repositoryId)   
             * 
             *    roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
             * 
             *     ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID becomes
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@IDENTITY_STORE_REPOSITORY_ID
             * 
             * and then the following replacement is executed
             * 
             * roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID, idOfTheRepositoryWhichRepresentsTheIdentityStore);
             * 
             * to produce the following result 
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             */

            if (StringUtils.contains(roleXml,
                    "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore)) {
                roleXml = StringUtils.replace(roleXml,
                        "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore,
                        "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore);
            }

            //Obtain content object
            ImportConfiguration configuration = ImportConfiguration.object().persist(PersistMode.DO_NOT_PERSIST)
                    .build();

            ContentObject roleObject = importDao.importContentObject(roleXml, configuration);

            if (roleObject == null) {
                throw new CmsException("Could not create a content object from provided source");
            }

            //fix system name
            roleObject.setSystemName(cmsRepositoryEntityUtils.fixSystemName(roleObject.getSystemName()));

            return roleObject;
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
        }

    }

}

From source file:org.broadleafcommerce.common.config.RuntimeEnvironmentPropertiesConfigurer.java

public void afterPropertiesSet() throws IOException {
    // If no environment override has been specified, used the default environments
    if (environments == null || environments.size() == 0) {
        environments = defaultEnvironments;
    }/* w  w w  .j a  v  a2  s.  c o m*/

    // Prepend the default property locations to the specified property locations (if any)
    Set<Resource> combinedLocations = new LinkedHashSet<Resource>();
    if (!CollectionUtils.isEmpty(overridableProperyLocations)) {
        combinedLocations.addAll(overridableProperyLocations);
    }

    if (!CollectionUtils.isEmpty(propertyLocations)) {
        combinedLocations.addAll(propertyLocations);
    }
    propertyLocations = combinedLocations;

    if (!environments.contains(defaultEnvironment)) {
        throw new AssertionError(
                "Default environment '" + defaultEnvironment + "' not listed in environment list");
    }

    if (keyResolver == null) {
        keyResolver = new SystemPropertyRuntimeEnvironmentKeyResolver();
    }

    String environment = determineEnvironment();
    ArrayList<Resource> allLocations = new ArrayList<Resource>();

    /* Process configuration in the following order (later files override earlier files
     * common-shared.properties
     * [environment]-shared.properties
     * common.properties
     * [environment].properties
     * -Dproperty-override-shared specified value, if any
     * -Dproperty-override specified value, if any  */
    Set<Set<Resource>> testLocations = new LinkedHashSet<Set<Resource>>();
    testLocations.add(propertyLocations);
    testLocations.add(defaultPropertyLocations);

    for (Resource resource : createBroadleafResource()) {
        if (resource.exists()) {
            allLocations.add(resource);
        }
    }

    for (Set<Resource> locations : testLocations) {
        for (Resource resource : createSharedCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createSharedPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }
    }

    Resource sharedPropertyOverride = createSharedOverrideResource();
    if (sharedPropertyOverride != null) {
        allLocations.add(sharedPropertyOverride);
    }

    Resource propertyOverride = createOverrideResource();
    if (propertyOverride != null) {
        allLocations.add(propertyOverride);
    }

    Properties props = new Properties();
    for (Resource resource : allLocations) {
        if (resource.exists()) {
            // We will log source-control managed properties with trace and overrides with info
            if (((resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)))
                    || LOG.isTraceEnabled()) {
                props = new Properties(props);
                props.load(resource.getInputStream());
                for (Entry<Object, Object> entry : props.entrySet()) {
                    if (resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)) {
                        logger.support("Read " + entry.getKey() + " from " + resource.getFilename());
                    } else {
                        LOG.trace("Read " + entry.getKey() + " from " + resource.getFilename());
                    }
                }
            }
        } else {
            LOG.debug("Unable to locate resource: " + resource.getFilename());
        }
    }

    setLocations(allLocations.toArray(new Resource[] {}));
}

From source file:org.broadleafcommerce.common.resource.service.ResourceMinificationServiceImpl.java

@Override
public Resource minify(Resource originalResource) {
    if (!getEnabled()) {
        LOG.trace("Minification is disabled, returning original resource");
        return originalResource;
    }/*w  w  w.j  a v a 2 s  .  c  o m*/

    if (originalResource.getFilename() == null) {
        LOG.warn("Attempted to modify resource without a filename, returning non-minified resource");
        return originalResource;
    }
    return minify(originalResource, originalResource.getFilename());
}

From source file:org.broadleafcommerce.common.web.resource.BroadleafResourceHttpRequestHandler.java

protected Resource getResourceInternal(HttpServletRequest request) {
    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    if (bundlingService.hasBundle(path)) {
        return bundlingService.getBundle(path);
    }/*from  w ww.  j  av  a2  s.com*/

    Resource unminifiedResource = null;

    if (sortedHandlers == null && handlers != null) {
        sortHandlers();
    }

    if (sortedHandlers != null) {
        for (AbstractGeneratedResourceHandler handler : sortedHandlers) {
            if (handler.canHandle(path)) {
                unminifiedResource = handler.getResource(path, getLocations());
                break;
            }
        }
    }

    if (unminifiedResource == null) {
        ExtensionResultHolder erh = new ExtensionResultHolder();
        extensionManager.getProxy().getOverrideResource(path, erh);
        if (erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR) != null) {
            unminifiedResource = (Resource) erh.getContextMap()
                    .get(ResourceRequestExtensionHandler.RESOURCE_ATTR);
        }
    }

    if (unminifiedResource == null) {
        unminifiedResource = super.getResource(request);
    }

    try {
        if (!minifyService.getEnabled() || !minifyService.getAllowSingleMinification()) {
            return unminifiedResource;
        }
    } finally {
        ThreadLocalManager.remove();
    }

    LOG.warn("Minifying individual file - this should only be used in development to trace down particular "
            + "files that are causing an exception in the minification service. The results of the minification "
            + "performed outside of a bundle are not stored to disk.");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bytes = null;
    InputStream is = null;
    try {
        is = unminifiedResource.getInputStream();
        StreamUtils.copy(is, baos);
        bytes = baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
            baos.close();
        } catch (IOException e2) {
            throw new RuntimeException("Could not close input stream", e2);
        }
    }

    LOG.debug("Attempting to minifiy " + unminifiedResource.getFilename());
    byte[] minifiedBytes = minifyService.minify(unminifiedResource.getFilename(), bytes);

    return new GeneratedResource(minifiedBytes, unminifiedResource.getFilename());
}

From source file:org.broadleafcommerce.common.web.resource.resolver.BundleResourceResolver.java

protected void logTraceInformation(Resource bundle) {
    if (LOG.isTraceEnabled()) {
        if (bundle == null) {
            LOG.trace("Resolving bundle, bundle is null");
        } else {/*w ww  .ja  v a  2  s  .co m*/
            LOG.trace("Resolving bundle, bundle is not null, bundle.exists() == " + bundle.exists()
                    + " ,filename = " + bundle.getFilename());
            try {
                LOG.trace("Resolving bundle - File Path" + bundle.getFile().getAbsolutePath());
            } catch (IOException e) {
                LOG.error("IOException debugging bundle code", e);
            }
        }
    }
}