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

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

Introduction

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

Prototype

public UrlResource(String path) throws MalformedURLException 

Source Link

Document

Create a new UrlResource based on a URL path.

Usage

From source file:org.gridgain.grid.GridFactory.java

/**
 * Starts all grids specified within given Spring XML configuration file URL. If grid with given name
 * is already started, then exception is thrown. In this case all instances that may
 * have been started so far will be stopped too.
 * <p>// ww  w  .j a va 2 s .c  o m
 * Usually Spring XML configuration file will contain only one Grid definition. Note that
 * Grid configuration bean(s) is retrieved form configuration file by type, so the name of
 * the Grid configuration bean is ignored.
 *
 * @param springCfgUrl Spring XML configuration file URL. This cannot be {@code null}.
 * @param ctx Optional Spring application context.
 * @return Started grid. If Spring configuration contains multiple grid instances,
 *      then the 1st found instance is returned.
 * @throws GridException If grid could not be started or configuration
 *      read. This exception will be thrown also if grid with given name has already
 *      been started or Spring XML configuration file is invalid.
 */
// Warning is due to Spring.
public static Grid start(URL springCfgUrl, @Nullable ApplicationContext ctx) throws GridException {
    A.notNull(springCfgUrl, "springCfgUrl");

    boolean isLog4jUsed = GridFactory.class.getClassLoader()
            .getResource("org/apache/log4j/Appender.class") != null;

    Object rootLog = null;

    Object nullApp = null;

    if (isLog4jUsed)
        try {
            // Add no-op logger to remove no-appender warning.
            Class logCls = Class.forName("org.apache.log4j.Logger");

            rootLog = logCls.getMethod("getRootLogger").invoke(logCls);

            nullApp = Class.forName("org.apache.log4j.varia.NullAppender").newInstance();

            Class appCls = Class.forName("org.apache.log4j.Appender");

            rootLog.getClass().getMethod("addAppender", appCls).invoke(rootLog, nullApp);
        } catch (Exception e) {
            throw new GridException("Failed to add no-op logger for Log4j.", e);
        }

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(springCfgUrl));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new GridException("Failed to instantiate Spring XML application context [springUrl="
                + springCfgUrl + ", err=" + e.getMessage() + ']', e);
    }

    Map<String, GridConfiguration> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
        throw new GridException(
                "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']',
                e);
    }

    if (cfgMap == null)
        throw new GridException("Failed to find a single grid factory configuration in: " + springCfgUrl);

    if (isLog4jUsed) {
        try {
            // Remove previously added no-op logger.
            Class appenderCls = Class.forName("org.apache.log4j.Appender");

            rootLog.getClass().getMethod("removeAppender", appenderCls).invoke(rootLog, nullApp);
        } catch (Exception e) {
            throw new GridException("Failed to remove previously added no-op logger for Log4j.", e);
        }
    }

    if (cfgMap.isEmpty())
        throw new GridException("Can't find grid factory configuration in: " + springCfgUrl);

    List<GridNamedInstance> grids = new ArrayList<GridNamedInstance>(cfgMap.size());

    try {
        for (GridConfiguration cfg : cfgMap.values()) {
            assert cfg != null;

            // Use either user defined context or our one.
            GridNamedInstance grid = start0(cfg, ctx == null ? springCtx : ctx);

            // Add it if it was not stopped during startup.
            if (grid != null)
                grids.add(grid);
        }
    } catch (GridException e) {
        // Stop all instances started so far.
        for (GridNamedInstance grid : grids) {
            try {
                grid.stop(true, false);
            } catch (Exception e1) {
                U.error(grid.log, "Error when stopping grid: " + grid, e1);
            }
        }

        throw e;
    }

    // Return the first grid started.
    GridNamedInstance res = !grids.isEmpty() ? grids.get(0) : null;

    return res != null ? res.grid() : null;
}

From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java

/** {@inheritDoc} */
@Override//w  w  w  . j  a v a  2  s. co m
public Map<Class<?>, Object> loadBeans(URL cfgUrl, Class<?>... beanClasses) throws GridException {
    assert beanClasses.length > 0;

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl));

        springCtx.refresh();
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new GridException("Failed to instantiate Spring XML application context "
                    + "(make sure all classes used in Spring configuration are present at CLASSPATH) "
                    + "[springUrl=" + cfgUrl + ']', e);
        else
            throw new GridException("Failed to instantiate Spring XML application context [springUrl=" + cfgUrl
                    + ", err=" + e.getMessage() + ']', e);
    }

    Map<Class<?>, Object> beans = new HashMap<>();

    for (Class<?> cls : beanClasses)
        beans.put(cls, bean(springCtx, cls));

    return beans;
}

From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java

/**
 * Creates Spring application context. Optionally excluded properties can be specified,
 * it means that if such a property is found in {@link GridConfiguration}
 * then it is removed before the bean is instantiated.
 * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses.
 *
 * @param cfgUrl Resource where config file is located.
 * @param excludedProps Properties to be excluded.
 * @return Spring application context./*from w w  w .j ava 2 s . c  om*/
 */
public static ApplicationContext applicationContext(URL cfgUrl, final String... excludedProps) {
    GenericApplicationContext springCtx = new GenericApplicationContext();

    BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                BeanDefinition def = beanFactory.getBeanDefinition(beanName);

                if (def.getBeanClassName() != null) {
                    try {
                        Class.forName(def.getBeanClassName());
                    } catch (ClassNotFoundException ignored) {
                        ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName);

                        continue;
                    }
                }

                MutablePropertyValues vals = def.getPropertyValues();

                for (PropertyValue val : new ArrayList<>(vals.getPropertyValueList())) {
                    for (String excludedProp : excludedProps) {
                        if (val.getName().equals(excludedProp))
                            vals.removePropertyValue(val);
                    }
                }
            }
        }
    };

    springCtx.addBeanFactoryPostProcessor(postProc);

    new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl));

    springCtx.refresh();

    return springCtx;
}

From source file:org.gridgain.grid.loaders.glassfish.GridGlassfishLoader.java

/**
 * Starts all grids with given properties.
 *
 * @param props Startup properties.// w  w  w  . ja va  2s  .co  m
 * @throws ServerLifecycleException Thrown in case of startup fails.
 */
@SuppressWarnings({ "unchecked" })
private void start(Properties props) throws ServerLifecycleException {
    GridLogger log = new GridJclLogger(LogFactory.getLog("GridGain"));

    if (props != null)
        cfgFile = props.getProperty(cfgFilePathParam);

    if (cfgFile == null)
        throw new ServerLifecycleException("Failed to read property: " + cfgFilePathParam);

    ctxClsLdr = Thread.currentThread().getContextClassLoader();

    // Set thread context classloader because Spring use it for loading classes.
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

    URL cfgUrl = U.resolveGridGainUrl(cfgFile);

    if (cfgUrl == null)
        throw new ServerLifecycleException("Failed to find Spring configuration file (path provided should be "
                + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): " + cfgFile);

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx);

        xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new ServerLifecycleException(
                "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
        // Note: Spring is not generics-friendly.
        cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
        throw new ServerLifecycleException(
                "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']',
                e);
    }

    if (cfgMap == null)
        throw new ServerLifecycleException("Failed to find a single grid factory configuration in: " + cfgUrl);

    if (cfgMap.isEmpty())
        throw new ServerLifecycleException("Can't find grid factory configuration in: " + cfgUrl);

    try {
        for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) {
            assert cfg != null;

            GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg);

            // Set Glassfish logger.
            if (cfg.getGridLogger() == null)
                adapter.setGridLogger(log);

            Grid grid = G.start(adapter, springCtx);

            // Test if grid is not null - started properly.
            if (grid != null)
                gridNames.add(grid.name());
        }
    } catch (GridException e) {
        // Stop started grids only.
        for (String name : gridNames)
            G.stop(name, true);

        throw new ServerLifecycleException("Failed to start GridGain.", e);
    }
}

From source file:org.gridgain.grid.loaders.websphere.GridWebsphereLoader.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override/*  w ww . jav  a  2  s.c o  m*/
public void initialize(Properties properties) throws Exception {
    GridLogger log = new GridJclLogger(LogFactory.getLog("GridGain"));

    cfgFile = properties.getProperty(cfgFilePathParam);

    if (cfgFile == null)
        throw new IllegalArgumentException("Failed to read property: " + cfgFilePathParam);

    String workMgrName = properties.getProperty(workMgrParam);

    URL cfgUrl = U.resolveGridGainUrl(cfgFile);

    if (cfgUrl == null)
        throw new IllegalArgumentException("Failed to find Spring configuration file (path provided should be "
                + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): " + cfgFile);

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx);

        xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new IllegalArgumentException(
                "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
        // Note: Spring is not generics-friendly.
        cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
        throw new IllegalArgumentException(
                "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']',
                e);
    }

    if (cfgMap == null)
        throw new IllegalArgumentException("Failed to find a single grid factory configuration in: " + cfgUrl);

    if (cfgMap.isEmpty())
        throw new IllegalArgumentException("Can't find grid factory configuration in: " + cfgUrl);

    try {
        ExecutorService execSvc = null;

        MBeanServer mbeanSrvr = null;

        for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) {
            assert cfg != null;

            GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg);

            // Set WebSphere logger.
            if (cfg.getGridLogger() == null)
                adapter.setGridLogger(log);

            if (cfg.getExecutorService() == null) {
                if (execSvc == null) {
                    if (workMgrName != null)
                        execSvc = new GridThreadWorkManagerExecutor(workMgrName);
                    else {
                        // Obtain/create singleton.
                        J2EEServiceManager j2eeMgr = J2EEServiceManager.getSelf();

                        // Start it if was not started before.
                        j2eeMgr.start();

                        // Create new configuration.
                        CommonJWorkManagerConfiguration workMgrCfg = j2eeMgr
                                .createCommonJWorkManagerConfiguration();

                        workMgrCfg.setName("GridGain");
                        workMgrCfg.setJNDIName("wm/gridgain");

                        // Set worker.
                        execSvc = new GridThreadWorkManagerExecutor(j2eeMgr.getCommonJWorkManager(workMgrCfg));
                    }
                }

                adapter.setExecutorService(execSvc);
            }

            if (cfg.getMBeanServer() == null) {
                if (mbeanSrvr == null)
                    mbeanSrvr = AdminServiceFactory.getMBeanFactory().getMBeanServer();

                adapter.setMBeanServer(mbeanSrvr);
            }

            Grid grid = G.start(adapter, springCtx);

            // Test if grid is not null - started properly.
            if (grid != null)
                gridNames.add(grid.name());
        }
    } catch (GridException e) {
        // Stop started grids only.
        for (String name : gridNames)
            G.stop(name, true);

        throw new IllegalArgumentException("Failed to start GridGain.", e);
    }
}

From source file:org.jahia.data.templates.JahiaTemplatesPackage.java

/**
 * Returns a resource from the module's bundle for the specified path.
 *
 * @param relativePath//from w  w w  .ja v  a2  s.  co m
 *            a path of the bundle resource
 * @return a resource from the module's bundle for the specified path
 * @see Bundle#getEntry(String)
 */
public Resource getResource(String relativePath) {
    if (relativePath == null) {
        return null;
    }
    if (getSourcesFolder() != null && getSourcesFolder().exists()) {
        try {
            File file = new File(getSourcesFolder(), "src/main/resources/" + relativePath);
            if (file.exists()) {
                return new UrlResource(file.toURI());
            }
        } catch (MalformedURLException e) {
            // file.toURI cannot return malformed URL
        }
    }
    URL entryURL = getResourceFromCache(relativePath);
    if (entryURL != null) {
        return new BundleResource(entryURL, bundle);
    }
    return null;
}

From source file:org.jahia.data.templates.JahiaTemplatesPackage.java

/**
 * Returns resources from the module's bundle and its attached fragments for the specified path.
 *
 * @param relativePath//  ww w . ja v  a 2s.c  om
 *            a path of the bundle resource
 * @return resources from the module's bundle and its attached fragments for the specified path
 * @see Bundle#findEntries(String, String, boolean)
 */
public Resource[] getResources(String relativePath) {
    List<Resource> resources = null;
    File sourceLocation = getSourcesFolder() != null
            ? new File(getSourcesFolder(), "src/main/resources/" + relativePath)
            : null;
    if (sourceLocation != null && sourceLocation.exists()) {
        File[] files = sourceLocation.listFiles();
        if (files == null || files.length == 0) {
            return NO_RESOURCES;
        }
        resources = new ArrayList<Resource>();
        for (File file : files) {
            try {
                resources.add(new UrlResource(file.toURI()));
            } catch (MalformedURLException e) {
                // file.toURI cannot return malformed URL
            }
        }
    } else {
        Enumeration<URL> resourceEnum = bundle.findEntries(relativePath, null, false);
        if (resourceEnum == null) {
            return NO_RESOURCES;
        } else {
            resources = new ArrayList<Resource>();
            while (resourceEnum.hasMoreElements()) {
                resources.add(new BundleResource(resourceEnum.nextElement(), bundle));
            }
        }
    }
    return resources != null ? resources.toArray(new Resource[resources.size()]) : NO_RESOURCES;
}

From source file:org.jahia.modules.tools.taglibs.GroovyConsoleHelper.java

/**
 * Returns a generated HTML with form elements for the script parameters.
 * // w  w w  .j ava 2 s . com
 * @param scriptURI
 * @param request
 * @return
 */
public static String getScriptCustomFormElements(String scriptURI, HttpServletRequest request) {
    if (StringUtils.isBlank(scriptURI)) {
        return StringUtils.EMPTY;
    }
    final StringBuilder sb = new StringBuilder();
    try {
        final UrlResource resource = new UrlResource(
                StringUtils.substringBeforeLast(scriptURI, ".groovy") + ".properties");
        if (resource.exists()) {
            final Properties confs = new Properties();
            confs.load(resource.getInputStream());
            final String[] paramNames = StringUtils
                    .split(confs.getProperty("script.parameters.names", "").replaceAll("\\s", ""), ",");
            for (String paramName : paramNames) {
                generateFormElement(paramName.trim(), sb, confs, request);
            }

        }
    } catch (IOException e) {
        logger.error("An error occured while reading the configurations for the script " + scriptURI, e);
        return StringUtils.EMPTY;
    }
    final String formElements = sb.toString();
    if (StringUtils.isBlank(formElements)) {
        return StringUtils.EMPTY;
    }
    return sb.delete(0, sb.length()).append("<fieldset><legend>Script configuration</legend>")
            .append(formElements).append("</fieldset>").toString();
}

From source file:org.jahia.modules.tools.taglibs.GroovyConsoleHelper.java

/**
 * Returns an array of parameter names for the specified script or <code>null</code> if the script has no parameters.
 * /* www .  java2s  .c om*/
 * @param scriptURI the script URI to get parameter names for
 * @return an array of parameter names for the specified script or <code>null</code> if the script has no parameters
 */
public static String[] getScriptParamNames(String scriptURI) {
    try {
        final UrlResource resource = new UrlResource(
                StringUtils.substringBeforeLast(scriptURI, ".groovy") + ".properties");
        if (resource.exists()) {
            final Properties confs = new Properties();
            confs.load(resource.getInputStream());
            return StringUtils.split(confs.getProperty("script.parameters.names", "").replaceAll("\\s", ""),
                    ",");
        }
    } catch (IOException e) {
        logger.error("An error occured while reading the configurations for the script " + scriptURI, e);
    }
    return null;
}

From source file:org.jahia.modules.ugp.showcase.persistence.DataInitializer.java

private List<String> readInitialData() throws IOException {
    UrlResource dataResource = new UrlResource(bundle.getEntry("/META-INF/users.csv"));
    try (InputStream is = dataResource.getInputStream()) {
        return IOUtils.readLines(is);
    }//from w  w w .jav  a  2 s . c o m
}