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.codehaus.groovy.grails.web.servlet.view.GroovyPageView.java

public static GroovyPagesException createGroovyPageException(Exception exception,
        GroovyPagesTemplateEngine engine, String pageUrl) {
    GroovyPageTemplate t = (GroovyPageTemplate) engine.createTemplate(pageUrl);
    StackTraceElement[] stackTrace = exception.getStackTrace();
    String className = stackTrace[0].getClassName();
    int lineNumber = stackTrace[0].getLineNumber();
    if (className.contains("_gsp")) {
        int[] lineNumbers = t.getMetaInfo().getLineNumbers();
        if (lineNumber < lineNumbers.length) {
            lineNumber = lineNumbers[lineNumber - 1];
        }/*from w  w w .  j av a 2s  .co m*/
    }

    Resource resource = pageUrl != null ? engine.getResourceForUri(pageUrl) : null;
    String file;
    try {
        file = resource != null && resource.exists() ? resource.getFile().getAbsolutePath() : pageUrl;
    } catch (IOException e) {
        file = pageUrl;
    }

    return new GroovyPagesException("Error processing GroovyPageView: " + exception.getMessage(), exception,
            lineNumber, file);
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

@Override
public Decorator getNamedDecorator(HttpServletRequest request, String name) {
    if (StringUtils.isBlank(name))
        return null;

    if (Environment.getCurrent() != Environment.DEVELOPMENT && decoratorMap.containsKey(name)) {
        return decoratorMap.get(name);
    }/* www  .ja va  2s  . c om*/

    String decoratorName = name;
    if (!name.matches("(.+)(\\.)(\\w{2}|\\w{3})")) {
        name += DEFAULT_VIEW_TYPE;
    }
    String decoratorPage = DEFAULT_DECORATOR_PATH + '/' + name;

    ResourceLoader resourceLoader = establishResourceLoader();

    // lookup something like /WEB-INF/grails-app/views/layouts/[NAME].gsp
    Resource res = resourceLoader.getResource(decoratorPage);
    Decorator d = null;
    if (!res.exists()) {
        // lookup something like /WEB-INF/plugins/myplugin/grails-app/views/layouts/[NAME].gsp
        String pathToView = lookupPathToControllerView(request, name);
        res = pathToView != null ? resourceLoader.getResource(pathToView) : null;
        if (res != null && res.exists()) {
            decoratorPage = pathToView;
            d = useExistingDecorator(request, decoratorName, decoratorPage);
        } else {
            // scan /WEB-INF/plugins/*/grails-app/views/layouts/[NAME].gsp for first matching
            String pluginViewLocation = searchPluginViews(name, resourceLoader);
            if (pluginViewLocation == null) {
                pluginViewLocation = searchPluginViewsInBinaryPlugins(name);

            }

            if (pluginViewLocation != null) {
                decoratorPage = pluginViewLocation;
                d = useExistingDecorator(request, decoratorName, decoratorPage);
            }

        }
    } else {
        d = useExistingDecorator(request, decoratorName, decoratorPage);
    }
    return d;
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

private String searchPluginViewsInDevelopmentMode(String name) {

    String pluginViewLocation = null;
    for (Resource resource : GrailsPluginUtils.getPluginDirectories()) {
        try {/*  ww  w  .  j a  v a 2 s. c  o m*/
            final String pathToLayoutInPlugin = "grails-app/views/layouts/" + name;
            final String absolutePathToResource = resource.getFile().getAbsolutePath();
            if (!absolutePathToResource.endsWith("/")) {
                resource = new FileSystemResource(absolutePathToResource + '/');
            }
            final Resource layoutPath = resource.createRelative(pathToLayoutInPlugin);
            if (layoutPath.exists()) {
                GrailsPluginInfo info = GrailsPluginUtils.getPluginBuildSettings()
                        .getPluginInfo(absolutePathToResource);
                pluginViewLocation = GrailsResourceUtils.WEB_INF + "/plugins/" + info.getFullName() + '/'
                        + pathToLayoutInPlugin;
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return pluginViewLocation;
}

From source file:org.craftercms.core.store.impl.filesystem.FileSystemContentStoreAdapter.java

@Override
public Context createContext(String id, String storeServerUrl, String username, String password,
        String rootFolderPath, boolean mergingOn, boolean cacheOn, int maxAllowedItemsInCache,
        boolean ignoreHiddenFiles) throws RootFolderNotFoundException, StoreException, AuthenticationException {
    Resource rootFolderResource = resourceLoader.getResource(rootFolderPath);

    if (!rootFolderResource.exists()) {
        throw new RootFolderNotFoundException("Root folder " + rootFolderPath
                + " not found (make sure that it has a valid URL " + "prefix (e.g. file:))");
    }/*  ww w  .j  av  a  2  s .  c o m*/

    FileSystemFile rootFolder;
    try {
        rootFolder = new FileSystemFile(rootFolderResource.getFile());
    } catch (IOException e) {
        throw new StoreException("Unable to retrieve file handle for root folder " + rootFolderPath, e);
    }

    return new FileSystemContext(id, this, null, rootFolderPath, rootFolder, mergingOn, cacheOn,
            maxAllowedItemsInCache, ignoreHiddenFiles);
}

From source file:org.craftercms.engine.service.context.SiteContextFactory.java

protected ConfigurableApplicationContext getApplicationContext(SiteContext siteContext,
        URLClassLoader classLoader, HierarchicalConfiguration config, String[] applicationContextPaths,
        ResourceLoader resourceLoader) {
    try {/*from  www. ja  v a 2  s  .c om*/
        List<Resource> resources = new ArrayList<>();

        for (String path : applicationContextPaths) {
            Resource resource = resourceLoader.getResource(path);
            if (resource.exists()) {
                resources.add(resource);
            }
        }

        if (CollectionUtils.isNotEmpty(resources)) {
            String siteName = siteContext.getSiteName();

            logger.info("--------------------------------------------------");
            logger.info("<Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);
            appContext.setClassLoader(classLoader);

            if (config != null) {
                MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
                propertySources.addFirst(new ApacheCommonsConfiguration2PropertySource("siteConfig", config));
            }

            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
            reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

            for (Resource resource : resources) {
                reader.loadBeanDefinitions(resource);
            }

            appContext.refresh();

            logger.info("--------------------------------------------------");
            logger.info("</Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            return appContext;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new SiteContextCreationException(
                "Unable to load application context for site '" + siteContext.getSiteName() + "'", e);
    }
}

From source file:org.dataconservancy.access.connector.AbstractConnectorIT.java

@BeforeClass
public static void getAllTestEntities() throws IOException, InvalidXmlException {
    final String entitiesResource = "/entities";
    final Resource entities = rl.getResource(entitiesResource);
    assertNotNull(entities);/*from  w ww .  j a v  a 2 s  . co  m*/
    assertTrue(entities.exists() && entities.getFile().canRead() && entities.getFile().isDirectory());
    Collection<File> files = FileUtils.listFiles(entities.getFile(), new String[] { "xml" }, false);
    for (File f : files) {
        Dcp dcp = mb.buildSip(new FileInputStream(f));
        allTestEntities.addAll(dcp.getCollections());
        allTestEntities.addAll(dcp.getDeliverableUnits());
        allTestEntities.addAll(dcp.getEvents());
        allTestEntities.addAll(dcp.getFiles());
        allTestEntities.addAll(dcp.getManifestations());
    }

    for (DcsEntity e : allTestEntities) {
        allTestEntitiesById.put(e.getId(), e);
    }
}

From source file:org.dataconservancy.cos.osf.client.model.AbstractMockServerTest.java

/**
 * Starts mock HTTP servers on the port specified by the OSF client configuration and the Waterbutler client
 * configuration// w  w  w  .  j  a  v  a  2 s . c o m
 */
@Before
public void startMockServer() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();

    final JacksonConfigurer<OsfClientConfiguration> osfConfigurer = new DefaultOsfJacksonConfigurer<>();
    final JacksonConfigurer<WbClientConfiguration> wbConfigurer = new DefaultWbJacksonConfigurer<>();

    final ResourceLoader loader = new DefaultResourceLoader();

    final Resource configuration = loader.getResource(getOsfServiceConfigurationResource());
    assertTrue("Unable to resolve configuration resource: '" + getOsfServiceConfigurationResource() + "'",
            configuration.exists());

    mockServer = ClientAndServer.startClientAndServer(
            osfConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper,
                    OsfClientConfiguration.class).getPort());

    wbMockServer = ClientAndServer.startClientAndServer(
            wbConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper,
                    WbClientConfiguration.class).getPort());

    /* Sets up the expectations of the mock http server.
     *
     * Invokes the NodeResponseCallback when the HTTP header "X-Response-Resource" is present.
     * The header value is a classpath resource to the JSON document to be serialized for the
     * response.
     */
    mockServer.when(request().withHeader(X_RESPONSE_RESOURCE))
            .callback(callback().withCallbackClass(NodeResponseCallback.class.getName()));
    wbMockServer.when(request().withHeader(X_RESPONSE_RESOURCE))
            .callback(callback().withCallbackClass(NodeResponseCallback.class.getName()));
}

From source file:org.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

public void bootstrapFormats() throws InterruptedException, IOException {

    if (isDisabled) {
        log.info("MetadataFormatRegistryBootstrap is disabled; not executing bootstrapping process.");
        return;/*from w w  w. j  a  v a 2s.c  o m*/
    }

    long bootStart = System.currentTimeMillis();
    log.info("Bootstrapping the DCS... ");
    MetadataSchemeMapper schemeMapper = new MetadataSchemeMapper();

    MetadataFormatMapper mapper = new MetadataFormatMapper(schemeMapper);

    Iterator<RegistryEntry<DcsMetadataFormat>> iter = memoryRegistry.iterator();

    List<DepositInfo> depositStatus = new ArrayList<DepositInfo>();

    while (iter.hasNext()) {
        RegistryEntry<DcsMetadataFormat> registryEntry = iter.next();

        try {
            if (queryService.lookup(registryEntry.getId()) != null) {
                // The archive already has the entry
                log.debug("Not bootstrapping registry entry {}: it is already in the archive.",
                        registryEntry.getId());
                continue;
            }
        } catch (QueryServiceException e) {
            log.warn("Error depositing DCP (skipping it): " + e.getMessage(), e);
            continue;
        }

        final Dcp entryDcp = mapper.to(registryEntry, null);

        for (DcsFile dcsFile : entryDcp.getFiles()) {
            final Resource r;
            if (dcsFile.getSource().startsWith(FILE_PREFIX)) {
                r = new FileSystemResource(new URL(dcsFile.getSource()).getPath());
            } else if (dcsFile.getSource().startsWith(CLASSPATH_PREFIX)) {
                r = new ClassPathResource(dcsFile.getSource().substring(CLASSPATH_PREFIX.length()));
            } else {
                throw new RuntimeException(
                        "Unknown file source " + dcsFile.getSource() + " for file name " + dcsFile.getName());
            }

            if (!r.exists()) {
                throw new RuntimeException("Resource " + r.getFilename() + " doesn't exist.");
            }

            Map<String, String> metadata = new HashMap<String, String>();
            HttpHeaderUtil.addDigest("SHA-1", calculateChecksum("SHA-1", r), metadata);
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_DISPOSITION, "filename=" + r.getFilename());
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Long.toString(r.contentLength()));
            DepositInfo info = fileManager.deposit(r.getInputStream(), APPLICATION_XML, null, metadata);
            dcsFile.setSource(info.getMetadata().get(SRC_HEADER));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        modelBuilder.buildSip(entryDcp, baos);
        try {
            Map<String, String> metadata = new HashMap<String, String>();
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Integer.toString(baos.size()));
            final ByteArrayInputStream byteIn = new ByteArrayInputStream(baos.toByteArray());
            depositStatus.add(manager.deposit(byteIn, APPLICATION_XML, DCP_PACKAGING, metadata));
        } catch (PackageException e) {
            log.warn("Error depositing DCP: " + e.getMessage(), e);
            continue;
        }
    }

    Iterator<DepositInfo> statusItr = depositStatus.iterator();

    while (statusItr.hasNext()) {
        DepositInfo info = statusItr.next();
        try {
            if (!checkStatusUntilTimeout(info, 600000)) {
                File f;
                FileOutputStream fos = null;
                try {
                    f = File.createTempFile("bootstrap-", ".xml");
                    fos = new FileOutputStream(f);
                    IOUtils.copy(info.getDepositStatus().getInputStream(), fos);
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
                log.warn(
                        "Error bootstrapping the DCS; error depositing package {}: see {} for more information.",
                        info.getDepositID(), f.getAbsolutePath());
            }
        } catch (Exception e) {
            log.warn("Error bootstrapping the DCS; error depositing package {}: {}",
                    new Object[] { info.getDepositID(), e.getMessage(), e });
        }
    }

    log.info("Bootstrap complete in {} ms", System.currentTimeMillis() - bootStart);
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.support.BlueprintConfigurationScanner.java

/**
 * Checks if the given bundle contains existing configurations. The absolute paths are returned without performing
 * any checks./*from  w w  w. j  a  v a 2  s.  c  o m*/
 * 
 * @return
 */
private String[] findValidBlueprintConfigs(Bundle bundle, String[] locations) {
    List<String> configs = new ArrayList<String>(locations.length);
    ResourcePatternResolver loader = new OsgiBundleResourcePatternResolver(bundle);

    boolean debug = log.isDebugEnabled();
    for (String location : locations) {
        if (isAbsolute(location)) {
            configs.add(location);
        }
        // resolve the location to check if it's present
        else {
            try {
                String loc = location;
                if (loc.endsWith("/")) {
                    loc = loc + "*.xml";
                }
                Resource[] resources = loader.getResources(loc);
                if (!ObjectUtils.isEmpty(resources)) {
                    for (Resource resource : resources) {
                        if (resource.exists()) {
                            String value = resource.getURL().toString();
                            if (debug)
                                log.debug("Found location " + value);
                            configs.add(value);
                        }
                    }
                }
            } catch (IOException ex) {
                if (debug)
                    log.debug("Cannot resolve location " + location, ex);
            }
        }
    }
    return (String[]) configs.toArray(new String[configs.size()]);
}

From source file:org.entando.entando.apsadmin.portal.model.PageModelAction.java

private boolean checkModelResource(String path) throws Throwable {
    boolean existsJsp = false;
    if (StringUtils.isBlank(path)) {
        return existsJsp;
    }/*from ww  w.ja  v  a2 s .  co m*/
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(path);
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        if (resource.exists()) {
            return true;
        }
    }
    return false;
}