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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:com.brienwheeler.lib.db.LocationValidatingPersistenceUnitManager.java

/**
 * Accept a list of locations for persistence XML files.  Before passing this list
 * to our superclass DefaultPersistenceUnitManager, check each location on the list
 * for actual existence.//from   w  w  w . j a  va 2s.  c o  m
 */
@Override
public void setPersistenceXmlLocations(String... persistenceXmlLocations) {
    ValidationUtils.assertNotNull(persistenceXmlLocations, "persistenceXmlLocations cannot be null");
    List<String> goodLocations = new ArrayList<String>();

    ResourceEditor editor = new ResourceEditor();
    for (String location : persistenceXmlLocations) {
        if (location == null || location.isEmpty())
            continue;

        editor.setAsText(location);
        Resource resource = (Resource) editor.getValue();
        if (resource != null && resource.exists()) {
            log.debug("using valid persistence XML location: " + location);
            goodLocations.add(location);
        } else {
            log.warn("ignoring invalid persistence XML location: " + location);
        }
    }

    String[] valid = goodLocations.toArray(new String[goodLocations.size()]);
    log.info("using validated persistence locations: [" + ArrayUtils.toString(valid) + "]");
    super.setPersistenceXmlLocations(valid);
}

From source file:com.qcadoo.view.internal.resource.module.UniversalResourceModule.java

@Override
public boolean serveResource(final HttpServletRequest request, final HttpServletResponse response) {
    Resource resource = getResourceFromURI(request.getRequestURI());
    if (resource != null && resource.exists()) {
        response.setContentType(getContentTypeFromURI(request));
        try {/* ww  w.  j a v  a  2s  .  com*/
            IOUtils.copy(resource.getInputStream(), response.getOutputStream());
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
        return true;
    } else {
        return false;
    }
}

From source file:com.searchbox.framework.service.DirectoryService.java

public File createFile(String fname) {
    Resource tempDir = context.getResource("WEB-INF/temp/");
    if (!tempDir.exists()) {
        try {/*from   w  ww .j  ava 2s.  c o  m*/
            tempDir.getFile().mkdirs();
        } catch (IOException e) {
            LOGGER.error("Could not create temp file in directoryService", e);
        }
    }
    try {
        File newFile = new File(tempDir.getFile().getAbsolutePath() + "/" + fname);
        newFile.deleteOnExit();
        return newFile;
    } catch (IOException e) {
        LOGGER.error("Could not create temp file in directoryService", e);

    }
    return null;
}

From source file:it.geosolutions.geoserver.jms.impl.utils.JMSPropertyPlaceholderConfigurer.java

public JMSPropertyPlaceholderConfigurer(Resource defaultFile, JMSConfiguration config) throws IOException {
    if (!defaultFile.exists()) {
        throw new IOException("Unable to locate the default properties file at:" + defaultFile);
    }/*from  w ww . ja  va 2 s. c o m*/
    this.defaults = defaultFile;
    this.config = config;
}

From source file:de.codecentric.boot.admin.actuate.LogfileMvcEndpoint.java

private boolean isAvailable() {
    if (!enabled) {
        return false;
    }/*from  w w  w. j a  v a2s  . c o  m*/

    if (logfile == null) {
        LOGGER.error("Logfile download failed for missing property 'logging.file'");
        return false;
    }

    Resource file = new FileSystemResource(logfile);
    if (!file.exists()) {
        LOGGER.error("Logfile download failed for missing file at path={}", logfile);
        return false;
    }

    return true;
}

From source file:org.solmix.runtime.support.spring.ContainerEntityResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource source = super.resolveEntity(publicId, systemId);
    if (null == source && null != systemId) {
        // try the schema and dtd resolver in turn, ignoring the suffix in publicId
        LOG.info("Attempting to resolve systemId {}", systemId);
        source = schemaResolver.resolveEntity(publicId, systemId);
        if (null == source) {
            source = dtdResolver.resolveEntity(publicId, systemId);
        }//from www . j  av  a  2s. c  o  m
    }
    String resourceLocation = schemaMappings.get(systemId);
    if (resourceLocation != null && publicId == null) {
        Resource resource = new ClassPathResource(resourceLocation, classLoader);
        if (resource != null && resource.exists()) {
            source.setPublicId(systemId);
            source.setSystemId(resource.getURL().toString());
        }
    }
    return source;
}

From source file:com.dvidder.service.AccountService.java

@Transactional
public byte[] getProfilePictureForUsername(String username) throws IOException {
    Account account = accountRepository.findByUsername(username);
    if (account.getProfilePicture().isDefaultPic()) {

        byte[] imgData = new byte[5000];
        Resource resource = new ClassPathResource("static/img/default-profile-pic.png");
        if (!resource.exists()) {
            System.out.println("RESOURCE DOESN'T EXIST");
        } else {/*from   w w  w  . ja v  a2  s . co  m*/
            System.out.println("YES, RESOURCE EXISTS");

            System.out.println("resource content length: " + resource.contentLength());
        }

        imgData = IOUtils.toByteArray(resource.getInputStream());
        System.out.println("byte array length: " + imgData.length);
        return imgData;
    }
    return accountRepository.findByUsername(username).getProfilePicture().getImageData();
}

From source file:com.ctv.ViewResolverCustom.java

/**
 * Checking the real existance of the content
 * @param viewName//  w  ww.  j  av a  2  s . com
 * @param locale
 * @return 
 */
@Override
protected boolean canHandle(String viewName, Locale locale) {
    if (viewName.startsWith(REDIRECT_URL_PREFIX) || viewName.startsWith(FORWARD_URL_PREFIX))
        return true;

    if (!super.canHandle(viewName, locale))
        return false;

    for (ITemplateResolver resolver : getTemplateEngine().getTemplateResolvers()) {
        if (resolver instanceof TemplateResolver) {
            TemplateResolver templateResolver = (TemplateResolver) resolver;
            String prefix = templateResolver.getPrefix();
            String suffix = templateResolver.getSuffix();
            // Remove the include part if the view is an include
            String viewNameFinal = cleanViewName(viewName);
            Resource res = applicationContext.getResource(prefix + viewNameFinal + suffix);
            if (res != null && res.exists())
                return true;
        }
    }
    return false;
}

From source file:cherry.foundation.testtool.stub.StubConfigurer.java

public void configure() throws IOException {
    for (Resource r : resources) {
        if (!r.exists()) {
            continue;
        }/* w  w w  .  j ava 2  s .  c  om*/
        try (InputStream in = r.getInputStream()) {
            Map<Class<?>, Map<String, Object>> map = objectMapper.readValue(in,
                    new TypeReference<LinkedHashMap<Class<?>, Map<String, Object>>>() {
                    });
            for (Map.Entry<Class<?>, Map<String, Object>> entry : map.entrySet()) {
                Multimap<String, Method> methodMap = createMethodMap(entry.getKey().getDeclaredMethods());
                for (Map.Entry<String, Object> ent : entry.getValue().entrySet()) {
                    if (!methodMap.containsKey(ent.getKey())) {
                        continue;
                    }
                    for (Method method : methodMap.get(ent.getKey())) {
                        JavaType type = objectMapper.getTypeFactory()
                                .constructType(method.getGenericReturnType());
                        List<Config> cfglist = parseConfig(ent.getValue());
                        for (Config cfg : cfglist) {
                            Object v = parseValue(cfg, type);
                            if (cfglist.size() == 1) {
                                repository.get(method).alwaysReturn(v);
                            } else {
                                repository.get(method).thenReturn(v);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.solmix.runtime.support.spring.SpringResourceResolver.java

@Override
public <T> T resolve(String resourceName, Class<T> resourceType) {

    try {//from w  ww .  j  ava2  s  .  c om
        T resource = null;
        if (resourceName == null) {
            String names[] = context.getBeanNamesForType(resourceType);
            if (names != null && names.length > 0) {
                resource = resourceType.cast(context.getBean(names[0], resourceType));
            }
        } else {
            resource = resourceType.cast(context.getBean(resourceName, resourceType));
        }
        return resource;
    } catch (NoSuchBeanDefinitionException def) {
        //ignore
    }
    try {
        if (ClassLoader.class.isAssignableFrom(resourceType)) {
            return resourceType.cast(context.getClassLoader());
        } else if (URL.class.isAssignableFrom(resourceType)) {
            Resource r = context.getResource(resourceName);
            if (r != null && r.exists()) {
                r.getInputStream().close(); //checks to see if the URL really can resolve
                return resourceType.cast(r.getURL());
            }
        }
    } catch (IOException e) {
        //ignore
    }
    return null;
}