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

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

Introduction

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

Prototype

default boolean isReadable() 

Source Link

Document

Indicate whether non-empty contents of this resource can be read via #getInputStream() .

Usage

From source file:batch.demo.job.FlatFilePartitioner.java

/**
 * Checks whether the specified {@link Resource} is valid.
 *
 * @param resource the resource to check
 * @throws IllegalStateException if the resource is invalid
 *///from www  .jav  a2s  .  c  o m
protected void checkResource(Resource resource) {
    Assert.notNull(resource, "Resource is not set");
    if (!resource.exists()) {
        throw new IllegalStateException("Input resource must exist: " + resource);
    }
    if (!resource.isReadable()) {
        throw new IllegalStateException("Input resource must be readable: " + resource);
    }
}

From source file:com.vilt.minium.script.test.impl.MiniumRhinoTestsSupport.java

protected Resource getResource(MiniumRhinoTestContextManager contextManager, JsVariable jsVariable) {
    String resourcePath = jsVariable.resource();
    Resource resource = null;
    if (StringUtils.isNotEmpty(resourcePath)) {
        resource = new DefaultResourceLoader(classLoader).getResource(resourcePath);
    } else if (StringUtils.isNotEmpty(jsVariable.resourceBean())) {
        resource = contextManager.getContext().getBean(jsVariable.resourceBean(), Resource.class);
    }/*  ww  w  .j  av  a 2  s  . com*/
    if (resource == null)
        return null;

    checkState(resource.exists() && resource.isReadable());
    return resource;
}

From source file:org.powertac.samplebroker.core.BrokerPropertiesService.java

private boolean validXmlResource(Resource xml) {
    try {/*from w w  w  . j  a  va2s .  c  o  m*/
        log.info("Validating resource " + xml.getURI());
        String path = xml.getURI().toString();
        for (String regex : excludedPaths) {
            if (path.matches(regex)) {
                return false;
            }
            if (!xml.exists()) {
                log.warn("Resource " + xml.getURI() + " does not exist");
                return false;
            }
            if (!xml.isReadable()) {
                log.warn("Resource " + xml.getURI() + " is not readable");
                return false;
            }
        }
        return true;
    } catch (IOException e) {
        log.error("Should not happen: " + e.toString());
        return false;
    } catch (Exception e) {
        log.error("Validation error " + e.toString());
        e.printStackTrace();
        return false;
    }
}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected List<Class<?>> getClasses(Resource[] resources) {
    List<Class<?>> annotated = new ArrayList<>();

    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader;
            try {
                metadataReader = metadataReaderFactory.getMetadataReader(resource);
            } catch (IOException e) {
                throw new RuntimeException("Unable to read metadata resource", e);
            }//from www .  ja v  a2 s. c  o m

            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())) {
                ClassMetadata classMetadata = metadataReader.getClassMetadata();
                Class c = ReflectionHelper.getClass(classMetadata.getClassName());
                annotated.add(c);
            }
        }
    }

    return annotated;
}

From source file:net.opentsdb.contrib.tsquare.support.TsWebApplicationContextInitializer.java

private TsdbConfigPropertySource loadTsdbConfig(final ResourcePatternResolver resolver) throws IOException {
    Resource configResource = null;

    for (final String location : OVERRIDE_SEARCH_LOCATIONS) {
        final String fullLoc = String.format("%s%s", location, CONFIG_FILENAME);
        log.debug("Searching for TSDB config in {}", fullLoc);

        final Resource res = resolver.getResource(fullLoc);
        if (res != null && res.exists()) {
            configResource = res;//from  w w  w.  ja  va 2  s.co  m
            log.info("Found TSDB config file using {} ", fullLoc);
            break;
        }
    }

    if (configResource == null) {
        return new TsdbConfigPropertySource(PROPERTY_SOURCE_NAME, new Config(true));
    } else if (configResource.isReadable()) {
        return new TsdbConfigPropertySource(PROPERTY_SOURCE_NAME,
                new Config(configResource.getFile().getAbsolutePath()));
    } else {
        throw new IllegalStateException("Unable to locate any TSDB config files!");
    }
}

From source file:com.gzj.tulip.jade.context.spring.JadeComponentProvider.java

/**
 * jar?JadeDAO?/*from ww w.j  a  v  a2s .c o  m*/
 * <p>
 * ?BeanDefinition?DAO??
 * {@link BeanDefinition#getBeanClassName()} DAO???
 * <p>
 * BeanDefinition??Spring???
 */
public Set<BeanDefinition> findCandidateComponents(String uriPrefix) {
    if (!uriPrefix.endsWith("/")) {
        uriPrefix = uriPrefix + "/";
    }
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = uriPrefix + this.resourcePattern;
        boolean traceEnabled = logger.isDebugEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        if (debugEnabled) {
            logger.debug("[jade/find] find " + resources.length + " resources for " + packageSearchPath);
        }
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("[jade/find] scanning " + resource);
            }
            // resourcePatternResolver.getResources?classPathResourcesmetadataReadergetInputStreamnull
            // ???exists
            if (!resource.exists()) {
                if (debugEnabled) {
                    logger.debug("Ignored because not exists:" + resource);
                }
            } else if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setResource(resource);
                    sbd.setSource(resource);
                    if (sbd.getMetadata().isInterface() && sbd.getMetadata().isIndependent()) {
                        if (debugEnabled) {
                            logger.debug("Identified candidate component class: " + resource);
                        }
                        candidates.add(sbd);
                    } else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not a interface top-level class: " + resource);
                        }
                    }
                } else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not matching any filter: " + resource);
                    }
                }
            } else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during jade scanning", ex);
    }
    return candidates;
}

From source file:com.wantscart.jade.core.JadeDaoComponentProvider.java

/**
 * Scan the class path for candidate components.
 * /*w w  w .  ja  v  a  2  s  .  c o m*/
 *  basePackage the package to check for annotated classes
 *  a corresponding Set of autodetected bean definitions
 */
public Set<BeanDefinition> findCandidateComponents(String uriPrefix) {
    if (!uriPrefix.endsWith("/")) {
        uriPrefix = uriPrefix + "/";
    }
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = uriPrefix + this.resourcePattern;
        boolean traceEnabled = logger.isDebugEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        if (debugEnabled) {
            logger.debug("[jade/find] find " + resources.length + " resources for " + packageSearchPath);
        }
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("[jade/find] scanning " + resource);
            }
            // resourcePatternResolver.getResources?classPathResourcesmetadataReadergetInputStreamnull
            // ???exists
            if (!resource.exists()) {
                if (debugEnabled) {
                    logger.debug("Ignored because not exists:" + resource);
                }
            } else if (resource.isReadable()) {
                MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setResource(resource);
                    sbd.setSource(resource);
                    if (isCandidateComponent(sbd)) {
                        if (debugEnabled) {
                            logger.debug("Identified candidate component class: " + resource);
                        }
                        candidates.add(sbd);
                    } else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not a interface top-level class: " + resource);
                        }
                    }
                } else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not matching any filter: " + resource);
                    }
                }
            } else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during jade scanning", ex);
    }
    return candidates;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGenerator.java

/**
 * Executes an arbitrary SQL script file for a specific database schema.
 * //from   www  .  j  a  va  2 s  . c  o m
 * <p>The first parameter for this method must be one of the supported {@link SchemaType}s.
 * 
 * <p>The second parameter is a {@link Resource} that points to a SQL script file resource (e.g. {@link FileSystemResource}). 
 * 
 * @param schemaType - a {@link SchemaType} representing the database schema to run a SQL script file against
 * @param sqlScriptFileResource - the SQL script file resource to be executed
 * @throws IOException if the SQL script file resource is not readable
 * @throws SQLException if an error occurs while executing a SQL script
 */
public void executeSQLScriptFile(final SchemaType schemaType, final Resource sqlScriptFileResource)
        throws IOException, SQLException {

    logger.info("Executing SQL script file '" + sqlScriptFileResource + "' for schema '" + schemaType + "'");

    List<String> sqlStmts = null;

    // Check the provided parameters to ensure that they are not null, otherwise throw an exception
    if (schemaType != null && sqlScriptFileResource != null) {

        // If the SQL script file resource is not readable, throw an exception
        if (!sqlScriptFileResource.isReadable())
            throw new IOException("SQL script file resource '" + sqlScriptFileResource + "' is not readable.");

        // Get the SQL statements from the SQL file
        sqlStmts = getSQLStmtsToLowerCaseFromFile(sqlScriptFileResource.getURL());
        for (String sql : sqlStmts) {
            System.out.println(sql + ";");
        }
        try {
            if (schemaType.equals(SchemaType.LOCAL_COMMON))
                dccCommonLocalJdbcTemplate.batchUpdate(sqlStmts.toArray(new String[] {}));
            else if (schemaType.equals(SchemaType.LOCAL_DISEASE))
                diseaseLocalJdbcTemplate.batchUpdate(sqlStmts.toArray(new String[] {}));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else
        throw new NullPointerException("Cannot execute SQL script file for schema '" + schemaType
                + "' and file '" + sqlScriptFileResource + "'.");

    logger.info("Done executing SQL script file.");
}

From source file:org.apache.syncope.core.logic.LoggerLogic.java

@PreAuthorize("hasRole('" + StandardEntitlement.AUDIT_LIST + "') or hasRole('"
        + StandardEntitlement.NOTIFICATION_LIST + "')")
public List<EventCategoryTO> listAuditEvents() {
    // use set to avoid duplications or null elements
    Set<EventCategoryTO> events = new HashSet<>();

    try {/*from  w  ww  .j  av a  2  s.c o  m*/
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(
                        SystemPropertyUtils.resolvePlaceholders(this.getClass().getPackage().getName()))
                + "/**/*.class";

        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                final Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());

                if (clazz.isAnnotationPresent(Component.class) && AbstractLogic.class.isAssignableFrom(clazz)) {
                    EventCategoryTO eventCategoryTO = new EventCategoryTO();
                    eventCategoryTO.setCategory(clazz.getSimpleName());
                    for (Method method : clazz.getDeclaredMethods()) {
                        if (Modifier.isPublic(method.getModifiers())) {
                            eventCategoryTO.getEvents().add(method.getName());
                        }
                    }
                    events.add(eventCategoryTO);
                }
            }
        }

        // SYNCOPE-608
        EventCategoryTO authenticationControllerEvents = new EventCategoryTO();
        authenticationControllerEvents.setCategory(AuditElements.AUTHENTICATION_CATEGORY);
        authenticationControllerEvents.getEvents().add(AuditElements.LOGIN_EVENT);
        events.add(authenticationControllerEvents);

        events.add(new EventCategoryTO(EventCategoryType.PROPAGATION));
        events.add(new EventCategoryTO(EventCategoryType.PULL));
        events.add(new EventCategoryTO(EventCategoryType.PUSH));

        for (AnyTypeKind anyTypeKind : AnyTypeKind.values()) {
            for (ExternalResource resource : resourceDAO.findAll()) {
                EventCategoryTO propEventCategoryTO = new EventCategoryTO(EventCategoryType.PROPAGATION);
                EventCategoryTO syncEventCategoryTO = new EventCategoryTO(EventCategoryType.PULL);
                EventCategoryTO pushEventCategoryTO = new EventCategoryTO(EventCategoryType.PUSH);

                propEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                propEventCategoryTO.setSubcategory(resource.getKey());

                syncEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                pushEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                syncEventCategoryTO.setSubcategory(resource.getKey());
                pushEventCategoryTO.setSubcategory(resource.getKey());

                for (ResourceOperation resourceOperation : ResourceOperation.values()) {
                    propEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    syncEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    pushEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                }

                for (UnmatchingRule unmatching : UnmatchingRule.values()) {
                    String event = UnmatchingRule.toEventName(unmatching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                for (MatchingRule matching : MatchingRule.values()) {
                    String event = MatchingRule.toEventName(matching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                events.add(propEventCategoryTO);
                events.add(syncEventCategoryTO);
                events.add(pushEventCategoryTO);
            }
        }

        for (SchedTask task : taskDAO.<SchedTask>findAll(TaskType.SCHEDULED)) {
            EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
            eventCategoryTO.setCategory(Class.forName(task.getJobDelegateClassName()).getSimpleName());
            events.add(eventCategoryTO);
        }

        EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PullJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);

        eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PushJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);
    } catch (Exception e) {
        LOG.error("Failure retrieving audit/notification events", e);
    }

    return new ArrayList<>(events);
}