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.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java

/**
 * Make sure if the resource is a directory as HTML it's handled properly.
 *
 * @throws Exception On any error/*  w  w  w  .  j  av  a 2  s  .co m*/
 */
@Test
public void canHandleRequestForDirectoryHtml() throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final String path = UUID.randomUUID().toString();
    Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path);
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.TEXT_HTML_VALUE);
    final String forwardedUrl = UUID.randomUUID().toString();
    Mockito.when(request.getHeader(JobConstants.GENIE_FORWARDED_FROM_HEADER)).thenReturn(forwardedUrl);
    final Resource resource = Mockito.mock(Resource.class);
    Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource);
    Mockito.when(resource.exists()).thenReturn(true);
    final File file = Mockito.mock(File.class);
    Mockito.when(resource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(true);

    final String html = UUID.randomUUID().toString();

    Mockito.when(this.directoryWriter.toHtml(Mockito.eq(file), Mockito.eq(forwardedUrl), Mockito.eq(false)))
            .thenReturn(html);

    final ServletOutputStream os = Mockito.mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(os);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).setContentType(MediaType.TEXT_HTML_VALUE);
    Mockito.verify(response, Mockito.times(1)).getOutputStream();
    Mockito.verify(this.directoryWriter, Mockito.times(1)).toHtml(Mockito.eq(file), Mockito.eq(forwardedUrl),
            Mockito.eq(false));
    Mockito.verify(os, Mockito.times(1)).write(html.getBytes(Charset.forName("UTF-8")));
}

From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java

/**
 * Make sure if the resource is a directory as JSON it's handled properly.
 *
 * @throws Exception On any error//from w ww  . j av a 2 s  .c om
 */
@Test
public void canHandleRequestForDirectoryJson() throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final String path = UUID.randomUUID().toString();
    Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path);
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(null);
    final String requestUrl = UUID.randomUUID().toString();
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl));
    final Resource resource = Mockito.mock(Resource.class);
    Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource);
    Mockito.when(resource.exists()).thenReturn(true);
    final File file = Mockito.mock(File.class);
    Mockito.when(resource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(true);

    final String html = UUID.randomUUID().toString();

    Mockito.when(this.directoryWriter.toJson(Mockito.eq(file), Mockito.eq(requestUrl), Mockito.eq(false)))
            .thenReturn(html);

    final ServletOutputStream os = Mockito.mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(os);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).setContentType(MediaType.APPLICATION_JSON_VALUE);
    Mockito.verify(response, Mockito.times(1)).getOutputStream();
    Mockito.verify(this.directoryWriter, Mockito.times(1)).toJson(Mockito.eq(file), Mockito.eq(requestUrl),
            Mockito.eq(false));
    Mockito.verify(os, Mockito.times(1)).write(html.getBytes(Charset.forName("UTF-8")));
}

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

public ConfigRoot getConfigRoot() {
    try {//from  w w  w .j  a  v a 2 s  .c  om

        File file = new File(getRootResource().getFile(), "config");
        Resource child = new FileSystemResource(file);

        log.debug("config root:" + child.getURI());

        if (!child.exists()) {
            child.getFile().mkdirs();
        }
        return new ConfigRootImpl(child);
    } catch (Exception e) {
    }
    return null;
}

From source file:it.tidalwave.northernwind.frontend.ui.component.htmltemplate.TextHolder.java

private void loadTemplate() throws IOException {
    // FIXME: this should be done only once...
    Resource resource = null;

    for (Class<?> clazz = getClass(); clazz.getSuperclass() != null; clazz = clazz.getSuperclass()) {
        final String templateName = clazz.getSimpleName() + ".txt";
        resource = new ClassPathResource(templateName, clazz);

        if (resource.exists()) {
            break;
        }//  ww  w .  j  a  va 2 s .co m
    }

    try {
        if (resource == null) {
            throw new FileNotFoundException();
        }

        final @Cleanup Reader r = new InputStreamReader(resource.getInputStream());
        final CharBuffer charBuffer = CharBuffer.allocate((int) resource.contentLength());
        final int length = r.read(charBuffer);
        r.close();
        template = new String(charBuffer.array(), 0, length);
    } catch (FileNotFoundException e) // no specific template, fallback
    {
        log.warn("No template for {}, using default", getClass().getSimpleName());
        template = "$content$\n";
    }
}

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 w  w  w  .  ja v  a 2 s  . 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.netflix.genie.agent.execution.services.impl.FetchingCacheServiceImpl.java

private void lookupOrDownload(final URI sourceFileUri, final File destinationFile)
        throws DownloadException, IOException {

    final String uriString = sourceFileUri.toASCIIString();

    log.debug("Lookup: {}", uriString);

    // Unique id to store the resource on local disk
    final String resourceCacheId = getResourceCacheId(sourceFileUri);

    // Get a handle to the resource
    final Resource resource = resourceLoader.getResource(uriString);

    if (!resource.exists()) {
        throw new DownloadException("Resource not found: " + uriString);
    }/* w  w  w.  ja  v  a 2  s  . co m*/

    final long resourceLastModified = resource.lastModified();

    //Handle to resourceCacheId/version
    final File cacheResourceVersionDir = getCacheResourceVersionDir(resourceCacheId, resourceLastModified);

    //Create the resource version dir in cache if it does not exist
    createDirectoryStructureIfNotExists(cacheResourceVersionDir);

    try (CloseableLock lock = fileLockFactory
            .getLock(touchCacheResourceVersionLockFile(resourceCacheId, resourceLastModified));) {
        //Critical section begin
        lock.lock();

        //Handle to the resource cached locally
        final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile(resourceCacheId,
                resourceLastModified);

        if (!cachedResourceVersionDataFile.exists()) {
            log.debug("Cache miss: {} (id: {})", uriString, resourceCacheId);

            // Download the resource into the download file in cache
            // resourceCacheId/version/data.tmp
            final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile(resourceCacheId,
                    resourceLastModified);
            try (InputStream in = resource.getInputStream();
                    OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile)) {
                FileCopyUtils.copy(in, out);
                Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile);
            }
        } else {
            log.debug("Cache hit: {} (id: {})", uriString, resourceCacheId);
        }

        //Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile
        Files.copy(cachedResourceVersionDataFile, destinationFile);
        //Critical section end
    } catch (LockException e) {
        throw new DownloadException("Error downloading dependency", e);
    }

    //Clean up any older versions
    cleanUpTaskExecutor.execute(new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified));
}

From source file:org.obiba.onyx.core.domain.participant.ParticipantMetadata.java

/**
 * Loads (or re-loads) configuration information stored in the configuration file.
 * // w  ww.j a  v  a2 s.  c om
 * @throws IOException on an I/O error
 */
public void initConfig() throws IOException {
    ResourcePatternResolver resolver = (ResourcePatternResolver) this.resourceLoader;
    Resource[] resources = null;
    Resource configPath = resolver.getResource(onyxConfigPath);

    // Load essential participant attributes.
    if (configPath != null && configPath.exists()) {
        // Load from a user/admin configured file, if it exists...
        resources = resolver.getResources(onyxConfigPath + "/" + ESSENTIAL_PARTICIPANT_ATTRIBUTES_FILENAME);
    }
    if (!resources[0].exists()) {
        // ...if not load from within the onyx-core.jar file.
        resources = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "META-INF/"
                + ESSENTIAL_PARTICIPANT_ATTRIBUTES_FILENAME);
    }
    initEssentialAttributes(resources);

    // Load configured participant attributes.
    if (configPath != null && configPath.exists()) {
        resources = resolver.getResources(onyxConfigPath + "/" + PARTICIPANT_ATTRIBUTES_FILENAME);
        initConfiguredAttributes(resources);
    }
}

From source file:com.haulmont.cuba.testsupport.TestContainer.java

protected void initAppProperties() {
    final Properties properties = new Properties();

    List<String> locations = getAppPropertiesFiles();
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    for (String location : locations) {
        Resource resource = resourceLoader.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                properties.load(stream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/* w w w.j  av  a 2 s. c  om*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }

    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(String key) {
            String subst = properties.getProperty(key);
            return subst != null ? subst : System.getProperty(key);
        }
    });
    for (Object key : properties.keySet()) {
        String value = substitutor.replace(properties.getProperty((String) key));
        appProperties.put((String) key, value);
    }

    File dir;
    dir = new File(appProperties.get("cuba.confDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.logDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.tempDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.dataDir"));
    dir.mkdirs();
}

From source file:de.ecw.zabos.license.License.java

/**
 * License-File einlesen und dekodieren//from   ww w  . ja  va  2s .  c  om
 * 
 * @param _licensePath
 * @return
 */
public boolean readLicense(Resource _licensePath) {
    try {
        if (!_licensePath.exists()) {
            throw new Exception("Lizenz-Datei [" + _licensePath.toString() + "]  nicht gefunden");
        }

        File f = _licensePath.getFile();

        FileInputStream ifs = new FileInputStream(f);

        byte[] senc = new byte[512];
        if (f.length() != 512) {
            // Filegroesse stimmt nicht
            return false;
        }
        int i;
        for (i = 0; i < 512; i++) {
            senc[i] = (byte) ((ifs.read() ^ xor_key[i]) & 0xFF);
        }
        // Bits extrahieren
        byte[] uenc = new byte[64];
        int off = 0;
        for (i = 0; i < 64; i++) {
            uenc[i] = (byte) (((senc[off + 0] & 0x01)) | (((senc[off + 1]) & 0x02)) | (((senc[off + 2]) & 0x04))
                    | (((senc[off + 3]) & 0x08)) | (((senc[off + 4]) & 0x10)) | (((senc[off + 5]) & 0x20))
                    | (((senc[off + 6]) & 0x40)) | (((senc[off + 7]) & 0x80)));
            off += 8;
        }
        // Felder extrahieren
        long t;
        long aus;
        aus = (uenc[OFF_AUSSTELLUNGSDATUM + 0] & 0xFF);
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 1] & 0xFF);
        aus |= t << 8;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 2] & 0xFF);
        aus |= t << 16;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 3] & 0xFF);
        aus |= t << 24;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 4] & 0xFF);
        aus |= t << 32;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 5] & 0xFF);
        aus |= t << 40;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 6] & 0xFF);
        aus |= t << 48;
        t = (uenc[OFF_AUSSTELLUNGSDATUM + 7] & 0xFF);
        aus |= t << 56;
        ausstellungsdatum = new UnixTime(aus);

        long ab;
        ab = (uenc[OFF_ABLAUFDATUM + 0] & 0xFF);
        t = (uenc[OFF_ABLAUFDATUM + 1] & 0xFF);
        ab |= t << 8;

        t = (uenc[OFF_ABLAUFDATUM + 2] & 0xFF);
        ab |= t << 16;
        t = (uenc[OFF_ABLAUFDATUM + 3] & 0xFF);
        ab |= t << 24;
        t = (uenc[OFF_ABLAUFDATUM + 4] & 0xFF);
        ab |= t << 32;
        t = (uenc[OFF_ABLAUFDATUM + 5] & 0xFF);
        ab |= t << 40;
        t = (uenc[OFF_ABLAUFDATUM + 6] & 0xFF);
        ab |= t << 48;
        t = (uenc[OFF_ABLAUFDATUM + 7] & 0xFF);
        ab |= t << 56;
        ablaufdatum = new UnixTime(ab);

        kundennummer = (uenc[OFF_KUNDENNUMMER + 0] & 0xFF) | ((uenc[OFF_KUNDENNUMMER + 1] & 0xFF) << 8)
                | ((uenc[OFF_KUNDENNUMMER + 2] & 0xFF) << 16) | ((uenc[OFF_KUNDENNUMMER + 3] & 0xFF) << 24);
        majorVersion = uenc[OFF_MAJOR_VERSION];
        minorVersion = uenc[OFF_MINOR_VERSION];
        schleifen = (short) ((uenc[OFF_SCHLEIFEN + 0] & 0xFF) | ((uenc[OFF_SCHLEIFEN + 1] & 0xFF) << 8));
        personen = (short) ((uenc[OFF_PERSONEN + 0] & 0xFF) | ((uenc[OFF_PERSONEN + 1] & 0xFF) << 8));
        off = OFF_USER;
        i = 0;
        StringBuffer sb = new StringBuffer();
        while ((i++ < 18) && (uenc[off] != 0)) {
            sb.append((char) (uenc[off++] & 0xFF));
        }
        user = sb.toString();

        off = OFF_PASSWD;
        i = 0;
        sb = new StringBuffer();
        while ((i++ < 18) && (uenc[off] != 0)) {
            sb.append((char) (uenc[off++] & 0xFF));
        }
        passwd = sb.toString();

        // Debug
        System.err.println("====================================");
        System.err.println(" ZABOS LIZENZ INFORMATIONEN:");
        System.err.println("====================================");
        System.err.println("Ausstellungsdatum: " + ausstellungsdatum);
        System.err.println("Ablaufdatum: " + ablaufdatum);
        System.err.println("Kundennummer: " + kundennummer);
        System.err.println("Version: " + majorVersion + "." + minorVersion);
        System.err.println("Schleifen: " + schleifen);
        System.err.println("Personen: " + personen);
        System.err.println("Gateway-User: " + user);
        System.err.println("Gateway-Passwd: xxx");
        return true;

    } catch (Exception e) {
        System.err.println("Die Lizenz-Datei " + _licensePath + " konnte nicht geoeffnet werden (cwd=\""
                + System.getProperty("user.dir") + "\")");
        e.printStackTrace();
    }

    return false;
}

From source file:org.alfresco.util.resource.HierarchicalResourceLoader.java

/**
 * Get a resource using the defined class hierarchy as a search path.
 * /*  ww  w  .j ava 2 s .  c  o m*/
 * @param location          the location including a {@link #DEFAULT_DIALECT_PLACEHOLDER placeholder}
 * @return                  a resource found by successive searches using class name replacement, or
 *                          <tt>null</tt> if not found.
 */
@SuppressWarnings("unchecked")
@Override
public Resource getResource(String location) {
    if (dialectClass == null || dialectBaseClass == null) {
        return super.getResource(location);
    }

    // If a property value has not been substituted, extract the property name and load from system
    String dialectBaseClassStr = dialectBaseClass;
    if (!PropertyCheck.isValidPropertyString(dialectBaseClass)) {
        String prop = PropertyCheck.getPropertyName(dialectBaseClass);
        dialectBaseClassStr = System.getProperty(prop, dialectBaseClass);
    }
    String dialectClassStr = dialectClass;
    if (!PropertyCheck.isValidPropertyString(dialectClass)) {
        String prop = PropertyCheck.getPropertyName(dialectClass);
        dialectClassStr = System.getProperty(prop, dialectClass);
    }

    Class<?> dialectBaseClazz;
    try {
        dialectBaseClazz = Class.forName(dialectBaseClassStr);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Dialect base class not found: " + dialectBaseClassStr);
    }
    Class<?> dialectClazz;
    try {
        dialectClazz = Class.forName(dialectClassStr);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Dialect class not found: " + dialectClassStr);
    }
    // Ensure that we are dealing with classes and not interfaces
    if (!Object.class.isAssignableFrom(dialectBaseClazz)) {
        throw new RuntimeException(
                "Dialect base class must be derived from java.lang.Object: " + dialectBaseClazz.getName());
    }
    if (!Object.class.isAssignableFrom(dialectClazz)) {
        throw new RuntimeException(
                "Dialect class must be derived from java.lang.Object: " + dialectClazz.getName());
    }
    // We expect these to be in the same hierarchy
    if (!dialectBaseClazz.isAssignableFrom(dialectClazz)) {
        throw new RuntimeException("Non-existent HierarchicalResourceLoader hierarchy: "
                + dialectBaseClazz.getName() + " is not a superclass of " + dialectClazz);
    }

    Class<? extends Object> clazz = dialectClazz;
    Resource resource = null;
    while (resource == null) {
        // Do replacement
        String newLocation = location.replaceAll(DEFAULT_DIALECT_REGEX, clazz.getName());
        resource = super.getResource(newLocation);
        if (resource != null && resource.exists()) {
            // Found
            break;
        }
        // Not found
        resource = null;
        // Are we at the base class?
        if (clazz.equals(dialectBaseClazz)) {
            // We don't go any further
            break;
        }
        // Move up the hierarchy
        clazz = clazz.getSuperclass();
        if (clazz == null) {
            throw new RuntimeException("Non-existent HierarchicalResourceLoaderBean hierarchy: "
                    + dialectBaseClazz.getName() + " is not a superclass of " + dialectClazz);
        }
    }
    return resource;
}