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:org.twinkql.context.TwinkqlContextFactory.java

/**
 * Load configuration file./*from   w w w  .  j  av  a 2  s.  com*/
 *
 * @return the twinkql config
 */
protected TwinkqlConfig loadConfigurationFile() {
    PathMatchingResourcePatternResolver resolver = this.createPathMatchingResourcePatternResolver();

    Resource configFile = resolver.getResource(this.configurationFile);

    TwinkqlConfig config = null;
    if (!configFile.exists()) {
        this.log.warn("No Twinql Configuration File specified. Using defaults.");
    } else {
        config = this.loadTwinkqlConfig(configFile);
    }

    return config;
}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

@Override
public DesktopTheme loadTheme(String themeName) {
    String themeLocations = config.getResourceLocations();
    StrTokenizer tokenizer = new StrTokenizer(themeLocations);
    String[] locationList = tokenizer.getTokenArray();

    List<String> resourceLocationList = new ArrayList<>();
    DesktopThemeImpl theme = createTheme(themeName, locationList);
    theme.setName(themeName);/*from  w  ww .j a  v a2  s .  co m*/
    for (String location : locationList) {
        resourceLocationList.add(getResourcesDir(themeName, location));

        String xmlLocation = getConfigFileName(themeName, location);
        Resource resource = resources.getResource(xmlLocation);
        if (resource.exists()) {
            try {
                loadThemeFromXml(theme, resource);
            } catch (IOException e) {
                log.error("Error", e);
            }
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }

    DesktopResources desktopResources = new DesktopResources(resourceLocationList, resources);
    theme.setResources(desktopResources);

    return theme;
}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

private DesktopThemeImpl createTheme(String themeName, String[] locationList) {
    String themeClassName = null;
    for (String location : locationList) {
        String xmlLocation = getConfigFileName(themeName, location);
        Resource resource = resources.getResource(xmlLocation);
        if (resource.exists()) {
            try {
                Document doc = readXmlDocument(resource);
                final Element rootElement = doc.getRootElement();

                List<Element> classElements = rootElement.elements("class");
                if (!classElements.isEmpty()) {
                    themeClassName = classElements.get(0).getTextTrim();
                }/*from   ww  w  .ja  v a2  s . c  om*/
            } catch (IOException e) {
                log.error("Error", e);
            }
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }
    if (themeClassName != null) {
        try {
            Class themeClass = Class.forName(themeClassName);
            return (DesktopThemeImpl) themeClass.newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
    return new DesktopThemeImpl();
}

From source file:org.ireland.jnetty.webapp.ServletContextImpl.java

/**
 * Returns a resource for the given uri.
 * //  ww  w .  j  av  a  2 s .c o m
 *
 * @see org.springframework.mock.web.MockServletContext
 */
@Override
public URL getResource(String path) throws java.net.MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));

    if (!resource.exists()) {
        return null;
    }
    try {
        return resource.getURL();
    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        log.info("Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

/**
 * {@inheritDoc}/*  ww w . j  ava 2 s. co m*/
 */
@Override
public void serveResource(final String jobId, final URL baseUrl, final String relativePath,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    // TODO: Metrics
    // Is the job running or not?
    final JobStatus jobStatus;
    try {
        jobStatus = this.jobPersistenceService.getJobStatus(jobId);
    } catch (final GenieNotFoundException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
        return;
    }

    // Is it V3 or V4?
    final boolean isV4;
    try {
        isV4 = this.jobPersistenceService.isV4(jobId);
    } catch (final GenieJobNotFoundException nfe) {
        // Really after the last check this shouldn't happen but just in case
        log.error(nfe.getMessage(), nfe);
        response.sendError(HttpStatus.NOT_FOUND.value(), nfe.getMessage());
        return;
    }

    // Normalize the base url. Make sure it ends in /.
    final URI baseUri;
    try {
        baseUri = new URI(baseUrl.toString() + SLASH).normalize();
    } catch (final URISyntaxException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Unable to convert " + baseUrl + " to valid URI");
        return;
    }

    if (jobStatus.isActive() && isV4) {

        final Optional<JobDirectoryManifest> manifest = this.agentFileStreamService.getManifest(jobId);
        if (!manifest.isPresent()) {
            log.error("Manifest not found for active job: {}", jobId);
            response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(),
                    "Could not load manifest for job: " + jobId);
            return;
        }

        final URI jobDirRoot;
        try {
            jobDirRoot = new URI(AgentFileProtocolResolver.URI_SCHEME, jobId, SLASH, null);
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }

        this.handleRequest(baseUri, relativePath, request, response, manifest.get(), jobDirRoot);

    } else if (jobStatus.isActive()) {
        // Active V3 job

        // TODO: Manifest creation could be expensive
        final Resource jobDir = this.jobFileService.getJobFileAsResource(jobId, "");
        if (!jobDir.exists()) {
            log.error("Job directory {} doesn't exist. Unable to serve job contents.", jobDir);
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        final URI jobDirRoot;
        try {
            // Make sure the directory ends in a slash. Normalize will ensure only single slash
            jobDirRoot = new URI(jobDir.getURI().toString() + SLASH).normalize();
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }
        final Path jobDirPath = Paths.get(jobDirRoot);

        final JobDirectoryManifest manifest = new JobDirectoryManifest(jobDirPath, false);
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    } else {
        // Archived job
        final JobDirectoryManifest manifest;
        final URI jobDirRoot;
        try {
            final ManifestCacheValue cacheValue = this.manifestCache.get(jobId);
            manifest = cacheValue.getManifest();
            jobDirRoot = cacheValue.getJobDirectoryRoot();
        } catch (final Exception e) {
            // TODO: more fine grained exception handling
            if (e.getCause() instanceof JobNotArchivedException) {
                // will be thrown from the manifest loader
                log.error(e.getCause().getMessage(), e.getCause());
                response.sendError(HttpStatus.NOT_FOUND.value(), e.getCause().getMessage());
            } else {
                log.error(e.getMessage(), e);
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }
            return;
        }
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    }
}

From source file:com.atolcd.alfresco.repo.patch.SchemaUpgradeScriptPatch.java

/**
 * Replaces the dialect placeholder in the script URL and attempts to find a
 * file for it. If not found, the dialect hierarchy will be walked until a
 * compatible script is found. This makes it possible to have scripts that
 * are generic to all dialects.//from  ww  w.  j  a  v  a 2 s  . c  om
 * 
 * @return Returns an input stream onto the script, otherwise null
 */
@SuppressWarnings("rawtypes")
private InputStream getScriptInputStream(Class dialectClazz, String scriptUrl) throws Exception {
    // replace the dialect placeholder
    String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_SCRIPT_DIALECT, dialectClazz.getName());
    // get a handle on the resource
    Resource resource = rpr.getResource(dialectScriptUrl);
    if (!resource.exists()) {
        // it wasn't found. Get the superclass of the dialect and try again
        Class superClazz = dialectClazz.getSuperclass();
        if (Dialect.class.isAssignableFrom(superClazz)) {
            // we still have a Dialect - try again
            return getScriptInputStream(superClazz, scriptUrl);
        } else {
            // we have exhausted all options
            return null;
        }
    } else {
        // we have a handle to it
        return resource.getInputStream();
    }
}

From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java

/**
 * Causes the historical dataPointMap to load from a file determined by archiveFileLocation
 * @param archiveFile file definition to persist the data set to
 * @return true if dataPointMap loaded correctly, false if not
 *//*from   w ww  .  ja  v  a2  s  .c om*/
@PostConstruct
public boolean load() {

    repositoryLoaded = false;

    if (!persistHistoricData) {
        LOG.info("not loading persisted data as persistHistoricData=false");
        return false;
    }

    if (archiveFileName == null || archiveFileDirectoryLocation == null) {
        LOG.error("not using historical data from file as incorrect file location:"
                + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName="
                + archiveFileName);
        return false;
    }

    String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName;

    File archiveFile = null;

    try {
        Resource resource = resourceLoader.getResource(archiveFileLocation);
        if (!resource.exists()) {
            LOG.warn("cannot load historical data as file at archiveFileLocation='" + archiveFileLocation
                    + "' does not exist");
            return false;
        }

        archiveFile = new File(resource.getURL().getFile());
    } catch (IOException e) {
        LOG.error("cannot load historical data from file at archiveFileLocation='" + archiveFileLocation
                + "' due to error:", e);
        return false;
    } catch (Exception e) {
        LOG.error("cannot load historical data from file at archiveFileLocation='" + archiveFileLocation
                + "' due to error:", e);
        return false;
    }

    try {

        //TODO CHANGE TO PACKAGE
        //         JAXBContext jaxbContext = JAXBContext.newInstance(
        //               PmatrixDpdCalculatorImpl.class,
        //               PmatrixDpdCalculatorEmaImpl.class,
        //               PmatrixDpdCalculatorRepository.class,
        //               org.opennms.features.vaadin.pmatrix.model.NameValuePair.class);

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance(
                "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator");

        Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();

        Object unmarshalledObject = jaxbUnMarshaller.unmarshal(archiveFile);

        if (unmarshalledObject instanceof PmatrixDpdCalculatorRepository) {
            PmatrixDpdCalculatorRepository pdcr = (PmatrixDpdCalculatorRepository) unmarshalledObject;
            dataPointMap = pdcr.getDataPointMap();

            LOG.info("successfully unmarshalled historical pmatrix data from file location:"
                    + archiveFile.getAbsolutePath());
            repositoryLoaded = true;
            return true;
        } else {
            LOG.error("cant unmarshal received object:" + unmarshalledObject);
        }

    } catch (JAXBException e) {
        LOG.error("problem unmarshalling file: " + archiveFile.getAbsolutePath(), e);
    } catch (Exception e) {
        LOG.error("problem unmarshalling file: " + archiveFile.getAbsolutePath(), e);
    }
    return false;

}

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);
    }/*from  w ww .  jav a2 s  .  c  om*/
    if (resource == null)
        return null;

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

From source file:org.toobsframework.transformpipeline.domain.XSLUriResolverImpl.java

protected URL resolveContextResource(String xslFile, String string) throws IOException {
    Resource configFileURL = null;
    String systemId = null;/*  w w  w.  j  a va2  s . c  o  m*/
    for (int i = 0; i < this.contextBase.size(); i++) {
        systemId = this.contextBase.get(i) + xslFile;

        if (log.isDebugEnabled()) {
            log.debug("Checking for: " + systemId);
        }
        configFileURL = applicationContext.getResource(systemId);

        if (null != configFileURL) {
            break;
        }
    }
    if (configFileURL.exists()) {
        return configFileURL.getURL();
    }
    return null;
}

From source file:net.sourceforge.vulcan.spring.SpringFileStore.java

Resource getConfigurationResource() throws StoreException {
    final File config = getConfigFile();
    final Resource configResource;

    if (config.exists()) {
        configResource = new FileSystemResource(config);
    } else {/*from w w  w  .ja  va 2s .c om*/
        eventHandler.reportEvent(new WarningEvent(this, "FileStore.default.config"));
        configResource = new UrlResource(getClass().getResource("default-config.xml"));
    }

    if (!configResource.exists()) {
        throw new StoreException("Resource " + configResource + " does not exist", null);
    }
    return configResource;
}