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.patientview.common.test.BaseTestPvDbSchema.java

@Before
public void testDbCreate() throws Exception {

    if (!isLocalTestEnvironment) {
        boolean isTestEnvironment = configEnvironment != null && configEnvironment.equals("test");
        if (!isTestEnvironment) {
            throw new IllegalStateException("Cannot run tests using " + configEnvironment
                    + " profile you risk overwriting a real database");
        }/* w w  w.ja  va2s.com*/

        LOGGER.info("Starting db setup");

        // a list of all the sql file names we need to run in order
        List<String> sqlFileNames = new ArrayList<String>();
        sqlFileNames.add("sql/1-pvdbschema-create.sql");

        // work out the feature number we need to increment the db to
        Resource txtResource = applicationContext.getResource("classpath:current-db-feature-num.txt");

        Assert.assertTrue("null resource", txtResource != null && txtResource.exists());

        int featureNum = Integer.parseInt(IOUtils.toString(txtResource.getInputStream()));

        Assert.assertTrue("Invalid feature version", featureNum > 0);

        // iterate through the features folders and grab the features we need
        for (int i = 1; i <= featureNum; i++) {
            sqlFileNames.add("sql/features/" + i + "/" + i + ".sql");
        }

        if (!sqlFileNames.isEmpty()) {
            Connection connection = null;

            try {
                connection = dataSource.getConnection();

                if (!isTableCreated) {
                    // empty db
                    emptyDatabase(connection);

                    // create tables
                    createTables(connection, sqlFileNames);

                    isTableCreated = true;
                } else {
                    clearData(connection);
                }

            } finally {
                if (connection != null) {
                    connection.close();
                }
            }
        }
    }
}

From source file:org.quackbot.impl.HibernateMain.java

public void initHibernate() throws IOException {
    //First, make sure there's a quackbot.properties
    Resource propertyResource = new PathMatchingResourcePatternResolver()
            .getResource("classpath:quackbot.properties");
    if (!propertyResource.exists()) {
        System.err.println("quackbot.properties not found in classpath!");
        return;/*from  w  w w.  j  av  a2s.  c  om*/
    }

    //Try to load it
    properties = new Properties();
    properties.load(propertyResource.getInputStream());

    //Use default config file or user specified ones if they exist
    String configsProperty = properties.getProperty("spring.configs");
    if (StringUtils.isNotBlank(configsProperty)) {
        configs = configsProperty.split(",");
        for (int i = 0; i < configs.length; i++)
            configs[i] = configs[i].trim();
    } else
        configs = new String[] { "classpath:spring-impl.xml" };

    //Load spring
    context = new ClassPathXmlApplicationContext(configs);
    context.registerShutdownHook();
}

From source file:org.red5.server.ContextLoader.java

/**
 * Loads context settings from ResourceBundle (.properties file)
 *
 * @throws Exception        I/O exception, casting exception and others
 *///  www .j  a v a 2 s .  c o m
public void init() throws Exception {
    // Load properties bundle
    Properties props = new Properties();
    Resource res = applicationContext.getResource(contextsConfig);
    if (!res.exists()) {
        log.error("Contexts config must be set.");
        return;
    }

    // Load properties file
    props.load(res.getInputStream());

    // Iterate thru properties keys and replace config attributes with system attributes
    for (Object key : props.keySet()) {
        String name = (String) key;
        String config = props.getProperty(name);
        // TODO: we should support arbitrary property substitution
        config = config.replace("${red5.root}", System.getProperty("red5.root"));
        config = config.replace("${red5.config_root}", System.getProperty("red5.config_root"));
        log.info("Loading: " + name + " = " + config);

        // Load context
        loadContext(name, config);
    }

}

From source file:org.red5.server.persistence.FilePersistence.java

/**
 * Load resource with given name and attaches to persistable object
 * @param name             Resource name
 * @param object           Object to attach to
 * @return                 Persistable object
 *///from  w  w  w  .j  a va  2 s  .  c  o m
private IPersistable doLoad(String name, IPersistable object) {
    IPersistable result = object;
    Resource data = resources.getResource(name);
    if (data == null || !data.exists()) {
        // No such file
        return null;
    }

    FileInputStream input;
    String filename;
    try {
        File fp = data.getFile();
        if (fp.length() == 0) {
            // File is empty
            log.error("The file at " + data.getFilename() + " is empty.");
            return null;
        }

        filename = fp.getAbsolutePath();
        input = new FileInputStream(filename);
    } catch (FileNotFoundException e) {
        log.error("The file at " + data.getFilename() + " does not exist.");
        return null;
    } catch (IOException e) {
        log.error("Could not load file from " + data.getFilename() + '.', e);
        return null;
    }

    try {
        ByteBuffer buf = ByteBuffer.allocate(input.available());
        try {
            ServletUtils.copy(input, buf.asOutputStream());
            buf.flip();
            Input in = new Input(buf);
            Deserializer deserializer = new Deserializer();
            String className = (String) deserializer.deserialize(in);
            if (result == null) {
                // We need to create the object first
                try {
                    Class theClass = Class.forName(className);
                    Constructor constructor = null;
                    try {
                        // Try to create object by calling constructor with Input stream as
                        // parameter.
                        for (Class interfaceClass : in.getClass().getInterfaces()) {
                            constructor = theClass.getConstructor(new Class[] { interfaceClass });
                            if (constructor != null) {
                                break;
                            }
                        }
                        if (constructor == null) {
                            throw new NoSuchMethodException();
                        }

                        result = (IPersistable) constructor.newInstance(in);
                    } catch (NoSuchMethodException err) {
                        // No valid constructor found, use empty
                        // constructor.
                        result = (IPersistable) theClass.newInstance();
                        result.deserialize(in);
                    } catch (InvocationTargetException err) {
                        // Error while invoking found constructor, use empty
                        // constructor.
                        result = (IPersistable) theClass.newInstance();
                        result.deserialize(in);
                    }
                } catch (ClassNotFoundException cnfe) {
                    log.error("Unknown class " + className);
                    return null;
                } catch (IllegalAccessException iae) {
                    log.error("Illegal access.", iae);
                    return null;
                } catch (InstantiationException ie) {
                    log.error("Could not instantiate class " + className);
                    return null;
                }

                // Set object's properties
                result.setName(getObjectName(name));
                result.setPath(getObjectPath(name, result.getName()));
            } else {
                // Initialize existing object
                String resultClass = result.getClass().getName();
                if (!resultClass.equals(className)) {
                    log.error("The classes differ: " + resultClass + " != " + className);
                    return null;
                }

                result.deserialize(in);
            }
        } finally {
            buf.release();
            buf = null;
        }
        if (result.getStore() != this) {
            result.setStore(this);
        }
        super.save(result);
        if (log.isDebugEnabled()) {
            log.debug("Loaded persistent object " + result + " from " + filename);
        }
    } catch (IOException e) {
        log.error("Could not load file at " + filename);
        return null;
    }

    return result;
}

From source file:org.red5.server.persistence.FilePersistence.java

/** {@inheritDoc} */
@Override//  www . j  a  v  a 2  s.  co  m
public boolean remove(String name) {
    super.remove(name);
    String filename = path + '/' + name + extension;
    Resource resFile = resources.getResource(filename);
    if (!resFile.exists()) {
        // File already deleted
        return true;
    }

    try {
        boolean result = resFile.getFile().delete();
        if (result) {
            checkRemoveEmptyDirectories(filename);
        }
        return result;
    } catch (IOException err) {
        return false;
    }
}

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

/** {@inheritDoc} */
public void saveAs(String name, boolean isAppend)
        throws IOException, ResourceNotFoundException, ResourceExistException {
    try {//w w w .  j av  a2 s  .c o  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<Object, Object> paramMap = new HashMap<Object, 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);
    }
}

From source file:org.slc.sli.ingestion.tenant.TenantPopulator.java

/**
 * Loads a TenantRecord from a tenant resource
 *
 * @param resourcePath//from w  w w .java2  s. c o  m
 *            to load into a tenant record
 * @return the loaded tenant
 */
private TenantRecord loadTenant(String resourcePath) {
    TenantRecord tenant = null;
    InputStream tenantIs = null;
    try {
        Resource config = resourceLoader.getResource(resourcePath);

        if (config.exists()) {
            tenantIs = config.getInputStream();
            tenant = TenantRecord.parse(tenantIs);
        }
    } catch (IOException e) {
        LogUtil.error(LOG, "Exception encountered loading tenant resource: ", e);
    } finally {
        IOUtils.closeQuietly(tenantIs);
    }
    return tenant;
}

From source file:org.slc.sli.ingestion.transformation.normalization.did.DidEntityConfigReader.java

public synchronized DidEntityConfig getDidEntityConfiguration(String entityType) {
    if (!didEntityConfigurations.containsKey(entityType)) {
        InputStream configIs = null;
        try {/*  ww  w.  j av a  2  s  . com*/
            Resource config = resourceLoader.getResource(searchPath + entityType + CONFIG_EXT);

            if (config.exists()) {
                configIs = config.getInputStream();
                didEntityConfigurations.put(entityType, DidEntityConfig.parse(configIs));
            } else {
                LOG.warn("no config found for entity type {}", entityType);
                didEntityConfigurations.put(entityType, NOT_FOUND);
            }
        } catch (IOException e) {
            LogUtil.error(LOG, "Error loading entity type " + entityType, e);
            didEntityConfigurations.put(entityType, NOT_FOUND);
        } finally {
            IOUtils.closeQuietly(configIs);
        }
    }

    return didEntityConfigurations.get(entityType);
}

From source file:org.slc.sli.ingestion.transformation.normalization.EntityConfigFactory.java

public synchronized EntityConfig getEntityConfiguration(String entityType) {
    if (!entityConfigurations.containsKey(entityType)) {
        InputStream configIs = null;
        try {/*from  www.  j a va  2  s  .  c  o  m*/
            Resource config = resourceLoader.getResource(searchPath + entityType + CONFIG_EXT);

            if (config.exists()) {
                configIs = config.getInputStream();
                entityConfigurations.put(entityType, EntityConfig.parse(configIs));
            } else {
                LOG.warn("no config found for entity type {}", entityType);
                entityConfigurations.put(entityType, NOT_FOUND);
            }
        } catch (IOException e) {
            LogUtil.error(LOG, "Error loading entity type " + entityType, e);
            entityConfigurations.put(entityType, NOT_FOUND);
        } finally {
            IOUtils.closeQuietly(configIs);
        }
    }

    return entityConfigurations.get(entityType);
}

From source file:org.springframework.batch.admin.integration.JobLaunchRequestFileAdapterTests.java

@Test
public void testSimpleJob() throws Exception {
    JobLaunchRequest request = adapter.adapt(new File("src/test/resources/data/test.txt"));
    assertEquals("foo", request.getJob().getName());
    String fileName = request.getJobParameters().getString("input.file");
    Resource resource = new DefaultResourceLoader().getResource(fileName);
    assertTrue("File does not exist: " + fileName, resource.exists());
    assertNotNull("File is empty", IOUtils.toString(resource.getInputStream()));
}