http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/apache/ignite/cache/spring/package.html ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/apache/ignite/cache/spring/package.html b/modules/spring/src/main/java/org/apache/ignite/cache/spring/package.html new file mode 100644 index 0000000..20f7a98 --- /dev/null +++ b/modules/spring/src/main/java/org/apache/ignite/cache/spring/package.html @@ -0,0 +1,23 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html> +<body> + <!-- Package description. --> + Contains implementation of Spring cache abstraction and <code>@Cacheable</code> annotation. +</body> +</html>
http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/GridGainSpring.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/GridGainSpring.java b/modules/spring/src/main/java/org/gridgain/grid/GridGainSpring.java deleted file mode 100644 index b78f52c..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/GridGainSpring.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid; - -import org.apache.ignite.*; -import org.apache.ignite.configuration.*; -import org.apache.ignite.internal.*; -import org.apache.ignite.internal.processors.resource.*; -import org.jetbrains.annotations.*; -import org.springframework.context.*; - -import java.net.*; - -/** - * Factory methods to start GridGain with optional Spring application context, this context can be injected into - * grid tasks and grid jobs using {@link org.apache.ignite.resources.IgniteSpringApplicationContextResource @IgniteSpringApplicationContextResource} - * annotation. - * <p> - * You can also instantiate grid directly from Spring without using {@code GridGain}. - * For more information refer to {@link GridSpringBean} documentation. - */ -public class GridGainSpring { - /** - * Starts grid with default configuration. By default this method will - * use grid configuration defined in {@code GRIDGAIN_HOME/config/default-config.xml} - * configuration file. If such file is not found, then all system defaults will be used. - * - * @param springCtx Optional Spring application context, possibly {@code null}. - * Spring bean definitions for bean injection are taken from this context. - * If provided, this context can be injected into grid tasks and grid jobs using - * {@link org.apache.ignite.resources.IgniteSpringApplicationContextResource @IgniteSpringApplicationContextResource} annotation. - * @return Started grid. - * @throws IgniteCheckedException If default grid could not be started. This exception will be thrown - * also if default grid has already been started. - */ - public static Ignite start(@Nullable ApplicationContext springCtx) throws IgniteCheckedException { - return GridGainEx.start(new GridSpringResourceContextImpl(springCtx)); - } - - /** - * Starts grid with given configuration. - * - * @param cfg Grid configuration. This cannot be {@code null}. - * @param springCtx Optional Spring application context, possibly {@code null}. - * Spring bean definitions for bean injection are taken from this context. - * If provided, this context can be injected into grid tasks and grid jobs using - * {@link org.apache.ignite.resources.IgniteSpringApplicationContextResource @IgniteSpringApplicationContextResource} annotation. - * @return Started grid. - * @throws IgniteCheckedException If grid could not be started. This exception will be thrown - * also if named grid has already been started. - */ - public static Ignite start(IgniteConfiguration cfg, @Nullable ApplicationContext springCtx) throws IgniteCheckedException { - return GridGainEx.start(cfg, new GridSpringResourceContextImpl(springCtx)); - } - - /** - * Starts all grids specified within given Spring XML configuration file. 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> - * 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 springCfgPath Spring XML configuration file path or URL. This cannot be {@code null}. - * @param springCtx Optional Spring application context, possibly {@code null}. - * Spring bean definitions for bean injection are taken from this context. - * If provided, this context can be injected into grid tasks and grid jobs using - * {@link org.apache.ignite.resources.IgniteSpringApplicationContextResource @IgniteSpringApplicationContextResource} annotation. - * @return Started grid. If Spring configuration contains multiple grid instances, - * then the 1st found instance is returned. - * @throws IgniteCheckedException 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. - */ - public static Ignite start(String springCfgPath, @Nullable ApplicationContext springCtx) throws IgniteCheckedException { - return GridGainEx.start(springCfgPath, null, new GridSpringResourceContextImpl(springCtx)); - } - - /** - * 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> - * 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 springCtx Optional Spring application context, possibly {@code null}. - * Spring bean definitions for bean injection are taken from this context. - * If provided, this context can be injected into grid tasks and grid jobs using - * {@link org.apache.ignite.resources.IgniteSpringApplicationContextResource @GridSpringApplicationContextResource} annotation. - * @return Started grid. If Spring configuration contains multiple grid instances, - * then the 1st found instance is returned. - * @throws IgniteCheckedException 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. - */ - public static Ignite start(URL springCfgUrl, @Nullable ApplicationContext springCtx) throws IgniteCheckedException { - return GridGainEx.start(springCfgUrl, null, new GridSpringResourceContextImpl(springCtx)); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/GridSpringBean.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/GridSpringBean.java b/modules/spring/src/main/java/org/gridgain/grid/GridSpringBean.java deleted file mode 100644 index 74daa11..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/GridSpringBean.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.cluster.*; -import org.apache.ignite.configuration.*; -import org.apache.ignite.plugin.*; -import org.apache.ignite.product.*; -import org.apache.ignite.hadoop.*; -import org.apache.ignite.plugin.security.*; -import org.apache.ignite.internal.util.typedef.*; -import org.apache.ignite.internal.util.typedef.internal.*; -import org.jetbrains.annotations.*; -import org.springframework.beans.*; -import org.springframework.beans.factory.*; -import org.springframework.context.*; - -import java.io.*; -import java.util.*; -import java.util.concurrent.*; - -/** - * Grid Spring bean allows to bypass {@link Ignition} methods. - * In other words, this bean class allows to inject new grid instance from - * Spring configuration file directly without invoking static - * {@link Ignition} methods. This class can be wired directly from - * Spring and can be referenced from within other Spring beans. - * By virtue of implementing {@link DisposableBean} and {@link InitializingBean} - * interfaces, {@code GridSpringBean} automatically starts and stops underlying - * grid instance. - * <p> - * <h1 class="header">Spring Configuration Example</h1> - * Here is a typical example of describing it in Spring file: - * <pre name="code" class="xml"> - * <bean id="mySpringBean" class="org.gridgain.grid.GridSpringBean"> - * <property name="configuration"> - * <bean id="grid.cfg" class="org.gridgain.grid.GridConfiguration"> - * <property name="gridName" value="mySpringGrid"/> - * </bean> - * </property> - * </bean> - * </pre> - * Or use default configuration: - * <pre name="code" class="xml"> - * <bean id="mySpringBean" class="org.gridgain.grid.GridSpringBean"/> - * </pre> - * <h1 class="header">Java Example</h1> - * Here is how you may access this bean from code: - * <pre name="code" class="java"> - * AbstractApplicationContext ctx = new FileSystemXmlApplicationContext("/path/to/spring/file"); - * - * // Register Spring hook to destroy bean automatically. - * ctx.registerShutdownHook(); - * - * Grid grid = (Grid)ctx.getBean("mySpringBean"); - * </pre> - * <p> - */ -public class GridSpringBean implements Ignite, DisposableBean, InitializingBean, - ApplicationContextAware, Externalizable { - /** */ - private static final long serialVersionUID = 0L; - - /** */ - private Ignite g; - - /** */ - private IgniteConfiguration cfg; - - /** */ - private ApplicationContext appCtx; - - /** {@inheritDoc} */ - @Override public IgniteConfiguration configuration() { - return cfg; - } - - /** - * Sets grid configuration. - * - * @param cfg Grid configuration. - */ - public void setConfiguration(IgniteConfiguration cfg) { - this.cfg = cfg; - } - - /** {@inheritDoc} */ - @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { - appCtx = ctx; - } - - /** {@inheritDoc} */ - @Override public void destroy() throws Exception { - // If there were some errors when afterPropertiesSet() was called. - if (g != null) { - // Do not cancel started tasks, wait for them. - G.stop(g.name(), false); - } - } - - /** {@inheritDoc} */ - @Override public void afterPropertiesSet() throws Exception { - if (cfg == null) - cfg = new IgniteConfiguration(); - - g = GridGainSpring.start(cfg, appCtx); - } - - /** {@inheritDoc} */ - @Override public IgniteLogger log() { - assert cfg != null; - - return cfg.getGridLogger(); - } - - /** {@inheritDoc} */ - @Override public IgniteProduct product() { - assert g != null; - - return g.product(); - } - - /** {@inheritDoc} */ - @Override public Collection<GridCache<?, ?>> caches() { - assert g != null; - - return g.caches(); - } - - /** {@inheritDoc} */ - @Override public Collection<IgniteStreamer> streamers() { - assert g != null; - - return g.streamers(); - } - - /** {@inheritDoc} */ - @Override public IgniteCompute compute() { - assert g != null; - - return g.compute(); - } - - /** {@inheritDoc} */ - @Override public IgniteManaged managed() { - assert g != null; - - return g.managed(); - } - - /** {@inheritDoc} */ - @Override public IgniteMessaging message() { - assert g != null; - - return g.message(); - } - - /** {@inheritDoc} */ - @Override public IgniteEvents events() { - assert g != null; - - return g.events(); - } - - /** {@inheritDoc} */ - @Override public ExecutorService executorService() { - assert g != null; - - return g.executorService(); - } - - /** {@inheritDoc} */ - @Override public IgniteCluster cluster() { - assert g != null; - - return g.cluster(); - } - - /** {@inheritDoc} */ - @Override public IgniteCompute compute(ClusterGroup prj) { - assert g != null; - - return g.compute(prj); - } - - /** {@inheritDoc} */ - @Override public IgniteMessaging message(ClusterGroup prj) { - assert g != null; - - return g.message(prj); - } - - /** {@inheritDoc} */ - @Override public IgniteEvents events(ClusterGroup prj) { - assert g != null; - - return g.events(prj); - } - - /** {@inheritDoc} */ - @Override public IgniteManaged managed(ClusterGroup prj) { - assert g != null; - - return g.managed(prj); - } - - /** {@inheritDoc} */ - @Override public ExecutorService executorService(ClusterGroup prj) { - assert g != null; - - return g.executorService(prj); - } - - /** {@inheritDoc} */ - @Override public IgniteScheduler scheduler() { - assert g != null; - - return g.scheduler(); - } - - /** {@inheritDoc} */ - @Override public GridSecurity security() { - assert g != null; - - return g.security(); - } - - /** {@inheritDoc} */ - @Override public IgnitePortables portables() { - assert g != null; - - return g.portables(); - } - - /** {@inheritDoc} */ - @Override public String name() { - assert g != null; - - return g.name(); - } - - /** {@inheritDoc} */ - @Override public <K, V> GridCache<K, V> cache(String name) { - assert g != null; - - return g.cache(name); - } - - /** {@inheritDoc} */ - @Override public <K, V> IgniteCache<K, V> jcache(@Nullable String name) { - assert g != null; - - return g.jcache(name); - } - - /** {@inheritDoc} */ - @Override public IgniteTransactions transactions() { - assert g != null; - - return g.transactions(); - } - - /** {@inheritDoc} */ - @Override public <K, V> IgniteDataLoader<K, V> dataLoader(@Nullable String cacheName) { - assert g != null; - - return g.dataLoader(cacheName); - } - - /** {@inheritDoc} */ - @Override public IgniteFs fileSystem(String name) { - assert g != null; - - return g.fileSystem(name); - } - - /** {@inheritDoc} */ - @Override public Collection<IgniteFs> fileSystems() { - assert g != null; - - return g.fileSystems(); - } - - /** {@inheritDoc} */ - @Override public GridHadoop hadoop() { - assert g != null; - - return g.hadoop(); - } - - /** {@inheritDoc} */ - @Nullable @Override public IgniteStreamer streamer(@Nullable String name) { - assert g != null; - - return g.streamer(name); - } - - /** {@inheritDoc} */ - @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { - assert g != null; - - return g.plugin(name); - } - - /** {@inheritDoc} */ - @Override public void close() throws IgniteCheckedException { - g.close(); - } - - /** {@inheritDoc} */ - @Override public String toString() { - return S.toString(GridSpringBean.class, this); - } - - /** {@inheritDoc} */ - @Override public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(g); - } - - /** {@inheritDoc} */ - @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - g = (Ignite)in.readObject(); - - cfg = g.configuration(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCache.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCache.java b/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCache.java deleted file mode 100644 index 8036759..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCache.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.spring; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.lang.*; -import org.apache.ignite.internal.util.typedef.*; -import org.springframework.cache.*; -import org.springframework.cache.support.*; - -import java.io.*; - -/** - * Spring cache implementation. - */ -class GridSpringCache implements Cache, Serializable { - /** */ - private String name; - - /** */ - private Ignite ignite; - - /** */ - private GridCacheProjection<Object, Object> cache; - - /** */ - private IgniteClosure<Object, Object> keyFactory; - - /** - * @param name Cache name. - * @param ignite Ignite instance. - * @param cache Cache. - * @param keyFactory Key factory. - */ - GridSpringCache(String name, Ignite ignite, GridCacheProjection<?, ?> cache, - IgniteClosure<Object, Object> keyFactory) { - assert cache != null; - - this.name = name; - this.ignite = ignite; - this.cache = (GridCacheProjection<Object, Object>)cache; - this.keyFactory = keyFactory != null ? keyFactory : F.identity(); - } - - /** {@inheritDoc} */ - @Override public String getName() { - return name; - } - - /** {@inheritDoc} */ - @Override public Object getNativeCache() { - return cache; - } - - /** {@inheritDoc} */ - @Override public ValueWrapper get(Object key) { - try { - Object val = cache.get(keyFactory.apply(key)); - - return val != null ? new SimpleValueWrapper(val) : null; - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to get value from cache [cacheName=" + cache.name() + - ", key=" + key + ']', e); - } - } - - /** {@inheritDoc} */ - @Override public <T> T get(Object key, Class<T> type) { - try { - Object val = cache.get(keyFactory.apply(key)); - - if (val != null && type != null && !type.isInstance(val)) - throw new IllegalStateException("Cached value is not of required type [cacheName=" + cache.name() + - ", key=" + key + ", val=" + val + ", requiredType=" + type + ']'); - - return (T)val; - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to get value from cache [cacheName=" + cache.name() + - ", key=" + key + ']', e); - } - } - - /** {@inheritDoc} */ - @Override public void put(Object key, Object val) { - try { - cache.putx(keyFactory.apply(key), val); - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to put value to cache [cacheName=" + cache.name() + - ", key=" + key + ", val=" + val + ']', e); - } - } - - /** {@inheritDoc} */ - @Override public ValueWrapper putIfAbsent(Object key, Object val) { - try { - Object old = cache.putIfAbsent(keyFactory.apply(key), val); - - return old != null ? new SimpleValueWrapper(old) : null; - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to put value to cache [cacheName=" + cache.name() + - ", key=" + key + ", val=" + val + ']', e); - } - } - - /** {@inheritDoc} */ - @Override public void evict(Object key) { - try { - cache.removex(keyFactory.apply(key)); - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to remove value from cache [cacheName=" + cache.name() + - ", key=" + key + ']', e); - } - } - - /** {@inheritDoc} */ - @Override public void clear() { - try { - ignite.compute(cache.gridProjection()).broadcast(new ClearClosure(cache)); - } - catch (IgniteCheckedException e) { - throw new IgniteException("Failed to clear cache [cacheName=" + cache.name() + ']', e); - } - } - - /** - * Closure that removes all entries from cache. - */ - private static class ClearClosure extends CAX implements Externalizable { - /** */ - private static final long serialVersionUID = 0L; - - /** Cache projection. */ - private GridCacheProjection<Object, Object> cache; - - /** - * For {@link Externalizable}. - */ - public ClearClosure() { - // No-op. - } - - /** - * @param cache Cache projection. - */ - private ClearClosure(GridCacheProjection<Object, Object> cache) { - this.cache = cache; - } - - /** {@inheritDoc} */ - @Override public void applyx() throws IgniteCheckedException { - cache.removeAll(); - } - - /** {@inheritDoc} */ - @Override public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(cache); - } - - /** {@inheritDoc} */ - @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - cache = (GridCacheProjection<Object, Object>)in.readObject(); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCacheManager.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCacheManager.java b/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCacheManager.java deleted file mode 100644 index c3dad9d..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringCacheManager.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.spring; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.configuration.*; -import org.apache.ignite.lang.*; -import org.apache.ignite.internal.util.typedef.*; -import org.springframework.beans.factory.*; -import org.springframework.cache.*; - -import java.util.*; - -/** - * Implementation of Spring cache abstraction based on GridGain cache. - * <h1 class="header">Overview</h1> - * Spring cache abstraction allows to enable caching for Java methods - * so that the result of a method execution is stored in some storage. If - * later the same method is called with the same set of parameters, - * the result will be retrieved from that storage instead of actually - * executing the method. For more information, refer to - * <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html"> - * Spring Cache Abstraction documentation</a>. - * <h1 class="header">How To Enable Caching</h1> - * To enable caching based on GridGain cache in your Spring application, - * you will need to do the following: - * <ul> - * <li> - * Start a GridGain node with configured cache in the same JVM - * where you application is running. - * </li> - * <li> - * Configure {@code GridSpringCacheManager} as a cache provider - * in Spring application context. - * </li> - * </ul> - * {@code GridSpringCacheManager} can start a node itself on its startup - * based on provided GridGain configuration. You can provide path to a - * Spring configuration XML file, like below (path can be absolute or - * relative to {@code GRIDGAIN_HOME}): - * <pre name="code" class="xml"> - * <beans xmlns="http://www.springframework.org/schema/beans" - * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - * xmlns:cache="http://www.springframework.org/schema/cache" - * xsi:schemaLocation=" - * http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> - * <-- Provide configuration file path. --> - * <bean id="cacheManager" class="org.gridgain.grid.cache.spring.GridSpringCacheManager"> - * <property name="configurationPath" value="examples/config/spring-cache.xml"/> - * </bean> - * - * <-- Use annotation-driven caching configuration. --> - * <cache:annotation-driven/> - * </beans> - * </pre> - * Or you can provide a {@link IgniteConfiguration} bean, like below: - * <pre name="code" class="xml"> - * <beans xmlns="http://www.springframework.org/schema/beans" - * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - * xmlns:cache="http://www.springframework.org/schema/cache" - * xsi:schemaLocation=" - * http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> - * <-- Provide configuration bean. --> - * <bean id="cacheManager" class="org.gridgain.grid.cache.spring.GridSpringCacheManager"> - * <property name="configuration"> - * <bean id="gridCfg" class="org.gridgain.grid.GridConfiguration"> - * ... - * </bean> - * </property> - * </bean> - * - * <-- Use annotation-driven caching configuration. --> - * <cache:annotation-driven/> - * </beans> - * </pre> - * Note that providing both configuration path and configuration bean is illegal - * and results in {@link IllegalArgumentException}. - * <p> - * If you already have GridGain node running within your application, - * simply provide correct Grid name, like below (if there is no Grid - * instance with such name, exception will be thrown): - * <pre name="code" class="xml"> - * <beans xmlns="http://www.springframework.org/schema/beans" - * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - * xmlns:cache="http://www.springframework.org/schema/cache" - * xsi:schemaLocation=" - * http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> - * <-- Provide Grid name. --> - * <bean id="cacheManager" class="org.gridgain.grid.cache.spring.GridSpringCacheManager"> - * <property name="gridName" value="myGrid"/> - * </bean> - * - * <-- Use annotation-driven caching configuration. --> - * <cache:annotation-driven/> - * </beans> - * </pre> - * This can be used, for example, when you are running your application - * in a J2EE Web container and use {@gglink org.gridgain.grid.startup.servlet.GridServletContextListenerStartup} - * for node startup. - * <p> - * If neither {@link #setConfigurationPath(String) configurationPath}, - * {@link #setConfiguration(IgniteConfiguration) configuration}, nor - * {@link #setGridName(String) gridName} are provided, cache manager - * will try to use default Grid instance (the one with the {@code null} - * name). If it doesn't exist, exception will be thrown. - * <h1>Starting Remote Nodes</h1> - * Remember that the node started inside your application is an entry point - * to the whole topology it connects to. You can start as many remote standalone - * nodes as you need using {@code bin/ggstart.{sh|bat}} scripts provided in - * GridGain distribution, and all these nodes will participate - * in caching data. - */ -public class GridSpringCacheManager implements CacheManager, InitializingBean { - /** Grid configuration file path. */ - private String cfgPath; - - /** Ignite configuration. */ - private IgniteConfiguration cfg; - - /** Grid name. */ - private String gridName; - - /** Ignite instance. */ - protected Ignite grid; - - /** - * Gets configuration file path. - * - * @return Grid configuration file path. - */ - public String getConfigurationPath() { - return cfgPath; - } - - /** - * Sets configuration file path. - * - * @param cfgPath Grid configuration file path. - */ - public void setConfigurationPath(String cfgPath) { - this.cfgPath = cfgPath; - } - - /** - * Gets configuration bean. - * - * @return Grid configuration bean. - */ - public IgniteConfiguration getConfiguration() { - return cfg; - } - - /** - * Sets configuration bean. - * - * @param cfg Grid configuration bean. - */ - public void setConfiguration(IgniteConfiguration cfg) { - this.cfg = cfg; - } - - /** - * Gets grid name. - * - * @return Grid name. - */ - public String getGridName() { - return gridName; - } - - /** - * Sets grid name. - * - * @param gridName Grid name. - */ - public void setGridName(String gridName) { - this.gridName = gridName; - } - - /** {@inheritDoc} */ - @SuppressWarnings("IfMayBeConditional") - @Override public void afterPropertiesSet() throws Exception { - assert grid == null; - - if (cfgPath != null && cfg != null) { - throw new IllegalArgumentException("Both 'configurationPath' and 'configuration' are " + - "provided. Set only one of these properties if you need to start a GridGain node inside of " + - "GridSpringCacheManager. If you already have a node running, omit both of them and set" + - "'gridName' property."); - } - - if (cfgPath != null) - grid = Ignition.start(cfgPath); - else if (cfg != null) - grid = Ignition.start(cfg); - else - grid = Ignition.ignite(gridName); - } - - /** {@inheritDoc} */ - @Override public Cache getCache(String name) { - assert grid != null; - - try { - return new GridSpringCache(name, grid, grid.cache(name), null); - } - catch (IllegalArgumentException ignored) { - return null; - } - } - - /** {@inheritDoc} */ - @Override public Collection<String> getCacheNames() { - assert grid != null; - - return F.viewReadOnly(grid.caches(), new IgniteClosure<GridCache<?,?>, String>() { - @Override public String apply(GridCache<?, ?> c) { - return c.name(); - } - }); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringDynamicCacheManager.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringDynamicCacheManager.java b/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringDynamicCacheManager.java deleted file mode 100644 index 135593d..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/GridSpringDynamicCacheManager.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.spring; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.internal.*; -import org.apache.ignite.internal.processors.cache.*; -import org.apache.ignite.lang.*; -import org.apache.ignite.internal.util.tostring.*; -import org.apache.ignite.internal.util.typedef.*; -import org.apache.ignite.internal.util.typedef.internal.*; -import org.springframework.cache.*; -import org.springframework.cache.annotation.*; - -import java.io.*; -import java.util.*; - -/** - * Extension of {@link GridSpringCacheManager} that adds an option to - * emulate dynamic cache creation for you Spring-based applications. - * <p> - * All the data will be actually cached in one GridGain cache. It's - * name should be provided to this cache manager via - * {@link #setDataCacheName(String)} configuration property. - * <p> - * Under the hood, this cache manager will create a cache projection - * for each cache name provided in {@link Cacheable}, {@link CachePut}, - * etc. annotations. Note that you're still able to use caches configured in - * GridGain configuration. Cache projection will be created only - * cache with provided name doesn't exist. - * <h1 class="header">Configuration</h1> - * {@link GridSpringDynamicCacheManager} inherits all configuration - * properties from {@link GridSpringCacheManager} (see it's JavaDoc - * for more information on how to enable GridGain-based caching in - * a Spring application). - * <p> - * Additionally you will need to set a GridGain cache name where the data for - * all dynamically created caches will be stored. By default its name - * is {@code null}, which refers to default cache. Here is the example - * of how to configure a named cache: - * <pre name="code" class="xml"> - * <beans xmlns="http://www.springframework.org/schema/beans" - * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - * xmlns:cache="http://www.springframework.org/schema/cache" - * xsi:schemaLocation=" - * http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> - * <-- Provide configuration file path --> - * <bean id="cacheManager" class="org.gridgain.grid.cache.spring.GridSpringCacheManager"> - * <property name="dataCacheName" value="myDataCache"/> - * </bean> - * - * ... - * </beans> - * </pre> - * - * @see GridSpringCacheManager - */ -public class GridSpringDynamicCacheManager extends GridSpringCacheManager { - /** Data cache name. */ - private String dataCacheName; - - /** Meta cache. */ - private GridCacheProjectionEx<MetaKey, Cache> metaCache; - - /** Data cache. */ - private GridCache<DataKey, Object> dataCache; - - /** - * Sets data cache name. - * - * @return Data cache name. - */ - public String getDataCacheName() { - return dataCacheName; - } - - /** - * Gets data cache name. - * - * @param dataCacheName Data cache name. - */ - public void setDataCacheName(String dataCacheName) { - this.dataCacheName = dataCacheName; - } - - /** {@inheritDoc} */ - @Override public void afterPropertiesSet() throws Exception { - super.afterPropertiesSet(); - - metaCache = ((GridEx)grid).utilityCache(MetaKey.class, Cache.class); - dataCache = grid.cache(dataCacheName); - } - - /** {@inheritDoc} */ - @Override public Cache getCache(final String name) { - Cache cache = super.getCache(name); - - if (cache != null) - return cache; - - try { - MetaKey key = new MetaKey(name); - - cache = metaCache.get(key); - - if (cache == null) { - cache = new GridSpringCache(name, grid, dataCache.projection(new ProjectionFilter(name)), - new IgniteClosure<Object, Object>() { - @Override public Object apply(Object o) { - return new DataKey(name, o); - } - }); - - Cache old = metaCache.putIfAbsent(key, cache); - - if (old != null) - cache = old; - } - - return cache; - } - catch (IgniteCheckedException e) { - throw new IgniteException(e); - } - } - - /** {@inheritDoc} */ - @Override public Collection<String> getCacheNames() { - Collection<String> names = F.view(super.getCacheNames(), new IgnitePredicate<String>() { - @Override public boolean apply(String name) { - return !F.eq(name, dataCacheName); - } - }); - - return F.concat(false, names, F.transform(metaCache.entrySetx(), - new IgniteClosure<Map.Entry<MetaKey, Cache>, String>() { - @Override public String apply(Map.Entry<MetaKey, Cache> e) { - return e.getKey().name; - } - })); - } - - /** - * Meta key. - */ - private static class MetaKey extends GridCacheUtilityKey<MetaKey> implements Externalizable { - /** Cache name. */ - private String name; - - /** - * For {@link Externalizable}. - */ - public MetaKey() { - // No-op. - } - - /** - * @param name Cache name. - */ - private MetaKey(String name) { - this.name = name; - } - - /** {@inheritDoc} */ - @Override protected boolean equalsx(MetaKey key) { - return name != null ? name.equals(key.name) : key.name == null; - } - - /** {@inheritDoc} */ - @Override public int hashCode() { - return name.hashCode(); - } - - /** {@inheritDoc} */ - @Override public void writeExternal(ObjectOutput out) throws IOException { - U.writeString(out, name); - } - - /** {@inheritDoc} */ - @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - name = U.readString(in); - } - - /** {@inheritDoc} */ - @Override public String toString() { - return S.toString(MetaKey.class, this); - } - } - - /** - * Data key. - */ - private static class DataKey implements Externalizable { - /** Cache name. */ - private String name; - - /** Key. */ - @GridToStringInclude - private Object key; - - /** - * @param name Cache name. - * @param key Key. - */ - private DataKey(String name, Object key) { - this.name = name; - this.key = key; - } - - /** - * For {@link Externalizable}. - */ - public DataKey() { - // No-op. - } - - /** {@inheritDoc} */ - @Override public boolean equals(Object o) { - if (this == o) - return true; - - if (o == null || getClass() != o.getClass()) - return false; - - DataKey key0 = (DataKey)o; - - return name != null ? name.equals(key0.name) : key0.name == null && - key != null ? key.equals(key0.key) : key0.key == null; - } - - /** {@inheritDoc} */ - @Override public int hashCode() { - int res = name != null ? name.hashCode() : 0; - - res = 31 * res + (key != null ? key.hashCode() : 0); - - return res; - } - - /** {@inheritDoc} */ - @Override public void writeExternal(ObjectOutput out) throws IOException { - U.writeString(out, name); - out.writeObject(key); - } - - /** {@inheritDoc} */ - @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - name = U.readString(in); - key = in.readObject(); - } - - /** {@inheritDoc} */ - @Override public String toString() { - return S.toString(DataKey.class, this); - } - } - - /** - * Projection filter. - */ - private static class ProjectionFilter implements IgniteBiPredicate<DataKey, Object>, Externalizable { - /** Cache name. */ - private String name; - - /** - * For {@link Externalizable}. - */ - public ProjectionFilter() { - // No-op. - } - - /** - * @param name Cache name. - */ - private ProjectionFilter(String name) { - this.name = name; - } - - /** {@inheritDoc} */ - @Override public boolean apply(DataKey key, Object val) { - return name != null ? name.equals(key.name) : key.name == null; - } - - /** {@inheritDoc} */ - @Override public void writeExternal(ObjectOutput out) throws IOException { - U.writeString(out, name); - } - - /** {@inheritDoc} */ - @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - name = U.readString(in); - } - - /** {@inheritDoc} */ - @Override public String toString() { - return S.toString(ProjectionFilter.class, this); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/main/java/org/gridgain/grid/cache/spring/package.html ---------------------------------------------------------------------- diff --git a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/package.html b/modules/spring/src/main/java/org/gridgain/grid/cache/spring/package.html deleted file mode 100644 index 20f7a98..0000000 --- a/modules/spring/src/main/java/org/gridgain/grid/cache/spring/package.html +++ /dev/null @@ -1,23 +0,0 @@ -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --> -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -<html> -<body> - <!-- Package description. --> - Contains implementation of Spring cache abstraction and <code>@Cacheable</code> annotation. -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/test/java/org/apache/ignite/internal/GridFactorySelfTest.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/test/java/org/apache/ignite/internal/GridFactorySelfTest.java b/modules/spring/src/test/java/org/apache/ignite/internal/GridFactorySelfTest.java new file mode 100644 index 0000000..988e1c3 --- /dev/null +++ b/modules/spring/src/test/java/org/apache/ignite/internal/GridFactorySelfTest.java @@ -0,0 +1,790 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.internal; + +import org.apache.ignite.*; +import org.apache.ignite.compute.*; +import org.apache.ignite.configuration.*; +import org.apache.ignite.events.*; +import org.apache.ignite.lifecycle.*; +import org.apache.ignite.resources.*; +import org.apache.ignite.spi.*; +import org.apache.ignite.spi.collision.*; +import org.apache.ignite.spi.discovery.tcp.*; +import org.apache.ignite.internal.util.lang.*; +import org.apache.ignite.internal.util.typedef.*; +import org.apache.ignite.internal.util.typedef.internal.*; +import org.apache.ignite.testframework.*; +import org.apache.ignite.testframework.config.*; +import org.apache.ignite.testframework.http.*; +import org.apache.ignite.testframework.junits.common.*; +import org.jetbrains.annotations.*; +import org.springframework.beans.*; +import org.springframework.beans.factory.config.*; +import org.springframework.beans.factory.support.*; +import org.springframework.beans.factory.xml.*; +import org.springframework.context.*; +import org.springframework.context.support.*; +import org.springframework.core.io.*; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + +import static org.apache.ignite.IgniteState.*; +import static org.apache.ignite.IgniteSystemProperties.*; + +/** + * Tests for {@link org.apache.ignite.Ignition}. + * @see org.gridgain.grid.kernal.GridFactoryVmShutdownTest + */ +@SuppressWarnings("UnusedDeclaration") +@GridCommonTest(group = "NonDistributed Kernal Self") +public class GridFactorySelfTest extends GridCommonAbstractTest { + /** */ + private static final AtomicInteger cnt = new AtomicInteger(); + + /** */ + private static final String CUSTOM_CFG_PATH = "modules/core/src/test/config/factory/custom-grid-name-spring-test.xml"; + + /** + * + */ + public GridFactorySelfTest() { + super(false); + + System.setProperty(GG_OVERRIDE_MCAST_GRP, + GridTestUtils.getNextMulticastGroup(GridFactorySelfTest.class)); + } + + /** {@inheritDoc} */ + @Override protected void beforeTest() throws Exception { + cnt.set(0); + } + + /** + * @throws Exception If failed. + */ + public void testStartGridWithConfigUrlString() throws Exception { + GridEmbeddedHttpServer srv = null; + String gridName = "grid_with_url_config"; + + try { + srv = GridEmbeddedHttpServer.startHttpServer().withFileDownloadingHandler(null, + GridTestUtils.resolveGridGainPath("/modules/core/src/test/config/default-spring-url-testing.xml")); + + Ignite ignite = G.start(srv.getBaseUrl()); + + assert gridName.equals(ignite.name()) : "Unexpected grid name: " + ignite.name(); + } + finally { + if (srv != null) + srv.stop(1); + + G.stop(gridName, false); + } + } + + /** + * @throws Exception If failed. + */ + public void testStartGridWithConfigUrl() throws Exception { + GridEmbeddedHttpServer srv = null; + String gridName = "grid_with_url_config"; + + try { + srv = GridEmbeddedHttpServer.startHttpServer().withFileDownloadingHandler(null, + GridTestUtils.resolveGridGainPath("modules/core/src/test/config/default-spring-url-testing.xml")); + + Ignite ignite = G.start(new URL(srv.getBaseUrl())); + + assert gridName.equals(ignite.name()) : "Unexpected grid name: " + ignite.name(); + } + finally { + if (srv != null) + srv.stop(1); + + G.stop(gridName, false); + } + } + + /** + * @throws Exception If failed. + */ + public void testLifecycleBeansNullGridName() throws Exception { + checkLifecycleBeans(null); + } + + /** + * @throws Exception If failed. + */ + public void testLifecycleBeansNotNullGridName() throws Exception { + checkLifecycleBeans("testGrid"); + } + + /** + * @param gridName Grid name. + * @throws Exception If test failed. + */ + private void checkLifecycleBeans(@Nullable String gridName) throws Exception { + TestLifecycleBean bean1 = new TestLifecycleBean(); + TestLifecycleBean bean2 = new TestLifecycleBean(); + + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setLifecycleBeans(bean1, bean2); + cfg.setGridName(gridName); + + cfg.setRestEnabled(false); + + try (Ignite g = GridGainSpring.start(cfg, new GenericApplicationContext())) { + bean1.checkState(gridName, true); + bean2.checkState(gridName, true); + } + + bean1.checkState(gridName, false); + bean2.checkState(gridName, false); + + checkLifecycleBean(bean1, gridName); + checkLifecycleBean(bean2, gridName); + } + + /** + * @param bean Bean to check. + * @param gridName Grid name to check for. + */ + private void checkLifecycleBean(TestLifecycleBean bean, String gridName) { + bean.checkErrors(); + + List<LifecycleEventType> evts = bean.getLifecycleEvents(); + + List<String> gridNames = bean.getGridNames(); + + assert evts.get(0) == LifecycleEventType.BEFORE_GRID_START : "Invalid lifecycle event: " + evts.get(0); + assert evts.get(1) == LifecycleEventType.AFTER_GRID_START : "Invalid lifecycle event: " + evts.get(1); + assert evts.get(2) == LifecycleEventType.BEFORE_GRID_STOP : "Invalid lifecycle event: " + evts.get(2); + assert evts.get(3) == LifecycleEventType.AFTER_GRID_STOP : "Invalid lifecycle event: " + evts.get(3); + + checkGridNameEquals(gridNames.get(0), gridName); + checkGridNameEquals(gridNames.get(1), gridName); + checkGridNameEquals(gridNames.get(2), gridName); + checkGridNameEquals(gridNames.get(3), gridName); + } + + /** + * @param n1 First name. + * @param n2 Second name. + */ + private void checkGridNameEquals(String n1, String n2) { + if (n1 == null) { + assert n2 == null; + + return; + } + + assert n1.equals(n2) : "Invalid grid names [name1=" + n1 + ", name2=" + n2 + ']'; + } + + /** + * @throws Exception If failed. + */ + @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) + public void testStartMultipleGridsFromSpring() throws Exception { + File cfgFile = + GridTestUtils.resolveGridGainPath(GridTestProperties.getProperty("loader.self.multipletest.config")); + + assert cfgFile != null; + + String path = cfgFile.getAbsolutePath(); + + info("Loading Grid from configuration file: " + path); + + final GridTuple<IgniteState> gridState1 = F.t(null); + final GridTuple<IgniteState> gridState2 = F.t(null); + + final Object mux = new Object(); + + IgniteListener factoryLsnr = new IgniteListener() { + @Override public void onStateChange(String name, IgniteState state) { + synchronized (mux) { + if ("grid-factory-test-1".equals(name)) + gridState1.set(state); + else if ("grid-factory-test-2".equals(name)) + gridState2.set(state); + } + } + }; + + G.addListener(factoryLsnr); + + G.start(path); + + assert G.ignite("grid-factory-test-1") != null; + assert G.ignite("grid-factory-test-2") != null; + + synchronized (mux) { + assert gridState1.get() == STARTED : + "Invalid grid state [expected=" + STARTED + ", returned=" + gridState1 + ']'; + assert gridState2.get() == STARTED : + "Invalid grid state [expected=" + STARTED + ", returned=" + gridState2 + ']'; + } + + G.stop("grid-factory-test-1", true); + G.stop("grid-factory-test-2", true); + + synchronized (mux) { + assert gridState1.get() == STOPPED : + "Invalid grid state [expected=" + STOPPED + ", returned=" + gridState1 + ']'; + assert gridState2.get() == STOPPED : + "Invalid grid state [expected=" + STOPPED + ", returned=" + gridState2 + ']'; + } + } + + /** + * @throws Exception If failed. + */ + public void testStartMultipleDefaultGrids() throws Exception { + try { + multithreaded( + new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + try { + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setRestEnabled(false); + + G.start(cfg); + } + catch (Throwable t) { + error("Caught exception while starting grid.", t); + } + + info("Thread finished."); + + return null; + } + }, + 5, + "grid-starter" + ); + + assert G.allGrids().size() == 1; + + assert G.ignite() != null; + } + finally { + G.stopAll(true); + } + } + + /** + * @throws Exception If failed. + */ + public void testStartMultipleNonDefaultGrids() throws Exception { + try { + multithreaded( + new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + try { + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setGridName("TEST_NAME"); + cfg.setRestEnabled(false); + + G.start(cfg); + } + catch (Throwable t) { + error("Caught exception while starting grid.", t); + } + + info("Thread finished."); + + return null; + } + }, + 5, + "grid-starter" + ); + + assert G.allGrids().size() == 1; + + assert G.ignite("TEST_NAME") != null; + } + finally { + G.stopAll(true); + } + } + + /** + * @throws Exception If failed. + */ + public void testConcurrentStartStop() throws Exception { + checkConcurrentStartStop("TEST_NAME"); + } + + /** + * @throws Exception If failed. + */ + public void testConcurrentStartStopDefaultGrid() throws Exception { + checkConcurrentStartStop(null); + } + + /** + * @param gridName Grid name ({@code null} for default grid). + * @throws Exception If failed. + */ + private void checkConcurrentStartStop(@Nullable final String gridName) throws Exception { + final AtomicInteger startedCnt = new AtomicInteger(); + final AtomicInteger stoppedCnt = new AtomicInteger(); + + IgniteListener lsnr = new IgniteListener() { + @SuppressWarnings("StringEquality") + @Override public void onStateChange(@Nullable String name, IgniteState state) { + assert name == gridName; + + info("On state change fired: " + state); + + if (state == STARTED) + startedCnt.incrementAndGet(); + else { + assert state == STOPPED : "Unexpected state: " + state; + + stoppedCnt.incrementAndGet(); + } + } + }; + + G.addListener(lsnr); + + try { + final int iterCnt = 3; + + multithreaded( + new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + for (int i = 0; i < iterCnt; i++) { + try { + IgniteConfiguration cfg = getConfiguration(gridName); + + G.start(cfg); + } + catch (Exception e) { + String msg = e.getMessage(); + + if (msg != null && + (msg.contains("Default grid instance has already been started.") || + msg.contains("Grid instance with this name has already been started:"))) + info("Caught expected exception: " + msg); + else + throw e; // Unexpected exception. + } + finally { + stopGrid(gridName); + } + } + + info("Thread finished."); + + return null; + } + }, + 5, + "tester" + ); + + assert G.allGrids().isEmpty(); + + assert startedCnt.get() == iterCnt; + assert stoppedCnt.get() == iterCnt; + } + finally { + G.removeListener(lsnr); + + G.stopAll(true); + } + } + + /** + * @throws Exception If failed. + */ + public void testGridStartRollback() throws Exception { + GridTestUtils.assertThrows( + log, + new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setRestEnabled(false); + + cfg.setDiscoverySpi(new TcpDiscoverySpi() { + @Override public void spiStart(String gridName) throws IgniteSpiException { + throw new IgniteSpiException("This SPI will never start."); + } + }); + + G.start(cfg); + + info("Thread finished."); + + return null; + } + }, + IgniteCheckedException.class, + null + ); + } + + /** + * @throws Exception If failed. + */ + public void disabledTestStartSingleInstanceSpi() throws Exception { + IgniteConfiguration cfg1 = getConfiguration(); + IgniteConfiguration cfg2 = getConfiguration(); + + cfg1.setCollisionSpi(new TestSingleInstancesCollisionSpi()); + cfg2.setCollisionSpi(new TestSingleInstancesCollisionSpi()); + + G.start(cfg1); + + assert G.state(cfg1.getGridName()) == STARTED; + assert G.state(getTestGridName() + '1') == STOPPED; + + G.stop(cfg1.getGridName(), false); + + assert G.state(cfg1.getGridName()) == STOPPED; + assert G.state(getTestGridName() + '1') == STOPPED; + + cfg2.setGridName(getTestGridName() + '1'); + + G.start(cfg2); + + assert G.state(cfg1.getGridName()) == STOPPED; + assert G.state(getTestGridName() + '1') == STARTED; + + G.stop(getTestGridName() + '1', false); + + assert G.state(cfg1.getGridName()) == STOPPED; + assert G.state(getTestGridName() + '1') == STOPPED; + + cfg2.setGridName(getTestGridName() + '1'); + + G.start(cfg2); + + assert G.state(getTestGridName() + '1') == STARTED; + assert G.state(getTestGridName()) == STOPPED; + + G.stop(getTestGridName() + '1', false); + G.stop(getTestGridName(), false); + + assert G.state(getTestGridName() + '1') == STOPPED; + assert G.state(getTestGridName()) == STOPPED; + } + + /** + * @throws Exception If failed. + */ + public void testStartMultipleInstanceSpi() throws Exception { + IgniteConfiguration cfg1 = getConfiguration(); + IgniteConfiguration cfg2 = getConfiguration(); + IgniteConfiguration cfg3 = getConfiguration(); + + cfg1.setCollisionSpi(new TestMultipleInstancesCollisionSpi()); + cfg2.setCollisionSpi(new TestMultipleInstancesCollisionSpi()); + cfg3.setCollisionSpi(new TestMultipleInstancesCollisionSpi()); + + cfg2.setGridName(getTestGridName() + '1'); + + G.start(cfg2); + + G.start(cfg1); + + cfg3.setGridName(getTestGridName() + '2'); + + G.start(cfg3); + + assert G.state(cfg1.getGridName()) == STARTED; + assert G.state(getTestGridName() + '1') == STARTED; + assert G.state(getTestGridName() + '2') == STARTED; + + G.stop(getTestGridName() + '2', false); + G.stop(cfg1.getGridName(), false); + G.stop(getTestGridName() + '1', false); + + assert G.state(cfg1.getGridName()) == STOPPED; + assert G.state(getTestGridName() + '1') == STOPPED; + assert G.state(getTestGridName() + '2') == STOPPED; + } + + /** + * @throws Exception If failed. + */ + @Override protected void afterTest() throws Exception { + G.stopAll(false); + } + + /** */ + @IgniteSpiMultipleInstancesSupport(true) + private static class TestMultipleInstancesCollisionSpi extends IgniteSpiAdapter implements CollisionSpi { + /** Grid logger. */ + @IgniteLoggerResource + private IgniteLogger log; + + /** {@inheritDoc} */ + @Override public void onCollision(CollisionContext ctx) { + // No-op. + } + + /** {@inheritDoc} */ + @Override public void spiStart(String gridName) throws IgniteSpiException { + // Start SPI start stopwatch. + startStopwatch(); + + // Ack start. + if (log.isInfoEnabled()) + log.info(startInfo()); + } + + /** {@inheritDoc} */ + @Override public void spiStop() throws IgniteSpiException { + // Ack stop. + if (log.isInfoEnabled()) + log.info(stopInfo()); + } + + /** {@inheritDoc} */ + @Override public void setExternalCollisionListener(CollisionExternalListener lsnr) { + // No-op. + } + } + + /** + * DO NOT CHANGE MULTIPLE INSTANCES SUPPORT. + * This test might be working on distributed environment. + */ + @IgniteSpiMultipleInstancesSupport(true) + private static class TestSingleInstancesCollisionSpi extends IgniteSpiAdapter implements CollisionSpi { + /** Grid logger. */ + @IgniteLoggerResource + private IgniteLogger log; + + /** {@inheritDoc} */ + @Override public void onCollision(CollisionContext ctx) { + // No-op. + } + + /** {@inheritDoc} */ + @Override public void spiStart(String gridName) throws IgniteSpiException { + // Start SPI start stopwatch. + startStopwatch(); + + // Ack start. + if (log.isInfoEnabled()) + log.info(startInfo()); + } + + /** {@inheritDoc} */ + @Override public void spiStop() throws IgniteSpiException { + // Ack stop. + if (log.isInfoEnabled()) + log.info(stopInfo()); + } + + /** {@inheritDoc} */ + @Override public void setExternalCollisionListener(CollisionExternalListener lsnr) { + // No-op. + } + } + + /** + * Lifecycle bean for testing. + */ + private static class TestLifecycleBean implements LifecycleBean { + /** Grid logger. */ + @IgniteLoggerResource + private IgniteLogger log; + + /** */ + @IgniteSpringApplicationContextResource + private ApplicationContext appCtx; + + /** */ + @IgniteInstanceResource + private Ignite ignite; + + /** Lifecycle events. */ + private final List<LifecycleEventType> evts = new ArrayList<>(); + + /** Grid names. */ + private final List<String> gridNames = new ArrayList<>(); + + /** */ + private final AtomicReference<Throwable> err = new AtomicReference<>(); + + /** {@inheritDoc} */ + @Override public void onLifecycleEvent(LifecycleEventType evt) { + evts.add(evt); + + gridNames.add(ignite.name()); + + try { + checkState(ignite.name(), + evt == LifecycleEventType.AFTER_GRID_START || evt == LifecycleEventType.BEFORE_GRID_STOP); + } + catch (Throwable e) { + log.error("Lifecycle bean failed state check: " + this, e); + + err.compareAndSet(null, e); + } + } + + /** + * Checks state of the bean. + * + * @param gridName Grid name. + * @param exec Try to execute something on the grid. + */ + void checkState(String gridName, boolean exec) { + assert log != null; + assert appCtx != null; + + assert F.eq(gridName, ignite.name()); + + if (exec) + // Execute any grid method. + G.ignite(gridName).events().localQuery(F.<IgniteEvent>alwaysTrue()); + } + + /** + * Gets ordered list of lifecycle events. + * + * @return Ordered list of lifecycle events. + */ + List<LifecycleEventType> getLifecycleEvents() { + return evts; + } + + /** + * Gets ordered list of grid names. + * + * @return Ordered list of grid names. + */ + List<String> getGridNames() { + return gridNames; + } + + /** + * + */ + void checkErrors() { + if (err.get() != null) + fail("Exception has been caught by listener: " + err.get().getMessage()); + } + } + + /** + * Gets Spring application context by given path. + * + * @param path Spring application context configuration path. + * @return Spring application context. + * @throws IgniteCheckedException If given path or xml-configuration at this path is invalid. + */ + private GenericApplicationContext getSpringContext(String path) throws IgniteCheckedException { + try { + GenericApplicationContext ctx = new GenericApplicationContext(); + + new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(new UrlResource(U.resolveGridGainUrl(path))); + + ctx.refresh(); + + return ctx; + } + catch (BeansException e) { + throw new IgniteCheckedException("Failed to instantiate Spring XML application context: " + e.getMessage(), e); + } + } + + /** + * Gets test Spring application context with single {@link StringBuilder} bean + * with name "myBean" and value "Test string". + * + * @return Spring application context. + */ + private ApplicationContext getTestApplicationContext() { + AbstractBeanDefinition def = new GenericBeanDefinition(); + + def.setBeanClass(StringBuilder.class); + + ConstructorArgumentValues args = new ConstructorArgumentValues(); + args.addGenericArgumentValue("Test string"); + + def.setConstructorArgumentValues(args); + + GenericApplicationContext ctx = new GenericApplicationContext(); + + ctx.registerBeanDefinition("myBean", def); + + return ctx; + } + + /** + * @throws Exception If failed. + */ + public void testStopCancel() throws Exception { + IgniteConfiguration cfg = new IgniteConfiguration(); + + cfg.setRestEnabled(false); + + Ignite ignite = G.start(cfg); + + ignite.compute().execute(TestTask.class, null); + + G.stop(true); + } + + /** + * Test task. + */ + private static class TestTask extends ComputeTaskSplitAdapter<Void, Void> { + /** {@inheritDoc} */ + @Override protected Collection<? extends ComputeJob> split(int gridSize, Void arg) throws IgniteCheckedException { + return F.asSet(new TestJob()); + } + + /** {@inheritDoc} */ + @Nullable @Override public Void reduce(List<ComputeJobResult> results) throws IgniteCheckedException { + return null; + } + } + + /** + * Test job. + */ + private static class TestJob extends ComputeJobAdapter { + /** {@inheritDoc} */ + @SuppressWarnings("StatementWithEmptyBody") + @Override public Object execute() throws IgniteCheckedException { + long start = System.currentTimeMillis(); + + while (System.currentTimeMillis() - start < 3000); + + return null; + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/d0e6cace/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java b/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java new file mode 100644 index 0000000..6010bb1 --- /dev/null +++ b/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.internal; + +import org.apache.ignite.*; +import org.apache.ignite.configuration.*; +import org.apache.ignite.marshaller.*; +import org.apache.ignite.marshaller.optimized.*; +import org.apache.ignite.spi.discovery.tcp.*; +import org.apache.ignite.spi.discovery.tcp.ipfinder.*; +import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; +import org.apache.ignite.internal.util.typedef.*; +import org.apache.ignite.testframework.junits.common.*; + +/** + * Test for {@link GridSpringBean} serialization. + */ +public class GridSpringBeanSerializationSelfTest extends GridCommonAbstractTest { + /** IP finder. */ + private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); + + /** Marshaller. */ + private static final IgniteMarshaller MARSHALLER = new IgniteOptimizedMarshaller(); + + /** Attribute key. */ + private static final String ATTR_KEY = "checkAttr"; + + /** Bean. */ + private GridSpringBean bean; + + /** {@inheritDoc} */ + @Override protected void beforeTestsStarted() throws Exception { + bean = new GridSpringBean(); + + bean.setConfiguration(config()); + + bean.afterPropertiesSet(); + } + + /** + * @return Grid configuration. + */ + private IgniteConfiguration config() { + IgniteConfiguration cfg = new IgniteConfiguration(); + + TcpDiscoverySpi disco = new TcpDiscoverySpi(); + + disco.setIpFinder(IP_FINDER); + + cfg.setDiscoverySpi(disco); + + cfg.setUserAttributes(F.asMap(ATTR_KEY, true)); + + cfg.setRestEnabled(false); + + return cfg; + } + + /** {@inheritDoc} */ + @Override protected void afterTestsStopped() throws Exception { + bean.destroy(); + } + + /** + * @throws Exception If failed. + */ + public void testSerialization() throws Exception { + assert bean != null; + + GridSpringBean bean0 = MARSHALLER.unmarshal(MARSHALLER.marshal(bean), null); + + assert bean0 != null; + assert bean0.log() != null; + assert bean0.cluster().localNode() != null; + assert bean0.cluster().localNode().<Boolean>attribute(ATTR_KEY); + } +}