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:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.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.
 *
 * @return Returns an input stream onto the script, otherwise null
 *///from   w  w  w.j a  va  2s  .c o m
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
    ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(this.getClass().getClassLoader());
    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:com.wavemaker.tools.project.LocalStudioFileSystem.java

protected static Resource getDefaultWaveMakerHome() {

    Resource userHome = null;
    if (SystemUtils.IS_OS_WINDOWS) {
        String userProfileEnvVar = System.getenv("USERPROFILE");
        if (StringUtils.hasText(userProfileEnvVar)) {
            userProfileEnvVar = userProfileEnvVar.endsWith("/") ? userProfileEnvVar : userProfileEnvVar + "/";
            userHome = new FileSystemResource(System.getenv("USERPROFILE"));
        }/*from www  . j a v a2  s .c  om*/
    }
    if (userHome == null) {
        String userHomeProp = System.getProperty("user.home");
        userHomeProp = userHomeProp.endsWith("/") ? userHomeProp : userHomeProp + "/";
        userHome = new FileSystemResource(userHomeProp);
    }

    String osVersionStr = System.getProperty("os.version");
    if (osVersionStr.contains(".")) {
        String sub = osVersionStr.substring(osVersionStr.indexOf(".") + 1);
        if (sub.contains(".")) {
            osVersionStr = osVersionStr.substring(0, osVersionStr.indexOf('.', osVersionStr.indexOf('.') + 1));
        }
    }

    try {
        if (SystemUtils.IS_OS_WINDOWS) {
            userHome = new FileSystemResource(
                    javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory());
        } else if (SystemUtils.IS_OS_MAC) {
            userHome = userHome.createRelative("Documents/");
        }

        if (!userHome.exists()) {
            throw new WMRuntimeException(MessageResource.PROJECT_USERHOMEDNE, userHome);
        }

        Resource wmHome = userHome.createRelative(WAVEMAKER_HOME);
        if (!wmHome.exists()) {
            wmHome.getFile().mkdir();
        }
        return wmHome;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:org.brekka.stillingar.spring.resource.ScanningResourceSelector.java

/**
 * Search the specified base directory for files with names matching those in <code>names</code>. If the location
 * gets rejected then it should be added to the list of rejected locations.
 * //  w  w w .  jav a 2  s  .  c o  m
 * @param locationBase
 *            the location to search
 * @param names
 *            the names of files to find within the base location
 * @param rejected
 *            collects failed locations.
 * @return the resource or null if one cannot be found.
 */
protected Resource findInBaseDir(BaseDirectory locationBase, Set<String> names,
        List<RejectedSnapshotLocation> rejected) {
    Resource dir = locationBase.getDirResource();
    if (dir instanceof UnresolvableResource) {
        UnresolvableResource res = (UnresolvableResource) dir;
        rejected.add(new Rejected(locationBase.getDisposition(), null, res.getMessage()));
    } else {
        String dirPath = null;
        try {
            URI uri = dir.getURI();
            if (uri != null) {
                dirPath = uri.toString();
            }
        } catch (IOException e) {
            if (log.isWarnEnabled()) {
                log.warn(format("Resource dir '%s' has a bad uri", locationBase), e);
            }
        }
        String message;
        if (dir.exists()) {
            StringBuilder messageBuilder = new StringBuilder();
            for (String name : names) {
                try {
                    Resource location = dir.createRelative(name);
                    if (location.exists()) {
                        if (location.isReadable()) {
                            // We have found a file
                            return location;
                        }
                        if (messageBuilder.length() > 0) {
                            messageBuilder.append(" ");
                        }
                        messageBuilder.append("File '%s' exists but cannot be read.");
                    } else {
                        // Fair enough, it does not exist
                    }
                } catch (IOException e) {
                    // Location could not be resolved, log as warning, then move on to the next one.
                    if (log.isWarnEnabled()) {
                        log.warn(format("Resource location '%s' encountered problem", locationBase), e);
                    }
                }
            }
            if (messageBuilder.length() == 0) {
                message = "no configuration files found";
            } else {
                message = messageBuilder.toString();
            }
        } else {
            message = "Directory does not exist";
        }
        rejected.add(new Rejected(locationBase.getDisposition(), dirPath, message));
    }
    // No resource found
    return null;
}

From source file:org.apache.uima.ruta.RutaEnvironment.java

public RutaTable getWordTable(String table) {
    RutaTable result = tables.get(table);
    if (result == null) {
        if (table.endsWith("csv")) {
            ResourceLoader resourceLoader = new RutaResourceLoader(getResourcePaths());
            Resource resource = resourceLoader.getResource(table);
            if (resource.exists()) {
                try {
                    tables.put(table, new CSVTable(resource));
                } catch (IOException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                            "Error reading csv table " + table, e);
                }/*from w ww.ja v a2 s  . c o  m*/
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Can't find " + table + "!");
            }
        } else {
            try {
                RutaTable rutaTable = (RutaTable) owner.getContext().getResourceObject(table);
                tables.put(table, rutaTable);
            } catch (ResourceAccessException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Can't find external resource table" + table, e);
            }
        }
    }

    return tables.get(table);
}

From source file:org.apache.uima.ruta.RutaEnvironment.java

public RutaWordList getWordList(String list) {
    RutaWordList result = wordLists.get(list);
    UimaContext context = owner.getContext();
    Boolean dictRemoveWS = false;
    if (context != null) {
        dictRemoveWS = (Boolean) context.getConfigParameterValue(RutaEngine.PARAM_DICT_REMOVE_WS);
        if (dictRemoveWS == null) {
            dictRemoveWS = false;/*from ww w.  ja v  a 2s . co  m*/
        }
    }
    if (result == null) {
        if (list.endsWith("txt") || list.endsWith("twl") || list.endsWith("mtwl")) {
            ResourceLoader resourceLoader = new RutaResourceLoader(getResourcePaths());
            Resource resource = resourceLoader.getResource(list);
            if (resource.exists()) {
                try {
                    if (list.endsWith("mtwl")) {
                        wordLists.put(list, new MultiTreeWordList(resource));
                    } else {
                        wordLists.put(list, new TreeWordList(resource, dictRemoveWS));
                    }
                } catch (IOException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                            "Error reading word list" + list, e);
                }
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Can't find " + list + "!");
            }
        } else {
            try {
                RutaWordList rutaTable = (RutaWordList) context.getResourceObject(list);
                wordLists.put(list, rutaTable);
            } catch (ResourceAccessException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Can't find external resource table" + list, e);
            }
        }
    }

    return wordLists.get(list);
}

From source file:org.red5.server.stream.NoSyncServerStream.java

/** {@inheritDoc} */
public void saveAs(String name, boolean isAppend)
        throws IOException, ResourceNotFoundException, ResourceExistException {
    try {//w  w  w. j  a va 2 s. co m
        IScope scope = getScope();
        IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope,
                IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class);

        String filename = generator.generateFilename(scope, name, ".flv", GenerationType.RECORD);
        Resource res = scope.getContext().getResource(filename);
        if (!isAppend) {
            if (res.exists()) {
                // Per livedoc of FCS/FMS:
                // When "live" or "record" is used,
                // any previously recorded stream with the same stream
                // URI is deleted.
                if (!res.getFile().delete())
                    throw new IOException("file could not be deleted");
            }
        } else {
            if (!res.exists()) {
                // Per livedoc of FCS/FMS:
                // If a recorded stream at the same URI does not already
                // exist,
                // "append" creates the stream as though "record" was
                // passed.
                isAppend = false;
            }
        }

        if (!res.exists()) {
            // Make sure the destination directory exists
            try {
                String path = res.getFile().getAbsolutePath();
                int slashPos = path.lastIndexOf(File.separator);
                if (slashPos != -1) {
                    path = path.substring(0, slashPos);
                }
                File tmp = new File(path);
                if (!tmp.isDirectory()) {
                    tmp.mkdirs();
                }
            } catch (IOException err) {
                log.error("Could not create destination directory.", err);
            }
            res = scope.getResource(filename);
        }

        if (!res.exists()) {
            if (!res.getFile().canWrite()) {
                log.warn("File cannot be written to " + res.getFile().getCanonicalPath());
            }
            res.getFile().createNewFile();
        }
        FileConsumer fc = new FileConsumer(scope, res.getFile());
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (isAppend) {
            paramMap.put("mode", "append");
        } else {
            paramMap.put("mode", "record");
        }
        if (null == recordPipe) {
            recordPipe = new InMemoryPushPushPipe();
        }
        recordPipe.subscribe(fc, paramMap);
        recordingFilename = filename;
    } catch (IOException e) {
        log.warn("Save as exception", e);
    }
}