Example usage for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader

List of usage examples for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader

Introduction

In this page you can find the example usage for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader.

Prototype

public DefaultResourceLoader() 

Source Link

Document

Create a new DefaultResourceLoader.

Usage

From source file:org.openehealth.ipf.commons.xml.XsdValidator.java

public XsdValidator() {
    resourceLoader = new DefaultResourceLoader();
}

From source file:org.openspaces.pu.container.servicegrid.deploy.Deploy.java

public OperationalString buildOperationalString(String[] args) throws Exception {
    if (args.length == 0) {
        throw new IllegalArgumentException("The pu name must be defined");
    }/*  ww  w.  j  a  va 2 s . c  o  m*/
    String puPath = args[args.length - 1];
    File puFile = new File(puPath);
    String puName = puFile.getName().replace(' ', '_');
    // override pu name allows to change the actual pu name deployed from the on under deploy directory
    String overridePuName = puName;

    boolean deletePUFile = false;

    if (puFile.exists() && puFile.isDirectory()) {
        // this is a directory, jar it up and prepare it for upload
        File zipPUFile = new File(System.getProperty("java.io.tmpdir") + "/" + puName + ".zip");
        info("Deploying a directory [" + puFile.getAbsolutePath() + "], zipping it into ["
                + zipPUFile.getAbsolutePath() + "]");
        PUZipUtils.zip(puFile, zipPUFile);
        puFile = zipPUFile;
        deletePUFile = true;
    }

    if (puFile.getName().endsWith(".zip") || puFile.getName().endsWith(".jar")
            || puFile.getName().endsWith(".war")) {
        if (!puFile.exists()) {
            throw new IllegalArgumentException(
                    "File [" + puFile.getAbsolutePath() + "] not found and can't be deployed");
        }
        overridePuName = puFile.getName().substring(0, puFile.getName().length() - 4).replace(' ', '_');
        puPath = overridePuName;
    }

    CommandLineParser.Parameter[] params = CommandLineParser.parse(args, args.length - 1);

    RequiredDependencies instanceDeploymentDependencies = new RequiredDependencies();
    RequiredDependencies instanceStartDependencies = new RequiredDependencies();

    // check if we have a groups parameter and timeout parameter
    for (CommandLineParser.Parameter param : params) {
        if (param.getName().equalsIgnoreCase(KEY_GROUPS)) {
            setGroups(param.getArguments());
        }
        if (param.getName().equalsIgnoreCase(KEY_LOCATORS)) {
            StringBuilder sb = new StringBuilder();
            for (String arg : param.getArguments()) {
                sb.append(arg).append(',');
            }
            setLocators(sb.toString());
        }
        if (param.getName().equalsIgnoreCase(KEY_TIMEOUT)) {
            setLookupTimeout(Integer.valueOf(param.getArguments()[0]));
        }
        if (param.getName().equalsIgnoreCase(KEY_OVERRIDE_NAME)) {
            overridePuName = param.getArguments()[0];
        }
        if (param.getName().equalsIgnoreCase(KEY_DEPLOY_TIMEOUT)) {
            setDeployTimeout(Long.valueOf(param.getArguments()[0]));
        }
        if (RequiredDependenciesCommandLineParser.isInstanceDeploymentDependencies(param)) {
            instanceDeploymentDependencies = RequiredDependenciesCommandLineParser
                    .convertCommandlineParameterToInstanceDeploymentDependencies(param);
        }
        if (RequiredDependenciesCommandLineParser.isInstanceStartDependencies(param)) {
            instanceStartDependencies = RequiredDependenciesCommandLineParser
                    .convertCommandlineParameterToInstanceStartDependencies(param);
        }
        if (param.getName().equalsIgnoreCase(KEY_APPLICATION_NAME)) {
            setApplicationName(param.getArguments()[0]);
        }
    }

    info("Deploying [" + puName + "] with name [" + overridePuName + "] under groups "
            + Arrays.toString(getGroups()) + " and locators " + Arrays.toString(getLocators()));

    initGSM();
    initDeployAdmin();

    // check if the pu to deploy is an actual file on the file system and ends with jar, zip or war.
    if (puFile.exists() && (puFile.getName().endsWith(".zip") || puFile.getName().endsWith(".jar")
            || puFile.getName().endsWith(".war"))) {

        try {
            if (isOnGsmHost()) {
                // the client is on the same host as the gsm.
                // we can simply copy the pu instead of uploading it.
                copyPu(puPath, puFile);

            } else {
                // we deploy a jar/zip/war file, upload it to the GSM
                uploadPU(puPath, puFile);
            }
        } catch (UnknownHostException uhe) {
            // fall back to upload anyway
            logger.warn("Could not determine if client and GSM[" + gsm.getGSAServiceID() + "] are on the same "
                    + "host", uhe);
            uploadPU(puPath, puFile);

        } catch (RemoteException re) {
            // fall back to upload anyway
            logger.warn("Could not determine if client and GSM[" + gsm.getGSAServiceID() + "] are on the same "
                    + "host", re);
            uploadPU(puPath, puFile);
        }

        if (deletePUFile) {
            puFile.delete();
        }
    }

    if (!gsm.hasPUUnderDeploy(puPath)) {
        throw new ProcessingUnitNotFoundException(puName, gsm);
    }

    String codeserver = getCodebase(deployAdmin);
    if (logger.isDebugEnabled()) {
        logger.debug("Using codeserver [" + codeserver + "]");
    }

    //list remote files, only works with webster
    URL root = new URL(codeserver);

    BeanLevelProperties beanLevelProperties = new BeanLevelProperties();
    URL puPropsURL = new URL(root, puPath + "/META-INF/spring/pu.properties");
    try {
        InputStream is = puPropsURL.openStream();
        if (is != null) {
            beanLevelProperties.getContextProperties().load(is);
            is.close();
        }
    } catch (Exception e) {
        // ignore, no file
    }
    puPropsURL = new URL(root, puPath + "/pu.properties");
    try {
        InputStream is = puPropsURL.openStream();
        if (is != null) {
            beanLevelProperties.getContextProperties().load(is);
            is.close();
        }
    } catch (Exception e) {
        // ignore, no file
    }
    beanLevelProperties = BeanLevelPropertiesParser.parse(beanLevelProperties, params);

    //read pu xml
    String puString = "";
    try {
        puString = readFile(root, puPath, "/META-INF/spring/pu.xml");
    } catch (IOException e) {
        logger.debug("Failed to find puPath " + puPath, e);
        // ignore, it might be ok for war files
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Using PU xml [" + puString + "]");
    }

    boolean slaInPu = true;
    Resource resource;

    // check to see if sla was passed as a parameter
    String slaString = puString;
    for (CommandLineParser.Parameter param : params) {
        if (param.getName().equalsIgnoreCase(KEY_SLA)) {
            String slaLocation = param.getArguments()[0];
            info("Loading SLA from [" + slaLocation + "]");
            resource = new DefaultResourceLoader() {
                // override the default load from the classpath to load from the file system
                @Override
                protected Resource getResourceByPath(String path) {
                    return new FileSystemResource(path);
                }
            }.getResource(slaLocation);
            InputStreamReader reader = new InputStreamReader(resource.getInputStream());
            slaString = FileCopyUtils.copyToString(reader);
            reader.close();
            slaInPu = false;
        }
    }
    if (slaString == puString) {
        // no sla passed as a parameter, try and load from default locations
        try {
            slaString = readFile(root, puPath, "/META-INF/spring/sla.xml");
            slaInPu = false;
        } catch (IOException e) {
            // no sla string found
            try {
                slaString = readFile(root, puPath, "/sla.xml");
                slaInPu = false;
            } catch (IOException e1) {
                // no sla string found
            }
        }
    }

    //get sla from pu string
    SLA sla = new SLA();
    if (StringUtils.hasText(slaString)) {
        resource = new ByteArrayResource(slaString.getBytes());
        if (slaInPu) {
            XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(resource);
            // TODO: Need to find how to do it
            //            Map<String, PropertyResourceConfigurer> map = xmlBeanFactory.getBeansOfType(PropertyResourceConfigurer.class);
            //            for (PropertyResourceConfigurer cfg : map.values()) {
            //                cfg.postProcessBeanFactory(xmlBeanFactory);
            //            }
            try {
                sla = (SLA) xmlBeanFactory.getBean("SLA");
            } catch (NoSuchBeanDefinitionException e) {
                info("SLA Not Found in PU.  Using Default SLA.");
                sla = new SLA();
            }
        } else {
            // if we have specific sla file, load it as usual, so we can have deploy properties / system properties injected to it
            ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig();
            config.setBeanLevelProperties(beanLevelProperties);
            ResourceApplicationContext applicationContext = new ResourceApplicationContext(
                    new Resource[] { resource }, null, config);
            // start the application context
            applicationContext.refresh();
            try {
                sla = (SLA) applicationContext.getBean("SLA");
            } catch (NoSuchBeanDefinitionException e) {
                throw new IllegalArgumentException("Failed to find SLA from in [" + slaString + "]");
            } finally {
                applicationContext.close();
            }
        }
    }

    ClusterInfo clusterInfo = ClusterInfoParser.parse(params);
    if (clusterInfo != null) {

        // override specific cluster info parameters on the SLA
        if (clusterInfo.getSchema() != null && clusterInfo.getSchema().length() > 0) {
            info("Overriding SLA cluster schema with [" + clusterInfo.getSchema() + "]");
            sla.setClusterSchema(clusterInfo.getSchema());
        }
        if (clusterInfo.getNumberOfInstances() != null) {
            info("Overriding SLA numberOfInstances with [" + clusterInfo.getNumberOfInstances() + "]");
            sla.setNumberOfInstances(clusterInfo.getNumberOfInstances());
            if (clusterInfo.getNumberOfBackups() == null) {
                info("Overriding SLA numberOfBackups with [" + clusterInfo.getNumberOfBackups() + "]");
                sla.setNumberOfBackups(0);
            } else {
                info("Overriding SLA numberOfBackups with [" + clusterInfo.getNumberOfBackups() + "]");
                sla.setNumberOfBackups(clusterInfo.getNumberOfBackups());
            }
        }
    }

    for (CommandLineParser.Parameter param : params) {
        if (param.getName().equalsIgnoreCase(KEY_REQUIRES_ISOLATION)) {
            String requiresIsolation = param.getArguments()[0];
            sla.setRequiresIsolation(Boolean.parseBoolean(requiresIsolation));
            info("Overriding SLA requiresIsolation with [" + requiresIsolation + "]");
        }
        if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_VM)) {
            String maxInstancePerVm = param.getArguments()[0];
            sla.setMaxInstancesPerVM(Integer.valueOf(maxInstancePerVm));
            info("Overriding SLA maxInstancesPerVM with [" + maxInstancePerVm + "]");
        }
        if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_MACHINE)) {
            String maxInstancePerMachine = param.getArguments()[0];
            sla.setMaxInstancesPerMachine(Integer.valueOf(maxInstancePerMachine));
            info("Overriding SLA maxInstancesPerMachine with [" + maxInstancePerMachine + "]");
        }
        if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_ZONE)) {
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (String arg : param.getArguments()) {
                map.putAll(ZoneHelper.parse(arg));
            }
            sla.setMaxInstancesPerZone(map);
            info("Overriding SLA maxInstancesPerZone with [" + ZoneHelper.unparse(map) + "]");
        }
        if (param.getName().equalsIgnoreCase(KEY_ZONES)) {
            for (String arg : param.getArguments()) {
                sla.getRequirements().add(new ZoneRequirement(arg));
                info("Adding SLA required zone with [" + arg + "]");
            }
        }
        if (param.getName().equalsIgnoreCase(KEY_PRIMARY_ZONE)) {
            String primaryZone = param.getArguments()[0];
            sla.setPrimaryZone(primaryZone);
            info("Overriding SLA primaryZone with [" + primaryZone + "]");
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Using SLA " + sla);
    }

    processSecurityParameters(beanLevelProperties, params);

    //Get elastic properties
    Map<String, String> elasticProperties = new HashMap<String, String>();
    for (CommandLineParser.Parameter param : params) {
        if (param.getName().equalsIgnoreCase(KEY_ELASTIC_PROPERTIES)) {
            for (String argument : param.getArguments()) {
                int indexOfEqual = argument.indexOf("=");
                String name = argument.substring(0, indexOfEqual);
                String value = argument.substring(indexOfEqual + 1);
                elasticProperties.put(name, value);
            }
        }
    }

    //get pu type
    String puType = guessProcessingUnitType(puPath, puFile, root, puString, sla, beanLevelProperties);
    beanLevelProperties.getContextProperties().put("pu.type", puType);

    //deploy to sg
    return loadDeployment(puString, codeserver, sla, puPath, overridePuName, beanLevelProperties,
            elasticProperties, instanceDeploymentDependencies, instanceStartDependencies, applicationName);
}

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()));
}

From source file:org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.java

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
        final BeanDefinitionRegistry registry) {

    ResourceLoader resourceLoader = new DefaultResourceLoader();
    AnnotationRepositoryConfigurationSource configurationSource = getConfigurationSource();
    RepositoryConfigurationExtension extension = getRepositoryConfigurationExtension();
    extension.registerBeansForRoot(registry, configurationSource);

    RepositoryBeanNameGenerator generator = new RepositoryBeanNameGenerator();
    generator.setBeanClassLoader(this.beanClassLoader);

    Collection<RepositoryConfiguration<AnnotationRepositoryConfigurationSource>> repositoryConfigurations = extension
            .getRepositoryConfigurations(configurationSource, resourceLoader);

    for (RepositoryConfiguration<AnnotationRepositoryConfigurationSource> repositoryConfiguration : repositoryConfigurations) {
        RepositoryBeanDefinitionBuilder builder = new RepositoryBeanDefinitionBuilder(repositoryConfiguration,
                extension);//from w ww.ja  v a2 s . co m
        BeanDefinitionBuilder definitionBuilder = builder.build(registry, resourceLoader);
        extension.postProcess(definitionBuilder, configurationSource);

        String beanName = generator.generateBeanName(definitionBuilder.getBeanDefinition(), registry);
        registry.registerBeanDefinition(beanName, definitionBuilder.getBeanDefinition());
    }
}

From source file:org.springframework.cloud.stream.app.tensorflow.util.ModelExtractor.java

public byte[] getModel(String modelUri) {
    return getModel(new DefaultResourceLoader().getResource(modelUri));
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.
 * <p>ClassLoader access will happen via the thread context class loader.
 * @see org.springframework.core.io.DefaultResourceLoader
 *//*from  w  w  w  . java2s. c  o m*/
public PathMatchingResourcePatternResolver() {
    this.resourceLoader = new DefaultResourceLoader();
}

From source file:org.springframework.data.hadoop.admin.util.HadoopWorkflowDescriptorUtilsTest.java

@Test
public void testResoureLoader() {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    util.setResourceLoader(resourceLoader);
    ResourceLoader loader = util.getResourceLoader();
    Assert.assertNotNull(loader);/* ww  w  .  j a v  a 2 s.c o m*/
    Assert.assertEquals(resourceLoader, loader);
}

From source file:org.springframework.integration.expression.ReloadableResourceBundleExpressionSource.java

/**
 * Set the ResourceLoader to use for loading bundle properties files.
 * <p>The default is a DefaultResourceLoader. Will get overridden by the
 * ApplicationContext if running in a context, as it implements the
 * ResourceLoaderAware interface. Can be manually overridden when
 * running outside of an ApplicationContext.
 * @see org.springframework.core.io.DefaultResourceLoader
 * @see org.springframework.context.ResourceLoaderAware
 *///from w  ww  .ja  v a 2 s  . c om
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
}

From source file:org.springframework.mock.web.MockServletContext.java

/**
 * Create a new {@code MockServletContext} using the supplied resource base
 * path and resource loader./*from ww  w. j  a v a 2s  .  c o m*/
 * <p>Registers a {@link MockRequestDispatcher} for the Servlet named
 * {@literal 'default'}.
 * @param resourceBasePath the root directory of the WAR (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 * @see #registerNamedDispatcher
 */
public MockServletContext(String resourceBasePath, @Nullable ResourceLoader resourceLoader) {
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
    this.resourceBasePath = resourceBasePath;

    // Use JVM temp dir as ServletContext temp dir.
    String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
    if (tempDir != null) {
        this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
    }

    registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));
}

From source file:org.springframework.mock.web.portlet.MockPortletContext.java

/**
 * Create a new MockPortletContext./*from  w  w  w .ja v a 2s .  c o m*/
 * @param resourceBasePath the WAR root directory (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 */
public MockPortletContext(String resourceBasePath, ResourceLoader resourceLoader) {
    this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());

    // Use JVM temp dir as PortletContext temp dir.
    String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
    if (tempDir != null) {
        this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
    }
}