diff --git a/exo.kernel.component.cache/pom.xml b/exo.kernel.component.cache/pom.xml index d2282d87f..8fd7653e8 100644 --- a/exo.kernel.component.cache/pom.xml +++ b/exo.kernel.component.cache/pom.xml @@ -60,24 +60,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true - - - - jgroups.bind_addr - 127.0.0.1 - - - jgroups.stack - udp - - - - maven-antrun-plugin diff --git a/exo.kernel.component.cache/src/main/java/org/exoplatform/services/cache/concurrent/SimpleReplicatedExoCache.java b/exo.kernel.component.cache/src/main/java/org/exoplatform/services/cache/concurrent/SimpleReplicatedExoCache.java deleted file mode 100644 index f4f2cde66..000000000 --- a/exo.kernel.component.cache/src/main/java/org/exoplatform/services/cache/concurrent/SimpleReplicatedExoCache.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (C) 2014 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.concurrent; - -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.rpc.RPCService; -import org.exoplatform.services.rpc.RemoteCommand; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -/** - *

This implementation of {@link ExoCache} will behave exactly the same way as {@link ConcurrentFIFOExoCache} - * except in case of a cache change, indeed the modifications will be first applied locally - * then it will be replicated over the cluster asynchronously to limit the performance impact - * on the local cluster node.

- *

This class can be used as a drop-in replacement for {@link ConcurrentFIFOExoCache} in a cluster environment - * as long as we know that modifications like remove, clearCache, removeCachedObjects, put or putMap happen rarely. - * In other words, it should be used for caches that rarely change.

- * - * This limitation is due to the fact that the mechanism used for the replication - * has not been designed to support heavy load so it must be used with a lot of caution. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class SimpleReplicatedExoCache extends ConcurrentFIFOExoCache -{ - /** - * Logger. - */ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.cache.SimpleReplicatedExoCache"); - - /** - * Component used to execute commands over the cluster. - */ - private final RPCService rpcService; - - /** - * The generic command used to replicate changes over the cluster - */ - private RemoteCommand command; - - /** - * Id used to avoid launching twice the same command on the same node - */ - private final String id; - - /** - * The name of the current context - */ - private final String ctxName; - - public SimpleReplicatedExoCache() - { - ExoContainer container = ExoContainerContext.getCurrentContainer(); - this.rpcService = container.getComponentInstanceOfType(RPCService.class); - if (rpcService == null) - throw new IllegalArgumentException("The RPCService is required for this type of cache, please configure it first"); - this.ctxName = container.getContext().getName(); - this.id = UUID.randomUUID().toString(); - } - - SimpleReplicatedExoCache(ExoContainerContext ctx, RPCService rpcService) - { - if (rpcService == null) - throw new IllegalArgumentException("The RPCService is required for this type of cache, please configure it first"); - this.rpcService = rpcService; - this.ctxName = ctx.getName(); - this.id = UUID.randomUUID().toString(); - } - - @Override - public void setName(String s) - { - super.setName(s); - if (command == null) - { - command = rpcService.registerCommand(new RemoteCommand() - { - private final String commandId = SimpleReplicatedExoCache.class.getName() + "-" + getName() + "-" - + ctxName; - - public String getId() - { - return commandId; - } - - @SuppressWarnings("unchecked") - public Serializable execute(Serializable[] args) throws Throwable - { - if (!id.equals(args[0])) - { - if ("c".equals(args[1])) - { - try - { - clearCacheOnly(); - } - catch (Exception e) - { - LOG.warn("Could not clear the cache on other cluster nodes", e); - } - } - else if ("r".equals(args[1])) - { - try - { - removeOnly((Serializable)args[2]); - } - catch (Exception e) - { - LOG.warn("Could not remove the entry " + args[2] + " on other cluster nodes", e); - } - } - else if ("p".equals(args[1])) - { - try - { - putIfNeeded((K)args[2], (V)args[3]); - } - catch (Exception e) - { - LOG.warn("Could not put the entry " + args[2] + " on other cluster nodes", e); - } - } - else if ("m".equals(args[1])) - { - try - { - Map objs = (Map)args[2]; - for (Entry entry : objs.entrySet()) - { - putIfNeeded(entry.getKey(), entry.getValue()); - } - } - catch (Exception e) - { - LOG.warn("Could not put entries on other cluster nodes", e); - } - } - } - return true; - } - }); - } - } - - /** - * Removes the entry without replication - * @param name the key of the entry to remove - */ - void removeOnly(Serializable name) - { - super.remove(name); - } - - /** - * Clears the cache without replication - */ - void clearCacheOnly() - { - super.clearCache(); - } - - /** - * Puts the entry without replication only if the current cache - * doesn't have already the exact same entry with the same key and value - * @param name the key of the entry to put - * @param obj the value of the entry to put - */ - void putIfNeeded(K name, V obj) - { - V currrentValue = get(name); - if (currrentValue == null || !currrentValue.equals(obj)) - super.put(name, obj); - } - - @Override - public V remove(Serializable name) - { - V v = super.remove(name); - if (v != null) - { - try - { - rpcService.executeCommandOnAllNodes(command, false, id, "r", name); - } - catch (Exception e) - { - LOG.warn("Could not remove the entry " + name + " on other cluster nodes", e); - } - } - return v; - } - - @Override - public void clearCache() - { - super.clearCache(); - try - { - rpcService.executeCommandOnAllNodes(command, false, id, "c"); - } - catch (Exception e) - { - LOG.warn("Could not clear the cache on other cluster nodes", e); - } - } - - @Override - public void put(K name, V obj) - { - super.put(name, obj); - try - { - rpcService.executeCommandOnAllNodes(command, false, id, "p", name, obj); - } - catch (Exception e) - { - LOG.warn("Could not put the entry " + name + " on other cluster nodes", e); - } - } - - - @Override - public void putMap(Map objs) - { - super.putMap(objs); - try - { - rpcService.executeCommandOnAllNodes(command, false, id, "m", new HashMap(objs)); - } - catch (Exception e) - { - LOG.warn("Could not put entries on other cluster nodes", e); - } - } - - @Override - protected void finalize() throws Throwable - { - try - { - if (command != null) - { - rpcService.unregisterCommand(command); - } - } - finally - { - super.finalize(); - } - } -} diff --git a/exo.kernel.component.cache/src/test/java/org/exoplatform/services/cache/concurrent/TestSimpleReplicatedExoCache.java b/exo.kernel.component.cache/src/test/java/org/exoplatform/services/cache/concurrent/TestSimpleReplicatedExoCache.java deleted file mode 100644 index 6bcee8cf9..000000000 --- a/exo.kernel.component.cache/src/test/java/org/exoplatform/services/cache/concurrent/TestSimpleReplicatedExoCache.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (C) 2014 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.concurrent; - -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.rpc.jgv3.RPCServiceImpl; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.Collections; - -/** - * This is the unit test for the class {@link SimpleReplicatedExoCache} - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestSimpleReplicatedExoCache -{ - private PortalContainer container; - private RPCServiceImpl service1, service2; - - private SimpleReplicatedExoCache cache1, cache2; - - @Before - public void init() throws Exception - { - container = PortalContainer.getInstance(); - ConfigurationManager configManager = container.getComponentInstanceOfType(ConfigurationManager.class); - - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName("jgroups-configuration"); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - service1 = new RPCServiceImpl(container.getContext(), params, configManager); - service2 = new RPCServiceImpl(container.getContext(), params, configManager); - cache1 = new SimpleReplicatedExoCache(container.getContext(), service1); - cache2 = new SimpleReplicatedExoCache(container.getContext(), service2); - cache1.setName("TestSimpleReplicatedExoCache"); - cache2.setName("TestSimpleReplicatedExoCache"); - service1.start(); - service2.start(); - } - - @After - public void destroy() throws Exception - { - service1.stop(); - service2.stop(); - } - - @Test - public void testPut() throws Exception - { - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertEquals(0, cache2.getCacheSize()); - cache1.put("a", "value"); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals("value", cache2.get("a")); - // Make sure that if the value is the same we don't replace it on other nodes - String value1 = new String("value"); - Object value2 = cache2.get("a"); - cache1.put("a", value1); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertTrue(value1 == cache1.get("a")); - for (int i = 0; i < 5; i++) - { - Assert.assertEquals("value", cache2.get("a")); - Assert.assertTrue(value2 == cache2.get("a")); - Thread.sleep(200); - } - Assert.assertEquals("value", cache2.get("a")); - Assert.assertTrue(value2 == cache2.get("a")); - // Make sure that if the value has changed we replace it on other nodes - cache1.put("a", "value2"); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value2", cache1.get("a")); - for (int i = 0; i < 5; i++) - { - if (cache2.get("a").equals("value2")) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals("value2", cache2.get("a")); - } - - @Test - public void testPutMap() throws Exception - { - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertEquals(0, cache2.getCacheSize()); - cache1.putMap(Collections.singletonMap("a", "value")); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals("value", cache2.get("a")); - // Make sure that if the value is the same we don't replace it on other nodes - String value1 = new String("value"); - Object value2 = cache2.get("a"); - cache1.putMap(Collections.singletonMap("a", value1)); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertTrue(value1 == cache1.get("a")); - for (int i = 0; i < 5; i++) - { - Assert.assertEquals("value", cache2.get("a")); - Assert.assertTrue(value2 == cache2.get("a")); - Thread.sleep(200); - } - Assert.assertEquals("value", cache2.get("a")); - Assert.assertTrue(value2 == cache2.get("a")); - // Make sure that if the value has changed we replace it on other nodes - cache1.putMap(Collections.singletonMap("a", "value2")); - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals("value2", cache1.get("a")); - for (int i = 0; i < 5; i++) - { - if (cache2.get("a").equals("value2")) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals("value2", cache2.get("a")); - } - - @Test - public void testRemove() throws Exception - { - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertEquals(0, cache2.getCacheSize()); - cache1.put("a", "value"); - Assert.assertEquals(1, cache1.getCacheSize()); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals("value", cache1.remove("a")); - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertNull(cache1.get("a")); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() == 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(0, cache2.getCacheSize()); - Assert.assertNull(cache2.get("a")); - Assert.assertNull(cache1.remove("a")); - } - - @Test - public void testClearCache() throws Exception - { - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertEquals(0, cache2.getCacheSize()); - cache1.put("a", "value"); - cache1.put("b", "value"); - cache1.put("c", "value"); - Assert.assertEquals(3, cache1.getCacheSize()); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() == 3) - break; - Thread.sleep(200); - } - Assert.assertEquals(3, cache2.getCacheSize()); - cache1.clearCache(); - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertNull(cache1.get("a")); - Assert.assertNull(cache1.get("b")); - Assert.assertNull(cache1.get("c")); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() == 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(0, cache2.getCacheSize()); - Assert.assertNull(cache2.get("a")); - Assert.assertNull(cache2.get("b")); - Assert.assertNull(cache2.get("c")); - } - - @Test - public void testIsolation() throws Exception - { - SimpleReplicatedExoCache cache3 = new SimpleReplicatedExoCache(container.getContext(), service1); - SimpleReplicatedExoCache cache4 = new SimpleReplicatedExoCache(container.getContext(), service2); - cache3.setName("TestSimpleReplicatedExoCache.testIsolation"); - cache4.setName("TestSimpleReplicatedExoCache.testIsolation"); - Assert.assertEquals(0, cache1.getCacheSize()); - Assert.assertEquals(0, cache2.getCacheSize()); - Assert.assertEquals(0, cache3.getCacheSize()); - Assert.assertEquals(0, cache4.getCacheSize()); - cache1.put("a", "value"); - Assert.assertEquals(1, cache1.getCacheSize()); - for (int i = 0; i < 5; i++) - { - if (cache2.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals(0, cache3.getCacheSize()); - Assert.assertEquals(0, cache4.getCacheSize()); - cache4.put("a", "value2"); - Assert.assertEquals(1, cache1.getCacheSize()); - for (int i = 0; i < 5; i++) - { - if (cache3.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals(1, cache3.getCacheSize()); - Assert.assertEquals(1, cache4.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertEquals("value", cache2.get("a")); - Assert.assertEquals("value2", cache3.get("a")); - Assert.assertEquals("value2", cache4.get("a")); - Assert.assertEquals("value2", cache4.remove("a")); - for (int i = 0; i < 5; i++) - { - if (cache3.getCacheSize() == 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals(0, cache3.getCacheSize()); - Assert.assertEquals(0, cache4.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertEquals("value", cache2.get("a")); - Assert.assertNull(cache3.get("a")); - Assert.assertNull(cache4.get("a")); - cache4.putMap(Collections.singletonMap("a", "value2")); - for (int i = 0; i < 5; i++) - { - if (cache3.getCacheSize() > 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals(1, cache3.getCacheSize()); - Assert.assertEquals(1, cache4.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertEquals("value", cache2.get("a")); - Assert.assertEquals("value2", cache3.get("a")); - Assert.assertEquals("value2", cache4.get("a")); - cache4.clearCache(); - for (int i = 0; i < 5; i++) - { - if (cache3.getCacheSize() == 0) - break; - Thread.sleep(200); - } - Assert.assertEquals(1, cache1.getCacheSize()); - Assert.assertEquals(1, cache2.getCacheSize()); - Assert.assertEquals(0, cache3.getCacheSize()); - Assert.assertEquals(0, cache4.getCacheSize()); - Assert.assertEquals("value", cache1.get("a")); - Assert.assertEquals("value", cache2.get("a")); - Assert.assertNull(cache3.get("a")); - Assert.assertNull(cache4.get("a")); - } -} diff --git a/exo.kernel.component.cache/src/test/resources/conf/portal/udp.xml b/exo.kernel.component.cache/src/test/resources/conf/portal/udp.xml deleted file mode 100644 index 6eccfebf1..000000000 --- a/exo.kernel.component.cache/src/test/resources/conf/portal/udp.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.command/pom.xml b/exo.kernel.component.command/pom.xml deleted file mode 100644 index c35b44394..000000000 --- a/exo.kernel.component.command/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - 4.0.0 - - - io.meeds.kernel - kernel-parent - 7.0.x-SNAPSHOT - - - exo.kernel.component.command - - Meeds:: PLF:: Kernel :: Component :: Command Service - Implementation of Command Service of Exoplatform SAS 'eXo Kernel' project. - - - 0.35 - - - - - io.meeds.kernel - exo.kernel.container - - - io.meeds.kernel - exo.kernel.commons.test - test - - - io.github.weblegacy - commons-chain-web-jakarta-servlet - - - xml-apis - xml-apis - - - - - commons-digester - commons-digester - - - commons-logging - commons-logging - - - - - - - - maven-antrun-plugin - - - prepare-test-policy - process-test-resources - - - Creating Access Policy for tests - - - - - - - - - - - - - - - - - run - - - - - - - diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Action.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Action.java deleted file mode 100644 index 3adafff3a..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Action.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.action; - -import org.apache.commons.chain.Command; - -/** - * Created by The eXo Platform SAS
- * - * Action interface extends Command interface. - * - * @author Gennady Azarenkov - * @LevelAPI Platform - */ - -public interface Action extends Command -{ - -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionCatalog.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionCatalog.java deleted file mode 100644 index 720d7aa1d..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionCatalog.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.action; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ - -public class ActionCatalog -{ - - private Map commands; - - public ActionCatalog() - { - this.commands = new HashMap(); - } - - public Set getAllActions() - { - return new HashSet(commands.values()); - } - - public Map getAllEntries() - { - return commands; - } - - public Set getActions(Condition conditions) - { - HashSet actions = new HashSet(); - for (Map.Entry entry : commands.entrySet()) - { - if (entry.getKey().match(conditions)) - actions.add(entry.getValue()); - } - return actions; - } - - public Action getAction(Condition conditions, int index) - { - Iterator actions = getActions(conditions).iterator(); - for (int i = 0; actions.hasNext(); i++) - { - Action c = actions.next(); - if (i == index) - return c; - } - return null; - } - - public void addAction(ActionMatcher matcher, Action action) - { - commands.put(matcher, action); - } - - public void clear() - { - commands.clear(); - } -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionMatcher.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionMatcher.java deleted file mode 100644 index 064c9b4e8..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionMatcher.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.action; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ - -public interface ActionMatcher -{ - boolean match(Condition conditions); -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionService.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionService.java deleted file mode 100644 index 3e6ecf0fd..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/ActionService.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.action; - -import java.util.HashMap; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ - -public class ActionService extends HashMap -{ - - // public void addPlugin(ComponentPlugin plugin) { - // if (plugin instanceof AddActionCatalogPlugin) { - // AddActionCatalogPlugin cplugin = (AddActionCatalogPlugin) plugin; - // CatalogConfiguration conf = cplugin.getCatalogConfiguration(); - // ActionCatalog catalog = new ActionCatalog(); - // for(ActionConfiguration ac:(List )conf.getActions()) { - // try { - // ActionMatcher matcher = - // (ActionMatcher)Class.forName(ac.getMatcherFQCN()).newInstance(); - // Action action = (Action)Class.forName(ac.getActionFQCN()).newInstance(); - // catalog.addAction(matcher, action); - // } catch (Exception e) { - // e.printStackTrace(); - // } - // } - // put(conf.getName(), catalog); - // } - // } - -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Condition.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Condition.java deleted file mode 100644 index 38f6f0031..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/Condition.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.action; - -import java.util.HashMap; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ - -public class Condition extends HashMap -{ - -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/package-info.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/package-info.java deleted file mode 100644 index 0941b9651..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/action/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * This package provides classes to manage {@link org.exoplatform.services.command.action.Action} - */ -package org.exoplatform.services.command.action; \ No newline at end of file diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandLineParser.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandLineParser.java deleted file mode 100644 index 929a761b5..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandLineParser.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.impl; - -import org.apache.commons.chain.Context; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ -public interface CommandLineParser -{ - - /** - * parses command line and puts some parameters (if any) to the Context by - * some rules - * - * @param commandLine - * @param context - * @return command name - */ - String parse(String commandLine, Context context); -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java deleted file mode 100644 index 5bfe05ebb..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.impl; - -import org.apache.commons.chain.Catalog; -import org.apache.commons.chain.CatalogFactory; -import org.apache.commons.chain.config.ConfigParser; -import org.apache.commons.chain.impl.CatalogFactoryBase; -import org.apache.commons.digester.Digester; -import org.exoplatform.container.component.ComponentPlugin; -import org.exoplatform.container.spi.DefinitionByType; -import org.xml.sax.SAXException; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady - * Azarenkov - * @version $Id: CommandService.java 12832 2007-02-15 12:41:32Z geaz $ - */ -@DefinitionByType -public class CommandService -{ - - // protected Catalog catalog; - - protected CatalogFactory catalogFactory; - - protected Digester digester; - - public CommandService() - { - this.catalogFactory = CatalogFactoryBase.getInstance(); - - final ConfigParser parser = new ConfigParser(); - this.digester = parser.getDigester(); - } - - public void addPlugin(ComponentPlugin plugin) - { - // no needs to do anything as CatalogFactory is initialized in plugin - - // if (plugin instanceof CommonsXMLConfigurationPlugin) { - // CommonsXMLConfigurationPlugin cplugin = (CommonsXMLConfigurationPlugin) - // plugin; - // can just reinitialize it every time as have single instance - // catalog = cplugin.getCatalog(); - // Iterator names = cplugin.getCatalogNames(); - // while(names.hasNext()) { - // String name = (String)names.next(); - // catalogs.put(name, cplugin.getCatalog(name)); - // } - // } - } - - /** - * puts catalog (add or update) using XML input stream - * - * @param xml - * @throws IOException - * @throws SAXException - */ - public void putCatalog(final InputStream xml) throws IOException, SAXException - { - digester.clear(); - digester.parse(xml); - } - - /** - * @return default catalog - */ - public Catalog getCatalog() - { - Catalog catalog = catalogFactory.getCatalog(); - return catalog; - } - - /** - * @param name - * @return named catalog - */ - public Catalog getCatalog(String name) - { - Catalog catalog = catalogFactory.getCatalog(name); - return catalog; - - } - - /** - * @return iterator of catalog names. default catalog is not listed here! - */ - public Iterator getCatalogNames() - { - return catalogFactory.getNames(); - } - -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java deleted file mode 100644 index defb60e78..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.impl; - -import org.apache.commons.chain.config.ConfigParser; -import org.exoplatform.container.component.BaseComponentPlugin; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import java.net.URL; - -/** - * Created by The eXo Platform SAS.
The plugin for configuring - * command/chain catalog using "native" Apache Commons Chain's XML file - * - * @author Gennady - * Azarenkov - * @version $Id: CommonsXMLConfigurationPlugin.java 9846 2006-10-27 11:03:37Z - * geaz $ - */ - -public class CommonsXMLConfigurationPlugin extends BaseComponentPlugin -{ - - // protected Catalog defaultCatalog; - - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.cache.CommonsXMLConfigurationPlugin"); - - public CommonsXMLConfigurationPlugin(InitParams params, ConfigurationManager configurationManager) throws Exception - { - ValueParam confFile = params.getValueParam("config-file"); - if (confFile != null) - { - final String path = confFile.getValue(); - final ConfigParser parser = new ConfigParser(); - // may work for StandaloneContainer - - URL res = Thread.currentThread().getContextClassLoader().getResource(path); - - // for PortalContainer - if (res == null) - res = configurationManager.getResource(path); - if (res == null) - throw new Exception("Resource not found " + path); - LOG.info("Catalog configuration found at " + res); - - final URL fRes = res; - parser.parse(fRes); - } - - } -} diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/SimpleCommandLineParser.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/SimpleCommandLineParser.java deleted file mode 100644 index 59bfe5d8a..000000000 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/SimpleCommandLineParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command.impl; - -import org.apache.commons.chain.Context; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady Azarenkov - * @version $Id: $ - */ - -public class SimpleCommandLineParser implements CommandLineParser -{ - - protected final String parametersPropertyName; - - public SimpleCommandLineParser(String parametersPropertyName) - { - this.parametersPropertyName = parametersPropertyName; - } - - /* - * (non-Javadoc) - * @see - * org.exoplatform.services.command.impl.CommandLineParser#parse(java.lang - * .String, org.apache.commons.chain.Context) - */ - public String parse(String commandLine, Context context) - { - - context.remove(parametersPropertyName); - - // the rules: - // first word is command name (should be returned) - // else are parameters of command (should be put into Context under name == - // parametersPropertyName as array of Strings) - // mind contained string parameters - should be quoted (" or ') - // ///////////////////// - - StringTokenizer parser = new StringTokenizer(commandLine); - String commandName = null; - List params = new ArrayList(); - - while (parser.hasMoreTokens()) - { - String str = parser.nextToken(); - if (commandName == null) - commandName = str; - else - params.add(str); - } - // ////////////////////// - context.put(parametersPropertyName, params); - return commandName; - } - - /** - * @return parameters Property Name - */ - public String getParametersPropertyName() - { - return parametersPropertyName; - } - -} diff --git a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/CommandServiceTest.java b/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/CommandServiceTest.java deleted file mode 100644 index e2c09318f..000000000 --- a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/CommandServiceTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command; - -import junit.framework.TestCase; - -import org.apache.commons.chain.Catalog; -import org.apache.commons.chain.Command; -import org.apache.commons.chain.Context; -import org.apache.commons.chain.impl.CatalogFactoryBase; -import org.apache.commons.chain.impl.ContextBase; -import org.exoplatform.container.StandaloneContainer; -import org.exoplatform.services.command.impl.CommandService; - -import java.io.ByteArrayInputStream; - -/** - * Created by The eXo Platform SAS . - * - * @author Gennady Azarenkov - * @version $Id: CommandServiceTest.java 9296 2006-10-04 13:13:29Z geaz $ - */ -public class CommandServiceTest extends TestCase -{ - - private static final String IS = "" + "" + ""; - - private StandaloneContainer container; - - public void setUp() throws Exception - { - StandaloneContainer.setConfigurationPath("src/test/resources/conf/standalone/test-configuration.xml"); - - container = StandaloneContainer.getInstance(); - } - - public void testPluginConf() throws Exception - { - - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - assertNotNull(cservice); - - // preconfigured commands - assertTrue(cservice.getCatalog().getNames().hasNext()); - assertNotNull(cservice.getCatalog().getNames().next()); - - } - - public void testStringConf() throws Exception - { - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - Catalog c = cservice.getCatalog(); - - assertNull(c.getCommand("StrCommand")); - cservice.putCatalog(new ByteArrayInputStream(IS.getBytes())); - Catalog c1 = cservice.getCatalog(); - assertNotNull(c1.getCommand("StrCommand")); - - } - - public void testInitWithFile() throws Exception - { - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - cservice.putCatalog(getClass().getResourceAsStream("/conf/test-commands3.xml")); - assertTrue(cservice.getCatalogNames().hasNext()); - Catalog c1 = cservice.getCatalog("catalog1"); - assertNotNull(c1.getCommand("Command2")); - - } - - public void testExcecute() throws Exception - { - - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - Command c1 = cservice.getCatalog().getCommand("Execute2"); - Command c2 = cservice.getCatalog().getCommand("Command1"); - - Catalog c = cservice.getCatalog(); - - Context ctx = new ContextBase(); - ctx.put("test", Integer.valueOf(0)); - c1.execute(ctx); - c2.execute(ctx); - assertEquals(3, ((Integer)ctx.get("test")).intValue()); - - } - - public void tearDown() { - CatalogFactoryBase.clear(); - container.stop(); - - } - -} diff --git a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/MultiConfigServiceTest.java b/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/MultiConfigServiceTest.java deleted file mode 100644 index 10f865be2..000000000 --- a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/MultiConfigServiceTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command; - -import junit.framework.TestCase; - -import org.apache.commons.chain.impl.CatalogFactoryBase; -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.RootContainer; -import org.exoplatform.container.StandaloneContainer; -import org.exoplatform.services.command.impl.CommandService; - -import java.io.ByteArrayInputStream; -import java.util.Iterator; - -/** - * Created by The eXo Platform SAS . - * - * @author Gennady Azarenkov - * @version $Id:$ - */ -public class MultiConfigServiceTest extends TestCase -{ - - private StandaloneContainer container; - - private static final String IS = - "" + "" + ""; - - // amount of commands configured in multiple plugins - // CHECK it if change test-multi-configuration.xml !!! - private final int NUMBER_OF_COMMANDS_IN_DEF = 4; - - private final int NUMBER_OF_COMMANDS_IN_CATALOG1 = 2; - - public void setUp() throws Exception - { - StandaloneContainer.setConfigurationPath("src/test/resources/conf/standalone/test-multi-configuration.xml"); - - container = StandaloneContainer.getInstance(); - } - - /** - * Tests if multiple configuration is allowed - * - * @throws Exception - */ - public void testMultiConfig() throws Exception - { - - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - assertNotNull(cservice); - - assertTrue(cservice.getCatalogNames().hasNext()); - - Iterator commands = cservice.getCatalog().getNames(); - int cnt = 0; - while (commands.hasNext()) - { - commands.next(); - cnt++; - } - - assertEquals(NUMBER_OF_COMMANDS_IN_DEF, cnt); - - commands = cservice.getCatalog("catalog1").getNames(); - cnt = 0; - while (commands.hasNext()) - { - commands.next(); - cnt++; - } - - assertEquals(NUMBER_OF_COMMANDS_IN_CATALOG1, cnt); - - } - - public void testIfPutCatalogDoesNotRemoveCommands() throws Exception - { - - CommandService cservice = (CommandService)container.getComponentInstanceOfType(CommandService.class); - assertNotNull(cservice); - - assertTrue(cservice.getCatalogNames().hasNext()); - Iterator commands = cservice.getCatalog().getNames(); - int cnt = 0; - while (commands.hasNext()) - { - commands.next(); - cnt++; - } - - ByteArrayInputStream is = new ByteArrayInputStream(IS.getBytes()); - - cservice.putCatalog(is); - - assertTrue(cservice.getCatalogNames().hasNext()); - commands = cservice.getCatalog().getNames(); - cnt = 0; - while (commands.hasNext()) - { - commands.next(); - cnt++; - } - - commands = cservice.getCatalog("fromput").getNames(); - cnt = 0; - while (commands.hasNext()) - { - commands.next(); - cnt++; - } - - } - - public void tearDown() { - CatalogFactoryBase.clear(); - container.stop(); - - } -} diff --git a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/TestCommand1.java b/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/TestCommand1.java deleted file mode 100644 index 0613a380d..000000000 --- a/exo.kernel.component.command/src/test/java/org/exoplatform/services/command/TestCommand1.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.command; - -import org.apache.commons.chain.Command; -import org.apache.commons.chain.Context; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady - * Azarenkov - * @version $Id: TestCommand1.java 5799 2006-05-28 17:55:42Z geaz $ - */ - -public class TestCommand1 implements Command -{ - - public boolean execute(Context ctx) throws Exception - { - int tval = ((Integer)ctx.get("test")).intValue() + 1; - ctx.put("test", Integer.valueOf(tval)); - return false; - } - -} diff --git a/exo.kernel.component.command/src/test/resources/conf/standalone/test-configuration.xml b/exo.kernel.component.command/src/test/resources/conf/standalone/test-configuration.xml deleted file mode 100644 index 628a0cfde..000000000 --- a/exo.kernel.component.command/src/test/resources/conf/standalone/test-configuration.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - org.exoplatform.services.command.impl.CommandService - org.exoplatform.services.command.impl.CommandService - - - config.catalog - addPlugin - org.exoplatform.services.command.impl.CommonsXMLConfigurationPlugin - - - config-file - conf/test-commands.xml - - - - - - - - org.exoplatform.services.command.action.ActionService - - - diff --git a/exo.kernel.component.command/src/test/resources/conf/standalone/test-multi-configuration.xml b/exo.kernel.component.command/src/test/resources/conf/standalone/test-multi-configuration.xml deleted file mode 100644 index 99a3cb54a..000000000 --- a/exo.kernel.component.command/src/test/resources/conf/standalone/test-multi-configuration.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - org.exoplatform.services.command.impl.CommandService - org.exoplatform.services.command.impl.CommandService - - - config.catalog - addPlugin - org.exoplatform.services.command.impl.CommonsXMLConfigurationPlugin - - - config-file - conf/test-commands.xml - - - - - config.catalog - addPlugin - org.exoplatform.services.command.impl.CommonsXMLConfigurationPlugin - - - config-file - conf/test-commands2.xml - - - - - config.catalog - addPlugin - org.exoplatform.services.command.impl.CommonsXMLConfigurationPlugin - - - config-file - conf/test-commands3.xml - - - - - - - diff --git a/exo.kernel.component.command/src/test/resources/conf/test-commands.xml b/exo.kernel.component.command/src/test/resources/conf/test-commands.xml deleted file mode 100644 index 9c6dfc72b..000000000 --- a/exo.kernel.component.command/src/test/resources/conf/test-commands.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/exo.kernel.component.command/src/test/resources/conf/test-commands2.xml b/exo.kernel.component.command/src/test/resources/conf/test-commands2.xml deleted file mode 100644 index fa5fc8422..000000000 --- a/exo.kernel.component.command/src/test/resources/conf/test-commands2.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - diff --git a/exo.kernel.component.command/src/test/resources/conf/test-commands3.xml b/exo.kernel.component.command/src/test/resources/conf/test-commands3.xml deleted file mode 100644 index 4d94991fa..000000000 --- a/exo.kernel.component.command/src/test/resources/conf/test-commands3.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - diff --git a/exo.kernel.component.command/src/test/resources/test.policy b/exo.kernel.component.command/src/test/resources/test.policy deleted file mode 100644 index 4eb237000..000000000 --- a/exo.kernel.component.command/src/test/resources/test.policy +++ /dev/null @@ -1,27 +0,0 @@ -grant codeBase "@MAVEN_REPO@-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@TEST_CLASSES@-"{ - permission java.lang.RuntimePermission "manageContainer"; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.commons.test/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.commons/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.container/-"{ - permission java.security.AllPermission; -}; - - - - diff --git a/exo.kernel.component.common/pom.xml b/exo.kernel.component.common/pom.xml index df72cb463..1fe7552eb 100644 --- a/exo.kernel.component.common/pom.xml +++ b/exo.kernel.component.common/pom.xml @@ -76,21 +76,6 @@ com.sun.mail javax.mail - - org.jgroups - jgroups - - - com.atomikos - transactions-jta - provided - - - org.mockito - mockito-all - - - org.subethamail subethasmtp @@ -120,40 +105,13 @@ commons-dbcp test - - commons-pool - commons-pool - runtime - javax.activation javax.activation-api - - javax.transaction - javax.transaction-api - - - org.apache.maven.plugins - maven-surefire-plugin - - @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true - - - - jgroups.bind_addr - 127.0.0.1 - - - jgroups.stack - udp - - - - maven-antrun-plugin diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java deleted file mode 100644 index c450b4dcd..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.compress; - -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** - * Created by The eXo Platform SAS Author : Chung Nguyen - * nguyenchung136@yahoo.com Feb 10, 2006 - */ -public class CompressData -{ - /** - * The logger - */ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.CompressData"); - - private String base_; - - private List datas_ = new ArrayList(); - - protected static final int EOF = -1; - - protected static final int BUFFER = 2048; - - public CompressData() - { - - } - - public CompressData(String base) - { - base_ = base; - } - - public String getBase() - { - return base_; - } - - public void addFile(String entryName, File file) - { - try - { - InputStream is = new FileInputStream(file); - datas_.add(new InputStreamDataInstance(entryName, is)); - } - catch (FileNotFoundException e) - { - LOG.error(e.getLocalizedMessage(), e); - } - } - - public void addDir(File srcDir) - { - if (srcDir.isFile()) - { - addFile(srcDir.getName(), srcDir); - } - else - { - datas_.add(new FileDataInstance(srcDir.getName(), srcDir)); - } - // create recursive loop to go through all files in the srcDir..... - } - - public void addInputStream(String entryName, InputStream is) throws Exception - { - datas_.add(new InputStreamDataInstance(entryName, is)); - } - - public void createZipFile(String fileName) throws Exception - { - File fileZip = new File(fileName + ".zip"); - FileOutputStream out = new FileOutputStream(fileZip); - ZipOutputStream zos = new ZipOutputStream(out); - int size = datas_.size(); - byte InputData[] = new byte[BUFFER]; - if (size < 0) - { - throw new Exception("Data size is null"); - } - for (int i = 0; i < size; i++) - { - DataInstance di = datas_.get(i); - if (di instanceof InputStreamDataInstance) - { - InputStream is = di.getInputStream(); - zos.putNextEntry(new ZipEntry(di.getEntryName())); - int len; - while ((len = is.read(InputData)) != EOF) - { - zos.write(InputData, 0, len); - } - zos.closeEntry(); - } - else if (di instanceof FileDataInstance) - { - di.getZipOut(true, zos); - } - } - zos.close(); - out.close(); - } - - public void createZip(OutputStream os) throws Exception - { - int size = datas_.size(); - ZipOutputStream zos = new ZipOutputStream(os); - if (size == 0) - throw new Exception("Data is null"); - for (int i = 0; i < size; i++) - { - DataInstance di = datas_.get(i); - if (di instanceof InputStreamDataInstance) - { - InputStream is = di.getInputStream(); - zos.putNextEntry(new ZipEntry(di.getEntryName())); - int len; - byte InputData[] = new byte[BUFFER]; - while ((len = is.read(InputData)) != EOF) - { - zos.write(InputData, 0, len); - } - zos.closeEntry(); - } - else if (di instanceof FileDataInstance) - { - di.setType("Zip"); - InputStream is = di.getInputStream(); - int len; - byte[] data = new byte[BUFFER]; - while ((len = is.read(data)) != EOF) - { - os.write(data, 0, len); - } - is.close(); - } - } - zos.close(); - os.close(); - } - - public void createJarFile(String fileName) throws Exception - { - File fileZip = new File(fileName + ".jar"); - FileOutputStream out = new FileOutputStream(fileZip); - JarOutputStream jos = new JarOutputStream(out); - int size = datas_.size(); - if (size < 0) - throw new Exception("Data size is null"); - for (int i = 0; i < size; i++) - { - DataInstance di = datas_.get(i); - - if (di instanceof InputStreamDataInstance) - { - String entryName = di.getEntryName(); - InputStream is = di.getInputStream(); - jos.putNextEntry(new ZipEntry(entryName)); - int len; - byte InputData[] = new byte[BUFFER]; - while ((len = is.read(InputData)) != EOF) - { - jos.write(InputData, 0, len); - } - jos.closeEntry(); - } - else if (di instanceof FileDataInstance) - { - di.getJarOut(true, jos); - } - } - jos.close(); - out.close(); - } - - public void createJar(OutputStream os) throws Exception - { - int size = datas_.size(); - JarOutputStream jos = new JarOutputStream(os); - if (size == 0) - throw new Exception("Data is null"); - for (int i = 0; i < size; i++) - { - DataInstance di = datas_.get(i); - if (di instanceof InputStreamDataInstance) - { - InputStream is = di.getInputStream(); - - jos.putNextEntry(new ZipEntry(di.getEntryName())); - int len; - byte InputData[] = new byte[BUFFER]; - while ((len = is.read(InputData)) != EOF) - { - jos.write(InputData, 0, len); - } - jos.closeEntry(); - is.close(); - } - else if (di instanceof FileDataInstance) - { - di.setType("Jar"); - InputStream is = di.getInputStream(); - int len; - byte[] data = new byte[BUFFER]; - while ((len = is.read(data)) != EOF) - { - os.write(data, 0, len); - } - is.close(); - } - } - jos.close(); - os.close(); - } - - public void cleanDataInstance() - { - int count = datas_.size(); - for (int i = 0; i < count; i++) - { - datas_.remove(i); - } - } - - abstract public static class DataInstance - { - protected String entryName_; - - protected String typeZip_; - - abstract public InputStream getInputStream(); - - abstract public void getJarOut(boolean containParent, JarOutputStream jos) throws Exception; - - abstract public void getZipOut(boolean containParent, ZipOutputStream zos) throws Exception; - - public String getEntryName() - { - return entryName_; - } - - public void setType(String typeZip) - { - typeZip_ = typeZip; - } - - public String getType() - { - return typeZip_; - } - - } - - public static class FileDataInstance extends DataInstance - { - private File file_; - - public FileDataInstance(String entryName, File file) - { - entryName_ = entryName; - file_ = file; - } - - @Override - public InputStream getInputStream() - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - if (getType().equals("Zip")) - { - ZipOutputStream zos = new ZipOutputStream(baos); - try - { - getZipOut(true, zos); - } - catch (Exception e) - { - LOG.error(e.getLocalizedMessage(), e); - } - } - else - { - JarOutputStream jos; - try - { - jos = new JarOutputStream(baos); - getJarOut(true, jos); - } - catch (Exception e) - { - LOG.error(e.getLocalizedMessage(), e); - } - } - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - - try - { - baos.close(); - } - catch (IOException e) - { - LOG.error(e.getLocalizedMessage(), e); - } - - return is; - } - - @Override - public void getJarOut(boolean containParent, JarOutputStream jos) throws Exception - { - String path = file_.getAbsolutePath(); - InputStream bufInput = null; - List list = listFile(file_); - if (file_.isDirectory()) - list.remove(file_); - if (list == null || list.size() < 1) - throw new Exception("nothing in the list"); - for (File f : list) - { - StringBuilder filePath = new StringBuilder(f.getAbsolutePath()); - - if (f.getAbsolutePath().startsWith(path)) - { - if (containParent && file_.isDirectory()) - { - filePath = new StringBuilder(file_.getName()); - filePath.append(File.separator); - filePath.append(f.getAbsolutePath().substring(path.length() + 1)); - } - else if (file_.isDirectory()) - { - filePath = new StringBuilder(f.getAbsolutePath().substring(path.length() + 1)); - } - else - { - filePath = new StringBuilder(file_.getName()); - } - } - - if (f.isFile()) - { - bufInput = new FileInputStream(f); - } - else - { - filePath.append("/"); - } - - addToArchive(jos, bufInput, filePath.toString()); - } - } - - private List listFile(File dir) - { - final List list = new ArrayList(); - if (dir.isFile()) - { - list.add(dir); - return list; - } - dir.listFiles(new FileFilter() - { - public boolean accept(File f) - { - if (f.isDirectory()) - list.addAll(listFile(f)); - list.add(f); - return true; - } - }); - return list; - } - - public ZipOutputStream addToArchive(ZipOutputStream zipOutput, InputStream input, String entryName1) - throws Exception - { - byte data[] = new byte[BUFFER]; - ZipEntry entry = new ZipEntry(entryName1); - zipOutput.putNextEntry(entry); - if (input != null) - { - int count; - while ((count = input.read(data, 0, BUFFER)) != EOF) - zipOutput.write(data, 0, count); - } - zipOutput.closeEntry(); - return zipOutput; - } - - public JarOutputStream addToArchive(JarOutputStream jarOutput, InputStream input, String entryName1) - throws Exception - { - byte data[] = new byte[BUFFER]; - JarEntry entry = new JarEntry(entryName1); - jarOutput.putNextEntry(entry); - if (input != null) - { - int count; - while ((count = input.read(data, 0, BUFFER)) != EOF) - jarOutput.write(data, 0, count); - } - jarOutput.closeEntry(); - return jarOutput; - } - - @Override - public void getZipOut(boolean containParent, ZipOutputStream zos) throws Exception - { - String path = file_.getAbsolutePath(); - InputStream bufInput = null; - List list = listFile(file_); - if (file_.isDirectory()) - list.remove(file_); - if (list == null || list.size() < 1) - throw new Exception("nothing in the list"); - for (File f : list) - { - StringBuilder filePath = new StringBuilder(f.getAbsolutePath()); - - if (f.getAbsolutePath().startsWith(path)) - { - if (containParent && file_.isDirectory()) - { - filePath = new StringBuilder(file_.getName()); - filePath.append(File.separator); - filePath.append(f.getAbsolutePath().substring(path.length() + 1)); - } - else if (file_.isDirectory()) - { - filePath = new StringBuilder(f.getAbsolutePath().substring(path.length() + 1)); - } - else - { - filePath = new StringBuilder(file_.getName()); - } - } - - if (f.isFile()) - { - bufInput = new FileInputStream(f); - } - else - { - filePath.append("/"); - } - - addToArchive(zos, bufInput, filePath.toString()); - } - } - } - - public static class InputStreamDataInstance extends DataInstance - { - private InputStream is_; - - public InputStreamDataInstance(String entryName, InputStream is) - { - entryName_ = entryName; - is_ = is; - } - - @Override - public InputStream getInputStream() - { - return is_; - } - - @Override - public void getJarOut(boolean containParent, JarOutputStream jos) throws Exception - { - - } - - @Override - public void getZipOut(boolean containParent, ZipOutputStream zos) throws Exception - { - - } - - } - -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/DataSourceProvider.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/DataSourceProvider.java deleted file mode 100644 index 4a05e3dd3..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/DataSourceProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.jdbc; - -import org.exoplatform.container.spi.DefinitionByType; -import org.exoplatform.services.jdbc.impl.DataSourceProviderImpl; - -import javax.naming.NamingException; -import javax.sql.DataSource; - -/** - * This provider is used to get a {@link DataSource} in an uniform manner. - * It allows to wrap the {@link DataSource} in case it is defined as managed - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -@DefinitionByType(type = DataSourceProviderImpl.class) -public interface DataSourceProvider -{ - /** - * Try to get the data source from a lookup, if it can't a {@link NamingException} - * will be thrown - * @param dataSourceName the name of the data source to lookup - * @return the {@link DataSource} found thanks to the lookup. The original - * object could be wrap to another {@link DataSource} in order to support - * managed data source. - * @throws NamingException if the data source could not be found - */ - DataSource getDataSource(String dataSourceName) throws NamingException; - - /** - * Indicates whether or not the given data source is managed - * @param dataSourceName the data source to check - * @return true if the data source is managed, - * false otherwise - */ - boolean isManaged(String dataSourceName); -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/DataSourceProviderImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/DataSourceProviderImpl.java deleted file mode 100644 index 0701d4cee..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/DataSourceProviderImpl.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.jdbc.impl; - -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.container.xml.ValuesParam; -import org.exoplatform.services.jdbc.DataSourceProvider; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.transaction.TransactionService; - -import java.util.HashSet; -import java.util.Set; -import java.util.StringTokenizer; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import javax.transaction.TransactionManager; - -/** - * The default implementation of {@link DataSourceProvider}. It allows you - * to define a data source as managed thanks to the configuration of this - * component. When the data source is declared as managed, the {@link DataSource} - * object will be wrap into a {@link ManagedDataSource}. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class DataSourceProviderImpl implements DataSourceProvider -{ - - /** - * Logger - */ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.DataSourceProviderImpl"); - - /** - * The name of the parameter to know if the tx has to be checked or not. - */ - protected static final String PARAM_CHECK_TX = "check-tx-active"; - - /** - * The name of the parameter to know if the data sources are always managed. - */ - protected static final String PARAM_ALWAYS_MANAGED = "always-managed"; - - /** - * The name of the parameter of all the managed data sources. - */ - protected static final String PARAM_MANAGED_DS = "managed-data-sources"; - - /** - * The transaction manager - */ - protected final TransactionManager tm; - - /** - * Indicates if the data source needs to check if a tx is active - * to decide if the provided connection needs to be managed or not. - * If it is set to false, the data source will provide only - * managed connections if the data source itself is managed. - */ - protected boolean checkIfTxActive = true; - - /** - * Indicates that all the data sources are managed - */ - protected boolean alwaysManaged; - - /** - * A set of all the data sources that are managed - */ - protected final Set managedDS = new HashSet(); - - /** - * The default constructor - */ - public DataSourceProviderImpl(InitParams params) - { - this(params, null); - } - - /** - * The default constructor - */ - public DataSourceProviderImpl(InitParams params, TransactionService tService) - { - this.tm = tService == null ? null : tService.getTransactionManager(); - if (params != null) - { - ValueParam param = params.getValueParam(PARAM_CHECK_TX); - if (param != null) - { - this.checkIfTxActive = Boolean.valueOf(param.getValue()); - } - param = params.getValueParam(PARAM_ALWAYS_MANAGED); - if (param != null && Boolean.valueOf(param.getValue())) - { - this.alwaysManaged = true; - return; - } - ValuesParam vp = params.getValuesParam(PARAM_MANAGED_DS); - if (vp != null && vp.getValues() != null) - { - for (Object oValue : vp.getValues()) - { - String s = (String)oValue; - StringTokenizer st = new StringTokenizer(s, ","); - while (st.hasMoreTokens()) - { - String dsName = st.nextToken().trim(); - if (!dsName.isEmpty()) - { - managedDS.add(dsName); - } - } - } - } - } - } - - /** - * @throws NamingException - * @see org.exoplatform.services.jdbc.DataSourceProvider#getDataSource(java.lang.String) - */ - public DataSource getDataSource(String dataSourceName) throws NamingException - { - InitialContext ctx = new InitialContext(); - try - { - DataSource ds = (DataSource)ctx.lookup(dataSourceName); - // wrap the data source object if it is managed - return isManaged(dataSourceName) ? new ManagedDataSource(ds, tm, checkIfTxActive) : ds; - } - finally - { - try - { - ctx.close(); - } - catch (NamingException e) - { - LOG.warn("Failed to close naming context.", e); - } - } - } - - /** - * @see org.exoplatform.services.jdbc.DataSourceProvider#isManaged(java.lang.String) - */ - public boolean isManaged(String dataSourceName) - { - if (alwaysManaged) - { - return true; - } - else if (managedDS.isEmpty()) - { - return false; - } - return managedDS.contains(dataSourceName); - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedConnection.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedConnection.java deleted file mode 100644 index 340c52f9e..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedConnection.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.jdbc.impl; - -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import java.lang.reflect.Method; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -/** - * This classes wraps a jdbc connection in order to prevent any forbidden - * actions such as explicit commit/rollback. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class ManagedConnection implements Connection -{ - /** - * The logger - */ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.ManagedConnection"); - - /** - * The nested connection - */ - private final Connection con; - - /** - * default constructor - */ - public ManagedConnection(Connection con) - { - this.con = con; - } - - /** - * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) - */ - public boolean isWrapperFor(Class iface) throws SQLException - { - return con.isWrapperFor(iface); - } - - /** - * @see java.sql.Wrapper#unwrap(java.lang.Class) - */ - public T unwrap(Class iface) throws SQLException - { - return con.unwrap(iface); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String) - */ - public PreparedStatement prepareStatement(String sql) throws SQLException - { - return con.prepareStatement(sql); - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String) - */ - public CallableStatement prepareCall(String sql) throws SQLException - { - return con.prepareCall(sql); - } - - /** - * @see java.sql.Connection#nativeSQL(java.lang.String) - */ - public String nativeSQL(String sql) throws SQLException - { - return con.nativeSQL(sql); - } - - /** - * @see java.sql.Connection#setAutoCommit(boolean) - */ - public void setAutoCommit(boolean autoCommit) throws SQLException - { - con.setAutoCommit(autoCommit); - } - - /** - * @see java.sql.Connection#commit() - */ - public void commit() throws SQLException - { - // We cannot call commit explicitly, it will be done by the AS itself - } - - /** - * @see java.sql.Connection#rollback() - */ - public void rollback() throws SQLException - { - // We cannot call rollback explicitly, it will be done by the AS itself - } - - /** - * @see java.sql.Connection#close() - */ - public void close() throws SQLException - { - con.close(); - } - - /** - * @see java.sql.Connection#setReadOnly(boolean) - */ - public void setReadOnly(boolean readOnly) throws SQLException - { - con.setReadOnly(readOnly); - } - - /** - * @see java.sql.Connection#setCatalog(java.lang.String) - */ - public void setCatalog(String catalog) throws SQLException - { - con.setCatalog(catalog); - } - - /** - * @see java.sql.Connection#setTransactionIsolation(int) - */ - public void setTransactionIsolation(int level) throws SQLException - { - con.setTransactionIsolation(level); - } - - /** - * @see java.sql.Connection#clearWarnings() - */ - public void clearWarnings() throws SQLException - { - con.clearWarnings(); - } - - /** - * @see java.sql.Connection#createArrayOf(java.lang.String, java.lang.Object[]) - */ - public Array createArrayOf(String typeName, Object[] elements) throws SQLException - { - return con.createArrayOf(typeName, elements); - } - - /** - * @see java.sql.Connection#createBlob() - */ - public Blob createBlob() throws SQLException - { - return con.createBlob(); - } - - /** - * @see java.sql.Connection#createClob() - */ - public Clob createClob() throws SQLException - { - return con.createClob(); - } - - /** - * @see java.sql.Connection#createNClob() - */ - public NClob createNClob() throws SQLException - { - return con.createNClob(); - } - - /** - * @see java.sql.Connection#createSQLXML() - */ - public SQLXML createSQLXML() throws SQLException - { - return con.createSQLXML(); - } - - /** - * @see java.sql.Connection#createStatement() - */ - public Statement createStatement() throws SQLException - { - return con.createStatement(); - } - - /** - * @see java.sql.Connection#createStatement(int, int) - */ - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException - { - return con.createStatement(resultSetType, resultSetConcurrency); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int, int) - */ - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException - { - return con.prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String, int, int) - */ - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException - { - return con.prepareCall(sql, resultSetType, resultSetConcurrency); - } - - /** - * @see java.sql.Connection#setTypeMap(java.util.Map) - */ - public void setTypeMap(Map> map) throws SQLException - { - con.setTypeMap(map); - } - - /** - * @see java.sql.Connection#setSavepoint() - */ - public Savepoint setSavepoint() throws SQLException - { - return con.setSavepoint(); - } - - /** - * @see java.sql.Connection#setSavepoint(java.lang.String) - */ - public Savepoint setSavepoint(String name) throws SQLException - { - return con.setSavepoint(name); - } - - /** - * @see java.sql.Connection#rollback(java.sql.Savepoint) - */ - public void rollback(Savepoint savepoint) throws SQLException - { - // We cannot call rollback explicitly, it will be done by the AS itself - } - - /** - * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint) - */ - public void releaseSavepoint(Savepoint savepoint) throws SQLException - { - con.releaseSavepoint(savepoint); - } - - /** - * @see java.sql.Connection#createStatement(int, int, int) - */ - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException - { - return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } - - /** - * @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[]) - */ - public Struct createStruct(String typeName, Object[] attributes) throws SQLException - { - return con.createStruct(typeName, attributes); - } - - /** - * @see java.sql.Connection#getAutoCommit() - */ - public boolean getAutoCommit() throws SQLException - { - return con.getAutoCommit(); - } - - /** - * @see java.sql.Connection#isClosed() - */ - public boolean isClosed() throws SQLException - { - return con.isClosed(); - } - - /** - * @see java.sql.Connection#isReadOnly() - */ - public boolean isReadOnly() throws SQLException - { - return con.isReadOnly(); - } - - /** - * @see java.sql.Connection#getCatalog() - */ - public String getCatalog() throws SQLException - { - return con.getCatalog(); - } - - /** - * @see java.sql.Connection#getClientInfo() - */ - public Properties getClientInfo() throws SQLException - { - return con.getClientInfo(); - } - - /** - * @see java.sql.Connection#getClientInfo(java.lang.String) - */ - public String getClientInfo(String name) throws SQLException - { - return con.getClientInfo(name); - } - - /** - * @see java.sql.Connection#getMetaData() - */ - public DatabaseMetaData getMetaData() throws SQLException - { - return con.getMetaData(); - } - - /** - * @see java.sql.Connection#getTransactionIsolation() - */ - public int getTransactionIsolation() throws SQLException - { - return con.getTransactionIsolation(); - } - - /** - * @see java.sql.Connection#getWarnings() - */ - public SQLWarning getWarnings() throws SQLException - { - return con.getWarnings(); - } - - /** - * @see java.sql.Connection#getTypeMap() - */ - public Map> getTypeMap() throws SQLException - { - return con.getTypeMap(); - } - - /** - * @see java.sql.Connection#getHoldability() - */ - public int getHoldability() throws SQLException - { - return con.getHoldability(); - } - - /** - * @see java.sql.Connection#isValid(int) - */ - public boolean isValid(int timeout) throws SQLException - { - return con.isValid(timeout); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int) - */ - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException - { - return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String, int, int, int) - */ - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException - { - return con.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int) - */ - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException - { - return con.prepareStatement(sql, autoGeneratedKeys); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int[]) - */ - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException - { - return con.prepareStatement(sql, columnIndexes); - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, java.lang.String[]) - */ - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException - { - return con.prepareStatement(sql, columnNames); - } - - /** - * @see java.sql.Connection#setClientInfo(java.util.Properties) - */ - public void setClientInfo(Properties properties) throws SQLClientInfoException - { - con.setClientInfo(properties); - } - - /** - * @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String) - */ - public void setClientInfo(String name, String value) throws SQLClientInfoException - { - con.setClientInfo(name, value); - } - - /** - * @see java.sql.Connection#setHoldability(int) - */ - public void setHoldability(int holdability) throws SQLException - { - con.setHoldability(holdability); - } - - /** - * @see java.sql.Connection#setSchema(java.lang.String) - */ - public void setSchema(String schema) throws SQLException - { - try - { - Method m = con.getClass().getMethod("setSchema", String.class); - m.invoke(con, schema); - } - catch (NoSuchMethodException e) - { - LOG.debug("The method setSchema cannot be found in the class " + con.getClass() + - ", so we assume it is not supported"); - } - catch (Exception e) - { - throw new SQLException(e); - } - } - - /** - * @see java.sql.Connection#getSchema() - */ - public String getSchema() throws SQLException - { - try - { - Method m = con.getClass().getMethod("getSchema"); - return (String)m.invoke(con); - } - catch (NoSuchMethodException e) - { - LOG.debug("The method getSchema cannot be found in the class " + con.getClass() + - ", so we assume it is not supported"); - } - catch (Exception e) - { - throw new SQLException(e); - } - return null; - } - - /** - * @see java.sql.Connection#abort(java.util.concurrent.Executor) - */ - public void abort(Executor executor) throws SQLException - { - try - { - Method m = con.getClass().getMethod("abort", Executor.class); - m.invoke(con, executor); - } - catch (NoSuchMethodException e) - { - LOG.debug("The method abort cannot be found in the class " + con.getClass() + - ", so we assume it is not supported"); - } - catch (Exception e) - { - throw new SQLException(e); - } - } - - /** - * @see java.sql.Connection#setNetworkTimeout(java.util.concurrent.Executor, int) - */ - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException - { - try - { - Method m = con.getClass().getMethod("setNetworkTimeout", Executor.class, int.class); - m.invoke(con, executor, milliseconds); - } - catch (NoSuchMethodException e) - { - LOG.debug("The method setNetworkTimeout cannot be found in the class " + con.getClass() + - ", so we assume it is not supported"); - } - catch (Exception e) - { - throw new SQLException(e); - } - } - - /** - * @see java.sql.Connection#getNetworkTimeout() - */ - public int getNetworkTimeout() throws SQLException - { - try - { - Method m = con.getClass().getMethod("getNetworkTimeout"); - return (Integer)m.invoke(con); - } - catch (NoSuchMethodException e) - { - LOG.debug("The method getNetworkTimeout cannot be found in the class " + con.getClass() + - ", so we assume it is not supported"); - } - catch (Exception e) - { - throw new SQLException(e); - } - return 0; - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedDataSource.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedDataSource.java deleted file mode 100644 index fb50ea5cf..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/ManagedDataSource.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.jdbc.impl; - -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import java.io.PrintWriter; -import java.lang.reflect.Method; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.logging.Logger; - -import javax.sql.DataSource; -import javax.transaction.Status; -import javax.transaction.SystemException; -import javax.transaction.TransactionManager; - -/** - * This classes is used to wrap the original {@link DataSource} - * in order to be able to support the managed data sources with a limited - * amount of changes. A {@link DataSource} is expected to be wrapped only - * when a data source is defined and has been configured as managed - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class ManagedDataSource implements DataSource -{ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.ManagedDataSource"); - - /** - * The transaction manager - */ - private final TransactionManager tm; - - /** - * The wrapped {@link DataSource} - */ - private final DataSource ds; - - /** - * Indicates whether the tx status need to be check first to know - * if the provided connection needs to be managed or not - */ - private final boolean checkIfTxActive; - - /** - * default constructor - */ - public ManagedDataSource(DataSource ds, TransactionManager tm, boolean checkIfTxActive) - { - this.tm = tm; - this.ds = ds; - this.checkIfTxActive = checkIfTxActive; - } - - /** - * @see javax.sql.CommonDataSource#getLogWriter() - */ - public PrintWriter getLogWriter() throws SQLException - { - return ds.getLogWriter(); - } - - /** - * @see javax.sql.CommonDataSource#getLoginTimeout() - */ - public int getLoginTimeout() throws SQLException - { - return ds.getLoginTimeout(); - } - - /** - * @see javax.sql.CommonDataSource#setLogWriter(java.io.PrintWriter) - */ - public void setLogWriter(PrintWriter out) throws SQLException - { - ds.setLogWriter(out); - } - - /** - * @see javax.sql.CommonDataSource#setLoginTimeout(int) - */ - public void setLoginTimeout(int seconds) throws SQLException - { - ds.setLoginTimeout(seconds); - } - - /** - * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) - */ - public boolean isWrapperFor(Class iface) throws SQLException - { - return ds.isWrapperFor(iface); - } - - /** - * @see java.sql.Wrapper#unwrap(java.lang.Class) - */ - public T unwrap(Class iface) throws SQLException - { - return ds.unwrap(iface); - } - - /** - * @see javax.sql.DataSource#getConnection() - */ - public Connection getConnection() throws SQLException - { - Connection con = ds.getConnection(); - return providesManagedConnection() ? new ManagedConnection(con) : con; - } - - /** - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - public Connection getConnection(String username, String password) throws SQLException - { - Connection con = ds.getConnection(username, password); - return providesManagedConnection() ? new ManagedConnection(con) : con; - } - - /** - * Indicates whether or not a global tx is active - * @return true if a tx is active, false otherwise - */ - private boolean isTxActive() - { - try - { - return tm != null && tm.getStatus() != Status.STATUS_NO_TRANSACTION; - } - catch (SystemException e) - { - LOG.warn("We cannot know if a global tx is active", e); - } - return false; - } - - /** - * Indicates whether or not the provided connection needs to be managed - */ - private boolean providesManagedConnection() - { - return !checkIfTxActive || isTxActive(); - } - - /** - * @see javax.sql.CommonDataSource#getParentLogger() - */ - public Logger getParentLogger() throws SQLFeatureNotSupportedException - { - try - { - Method m = ds.getClass().getMethod("getParentLogger"); - return (Logger)m.invoke(ds); - } - catch (Exception e) - { - throw new SQLFeatureNotSupportedException(e); - } - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/NetService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/NetService.java deleted file mode 100644 index 9d9e0138e..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/NetService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.net; - -/** - * Created by The eXo Platform SAS Author : HoaPham phamvuxuanhoa@yahoo.com Jan - * 10, 2006 - */ -public interface NetService -{ - public long ping(String host, int port) throws Exception; -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java deleted file mode 100644 index 1bef4b60b..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.net.impl; - -import org.exoplatform.services.net.NetService; - -import java.net.Socket; - -/** - * Created by The eXo Platform SAS Author : HoaPham phamvuxuanhoa@yahoo.com Jan - * 10, 2006 - */ -public class NetServiceImpl implements NetService -{ - - public long ping(final String host, final int port) throws Exception - { - long startTime = 0; - long endTime = 0; - startTime = System.currentTimeMillis(); - Socket socket = new Socket(host, port); - endTime = System.currentTimeMillis(); - socket.close(); - return endTime - startTime; - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCException.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCException.java deleted file mode 100644 index 6f27aa10d..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -/** - * The root class of all the Exception related to the RPC Service - * - * @author Nicolas Filotto - * @version $Id$ - */ -public class RPCException extends Exception -{ - - /** - * The serial version UID - */ - private static final long serialVersionUID = -9113831373947878170L; - - public RPCException(String message, Throwable cause) - { - super(message, cause); - } - - public RPCException(String message) - { - super(message); - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCService.java deleted file mode 100644 index 015414ffc..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RPCService.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -import java.io.Serializable; -import java.util.List; - -/** - * This service provides mechanism to communicate with the other cluster nodes. This service will - * be based of JGroups as an underlying Transport. - * @author Nicolas Filotto - * @version $Id$ - */ -public interface RPCService -{ - - /** - * The permission needed to access to any methods of the RPCService - */ - public static final RuntimePermission ACCESS_RPC_SERVICE_PERMISSION = new RuntimePermission("accessRPCService"); - - /** - * Executes a command on all the cluster nodes. This method is equivalent to the other method of the - * same type but with the default timeout. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on each cluster node - * @param synchronous if true, sets group request mode to org.jgroups.blocks.GroupRequest#GET_ALL, - * and if false sets it to org.jgroups.blocks.GroupRequest#GET_NONE. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return a list of responses from all the members of the cluster. If we met an exception on a given node, - * the RPCException will be the corresponding response of this particular node - * @throws RPCException in the event of problems. - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - List executeCommandOnAllNodes(RemoteCommand command, boolean synchronous, Serializable... args) - throws RPCException, SecurityException; - - /** - * Executes a command synchronously on all the cluster nodes. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on each cluster node - * @param timeout a timeout after which to throw a replication exception. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return a list of responses from all the members of the cluster. If we met an exception on a given node, - * the RPCException will be the corresponding response of this particular node - * @throws RPCException in the event of problems. - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - List executeCommandOnAllNodes(RemoteCommand command, long timeout, Serializable... args) - throws RPCException, SecurityException; - - /** - * Executes a command on the coordinator only. This method is equivalent to the other method of the - * same type but with the default timeout. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on the coordinator node - * @param synchronous if true, sets group request mode to org.jgroups.blocks.GroupRequest#GET_ALL, - * and if false sets it to org.jgroups.blocks.GroupRequest#GET_NONE. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return the response of the coordinator. - * @throws RPCException in the event of problems. - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - Object executeCommandOnCoordinator(RemoteCommand command, boolean synchronous, Serializable... args) - throws RPCException, SecurityException; - - /** - * Executes a command synchronously on the coordinator only. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on the coordinator node - * @param timeout a timeout after which to throw a replication exception. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return the response of the coordinator. - * @throws RPCException in the event of problems. - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - Object executeCommandOnCoordinator(RemoteCommand command, long timeout, Serializable... args) throws RPCException, - SecurityException; - - /** - * Register a new {@link RemoteCommand} instance, it will be mapped to its id. If a command with the - * same Id has already been registered, a warning will be printed into the log file and the new - * command will replace the old one. - * @param command the instance of the {@link RemoteCommand} to register - * @return the command itself if it could be registered null otherwise - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - RemoteCommand registerCommand(RemoteCommand command) throws SecurityException; - - /** - * Unregister a {@link RemoteCommand} instance, if the id is known or the instance itself is known - * otherwise it will be ignored - * @param command the command to unregister - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - void unregisterCommand(RemoteCommand command) throws SecurityException; - - /** - * Indicates whether the local node is the coordinator of the cluster - * @return true if the coordinator is the coordinator, false otherwise - * throws RPCException in case the {@link RPCService} is in an illegal state - */ - boolean isCoordinator() throws RPCException; - - /** - * Register a new {@link TopologyChangeListener} - * @param listener the listener to be registered - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - void registerTopologyChangeListener(TopologyChangeListener listener) throws SecurityException; - - /** - * Unregister a {@link TopologyChangeListener} if it exists - * @param listener the listener to unregister - * @throws SecurityException if the {@link SecurityManager} is installed and the call method - * doesn't have the {@link RuntimePermission} ACCESS_RPC_SERVICE_PERMISSION - */ - void unregisterTopologyChangeListener(TopologyChangeListener listener) throws SecurityException; -} \ No newline at end of file diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RemoteCommand.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RemoteCommand.java deleted file mode 100644 index 3201cf084..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/RemoteCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -import java.io.Serializable; - -/** - * This class represents the command that can be executed on a remote server. - * A RemoteCommand needs to be ThreadSafe since it can be re-used by several - * threads in parallel. - * @author Nicolas Filotto - * @version $Id$ - */ -public interface RemoteCommand -{ - /** - * This method will execute the command on the local machine. - * @param args The parameters needed to execute the command - * @return arbitrary return value generated by performing this command - * @throws Throwable in the event of problems. - */ - Serializable execute(Serializable[] args) throws Throwable; - - /** - * Gives the id of the command - * @return the unique ID of the command - */ - String getId(); -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/SingleMethodCallCommand.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/SingleMethodCallCommand.java deleted file mode 100644 index f2cd9b7ad..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/SingleMethodCallCommand.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; - -/** - * This command will allow you to call one specific method with the arguments given by the execute method - * on a component. - * - * @author Nicolas Filotto - * @version $Id$ - */ -public class SingleMethodCallCommand implements RemoteCommand -{ - - /** - * The component on which we want to execute the method - */ - private final Object component; - - /** - * The method that we want to call - */ - private final Method method; - - /** - * The id of the command - */ - private final String id; - - /** - * - * @param component the component on which we want to execute the method - * @param methodName the name of the method - * @param parameterTypes the parameter array - * @throws NoSuchMethodException if a matching method is not found. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
    - * - *
  • invocation of - * {@link SecurityManager #checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared method - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * @throws ClassNotFoundException If the last parameter type is an array and we - * cannot find the type of the array - */ - public SingleMethodCallCommand(Object component, String methodName, Class... parameterTypes) - throws SecurityException, NoSuchMethodException, ClassNotFoundException - { - if (component == null) - { - throw new IllegalArgumentException("The component cannot be null"); - } - if (methodName == null || (methodName = methodName.trim()).length() == 0) - { - throw new IllegalArgumentException("The methodName cannot be empty"); - } - this.component = component; - this.method = component.getClass().getDeclaredMethod(methodName, parameterTypes); - if (!Modifier.isPublic(method.getModifiers())) - { - throw new IllegalArgumentException("The method '" + methodName + "' is not public"); - } - this.id = getId(component, method); - } - - /** - * {@inheritDoc} - */ - public Serializable execute(Serializable[] args) throws Throwable - { - try - { - return (Serializable)method.invoke(component, (Object[])args); - } - catch (Exception e) - { - throw new Exception("Could not execute the method " + id + " with the arguments " + Arrays.toString(args), e); - } - } - - /** - * {@inheritDoc} - */ - public String getId() - { - return id; - } - - /** - * Gives a unique Id from the component and the method - */ - private static String getId(Object component, Method method) - { - StringBuilder sb = new StringBuilder(); - sb.append(component.getClass().getName()); - sb.append('.'); - sb.append(method.getName()); - sb.append('('); - boolean first = true; - for (Class c : method.getParameterTypes()) - { - if (first) - { - first = false; - } - else - { - sb.append(','); - } - sb.append(c.getSimpleName()); - } - sb.append(')'); - return sb.toString(); - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeEvent.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeEvent.java deleted file mode 100644 index 834798a47..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -/** - * The event triggered anytime the cluster has changed of topology - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TopologyChangeEvent -{ - - /** - * Indicates whether the current node is the coordinator after this topology change - */ - private final boolean coordinator; - - /** - * Indicates whether the coordinator has changed - */ - private final boolean coordinatorHasChanged; - - /** - * Default constructor - * @param coordinatorHasChanged this parameter is set to true if the - * coordinator has changed, false otherwise - * @param coordinator this parameter is set to true if the current node - * is the coordinator, false otherwise - */ - public TopologyChangeEvent(boolean coordinatorHasChanged, boolean coordinator) - { - this.coordinator = coordinator; - this.coordinatorHasChanged = coordinatorHasChanged; - } - - /** - * Indicates whether the current node is the coordinator or not after the topology change - * @return true if the current node is the coordinator, false otherwise. - */ - public boolean isCoordinator() - { - return coordinator; - } - - /** - * Indicates whether the coordinator has changed after the topology change - * @return true if the coordinator has changed, false otherwise. - */ - public boolean isCoordinatorHasChanged() - { - return coordinatorHasChanged; - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeListener.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeListener.java deleted file mode 100644 index 0768b6fa3..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/TopologyChangeListener.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc; - -/** - * This interface is used to allow some components to be notified anytime the topology - * of the cluster changes, in other words any time a member of the cluster leave or join - * the cluster. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public interface TopologyChangeListener -{ - - /** - * Called anytime the topology of the cluster changes - * @param event the event triggered when the topology changes - */ - void onChange(TopologyChangeEvent event); -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java deleted file mode 100644 index 6fe6d047d..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java +++ /dev/null @@ -1,982 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc.impl; - -import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.rpc.RPCException; -import org.exoplatform.services.rpc.RPCService; -import org.exoplatform.services.rpc.RemoteCommand; -import org.exoplatform.services.rpc.TopologyChangeEvent; -import org.exoplatform.services.rpc.TopologyChangeListener; -import org.jgroups.Address; -import org.jgroups.Channel; -import org.jgroups.MembershipListener; -import org.jgroups.Message; -import org.jgroups.View; -import org.jgroups.blocks.MessageDispatcher; -import org.jgroups.blocks.RequestHandler; -import org.jgroups.conf.ConfiguratorFactory; -import org.jgroups.conf.ProtocolStackConfigurator; -import org.jgroups.util.Rsp; -import org.jgroups.util.RspList; -import org.picocontainer.Startable; - -import java.io.Externalizable; -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; -import java.io.Serializable; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; - -/** - * This class is a basic implementation of the {@link RPCService}, it is mainly based on the - * {@link MessageDispatcher} of JGroups. This implementation is not designed to give - * the best possible performances, it only aims to give a way to communicate with other nodes. - * - * @author Nicolas Filotto - * @version $Id$ - */ -public abstract class AbstractRPCService implements RPCService, Startable, RequestHandler, MembershipListener -{ - - /** - * Connection logger. - */ - protected static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.RPCServiceImpl"); - - /** - * The name of the parameter for the location of the JGroups configuration. - */ - protected static final String PARAM_JGROUPS_CONFIG = "jgroups-configuration"; - - /** - * The name of the parameter for the name of the cluster. - */ - protected static final String PARAM_CLUSTER_NAME = "jgroups-cluster-name"; - - /** - * The name of the parameter for the default timeout - */ - protected static final String PARAM_DEFAULT_TIMEOUT = "jgroups-default-timeout"; - - /** - * The name of the parameter to allow the failover - */ - protected static final String PARAM_ALLOW_FAILOVER = "allow-failover"; - - /** - * The name of the parameter for the retry timeout - */ - protected static final String PARAM_RETRY_TIMEOUT = "retry-timeout"; - - /** - * The value of the default timeout - */ - protected static final int DEFAULT_TIMEOUT = 0; - - /** - * The value of the default retry timeout - */ - protected static final int DEFAULT_RETRY_TIMEOUT = 20000; - - /** - * The default value of the cluster name - */ - protected static final String CLUSTER_NAME = "RPCService-Cluster"; - - /** - * The configurator used to create the JGroups Channel - */ - protected final ProtocolStackConfigurator configurator; - - /** - * The lock used to synchronize all the threads waiting for a topology change. - */ - private final Object topologyChangeLock = new Object(); - - /** - * The name of the cluster - */ - private final String clusterName; - - /** - * The JGroups Channel used to communicate with other nodes - */ - protected Channel channel; - - /** - * The current list of all the members of the cluster - */ - protected volatile List
members; - - /** - * The address of the current coordinator - */ - protected volatile Address coordinator; - - /** - * Indicates whether the current node is the coordinator of the cluster or not - */ - protected volatile boolean isCoordinator; - - /** - * The default value of the timeout - */ - private long defaultTimeout = DEFAULT_TIMEOUT; - - /** - * The value of the retry timeout - */ - private long retryTimeout = DEFAULT_RETRY_TIMEOUT; - - /** - * Indicates whether the failover capabilities are enabled - */ - private boolean allowFailover = true; - - /** - * The dispatcher used to launch the command of the cluster nodes - */ - protected MessageDispatcher dispatcher; - - /** - * The signal that indicates that the service is started, it will be used - * to make the application wait until the service is fully started to - * ensure that all the commands have been registered before handling - * incoming messages. - */ - private final CountDownLatch startSignal = new CountDownLatch(1); - - /** - * All the registered {@link TopologyChangeListener} - */ - private final List listeners = new CopyOnWriteArrayList(); - - /** - * Current State of the {@link org.exoplatform.services.rpc.jgv3.RPCServiceImpl} - */ - private volatile State state; - - /** - * All the commands that have been registered - */ - private volatile Map commands = - Collections.unmodifiableMap(new HashMap()); - - /** - * The public constructor - * @param ctx the {@link ExoContainerContext} from which we will extract the corresponding - * {@link ExoContainer} - * @param params the list of initial parameters - * @param configManager the configuration manager used to get the configuration - * of JGroups - */ - public AbstractRPCService(ExoContainerContext ctx, InitParams params, ConfigurationManager configManager) - { - if (params == null) - { - throw new IllegalArgumentException("The RPCServiceImpl requires some parameters"); - } - final URL properties = getProperties(params, configManager); - if (LOG.isInfoEnabled()) - { - LOG.info("The JGroups configuration used for the RPCServiceImpl will be loaded from " + properties); - } - - try - { - this.configurator = ConfiguratorFactory.getStackConfigurator(properties); - } - catch (Exception e) - { - throw new RuntimeException("Cannot load the JGroups configuration from " + properties, e.getCause()); - } - - this.clusterName = getClusterName(ctx, params); - if (LOG.isDebugEnabled()) - { - LOG.debug("The cluster name of the RPCServiceImpl has been set to " + clusterName); - } - String sTimeout = getValueParam(params, PARAM_DEFAULT_TIMEOUT); - if (sTimeout != null) - { - defaultTimeout = Integer.parseInt(sTimeout); - if (LOG.isDebugEnabled()) - { - LOG.debug("The default timeout of the RPCServiceImpl has been set to " + defaultTimeout); - } - } - String sAllowFailover = getValueParam(params, PARAM_ALLOW_FAILOVER); - if (sAllowFailover != null) - { - allowFailover = Boolean.valueOf(sAllowFailover); - if (LOG.isDebugEnabled()) - { - LOG.debug("The parameter '" + PARAM_ALLOW_FAILOVER + "' of the RPCServiceImpl has been set to " + allowFailover); - } - } - sTimeout = getValueParam(params, PARAM_RETRY_TIMEOUT); - if (sTimeout != null) - { - retryTimeout = Integer.parseInt(sTimeout); - if (LOG.isDebugEnabled()) - { - LOG.debug("The retry timeout of the RPCServiceImpl has been set to " + retryTimeout); - } - } - this.state = State.INITIALIZED; - } - - /** - * {@inheritDoc} - */ - public List executeCommandOnAllNodes(RemoteCommand command, boolean synchronous, Serializable... args) - throws RPCException - { - return executeCommandOnAllNodesMain(command, synchronous, defaultTimeout, args); - } - - /** - * {@inheritDoc} - */ - public List executeCommandOnAllNodes(RemoteCommand command, long timeout, Serializable... args) - throws RPCException - { - return executeCommandOnAllNodesMain(command, true, timeout, args); - } - - /** - * Executes a command on all the cluster nodes. This method is equivalent to the other method of the - * same type but with the default timeout. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on each cluster node - * @param synchronous if true, sets group request mode to org.jgroups.blocks.GroupRequest#GET_ALL, - * and if false sets it to org.jgroups.blocks.GroupRequest#GET_NONE. - * @param timeout a timeout after which to throw a replication exception. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return a list of responses from all the members of the cluster. If we met an exception on a given node, - * the RPCException will be the corresponding response of this particular node - * @throws RPCException in the event of problems. - */ - protected List executeCommandOnAllNodesMain(RemoteCommand command, boolean synchronous, long timeout, - Serializable... args) throws RPCException - { - return excecuteCommand(members, command, synchronous, timeout, args); - } - - /** - * {@inheritDoc} - */ - public Object executeCommandOnCoordinator(RemoteCommand command, boolean synchronous, Serializable... args) - throws RPCException - { - return executeCommandOnCoordinatorMain(command, synchronous, defaultTimeout, args); - } - - /** - * {@inheritDoc} - */ - public Object executeCommandOnCoordinator(RemoteCommand command, long timeout, Serializable... args) - throws RPCException - { - return executeCommandOnCoordinatorMain(command, true, timeout, args); - } - - /** - * Executes a command on the coordinator only. This method is equivalent to the other method of the - * same type but with the default timeout. The command must be registered first otherwise an - * {@link RPCException} will be thrown. - * - * @param command The command to execute on the coordinator node - * @param synchronous if true, sets group request mode to org.jgroups.blocks.GroupRequest#GET_ALL, - * and if false sets it to org.jgroups.blocks.GroupRequest#GET_NONE. - * @param timeout a timeout after which to throw a replication exception. - * @param args an array of {@link Serializable} objects corresponding to parameters of the command - * to execute remotely - * @return the response of the coordinator. - * @throws RPCException in the event of problems. - */ - protected Object executeCommandOnCoordinatorMain(RemoteCommand command, boolean synchronous, long timeout, - Serializable... args) throws RPCException - { - Address coordinator = this.coordinator; - Vector
v = new Vector
(1); - v.add(coordinator); - List lResults = excecuteCommand(v, command, synchronous, timeout, args); - Object result = lResults == null || lResults.size() == 0 ? null : lResults.get(0); - if (allowFailover && result instanceof MemberHasLeftException) - { - // The failover capabilities have been enabled and the coordinator seems to have left - if (coordinator.equals(this.coordinator)) - { - synchronized(topologyChangeLock) - { - if (coordinator.equals(this.coordinator)) - { - if (LOG.isTraceEnabled()) - LOG.trace("The coordinator did not change yet, we will relaunch the command after " - + retryTimeout + " ms or once a topology change has been detected"); - try - { - topologyChangeLock.wait(retryTimeout); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - } - } - } - if (LOG.isTraceEnabled()) - LOG.trace("The coordinator has changed, we will automatically retry with the new coordinator"); - return executeCommandOnCoordinator(command, synchronous, timeout, args); - } - else if (result instanceof RPCException) - { - throw (RPCException)result; - } - return result; - } - - /** - * Execute the command on all the nodes corresponding to the list of destinations. - * @param dests the list of members on which the command needs to be executed - * @param command the command to execute - * @param synchronous if true, sets group request mode to org.jgroups.blocks.GroupRequest#GET_ALL, and if false sets - * it to org.jgroups.blocks.GroupRequest#GET_NONE. - * @param timeout a timeout after which to throw a replication exception. - * @param args the list of parameters - * @return a list of responses from all the targeted members of the cluster. - * @throws RPCException in the event of problems. - */ - protected List excecuteCommand(final List
dests, RemoteCommand command, - final boolean synchronous, final long timeout, Serializable... args) throws RPCException - { - if (state != State.STARTED) - { - throw new RPCException( - "Cannot execute any commands if the service is not started, the current state of the service is " + state); - } - final String commandId = command.getId(); - if (commands.get(commandId) != command) - { - throw new RPCException("Command " + commandId + " unknown, please register your command first"); - } - final Message msg = new Message(); - setObject(msg, new MessageBody(dests.size() == 1 && dests != members ? dests.get(0) : null, commandId, args)); //NOSONAR - RspList rsps = null; - try - { - rsps = castMessage(dests, msg, synchronous, timeout); - } - catch (Exception e) - { - LOG.error("Could not cast the message corresponding to the command " + commandId + ".", e); - } - - if (LOG.isTraceEnabled()) - LOG.trace("responses: " + rsps); - if (rsps == null) - throw new RPCException("Could not get the responses for command " + commandId + "."); - if (!synchronous) - return Collections.emptyList();// async case - if (LOG.isTraceEnabled()) - { - LOG.trace("(" + getLocalAddress() + "): responses for command " + commandId + ":\n" + rsps); - } - List retval = new ArrayList(rsps.size()); - for (Address dest : dests) - { - Rsp rsp = rsps.get(dest); - if (rsp == null || (rsp.wasSuspected() && !rsp.wasReceived())) - { - // The corresponding member has left - retval.add(new MemberHasLeftException("No response for the member " + dest - + ", this member has probably left the cluster.")); - } - else if (!rsp.wasReceived()) - { - retval.add(new RPCException("Replication timeout for " + rsp.getSender() + ", rsp=" + rsp)); - } - else - { - Object value = rsp.getValue(); - if (value instanceof RPCException) - { - // if we have any application-level exceptions make sure we throw them!! - if (LOG.isTraceEnabled()) - LOG.trace("Recieved exception'" + value + "' from " + rsp.getSender(), (RPCException)value); - } - retval.add(value); - } - } - return retval; - } - - /** - * {@inheritDoc} - */ - public Object handle(Message msg) - { - String commandId = null; - try - { - // Ensure that the service is fully started before trying to execute any command - startSignal.await(); - MessageBody body = (MessageBody)msg.getObject(); - commandId = body.getCommandId(); - if (!body.accept(getLocalAddress())) - { - if (LOG.isTraceEnabled()) - { - LOG.trace("Command : " + commandId + " needs to be executed on the coordinator " + - "only and the local node is not the coordinator, the command will be ignored"); - } - return null; - } - RemoteCommand command = getCommand(commandId); - if (command == null) - { - return new RPCException("Command " + commandId + " unkown, please register your command first"); - } - Object execResult = command.execute(body.getArgs()); - if (LOG.isTraceEnabled()) - { - LOG.trace("Command : " + commandId + " executed, result is: " + execResult); - } - return execResult; - } - catch (Throwable x) //NOSONAR - { - if (LOG.isTraceEnabled()) - { - LOG.trace("Problems invoking command.", x); - } - return new RPCException("Cannot execute the command " + (commandId == null ? "" : commandId), x); - } - } - - /** - * {@inheritDoc} - */ - public void block() - { - } - - /** - * {@inheritDoc} - */ - public void suspect(Address suspectedMbr) - { - } - - /** - * {@inheritDoc} - */ - public void viewAccepted(View view) - { - boolean coordinatorHasChanged; - synchronized (topologyChangeLock) - { - this.members = getMembers(view); - Address currentCoordinator = coordinator; - this.coordinator = members != null && members.size() > 0 ? members.get(0) : null; - this.isCoordinator = coordinator != null && coordinator.equals(getLocalAddress()); - coordinatorHasChanged = currentCoordinator != null && !currentCoordinator.equals(coordinator); - // Release all the nodes - topologyChangeLock.notifyAll(); - } - onTopologyChange(coordinatorHasChanged); - } - - /** - * Called anytime the topology has changed, this method will notify all the listeners - * currently registered - * @param coordinatorHasChanged this parameter is set to true if the - * coordinator has changed, false otherwise - */ - private void onTopologyChange(boolean coordinatorHasChanged) - { - TopologyChangeEvent event = new TopologyChangeEvent(coordinatorHasChanged, isCoordinator); - for (TopologyChangeListener listener : listeners) - { - try - { - listener.onChange(event); - } - catch (Exception e) - { - LOG.warn("An error occurs with the listener of type " + listener.getClass(), e); - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized RemoteCommand registerCommand(RemoteCommand command) - { - if (command != null) - { - String commandId = command.getId(); - if (commandId == null) - { - throw new IllegalArgumentException("The command Id cannot be null"); - } - Map tmpCommands = new HashMap(this.commands); - RemoteCommand oldCommand = tmpCommands.put(commandId, command); - if (oldCommand != null && PropertyManager.isDevelopping()) - { - LOG.warn("A command has already been registered with the id " + commandId - + ", this command will be replaced with the new one"); - } - this.commands = Collections.unmodifiableMap(tmpCommands); - return command; - } - return null; - } - - /** - * {@inheritDoc} - */ - public synchronized void unregisterCommand(RemoteCommand command) - { - if (command != null) - { - String commandId = command.getId(); - if (commandId == null) - { - throw new IllegalArgumentException("The command Id cannot be null"); - } - if (commands.get(commandId) != command) - { - // We prevent to remove any command that has not been registered, thus we expect that - // the registered instance is exactly the same instance as the one that we want to - // unregister - if (PropertyManager.isDevelopping()) - { - LOG.warn("Cannot unregister an unknown RemoteCommand, either the command id " + commandId - + " is unknown or the instance of RemoteCommand to unregister is unknown"); - } - return; - } - Map tmpCommands = new HashMap(this.commands); - tmpCommands.remove(commandId); - this.commands = Collections.unmodifiableMap(tmpCommands); - } - } - - /** - * {@inheritDoc} - */ - public boolean isCoordinator() throws RPCException - { - if (state != State.STARTED) - { - throw new RPCException("Cannot know whether the local node is a coordinator or not if " + - "the service is not started, the current state of the service is " + state); - } - return isCoordinator; - } - - /** - * {@inheritDoc} - */ - public void registerTopologyChangeListener(TopologyChangeListener listener) throws SecurityException - { - if (listener == null) - { - return; - } - listeners.add(listener); - } - - /** - * {@inheritDoc} - */ - public void unregisterTopologyChangeListener(TopologyChangeListener listener) throws SecurityException - { - if (listener == null) - { - return; - } - listeners.remove(listener); - } - - /** - * Gives the {@link RemoteCommand} corresponding to the given id - * @param commandId the command id of the command to retrieve - * @return the corresponding {@link RemoteCommand} - */ - protected RemoteCommand getCommand(String commandId) - { - return commands.get(commandId); - } - - /** - * {@inheritDoc} - */ - public void start() - { - try - { - channel = createChannel(); - dispatcher = new MessageDispatcher(channel, null, AbstractRPCService.this, AbstractRPCService.this); - channel.connect(clusterName); - } - catch (Exception e) - { - throw new RuntimeException("Cannot initialize the Channel needed for the RPCServiceImpl", e.getCause()); - } - finally - { - this.state = State.STARTED; - startSignal.countDown(); - } - } - - /** - * {@inheritDoc} - */ - public void stop() - { - this.state = State.STOPPED; - this.isCoordinator = false; - if (channel != null && channel.isOpen()) - { - if (LOG.isInfoEnabled()) - LOG.info("Disconnecting and closing the Channel"); - channel.disconnect(); - channel.close(); - channel = null; - } - if (dispatcher != null) - { - dispatcher.stop(); - dispatcher = null; - } - } - - /** - * Gives the value of the default timeout - * @return the default timeout - */ - protected long getDefaultTimeout() - { - return defaultTimeout; - } - - /** - * Gives the name of the cluster - * @return the name of the cluster - */ - protected String getClusterName() - { - return clusterName; - } - - /** - * Gives the value of the retry timeout - * @return the value of the retry timeout - */ - protected long getRetryTimeout() - { - return retryTimeout; - } - - /** - * Indicates whether the failover capabilities are enabled or not - * @return true if the failover capabilities are allowed, false - * otherwise - */ - protected boolean isAllowFailover() - { - return allowFailover; - } - - /** - * Returns the channel's own address. The result of calling this method on an unconnected - * channel is implementation defined (may return null). Calling this method on a closed - * channel returns null. Successor to #getAddress(). Addresses can be used as destination - * in the send() operation. - * @return The channel's address (opaque) or null if it cannot be found - */ - protected abstract Address getLocalAddress(); - - /** - * Returns the IP address of current channel. - * @return The Host's address or null if it cannot be found - */ - public abstract String getHostAddress(); - - /** - * Cast a message to all the given members - * @param dests The members to which the message is to be sent. - * @param msg The message to be sent to the members. - * @param synchronous Indicates whether the message must be sent in synchronous or asynchronous mode. - * @param timeout If 0: wait forever. Otherwise, wait for responses or timeout time. - * @return A list of responses. Each response is an Object and associated to its sender. - * @throws Exception if any error occur while casting the message - */ - protected abstract RspList castMessage(List
dests, Message msg, boolean synchronous, long timeout) throws Exception; - - /** - * Create a channel - * @return An initialized channel - * @throws Exception if any error occur while creating the channel - */ - protected abstract Channel createChannel() throws Exception; - - /** - * Returns a reference to the List of members (ordered) - * Do NOT change this list, hence your will invalidate the view - * Make a copy if you have to modify it. - * - * @return a reference to the ordered list of members in this view - */ - protected abstract List
getMembers(View view); - - /** - * Takes an object and uses Java serialization to generate the byte[] buffer which - * is set in the message. - */ - protected abstract void setObject(Message m, Object o); - - /** - * Gives the value of the {@link ValueParam} corresponding to the given key - * @param params the list of initial parameters from which we want to extract the {@link ValueParam} - * @param parameterKey the name of the {@link ValueParam} that we are looking for - * @return the value if it exists, null otherwise - */ - private static String getValueParam(InitParams params, String parameterKey) - { - if (params != null) - { - ValueParam parameterKeyValue = params.getValueParam(parameterKey); - if (parameterKeyValue != null) - { - String parameterKeyValueString = parameterKeyValue.getValue(); - if (parameterKeyValueString != null) - { - return parameterKeyValueString.trim(); - } - } - } - return null; - } - - /** - * Gives the {@link URL} corresponding to the location of the JGroups configuration - * @param params the initial parameters from which we extract the parameter - * PARAM_JGROUPS_CONFIG - * @param configManager the configuration manager used to get the {@link URL} corresponding - * to the path given in the configuration of the RPCServiceImpl - * @return The {@link URL} corresponding to the location of the JGroups configuration, - * it will throw {@link RuntimeException} otherwise since it is a mandatory configuration. - */ - private static URL getProperties(InitParams params, ConfigurationManager configManager) - { - String configPath = getValueParam(params, PARAM_JGROUPS_CONFIG); - if (configPath == null) - { - throw new IllegalArgumentException("The parameter '" + PARAM_JGROUPS_CONFIG - + "' of RPCServiceImpl is mandatory"); - } - URL properties; - try - { - properties = configManager.getResource(configPath); - } - catch (Exception e) - { - throw new IllegalArgumentException("Cannot find the JGroups configuration at " + configPath, e); - } - if (properties == null) - { - throw new IllegalArgumentException("Cannot find the JGroups configuration at " + configPath); - } - return properties; - } - - /** - * Gives the name of the cluster that will be able to support several portal containers - * since the name will be post fixed with "-${container-name}" - * @param ctx the context from which we extract the name of the container - * @param params the list of initial parameters from which we get the value of the parameter - * PARAM_CLUSTER_NAME if it exists otherwise the value will be "RPCService-Cluster" - */ - private static String getClusterName(ExoContainerContext ctx, InitParams params) - { - String clusterName = getValueParam(params, PARAM_CLUSTER_NAME); - if (clusterName == null) - { - clusterName = CLUSTER_NAME; - } - return clusterName += "-" + ctx.getName(); - } - - /** - * This intern class will be used to - */ - public static class MessageBody implements Externalizable - { - /** - * The Id of the command to execute - */ - private String commandId; - - /** - * The list of parameters - */ - private Serializable[] args; - - /** - * The hash code of the expected destination - */ - private int destination; - - public MessageBody() - { - } - - /** - * @param dest The destination of the message - * @param commandId the id of the command to execute - * @param args the arguments to use - */ - public MessageBody(Address dest, String commandId, Serializable[] args) - { - this.commandId = commandId; - this.args = args; - this.destination = dest == null ? 0 : dest.hashCode(); - } - - public String getCommandId() - { - return commandId; - } - - public Serializable[] getArgs() - { - return args; - } - - /** - * Indicates whether or not the given message body accepts the given address - * @param address the address to check - * @return true if the message is for everybody or if the given address is the expected address, - * false otherwise - */ - public boolean accept(Address address) - { - return destination == 0 || destination == address.hashCode(); - } - - /** - * {@inheritDoc} - */ - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException - { - boolean unicast = in.readBoolean(); - if (unicast) - { - this.destination = in.readInt(); - } - this.commandId = in.readUTF(); - int size = in.readInt(); - if (size == -1) - { - this.args = null; - } - else - { - this.args = new Serializable[size]; - for (int i = 0; i < size; i++) - { - args[i] = (Serializable)in.readObject(); - } - } - } - - /** - * {@inheritDoc} - */ - public void writeExternal(ObjectOutput out) throws IOException - { - boolean unicast = destination != 0; - out.writeBoolean(unicast); - if (unicast) - { - out.writeInt(destination); - } - out.writeUTF(commandId); - if (args == null) - { - out.writeInt(-1); - } - else - { - out.writeInt(args.length); - for (int i = 0; i < args.length; i++) - { - out.writeObject(args[i]); - } - } - } - } - - /** - * All the potential states of the {@link org.exoplatform.services.rpc.jgv3.RPCServiceImpl} - */ - public enum State - { - INITIALIZED, STARTED, STOPPED - } - - public static class MemberHasLeftException extends RPCException - { - - /** - * The serial version UID - */ - private static final long serialVersionUID = 3558158913564367637L; - - public MemberHasLeftException(String message) - { - super(message); - } - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/jgv3/RPCServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/jgv3/RPCServiceImpl.java deleted file mode 100644 index 16d5a1768..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/jgv3/RPCServiceImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc.jgv3; - -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.services.rpc.impl.AbstractRPCService; -import org.jgroups.*; -import org.jgroups.blocks.RequestOptions; -import org.jgroups.blocks.ResponseMode; -import org.jgroups.stack.IpAddress; -import org.jgroups.util.RspList; - -import java.util.List; - -/** - * This class is the implementation of the {@link AbstractRPCService} for JGroups 3. - * - * @author Nicolas Filotto - * @version $Id$ - */ -public class RPCServiceImpl extends AbstractRPCService -{ - - /** - * {@inheritDoc} - */ - public RPCServiceImpl(ExoContainerContext ctx, InitParams params, ConfigurationManager configManager) - { - super(ctx, params, configManager); - } - - /** - * {@inheritDoc} - */ - protected Address getLocalAddress() - { - return channel.getAddress(); - } - - /** - * {@inheritDoc} - */ - public String getHostAddress() - { - String address = null; - org.jgroups.Address jgAddress = channel.getAddress() ; - if (!(jgAddress instanceof IpAddress)) - { - // this is the only way of getting physical address. - jgAddress = (org.jgroups.Address)channel.down(new Event(Event.GET_PHYSICAL_ADDRESS, jgAddress)); - } - if (jgAddress instanceof IpAddress) - { - address = ((IpAddress)jgAddress).getIpAddress().getHostAddress(); - } - else - { - LOG.error("Unsupported Address object : " + jgAddress.getClass().getName()); - } - return address; - } - - /** - * {@inheritDoc} - */ - protected RspList castMessage(List
dests, Message msg, boolean synchronous, long timeout) throws Exception - { - return dispatcher.castMessage(dests, msg, new RequestOptions(synchronous ? ResponseMode.GET_ALL - : ResponseMode.GET_NONE, timeout)); - } - - /** - * {@inheritDoc} - */ - protected Channel createChannel() throws Exception - { - return new JChannel(configurator); - } - - /** - * {@inheritDoc} - */ - public void unblock() - { - } - - /** - * {@inheritDoc} - */ - protected List
getMembers(View view) - { - return view.getMembers(); - } - - /** - * {@inheritDoc} - */ - protected void setObject(Message m, Object o) - { - m.setObject(o); - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/JobSchedulerServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/JobSchedulerServiceImpl.java index d901618c9..56c7eeacf 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/JobSchedulerServiceImpl.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/JobSchedulerServiceImpl.java @@ -413,10 +413,10 @@ public List getAllExcutingJobs() throws Exception public List getAllJobs() throws Exception { List jlist = new ArrayList(); - List jgroups = scheduler_.getJobGroupNames(); - for (int i = 0, length = jgroups.size(); i < length; i++) + List jobGroups = scheduler_.getJobGroupNames(); + for (int i = 0, length = jobGroups.size(); i < length; i++) { - Set jkeys = scheduler_.getJobKeys(GroupMatcher.jobGroupEquals(jgroups.get(i))); + Set jkeys = scheduler_.getJobKeys(GroupMatcher.jobGroupEquals(jobGroups.get(i))); for (JobKey jkey : jkeys) { jlist.add(scheduler_.getJobDetail(jkey)); @@ -737,8 +737,8 @@ private String getGroupName(String initialGroupName) */ private void loadAllJobKeys() { try { - List jgroups = scheduler_.getJobGroupNames(); - for (String jobGroupName : jgroups) + List jobGroups = scheduler_.getJobGroupNames(); + for (String jobGroupName : jobGroups) { Set jobGroupNames = scheduler_.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName)); persistedJobKeyList.addAll(jobGroupNames); diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/quartz.properties b/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/quartz.properties deleted file mode 100644 index 47c7da431..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/quartz.properties +++ /dev/null @@ -1,22 +0,0 @@ -# -# Configure Main Scheduler Properties -# - -org.quartz.scheduler.instanceName = TestScheduler -org.quartz.scheduler.instanceId = one - -# -# Configure ThreadPool -# - -org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool -org.quartz.threadPool.threadCount = 5 -org.quartz.threadPool.threadPriority = 4 - -# -# Configure JobStore -# - -org.quartz.jobStore.misfireThreshold = 5000 - -org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore \ No newline at end of file diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/DefaultThreadFactory.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/DefaultThreadFactory.java deleted file mode 100644 index 53f5d1389..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/DefaultThreadFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.threadpool.impl; - -/** - * $Id: DefaultThreadFactory.java 5332 2006-04-29 18:32:44Z geaz $ - * - * The contents of this file are subject to the ClickBlocks Public - * License Version 1.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.clickblocks.org - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied, including, but not limited to, the implied warranties of - * merchantability, fitness for a particular purpose and - * non-infringement. See the License for the specific language - * governing rights and limitations under the License. - * - * ClickBlocks, the ClickBlocks logo and combinations thereof are - * trademarks of ClickBlocks, LLC in the United States and other - * countries. - * - * The Initial Developer of the Original Code is ClickBlocks, LLC. - * Portions created by ClickBlocks, LLC are Copyright (C) 2000. - * All Rights Reserved. - * - * Contributor(s): Mark Grand - */ - -/** - * This is a default thread factory that creates vanilla threads. - */ -public class DefaultThreadFactory implements ThreadFactoryIF -{ - /** - * Return a Thread that runs the given Runnable object. - */ - public Thread createThread(Runnable r) - { - return new Thread(r); - } // createThread(Runnable) -} // class DefaultThreadFactory diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/Queue.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/Queue.java deleted file mode 100644 index e64bc00c4..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/Queue.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.threadpool.impl; - -/** - * $Id: Queue.java 5332 2006-04-29 18:32:44Z geaz $ - * - * The contents of this file are subject to the ClickBlocks Public - * License Version 1.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.clickblocks.org - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied, including, but not limited to, the implied warranties of - * merchantability, fitness for a particular purpose and - * non-infringement. See the License for the specific language - * governing rights and limitations under the License. - * - * ClickBlocks, the ClickBlocks logo and combinations thereof are - * trademarks of ClickBlocks, LLC in the United States and other - * countries. - * - * The Initial Developer of the Original Code is ClickBlocks, LLC. - * Portions created by ClickBlocks, LLC are Copyright (C) 2000. - * All Rights Reserved. - * - * Contributor(s): Mark Grand - */ - -import java.util.ArrayList; - -public class Queue -{ - private ArrayList data = new ArrayList(); - - private int maxQueueSize = Integer.MAX_VALUE; - - /** - * Put an object on the end of the queue. If the size of the queue is equal to - * or greater than the current value of maxQueueSize then this method will - * wait until the size of the queue shrinks to less than maxQueueSize. - * - * @param obj the object to put at end of queue - */ - synchronized public void put(Object obj) throws InterruptedException - { - if (Thread.currentThread().isInterrupted()) - throw new InterruptedException(); - if (obj == null) - throw new IllegalArgumentException("null"); - while (data.size() >= maxQueueSize) - { - try - { - wait(); - } - catch (InterruptedException e) - { - return; - } // try - } // while - data.add(obj); - notify(); - } // put(Object) - - /** - * Put an object on the end of the queue. If the size of the queue is equal to - * or greater than the current value of maxQueueSize then this method will - * wait until the size of the queue shrinks to less than maxQueueSize. - * - * @param obj the object to put at end of queue - * @param msecs If this method has to wait for the size of the queue to shrink - * to less than maxQueueSize, it will stop waiting after it has - * waited this many milliseconds. - * @return false if this method returns without queuing the given object - * becuase it had to wait msec milliseconds; otherwise true. - */ - synchronized public boolean put(Object obj, long msecs) throws InterruptedException - { - if (Thread.currentThread().isInterrupted()) - throw new InterruptedException(); - if (obj == null) - throw new IllegalArgumentException("null"); - long startTime = System.currentTimeMillis(); - long waitTime = msecs; - while (data.size() >= maxQueueSize) - { - waitTime = msecs - (System.currentTimeMillis() - startTime); - if (waitTime <= 0) - return false; - wait(waitTime); - } // while - data.add(obj); - notify(); - return true; - } // put(Object, long) - - /** - * Get an object from the front of the queue. If queue is empty, waits until - * it is not empty. - */ - synchronized public Object get() throws InterruptedException - { - while (data.size() == 0) - { - wait(); - } // while - Object obj = data.remove(0); - notify(); - return obj; - } // get() - - /** - * Get an object from the front of the queue. If queue is empty, waits until - * it is not empty. - * - * @param msecs The maximum number of milliseconds that this method should - * wait before giving up. - * @return The object at the front of the queue or null if there are no - * objects in the queue and the method has waited at least the given - * number of milliseconds for an object to be put in the queue. - */ - synchronized public Object get(long msecs) throws InterruptedException - { - long startTime = System.currentTimeMillis(); - long waitTime = msecs; - - if (data.size() > 0) - return data.remove(0); - while (true) - { - waitTime = msecs - (System.currentTimeMillis() - startTime); - if (waitTime <= 0) - return null; - wait(waitTime); - if (data.size() > 0) - { - Object obj = data.remove(0); - notify(); - return obj; - } // if data.size() - } // while - } // get(long) - - /** - * Set the maximum queue size. - */ - public void setMaxQueueSize(int newValue) - { - maxQueueSize = newValue; - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/ThreadFactoryIF.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/ThreadFactoryIF.java deleted file mode 100644 index 87db4a414..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/threadpool/impl/ThreadFactoryIF.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.threadpool.impl; - -/** - * $Id: ThreadFactoryIF.java 5332 2006-04-29 18:32:44Z geaz $ - * - * The contents of this file are subject to the ClickBlocks Public - * License Version 1.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.clickblocks.org - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied, including, but not limited to, the implied warranties of - * merchantability, fitness for a particular purpose and - * non-infringement. See the License for the specific language - * governing rights and limitations under the License. - * - * ClickBlocks, the ClickBlocks logo and combinations thereof are - * trademarks of ClickBlocks, LLC in the United States and other - * countries. - * - * The Initial Developer of the Original Code is ClickBlocks, LLC. - * Portions created by ClickBlocks, LLC are Copyright (C) 2000. - * All Rights Reserved. - * - * Contributor(s): Mark Grand - */ - -/** - * This interface in implemented by objects that create Thread objects. Classes - * that create Thread objects through this interface can be passed a - * ThreadFactoryIF object that creates an instance of Thread or a subclass of - * Thread with different properties. - */ -public interface ThreadFactoryIF -{ - /** - * Return a Thread that runs the given Runnable object. - */ - public Thread createThread(Runnable r); -} // interface ThreadFactoryIF diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/ActionNonTxAware.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/ActionNonTxAware.java deleted file mode 100644 index 4b535b81c..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/ActionNonTxAware.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction; - -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; - -/** - * This class describes all the actions that are not supposed to be called - * within a transaction - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public abstract class ActionNonTxAware -{ - /** - * The logger - */ - protected static final Log LOG = ExoLogger.getLogger(ActionNonTxAware.class); - - /** - * Executes the action outside the context of the current tx - * @param arg the argument to use to execute the action - * @return the result of the action - * @throws E if an error occurs while executing the action - */ - public R run(A... arg) throws E - { - final TransactionManager tm = getTransactionManager(); - Transaction tx = null; - try - { - if (tm != null) - { - try - { - tx = tm.suspend(); - } - catch (SystemException e) - { - LOG.warn("Cannot suspend the current transaction", e); - } - } - return execute(arg); - } - finally - { - if (tx != null) - { - try - { - tm.resume(tx); - } - catch (Exception e) - { - LOG.warn("Cannot resume the current transaction", e); - } - } - } - } - - /** - * Executes the action outside the context of the current tx. This - * method is equivalent to {@link ActionNonTxAware#run(Object[])}} but - * with null as parameter. - * @return the result of the action - * @throws E if an error occurs while executing the action - */ - public R run() throws E - { - return run((A[])null); - } - - /** - * Executes the action - * @param arg the argument to use to execute the action - * @return the result of the action - * @throws E if an error occurs while executing the action - */ - protected R execute(A... arg) throws E - { - if (arg == null || arg.length == 0) - { - return execute((A)null); - } - return execute(arg[0]); - } - - /** - * Executes the action - * @param arg the argument to use to execute the action - * @return the result of the action - * @throws E if an error occurs while executing the action - */ - protected R execute(A arg) throws E - { - return null; - } - - /** - * Gives the Transaction Manager that will be used while executing the action - * @return the {@link TransactionManager} to use - */ - protected abstract TransactionManager getTransactionManager(); -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/TransactionService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/TransactionService.java deleted file mode 100644 index bc95d1b56..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/TransactionService.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction; - -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; -import javax.transaction.xa.XAResource; - -/** - * Created by The eXo Platform SAS.
The transaction service - * - * @author Gennady - * Azarenkov - * @version $Id: $ - */ - -public interface TransactionService -{ - - /** - * @return TransactionManager - */ - TransactionManager getTransactionManager(); - - /** - * @return UserTransaction - */ - UserTransaction getUserTransaction(); - - /** - * @return default timeout in seconds - */ - int getDefaultTimeout(); - - /** - * Sets timeout in seconds, - * - * @param seconds int - * @throws SystemException - */ - void setTransactionTimeout(int seconds) throws SystemException; - - /** - * Enlists XA resource in transaction manager. - * - * @param xares XAResource - * @return true if the resource was enlisted successfully; otherwise - * false. - * - * @exception RollbackException Thrown to indicate that - * the transaction has been marked for rollback only. - * - * @exception IllegalStateException Thrown if the transaction in the - * target object is in the prepared state or the transaction is - * inactive. - * - * @exception SystemException Thrown if the transaction manager - * encounters an unexpected error condition. - */ - boolean enlistResource(XAResource xares) throws RollbackException, SystemException, IllegalStateException; - - /** - * Delists XA resource from transaction manager. - * - * @param xares XAResource - * @exception IllegalStateException Thrown if the transaction in the - * target object is inactive. - * - * @exception SystemException Thrown if the transaction manager - * encounters an unexpected error condition. - * - * @return true if the resource was delisted successfully; otherwise - * false. - */ - boolean delistResource(XAResource xares) throws RollbackException, SystemException, IllegalStateException; - -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java deleted file mode 100644 index f9d02f456..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.impl; - -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.transaction.TransactionService; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.InvalidTransactionException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.Status; -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; -import javax.transaction.xa.XAResource; - -/** - * This abstract class implements the main logic of all the methods expected for a - * {@link TransactionService}. If you intend to use a {@link TransactionManager} in - * standalone mode (not manager by your Application Server), you can set the - * transaction timeout thanks to the value-param called timeout - * the value of this parameter is expressed in seconds. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public abstract class AbstractTransactionService implements TransactionService -{ - /** - * The logger - */ - private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.AbstractTransactionService"); - - /** - * The default value of a transaction timeout in seconds - */ - private static final int DEFAULT_TIME_OUT = 60; - - /** - * The default timeout - */ - protected final int defaultTimeout; - - /** - * Indicates if the timeout has to be enforced - */ - protected final boolean forceTimeout; - - /** - * The current Transaction Manager - */ - private volatile TransactionManager tm; - - /** - * The current User Transaction - */ - private volatile UserTransaction ut; - - public AbstractTransactionService() - { - this(null); - } - - public AbstractTransactionService(InitParams params) - { - if (params != null && params.getValueParam("timeout") != null) - { - this.defaultTimeout = Integer.parseInt(params.getValueParam("timeout").getValue()); - this.forceTimeout = true; - } - else - { - this.defaultTimeout = DEFAULT_TIME_OUT; - this.forceTimeout = false; - } - } - - /** - * {@inheritDoc} - */ - public boolean delistResource(final XAResource xares) throws RollbackException, SystemException - { - TransactionManager tm = getTransactionManager(); - final Transaction tx = tm.getTransaction(); - if (tx != null) - { - int flag = XAResource.TMSUCCESS; - switch (tx.getStatus()) - { - case Status.STATUS_MARKED_ROLLBACK: - case Status.STATUS_ROLLEDBACK: - case Status.STATUS_ROLLING_BACK: flag = XAResource.TMFAIL; - } - return tx.delistResource(xares, flag); - } - else - { - throw new IllegalStateException("Could not delist the XA Resource since there is no active session"); - } - } - - /** - * {@inheritDoc} - */ - public boolean enlistResource(final XAResource xares) throws RollbackException, SystemException - { - TransactionManager tm = getTransactionManager(); - final Transaction tx = tm.getTransaction(); - if (tx != null) - { - return tx.enlistResource(xares); - } - else - { - throw new IllegalStateException("Could not enlist the XA Resource since there is no active session"); - } - } - - /** - * {@inheritDoc} - */ - public int getDefaultTimeout() - { - return defaultTimeout; - } - - /** - * {@inheritDoc} - */ - public final TransactionManager getTransactionManager() - { - if (tm == null) - { - synchronized (this) - { - if (tm == null) - { - TransactionManager tm; - try - { - tm = findTransactionManager(); - } - catch (Exception e) - { - throw new RuntimeException("Transaction manager not found", e); - } - if (forceTimeout) - { - // Only set the timeout when a timeout has been given into the - // configuration otherwise we assume that the value will be - // set at the AS level - tm = new TransactionManagerTxTimeoutAware(tm, defaultTimeout); - } - this.tm = tm; - } - } - } - return tm; - } - - /** - * Indicates whether or not the {@link TransactionManager} has been initialized - */ - protected boolean isTMInitialized() - { - return tm != null; - } - - /** - * This method will try to find the current {@link TransactionManager} - * @return the current {@link TransactionManager} - * @throws Exception if an error occurs while looking for the {@link TransactionManager} - */ - protected abstract TransactionManager findTransactionManager() throws Exception; - - /** - * {@inheritDoc} - */ - public final UserTransaction getUserTransaction() - { - if (ut == null) - { - synchronized (this) - { - if (ut == null) - { - UserTransaction ut; - try - { - ut = findUserTransaction(); - } - catch (Exception e) - { - throw new RuntimeException("UserTransaction not found", e); - } - this.ut = ut; - } - } - } - return ut; - } - - - /** - * This method will try to find the current {@link UserTransaction}, by default it will - * simply wraps a {@link TransactionManager} - * @return the current {@link UserTransaction} - * @throws Exception if an error occurs while looking for the {@link UserTransaction} - */ - protected UserTransaction findUserTransaction() throws Exception - { - return new UserTransactionWrapper(getTransactionManager()); - } - - /** - * {@inheritDoc} - */ - public void setTransactionTimeout(int seconds) throws SystemException - { - TransactionManager tm = getTransactionManager(); - tm.setTransactionTimeout(seconds); - } - - /** - * This class is used to enforce the {@link Transaction} timeout when a new transaction is - * created through the nested {@link TransactionManager} - * - * Created by The eXo Platform SAS - * Author : Nicolas Filotto - * nicolas.filotto@exoplatform.com - * 1 f�vr. 2010 - */ - private static class TransactionManagerTxTimeoutAware implements TransactionManager - { - /** - * The nested {@link TransactionManager} - */ - private final TransactionManager tm; - - /** - * The default timeout of the {@link Transaction} - */ - private final int defaultTimeout; - - /** - * This is used to know if a timeout has already been set for the next transaction - */ - private final ThreadLocal timeoutHasBeenSet = new ThreadLocal(); - - public TransactionManagerTxTimeoutAware(TransactionManager tm, int defaultTimeout) - { - this.tm = tm; - this.defaultTimeout = defaultTimeout; - } - - /** - * {@inheritDoc} - */ - public void begin() throws NotSupportedException, SystemException - { - if (timeoutHasBeenSet.get() != null) - { - // clean the ThreadLocal - timeoutHasBeenSet.set(null); - } - else - { - try - { - // Set the default transaction timeout - tm.setTransactionTimeout(defaultTimeout); - } - catch (Exception e) - { - LOG.warn("Cannot set the transaction timeout", e); - } - } - - // Start the transaction - tm.begin(); - } - - /** - * {@inheritDoc} - */ - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, - SecurityException, IllegalStateException, SystemException - { - tm.commit(); - } - - /** - * {@inheritDoc} - */ - public int getStatus() throws SystemException - { - return tm.getStatus(); - } - - /** - * {@inheritDoc} - */ - public Transaction getTransaction() throws SystemException - { - return tm.getTransaction(); - } - - /** - * {@inheritDoc} - */ - public void resume(final Transaction tx) throws InvalidTransactionException, IllegalStateException, - SystemException - { - tm.resume(tx); - } - - /** - * {@inheritDoc} - */ - public void rollback() throws IllegalStateException, SecurityException, SystemException - { - tm.rollback(); - } - - /** - * {@inheritDoc} - */ - public void setRollbackOnly() throws IllegalStateException, SystemException - { - tm.setRollbackOnly(); - } - - /** - * {@inheritDoc} - */ - public void setTransactionTimeout(int timeout) throws SystemException - { - tm.setTransactionTimeout(timeout); - timeoutHasBeenSet.set(true); - } - - /** - * {@inheritDoc} - */ - public Transaction suspend() throws SystemException - { - return tm.suspend(); - } - } - - /** - * This class is used to propose a default implementation of a {@link UserTransaction} - * from the {@link TransactionManager} - * @author Nicolas Filotto - * @version $Id$ - * - */ - private static class UserTransactionWrapper implements UserTransaction - { - - /** - * The {@link TransactionManager} that we will use to simulate a {@link UserTransaction} - */ - private final TransactionManager tm; - - /** - * Default Constructor - * @param tm - */ - public UserTransactionWrapper(TransactionManager tm) - { - this.tm = tm; - } - - /** - * @see javax.transaction.UserTransaction#begin() - */ - public void begin() throws NotSupportedException, SystemException - { - tm.begin(); - } - - /** - * @see javax.transaction.UserTransaction#commit() - */ - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, - SecurityException, IllegalStateException, SystemException - { - tm.commit(); - } - - /** - * @see javax.transaction.UserTransaction#rollback() - */ - public void rollback() throws IllegalStateException, SecurityException, SystemException - { - tm.rollback(); - } - - /** - * @see javax.transaction.UserTransaction#setRollbackOnly() - */ - public void setRollbackOnly() throws IllegalStateException, SystemException - { - tm.setRollbackOnly(); - } - - /** - * @see javax.transaction.UserTransaction#getStatus() - */ - public int getStatus() throws SystemException - { - return tm.getStatus(); - } - - /** - * @see javax.transaction.UserTransaction#setTransactionTimeout(int) - */ - public void setTransactionTimeout(int timeout) throws SystemException - { - tm.setTransactionTimeout(timeout); - } - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/atomikos/TransactionsEssentialsTransactionService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/atomikos/TransactionsEssentialsTransactionService.java deleted file mode 100644 index 304829a78..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/atomikos/TransactionsEssentialsTransactionService.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.impl.atomikos; - -import com.atomikos.icatch.jta.UserTransactionManager; - -import org.exoplatform.services.transaction.TransactionService; -import org.exoplatform.services.transaction.impl.AbstractTransactionService; -import org.exoplatform.services.transaction.impl.jboss.JBossTransactionService; - -import org.picocontainer.Startable; - -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; - -/** - * An implementation of a {@link TransactionService} for TransactionsEssentials from Atomikos - * to be used in standalone mode - * - * @deprecated {@link JBossTransactionService} used in all cases instead - * @author Nicolas Filotto - * @version $Id$ - * - */ -@Deprecated -public class TransactionsEssentialsTransactionService extends AbstractTransactionService implements Startable -{ - - /** - * @see org.exoplatform.services.transaction.impl.AbstractTransactionService#findTransactionManager() - */ - @Override - protected TransactionManager findTransactionManager() throws Exception - { - UserTransactionManager tm = new UserTransactionManager(); - tm.init(); - return tm; - } - - /** - * @see org.exoplatform.services.transaction.impl.AbstractTransactionService#findUserTransaction() - */ - @Override - protected UserTransaction findUserTransaction() throws Exception - { - return (UserTransaction)getTransactionManager(); - } - - /** - * @see org.picocontainer.Startable#start() - */ - public void start() - { - } - - /** - * @see org.picocontainer.Startable#stop() - */ - public void stop() - { - if (isTMInitialized()) - { - TransactionManager tm = getTransactionManager(); - if (tm instanceof UserTransactionManager) - { - UserTransactionManager utm = (UserTransactionManager)tm; - utm.close(); - } - } - } -} diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/jboss/JBossTransactionService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/jboss/JBossTransactionService.java deleted file mode 100644 index f9593a4b4..000000000 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/jboss/JBossTransactionService.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.impl.jboss; - -import org.exoplatform.services.transaction.impl.AbstractTransactionService; - -import javax.management.MBeanServer; -import javax.management.MBeanServerFactory; -import javax.management.ObjectName; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; - -/** - * @author Julien Viet - * @version $Revision$ - */ -public class JBossTransactionService extends AbstractTransactionService -{ - - /** - * {@inheritDoc} - */ - public TransactionManager findTransactionManager() - { - try - { - return (TransactionManager)new InitialContext().lookup("java:/TransactionManager"); - } - catch (NamingException e) - { - throw new IllegalStateException(e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public UserTransaction findUserTransaction() - { - try - { - return (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction"); - } - catch (NamingException e) - { - throw new IllegalStateException(e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int getDefaultTimeout() - { - try - { - MBeanServer server = (MBeanServer)MBeanServerFactory.findMBeanServer(null).iterator().next(); - return (Integer)server.getAttribute(ObjectName.getInstance("jboss:service=TransactionManager"), - "TransactionTimeout"); - } - catch (Exception e) - { - throw new IllegalStateException(e); - } - } -} diff --git a/exo.kernel.component.common/src/main/resources/conf/portal/generic-configuration.xml b/exo.kernel.component.common/src/main/resources/conf/portal/generic-configuration.xml deleted file mode 100644 index 256a68fed..000000000 --- a/exo.kernel.component.common/src/main/resources/conf/portal/generic-configuration.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - org.exoplatform.services.transaction.TransactionService - org.exoplatform.services.transaction.impl.atomikos.TransactionsEssentialsTransactionService - - - timeout - 5 - - - - - diff --git a/exo.kernel.component.common/src/main/resources/conf/standalone/configuration.xml b/exo.kernel.component.common/src/main/resources/conf/standalone/configuration.xml index 2e4140c93..fc9321c0f 100644 --- a/exo.kernel.component.common/src/main/resources/conf/standalone/configuration.xml +++ b/exo.kernel.component.common/src/main/resources/conf/standalone/configuration.xml @@ -20,10 +20,6 @@ --> - - org.exoplatform.services.net.NetService - org.exoplatform.services.net.impl.NetServiceImpl - org.exoplatform.services.listener.ListenerService diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/compress/TestCompressData.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/compress/TestCompressData.java deleted file mode 100644 index 783995e14..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/compress/TestCompressData.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.compress; - -import junit.framework.TestCase; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Created by The eXo Platform SAS Author : Chung Nguyen - * nguyenchung136@yahoo.com Feb 13, 2006 - */ -public class TestCompressData extends TestCase -{ - - public TestCompressData(String name) - { - super(name); - } - - public void testCompressData() throws Exception - { - CompressData compress = new CompressData(); - CompressData compressIS = new CompressData(); - InputStream in = new FileInputStream("src/test/resources/ZipService.java"); - InputStream in2 = new FileInputStream("src/test/resources/helper.txt"); - // ---------- TEST InputStream --------------// - compressIS.addInputStream("ZipService.java", in); - compressIS.addInputStream("helper.txt", in2); - compressIS.createJarFile("target/ZipServiceJar"); - compressIS.createZipFile("target/ZipServiceZip"); - in.close(); - in2.close(); - - // ----------- Test with Add File ------------------// - - File file = new File("src/test/resources/ZipService.java"); - File file2 = new File("src/test/resources/helper.txt"); - compress.addFile("ZipService.java", file); - compress.addFile("helper.txt", file2); - compress.createZipFile("target/testZipFile"); - compress.createJarFile("target/testJarFile"); - // compress.cleanDataInstance(); - // --------------- Test thu muc --------------------------------// - // TODO what is t? - // File folder = new File("/home/exo/setup/tailieu/chung/hcm/images"); - // File folder1 = new File("/home/exo/setup/tailieu/chung/hcm/xuly"); - // CompressData compressF = new CompressData(); - // compressF.addDir(folder); - // compressF.addDir(folder1); - // compressF.createZipFile("/home/exo/setup/tailieu/chung/hcm/TestZip"); - // compress.createJarFile("/home/exo/setup/tailieu/chung/hcm/TestJar"); - } - - /** - * Testcase based on http://jira.exoplatform.org/browse/KER-94 - * @throws Exception - */ - public void testCompressIS() throws Exception - { - - CompressData compressData = new CompressData(); - - File f1 = new File("src/test/resources/ZipService.java"); - File f2 = new File("src/test/resources/helper.txt"); - - compressData.addFile("ZipService.java", f1); - compressData.addFile("helper.txt", f2); - - OutputStream outStream = new FileOutputStream(new File("target/CompressedZipIS.zip")); - compressData.createZip(outStream); - outStream.close(); - - outStream = new FileOutputStream(new File("target/CompressedJarIS.jar")); - compressData.createJar(outStream); - outStream.close(); - - } -} diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/jdbc/impl/TestDataSourceProviderImpl.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/jdbc/impl/TestDataSourceProviderImpl.java deleted file mode 100644 index bc576bc19..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/jdbc/impl/TestDataSourceProviderImpl.java +++ /dev/null @@ -1,860 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.jdbc.impl; - -import junit.framework.TestCase; - -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.container.xml.ValuesParam; -import org.exoplatform.services.jdbc.DataSourceProvider; -import org.exoplatform.services.transaction.TransactionService; - -import java.io.PrintWriter; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; -import java.util.ArrayList; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; -import java.util.logging.Logger; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.sql.DataSource; -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.InvalidTransactionException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.Status; -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; -import javax.transaction.xa.XAResource; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestDataSourceProviderImpl extends TestCase -{ - private static String DS_NAME = "TestDataSourceProviderImpl-DS"; - - private String oldFactoryName; - - private MyDataSource mds; - - /** - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception - { - super.setUp(); - oldFactoryName = System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.exoplatform.services.naming.SimpleContextFactory"); - new InitialContext().bind(DS_NAME, mds = new MyDataSource()); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception - { - try - { - new InitialContext().unbind(DS_NAME); - } - finally - { - if (oldFactoryName == null) - { - System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); - } - else - { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, oldFactoryName); - } - super.tearDown(); - } - } - - public void testIsManaged() throws Exception - { - DataSourceProvider dsp = new DataSourceProviderImpl(null); - assertFalse(dsp.isManaged(DS_NAME)); - - InitParams params = new InitParams(); - dsp = new DataSourceProviderImpl(params); - assertFalse(dsp.isManaged(DS_NAME)); - - ValueParam paramConf = new ValueParam(); - paramConf.setName(DataSourceProviderImpl.PARAM_ALWAYS_MANAGED); - paramConf.setValue("true"); - params.addParameter(paramConf); - dsp = new DataSourceProviderImpl(params); - assertTrue(dsp.isManaged(DS_NAME)); - - paramConf.setValue("false"); - dsp = new DataSourceProviderImpl(params); - assertFalse(dsp.isManaged(DS_NAME)); - - ValuesParam paramsConf = new ValuesParam(); - paramsConf.setName(DataSourceProviderImpl.PARAM_MANAGED_DS); - ArrayList values = new ArrayList(); - values.add(DS_NAME); - values.add(" ds-foo1, ds-foo2 "); - values.add("ds-foo3"); - paramsConf.setValues(values); - params.addParameter(paramsConf); - dsp = new DataSourceProviderImpl(params); - assertTrue(dsp.isManaged(DS_NAME)); - assertTrue(dsp.isManaged("ds-foo1")); - assertTrue(dsp.isManaged("ds-foo2")); - assertTrue(dsp.isManaged("ds-foo3")); - } - - public void testGetDataSource() throws Exception - { - DataSourceProvider dsp = new DataSourceProviderImpl(null); - DataSource ds = dsp.getDataSource(DS_NAME); - assertNotNull(ds); - Connection con = ds.getConnection(); - con.commit(); - assertTrue(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertTrue(mds.con.committed); - - MyTransactionService mts = new MyTransactionService(); - mts.tm.setStatus(Status.STATUS_ACTIVE); - dsp = new DataSourceProviderImpl(null, mts); - ds = dsp.getDataSource(DS_NAME); - assertNotNull(ds); - con = ds.getConnection(); - con.commit(); - assertTrue(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertTrue(mds.con.committed); - mts.tm.setStatus(Status.STATUS_NO_TRANSACTION); - con = ds.getConnection(); - con.commit(); - assertTrue(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertTrue(mds.con.committed); - - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(DataSourceProviderImpl.PARAM_ALWAYS_MANAGED); - paramConf.setValue("true"); - params.addParameter(paramConf); - dsp = new DataSourceProviderImpl(params, mts); - ds = dsp.getDataSource(DS_NAME); - assertNotNull(ds); - mts.tm.setStatus(Status.STATUS_ACTIVE); - con = ds.getConnection(); - con.commit(); - assertFalse(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertFalse(mds.con.committed); - mts.tm.setStatus(Status.STATUS_NO_TRANSACTION); - con = ds.getConnection(); - con.commit(); - assertTrue(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertTrue(mds.con.committed); - - paramConf = new ValueParam(); - paramConf.setName(DataSourceProviderImpl.PARAM_CHECK_TX); - paramConf.setValue("false"); - params.addParameter(paramConf); - dsp = new DataSourceProviderImpl(params, mts); - ds = dsp.getDataSource(DS_NAME); - assertNotNull(ds); - mts.tm.setStatus(Status.STATUS_ACTIVE); - con = ds.getConnection(); - con.commit(); - assertFalse(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertFalse(mds.con.committed); - mts.tm.setStatus(Status.STATUS_NO_TRANSACTION); - con = ds.getConnection(); - con.commit(); - assertFalse(mds.con.committed); - con = ds.getConnection(null, null); - con.commit(); - assertFalse(mds.con.committed); - } - - private static class MyDataSource implements DataSource - { - public MyConnection con; - - /** - * @see javax.sql.CommonDataSource#getLogWriter() - */ - public PrintWriter getLogWriter() throws SQLException - { - return null; - } - - /** - * @see javax.sql.CommonDataSource#getLoginTimeout() - */ - public int getLoginTimeout() throws SQLException - { - return 0; - } - - /** - * @see javax.sql.CommonDataSource#setLogWriter(java.io.PrintWriter) - */ - public void setLogWriter(PrintWriter arg0) throws SQLException - { - } - - /** - * @see javax.sql.CommonDataSource#setLoginTimeout(int) - */ - public void setLoginTimeout(int arg0) throws SQLException - { - } - - /** - * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) - */ - public boolean isWrapperFor(Class arg0) throws SQLException - { - return false; - } - - /** - * @see java.sql.Wrapper#unwrap(java.lang.Class) - */ - public T unwrap(Class arg0) throws SQLException - { - return null; - } - - /** - * @see javax.sql.DataSource#getConnection() - */ - public Connection getConnection() throws SQLException - { - return con = new MyConnection(); - } - - /** - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - public Connection getConnection(String username, String password) throws SQLException - { - return con = new MyConnection(); - } - - /** - * @see javax.sql.CommonDataSource#getParentLogger() - */ - public Logger getParentLogger() throws SQLFeatureNotSupportedException - { - return null; - } - } - - private static class MyConnection implements Connection - { - - public boolean committed; - - /** - * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) - */ - public boolean isWrapperFor(Class iface) throws SQLException - { - return false; - } - - /** - * @see java.sql.Wrapper#unwrap(java.lang.Class) - */ - public T unwrap(Class iface) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String) - */ - public PreparedStatement prepareStatement(String sql) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String) - */ - public CallableStatement prepareCall(String sql) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#nativeSQL(java.lang.String) - */ - public String nativeSQL(String sql) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#setAutoCommit(boolean) - */ - public void setAutoCommit(boolean autoCommit) throws SQLException - { - } - - /** - * @see java.sql.Connection#commit() - */ - public void commit() throws SQLException - { - committed = true; - } - - /** - * @see java.sql.Connection#rollback() - */ - public void rollback() throws SQLException - { - } - - /** - * @see java.sql.Connection#close() - */ - public void close() throws SQLException - { - } - - /** - * @see java.sql.Connection#setReadOnly(boolean) - */ - public void setReadOnly(boolean readOnly) throws SQLException - { - } - - /** - * @see java.sql.Connection#setCatalog(java.lang.String) - */ - public void setCatalog(String catalog) throws SQLException - { - } - - /** - * @see java.sql.Connection#setTransactionIsolation(int) - */ - public void setTransactionIsolation(int level) throws SQLException - { - } - - /** - * @see java.sql.Connection#clearWarnings() - */ - public void clearWarnings() throws SQLException - { - } - - /** - * @see java.sql.Connection#createArrayOf(java.lang.String, java.lang.Object[]) - */ - public Array createArrayOf(String arg0, Object[] arg1) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createBlob() - */ - public Blob createBlob() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createClob() - */ - public Clob createClob() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createNClob() - */ - public NClob createNClob() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createSQLXML() - */ - public SQLXML createSQLXML() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createStatement() - */ - public Statement createStatement() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createStatement(int, int) - */ - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int, int) - */ - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String, int, int) - */ - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#setTypeMap(java.util.Map) - */ - public void setTypeMap(Map> map) throws SQLException - { - } - - /** - * @see java.sql.Connection#setSavepoint() - */ - public Savepoint setSavepoint() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#setSavepoint(java.lang.String) - */ - public Savepoint setSavepoint(String name) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#rollback(java.sql.Savepoint) - */ - public void rollback(Savepoint savepoint) throws SQLException - { - } - - /** - * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint) - */ - public void releaseSavepoint(Savepoint savepoint) throws SQLException - { - } - - /** - * @see java.sql.Connection#createStatement(int, int, int) - */ - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[]) - */ - public Struct createStruct(String arg0, Object[] arg1) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getAutoCommit() - */ - public boolean getAutoCommit() throws SQLException - { - return false; - } - - /** - * @see java.sql.Connection#isClosed() - */ - public boolean isClosed() throws SQLException - { - return false; - } - - /** - * @see java.sql.Connection#isReadOnly() - */ - public boolean isReadOnly() throws SQLException - { - return false; - } - - /** - * @see java.sql.Connection#getCatalog() - */ - public String getCatalog() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getClientInfo() - */ - public Properties getClientInfo() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getClientInfo(java.lang.String) - */ - public String getClientInfo(String arg0) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getMetaData() - */ - public DatabaseMetaData getMetaData() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getTransactionIsolation() - */ - public int getTransactionIsolation() throws SQLException - { - return 0; - } - - /** - * @see java.sql.Connection#getWarnings() - */ - public SQLWarning getWarnings() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getTypeMap() - */ - public Map> getTypeMap() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#getHoldability() - */ - public int getHoldability() throws SQLException - { - return 0; - } - - /** - * @see java.sql.Connection#isValid(int) - */ - public boolean isValid(int arg0) throws SQLException - { - return false; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int) - */ - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareCall(java.lang.String, int, int, int) - */ - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int) - */ - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, int[]) - */ - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#prepareStatement(java.lang.String, java.lang.String[]) - */ - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#setClientInfo(java.util.Properties) - */ - public void setClientInfo(Properties arg0) throws SQLClientInfoException - { - } - - /** - * @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String) - */ - public void setClientInfo(String arg0, String arg1) throws SQLClientInfoException - { - } - - /** - * @see java.sql.Connection#setHoldability(int) - */ - public void setHoldability(int holdability) throws SQLException - { - } - - /** - * @see java.sql.Connection#setSchema(java.lang.String) - */ - public void setSchema(String schema) throws SQLException - { - // TODO Auto-generated method stub - - } - - /** - * @see java.sql.Connection#getSchema() - */ - public String getSchema() throws SQLException - { - return null; - } - - /** - * @see java.sql.Connection#abort(java.util.concurrent.Executor) - */ - public void abort(Executor executor) throws SQLException - { - } - - /** - * @see java.sql.Connection#setNetworkTimeout(java.util.concurrent.Executor, int) - */ - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException - { - } - - /** - * @see java.sql.Connection#getNetworkTimeout() - */ - public int getNetworkTimeout() throws SQLException - { - return 0; - } - } - - private static class MyTransactionService implements TransactionService - { - public MyTransactionManager tm = new MyTransactionManager(); - - /** - * @see org.exoplatform.services.transaction.TransactionService#getTransactionManager() - */ - public TransactionManager getTransactionManager() - { - return tm; - } - - /** - * @see org.exoplatform.services.transaction.TransactionService#getUserTransaction() - */ - public UserTransaction getUserTransaction() - { - return null; - } - - /** - * @see org.exoplatform.services.transaction.TransactionService#getDefaultTimeout() - */ - public int getDefaultTimeout() - { - return 0; - } - - /** - * @see org.exoplatform.services.transaction.TransactionService#setTransactionTimeout(int) - */ - public void setTransactionTimeout(int seconds) throws SystemException - { - } - - /** - * @see org.exoplatform.services.transaction.TransactionService#enlistResource(javax.transaction.xa.XAResource) - */ - public boolean enlistResource(XAResource xares) throws RollbackException, SystemException, IllegalStateException - { - return false; - } - - /** - * @see org.exoplatform.services.transaction.TransactionService#delistResource(javax.transaction.xa.XAResource) - */ - public boolean delistResource(XAResource xares) throws RollbackException, SystemException, IllegalStateException - { - return false; - } - } - - private static class MyTransactionManager implements TransactionManager - { - - private int status; - - public void setStatus(int status) - { - this.status = status; - } - - /** - * @see javax.transaction.TransactionManager#begin() - */ - public void begin() throws NotSupportedException, SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#commit() - */ - public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, - SecurityException, IllegalStateException, SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#getStatus() - */ - public int getStatus() throws SystemException - { - return status; - } - - /** - * @see javax.transaction.TransactionManager#getTransaction() - */ - public Transaction getTransaction() throws SystemException - { - return null; - } - - /** - * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction) - */ - public void resume(Transaction tobj) throws InvalidTransactionException, IllegalStateException, SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#rollback() - */ - public void rollback() throws IllegalStateException, SecurityException, SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#setRollbackOnly() - */ - public void setRollbackOnly() throws IllegalStateException, SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#setTransactionTimeout(int) - */ - public void setTransactionTimeout(int seconds) throws SystemException - { - } - - /** - * @see javax.transaction.TransactionManager#suspend() - */ - public Transaction suspend() throws SystemException - { - return null; - } - - } -} diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java deleted file mode 100644 index f78f5d8bf..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.net.test; - -import junit.framework.TestCase; - -import org.exoplatform.container.PortalContainer; -import org.exoplatform.services.net.NetService; - -/** - * Created by The eXo Platform SAS Author : HoaPham phamvuxuanhoa@yahoo.com Jan - * 10, 2006 - */ -public class TestNetService extends TestCase -{ - private NetService service_; - - public TestNetService(String name) - { - super(name); - } - - public void setUp() throws Exception - { - if (service_ == null) - { - PortalContainer manager = PortalContainer.getInstance(); - service_ = (NetService)manager.getComponentInstanceOfType(NetService.class); - } - } - - public void tearDown() throws Exception - { - - } - - public void testNetService() throws Exception - { - ping("www.google.com", 80); - ping("www.vnexpress.net", 80); - ping("www.exoplatform.org", 80); - } - - private void ping(String host, int port) throws Exception - { - service_.ping(host, port); - } -} diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/rpc/impl/TestRPCServiceImpl.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/rpc/impl/TestRPCServiceImpl.java deleted file mode 100644 index d94cb5433..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/rpc/impl/TestRPCServiceImpl.java +++ /dev/null @@ -1,1282 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.rpc.impl; - -import junit.framework.TestCase; - -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.rpc.RPCException; -import org.exoplatform.services.rpc.RemoteCommand; -import org.exoplatform.services.rpc.SingleMethodCallCommand; -import org.exoplatform.services.rpc.TopologyChangeEvent; -import org.exoplatform.services.rpc.TopologyChangeListener; -import org.exoplatform.services.rpc.impl.AbstractRPCService.MemberHasLeftException; -import org.exoplatform.services.rpc.jgv3.RPCServiceImpl; -import org.jgroups.Address; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicReference; - -/** - * This is the unit test class for the service {@link RPCServiceImpl} - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestRPCServiceImpl extends TestCase -{ - private PortalContainer container; - private ConfigurationManager configManager; - - public void setUp() throws Exception - { - container = PortalContainer.getInstance(); - configManager = (ConfigurationManager)container.getComponentInstanceOfType(ConfigurationManager.class); - } - - public void testParameters() - { - InitParams params = null; - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a IllegalArgumentException since the jgroups config cannot be found"); - } - catch (IllegalArgumentException e) - { - // OK - } - params = new InitParams(); - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a IllegalArgumentException since the jgroups config cannot be found"); - } - catch (IllegalArgumentException e) - { - // OK - } - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - params.addParameter(paramConf); - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a IllegalArgumentException since the jgroups config cannot be found"); - } - catch (IllegalArgumentException e) - { - // OK - } - paramConf.setValue("fakePath"); - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a IllegalArgumentException since the jgroups config cannot be found"); - } - catch (IllegalArgumentException e) - { - // OK - } - paramConf.setValue("jar:/conf/portal/udp.xml"); - RPCServiceImpl service = null; - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(RPCServiceImpl.DEFAULT_TIMEOUT, service.getDefaultTimeout()); - assertEquals(RPCServiceImpl.DEFAULT_RETRY_TIMEOUT, service.getRetryTimeout()); - assertEquals(true, service.isAllowFailover()); - assertEquals(RPCServiceImpl.CLUSTER_NAME + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - ValueParam paramTimeout = new ValueParam(); - paramTimeout.setName(RPCServiceImpl.PARAM_DEFAULT_TIMEOUT); - paramTimeout.setValue("fakeValue"); - params.addParameter(paramTimeout); - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a NumberFormatException since the timeout is not properly set"); - } - catch (NumberFormatException e) - { - // OK - } - paramTimeout.setValue("60"); - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(60, service.getDefaultTimeout()); - assertEquals(RPCServiceImpl.DEFAULT_RETRY_TIMEOUT, service.getRetryTimeout()); - assertEquals(true, service.isAllowFailover()); - assertEquals(RPCServiceImpl.CLUSTER_NAME + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - ValueParam paramRetryTimeout = new ValueParam(); - paramRetryTimeout.setName(RPCServiceImpl.PARAM_RETRY_TIMEOUT); - paramRetryTimeout.setValue("fakeValue"); - params.addParameter(paramRetryTimeout); - try - { - new RPCServiceImpl(container.getContext(), params, configManager); - fail("We expect a NumberFormatException since the retry timeout is not properly set"); - } - catch (NumberFormatException e) - { - // OK - } - paramRetryTimeout.setValue("60"); - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(60, service.getDefaultTimeout()); - assertEquals(60, service.getRetryTimeout()); - assertEquals(true, service.isAllowFailover()); - assertEquals(RPCServiceImpl.CLUSTER_NAME + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - ValueParam paramAllowFailover = new ValueParam(); - paramAllowFailover.setName(RPCServiceImpl.PARAM_ALLOW_FAILOVER); - paramAllowFailover.setValue("fakeValue"); - params.addParameter(paramAllowFailover); - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(60, service.getDefaultTimeout()); - assertEquals(60, service.getRetryTimeout()); - assertEquals(false, service.isAllowFailover()); - assertEquals(RPCServiceImpl.CLUSTER_NAME + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - paramAllowFailover.setValue("TRUE"); - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(60, service.getDefaultTimeout()); - assertEquals(60, service.getRetryTimeout()); - assertEquals(true, service.isAllowFailover()); - assertEquals(RPCServiceImpl.CLUSTER_NAME + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - - ValueParam paramClusterName = new ValueParam(); - paramClusterName.setName(RPCServiceImpl.PARAM_CLUSTER_NAME); - paramClusterName.setValue("MyName"); - params.addParameter(paramClusterName); - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - assertEquals(60, service.getDefaultTimeout()); - assertEquals(paramClusterName.getValue() + "-" + container.getContext().getName(), service.getClusterName()); - } - finally - { - if (service != null) - { - service.stop(); - } - } - } - - public void testStates() throws Exception - { - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - RPCServiceImpl service = null; - RemoteCommand foo = new RemoteCommand() - { - - public String getId() - { - return "foo"; - } - - public String execute(Serializable[] args) throws Throwable - { - return null; - } - }; - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - - service.registerCommand(foo); - try - { - service.executeCommandOnAllNodes(foo, true); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnAllNodes(foo, 10); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(foo, true); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(foo, 100); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.isCoordinator(); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - service.start(); - assertEquals(true, service.isCoordinator()); - service.executeCommandOnAllNodes(foo, true); - service.executeCommandOnAllNodes(foo, 100); - service.executeCommandOnCoordinator(foo, true); - service.executeCommandOnCoordinator(foo, 100); - } - finally - { - if (service != null) - { - service.stop(); - } - } - try - { - service.executeCommandOnAllNodes(foo, true); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnAllNodes(foo, 10); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(foo, true); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(foo, 100); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - } - - public void testCommands() throws Exception - { - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - RPCServiceImpl service = null; - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - RemoteCommand fake = new RemoteCommand() - { - - public String getId() - { - return "fake"; - } - - public String execute(Serializable[] args) throws Throwable - { - return null; - } - }; - RemoteCommand fake2 = new RemoteCommand() - { - - public String getId() - { - return "fake2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return null; - } - }; - RemoteCommand fake2_Unregistered = new RemoteCommand() - { - - public String getId() - { - return "fake2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return null; - } - }; - service.registerCommand(fake2); - RemoteCommand Exception = new RemoteCommand() - { - - public String getId() - { - return "Exception"; - } - - public String execute(Serializable[] args) throws Throwable - { - throw new Exception("MyException"); - } - }; - service.registerCommand(Exception); - RemoteCommand Error = new RemoteCommand() - { - - public String getId() - { - return "Error"; - } - - public String execute(Serializable[] args) throws Throwable - { - throw new Error("MyError"); - } - } ; - service.registerCommand(Error); - RemoteCommand StringValue = new RemoteCommand() - { - - public String getId() - { - return "StringValue"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service.registerCommand(StringValue); - RemoteCommand NullValue = new RemoteCommand() - { - - public String getId() - { - return "NullValue"; - } - - public String execute(Serializable[] args) throws Throwable - { - return null; - } - }; - service.registerCommand(NullValue); - RemoteCommand LongTask = new RemoteCommand() - { - - public String getId() - { - return "LongTask"; - } - - public String execute(Serializable[] args) throws Throwable - { - Thread.sleep(2000); - return null; - } - }; - service.registerCommand(LongTask); - service.start(); - try - { - service.executeCommandOnAllNodes(fake, true); - fail("We expect a RPCException since the command is unknown"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(fake, true); - fail("We expect a RPCException since the command is unknown"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnAllNodes(fake2_Unregistered, true); - fail("We expect a RPCException since the command is unknown"); - } - catch (RPCException e) - { - // OK - } - try - { - service.executeCommandOnCoordinator(fake2_Unregistered, true); - fail("We expect a RPCException since the command is unknown"); - } - catch (RPCException e) - { - // OK - } - List result; - result = service.executeCommandOnAllNodes(Exception, true); - assertTrue(result != null && result.size() == 1); - assertTrue("We expect a RPCException since one node could not execute the command", result.get(0) instanceof RPCException); - try - { - service.executeCommandOnCoordinator(Exception, true); - fail("We expect a RPCException since one node could not execute the command"); - } - catch (RPCException e) - { - // OK - } - result = service.executeCommandOnAllNodes(Error, true); - assertTrue(result != null && result.size() == 1); - assertTrue("We expect a RPCException since one node could not execute the command", result.get(0) instanceof RPCException); - try - { - service.executeCommandOnCoordinator(Error, true); - fail("We expect a RPCException since one node could not execute the command"); - } - catch (RPCException e) - { - // OK - } - result = service.executeCommandOnAllNodes(LongTask, true); - assertNotNull(result); - assertTrue(result.size() == 1); - assertNull(result.get(0)); - Object o = service.executeCommandOnCoordinator(LongTask, true); - assertNull(o); - result = service.executeCommandOnAllNodes(LongTask, 1000); - assertNotNull(result); - assertTrue(result.size() == 1); - assertTrue("We expect an RPCException due to a Replication Timeout", result.get(0) instanceof RPCException); - try - { - service.executeCommandOnCoordinator(LongTask, 1000); - fail("We expect an RPCException due to a Replication Timeout"); - } - catch (RPCException e) - { - // OK - } - result = service.executeCommandOnAllNodes(LongTask, false); - assertNotNull(result); - assertTrue(result.isEmpty()); - assertNull(service.executeCommandOnCoordinator(LongTask, false)); - - result = service.executeCommandOnAllNodes(StringValue, true); - assertNotNull(result); - assertTrue(result.size() == 1); - assertEquals("OK", result.get(0)); - o = service.executeCommandOnCoordinator(StringValue, true); - assertEquals("OK", o); - result = service.executeCommandOnAllNodes(NullValue, true); - assertNotNull(result); - assertTrue(result.size() == 1); - assertNull(result.get(0)); - o = service.executeCommandOnCoordinator(NullValue, true); - assertNull(o); - } - finally - { - if (service != null) - { - service.stop(); - } - } - } - - public void testSeveralNodes() throws Exception - { - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - RPCServiceImpl service1 = null, service2 = null; - try - { - service1 = new RPCServiceImpl(container.getContext(), params, configManager); - service2 = new RPCServiceImpl(container.getContext(), params, configManager); - RemoteCommand CmdUnknownOnNode2 = new RemoteCommand() - { - - public String getId() - { - return "CmdUnknownOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service1.registerCommand(CmdUnknownOnNode2); - RemoteCommand ExceptionOnNode2 = new RemoteCommand() - { - - public String getId() - { - return "ExceptionOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service1.registerCommand(ExceptionOnNode2); - RemoteCommand ErrorOnNode2 = new RemoteCommand() - { - - public String getId() - { - return "ErrorOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service1.registerCommand(ErrorOnNode2); - - RemoteCommand LongTaskOnNode2 = new RemoteCommand() - { - - public String getId() - { - return "LongTaskOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service1.registerCommand(LongTaskOnNode2); - service1.registerCommand(new RemoteCommand() - { - - public String getId() - { - return "LongTask"; - } - - public String execute(Serializable[] args) throws Throwable - { - Thread.sleep(3000); - return "OldCoordinator"; - } - }); - service1.registerCommand(new RemoteCommand() - { - - public String getId() - { - return "OK"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }); - service2.registerCommand(new RemoteCommand() - { - - public String getId() - { - return "ExceptionOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - throw new Exception("MyException"); - } - }); - service2.registerCommand(new RemoteCommand() - { - - public String getId() - { - return "ErrorOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - throw new Error("MyError"); - } - }); - service2.registerCommand(new RemoteCommand() - { - - public String getId() - { - return "LongTaskOnNode2"; - } - - public String execute(Serializable[] args) throws Throwable - { - Thread.sleep(2000); - return null; - } - }); - RemoteCommand OK = new RemoteCommand() - { - - public String getId() - { - return "OK"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "OK"; - } - }; - service2.registerCommand(OK); - final RemoteCommand LongTask = new RemoteCommand() - { - - public String getId() - { - return "LongTask"; - } - - public String execute(Serializable[] args) throws Throwable - { - return "NewCoordinator"; - } - }; - service2.registerCommand(LongTask); - MyListener listener1 = new MyListener(); - service1.registerTopologyChangeListener(listener1); - MyListener listener2 = new MyListener(); - service2.registerTopologyChangeListener(listener2); - assertFalse(listener1.coordinatorHasChanged); - assertFalse(listener1.isCoordinator); - assertEquals(0, listener1.count); - assertFalse(listener2.coordinatorHasChanged); - assertFalse(listener2.isCoordinator); - assertEquals(0, listener2.count); - service1.start(); - assertFalse(listener1.coordinatorHasChanged); - assertTrue(listener1.isCoordinator); - assertEquals(1, listener1.count); - assertFalse(listener2.coordinatorHasChanged); - assertFalse(listener2.isCoordinator); - assertEquals(0, listener2.count); - service2.start(); - assertFalse(listener2.coordinatorHasChanged); - assertFalse(listener2.isCoordinator); - assertEquals(1, listener2.count); - assertFalse(listener1.coordinatorHasChanged); - assertTrue(listener1.isCoordinator); - assertEquals(2, listener1.count); - assertEquals(true, service1.isCoordinator()); - assertEquals(false, service2.isCoordinator()); - List result; - Object o; - result = service1.executeCommandOnAllNodes(CmdUnknownOnNode2, true); - assertTrue(result != null && result.size() == 2); - assertEquals("OK", result.get(0)); - assertTrue("We expect a RPCException since the command is unknown on node 2", result.get(1) instanceof RPCException); - o = service1.executeCommandOnCoordinator(CmdUnknownOnNode2, true); - assertEquals("OK", o); - - result = service1.executeCommandOnAllNodes(ExceptionOnNode2, true); - assertTrue(result != null && result.size() == 2); - assertEquals("OK", result.get(0)); - assertTrue("We expect a RPCException since the command fails on node 2", result.get(1) instanceof RPCException); - o = service1.executeCommandOnCoordinator(ExceptionOnNode2, true); - assertEquals("OK", o); - - result = service1.executeCommandOnAllNodes(ErrorOnNode2, true); - assertTrue(result != null && result.size() == 2); - assertEquals("OK", result.get(0)); - assertTrue("We expect a RPCException since the command fails on node 2", result.get(1) instanceof RPCException); - o = service1.executeCommandOnCoordinator(ErrorOnNode2, true); - assertEquals("OK", o); - - result = service1.executeCommandOnAllNodes(LongTaskOnNode2, 1000); - assertNotNull(result); - assertTrue(result.size() == 2); - assertEquals("OK", result.get(0)); - assertTrue("We expect an RPCException due to a Replication Timeout", result.get(1) instanceof RPCException); - o = service1.executeCommandOnCoordinator(LongTaskOnNode2, 1000); - assertEquals("OK", o); - - List
allMembers = service1.members; - List
coordinatorOnly = new ArrayList
(1); - coordinatorOnly.add(service1.coordinator); - - final RPCServiceImpl service = service2; - final AtomicReference error = new AtomicReference(); - final CountDownLatch doneSignal = new CountDownLatch(1); - Thread t = new Thread() - { - @Override - public void run() - { - try - { - Object o = service.executeCommandOnCoordinator(LongTask, true); - assertEquals("NewCoordinator", o); - } - catch (Throwable e) - { - error.set(e); - e.printStackTrace(); - } - finally - { - doneSignal.countDown(); - } - } - }; - t.start(); - service1.stop(); - listener2.waitTopologyChange(); - assertFalse(listener1.coordinatorHasChanged); - assertTrue(listener1.isCoordinator); - assertEquals(2, listener1.count); - assertTrue(listener2.coordinatorHasChanged); - assertTrue(listener2.isCoordinator); - assertEquals(2, listener2.count); - doneSignal.await(); - assertNull(error.get() != null ? error.get().getMessage() : "", error.get()); - result = service2.excecuteCommand(allMembers, OK, true, 0); - assertNotNull(result); - assertTrue(result.size() == 2); - assertTrue("We expect an RPCException due to a member that has left", result.get(0) instanceof MemberHasLeftException); - assertEquals("OK", result.get(1)); - result = service2.excecuteCommand(coordinatorOnly, OK, true, 0); - assertNotNull(result); - assertTrue(result.size() == 1); - assertTrue("We expect an RPCException due to a member that has left", result.get(0) instanceof MemberHasLeftException); - try - { - service1.isCoordinator(); - fail("We expect a RPCException since the current state is not the expected one"); - } - catch (RPCException e) - { - // OK - } - assertEquals(true, service2.isCoordinator()); - } - finally - { - if (service1 != null) - { - service1.stop(); - } - if (service2 != null) - { - service2.stop(); - } - } - } - - public void testSingleMethodCallCommand() throws Exception - { - try - { - new SingleMethodCallCommand(null, null); - fail("we expect an IllegalArgumentException"); - } - catch (IllegalArgumentException e) - { - // OK - } - MyService myService = new MyService(); - try - { - new SingleMethodCallCommand(myService, null); - fail("we expect an IllegalArgumentException"); - } - catch (IllegalArgumentException e) - { - // OK - } - try - { - new SingleMethodCallCommand(myService, "foo"); - fail("we expect an NoSuchMethodException"); - } - catch (NoSuchMethodException e) - { - // OK - } - try - { - new SingleMethodCallCommand(myService, "getPrivateName"); - fail("we expect an IllegalArgumentException since only the public methods are allowed"); - } - catch (IllegalArgumentException e) - { - // OK - } - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - RPCServiceImpl service = null; - try - { - service = new RPCServiceImpl(container.getContext(), params, configManager); - RemoteCommand getName = service.registerCommand(new SingleMethodCallCommand(myService, "getName")); - RemoteCommand add = service.registerCommand(new SingleMethodCallCommand(myService, "add", int.class)); - RemoteCommand evaluate1 = service.registerCommand(new SingleMethodCallCommand(myService, "evaluate", int[].class)); - RemoteCommand evaluate2 = service.registerCommand(new SingleMethodCallCommand(myService, "evaluate", List.class)); - RemoteCommand total1 = service.registerCommand(new SingleMethodCallCommand(myService, "total", int.class)); - RemoteCommand total2 = service.registerCommand(new SingleMethodCallCommand(myService, "total", int.class, int.class)); - RemoteCommand total3 = service.registerCommand(new SingleMethodCallCommand(myService, "total", int[].class)); - RemoteCommand total4 = service.registerCommand(new SingleMethodCallCommand(myService, "total", String.class, long.class, int[].class)); - RemoteCommand testTypes1 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", String[].class)); - RemoteCommand testTypes2 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", int[].class)); - RemoteCommand testTypes3 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", long[].class)); - RemoteCommand testTypes4 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", byte[].class)); - RemoteCommand testTypes5 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", short[].class)); - RemoteCommand testTypes6 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", char[].class)); - RemoteCommand testTypes7 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", double[].class)); - RemoteCommand testTypes8 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", float[].class)); - RemoteCommand testTypes9 = service.registerCommand(new SingleMethodCallCommand(myService, "testTypes", boolean[].class)); - - service.start(); - List result; - - assertEquals("name", service.executeCommandOnCoordinator(getName, true)); - result = service.executeCommandOnAllNodes(getName, true); - assertTrue(result != null && result.size() == 1); - assertEquals("name", result.get(0)); - - assertEquals(10, service.executeCommandOnCoordinator(add, true, 10)); - result = service.executeCommandOnAllNodes(add, true, 10); - assertTrue(result != null && result.size() == 1); - assertEquals(20, result.get(0)); - - assertEquals(100, service.executeCommandOnCoordinator(evaluate1, true, new int[]{10, 10, 10, 30, 40})); - result = service.executeCommandOnAllNodes(evaluate1, true, new int[]{10, 10, 10, 30, 40}); - assertTrue(result != null && result.size() == 1); - assertEquals(100, result.get(0)); - - List values = new ArrayList(); - values.add(10); - values.add(10); - values.add(10); - values.add(30); - values.add(40); - assertEquals(100, service.executeCommandOnCoordinator(evaluate2, true, (Serializable)values)); - result = service.executeCommandOnAllNodes(evaluate2, true, (Serializable)values); - assertTrue(result != null && result.size() == 1); - assertEquals(100, result.get(0)); - - assertEquals(10, service.executeCommandOnCoordinator(total1, true, 10)); - result = service.executeCommandOnAllNodes(total1, true, 10); - assertTrue(result != null && result.size() == 1); - assertEquals(10, result.get(0)); - - assertEquals(20, service.executeCommandOnCoordinator(total2, true, 10, 10)); - result = service.executeCommandOnAllNodes(total2, true, 10, 10); - assertTrue(result != null && result.size() == 1); - assertEquals(20, result.get(0)); - - assertEquals(100, service.executeCommandOnCoordinator(total3, true, new int[]{10, 10, 10, 30, 40})); - result = service.executeCommandOnAllNodes(total3, true, new int[]{10, 10, 10, 30, 40}); - assertTrue(result != null && result.size() == 1); - assertEquals(100, result.get(0)); - - assertEquals(100, service.executeCommandOnCoordinator(total4, true, "foo", 50, new int[]{10, 10, 10, 30, 40})); - result = service.executeCommandOnAllNodes(total4, true, "foo", 50, new int[]{10, 10, 10, 30, 40}); - assertTrue(result != null && result.size() == 1); - assertEquals(100, result.get(0)); - - assertEquals(0, service.executeCommandOnCoordinator(total4, true, "foo", 50, null)); - result = service.executeCommandOnAllNodes(total4, true, "foo", 50, null); - assertTrue(result != null && result.size() == 1); - assertEquals(0, result.get(0)); - - try - { - service.executeCommandOnCoordinator(total4, true, "foo", 50); - fail("We expect a RPCException since the list of arguments mismatch with what is expected"); - } - catch (RPCException e) - { - // OK - } - result = service.executeCommandOnAllNodes(total4, true, "foo", 50); - assertTrue(result != null && result.size() == 1); - assertTrue("We expect a RPCException since the list of arguments mismatch with what is expected", result.get(0) instanceof RPCException); - - assertEquals("foo", service.executeCommandOnCoordinator(testTypes1, true, (Serializable)new String[]{"foo"})); - result = service.executeCommandOnAllNodes(testTypes1, true, (Serializable)new String[]{"foo"}); - assertTrue(result != null && result.size() == 1); - assertEquals("foo", result.get(0)); - - assertEquals(10, service.executeCommandOnCoordinator(testTypes2, true, new int[]{10})); - result = service.executeCommandOnAllNodes(testTypes2, true, new int[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals(10, result.get(0)); - - assertEquals(11L, service.executeCommandOnCoordinator(testTypes3, true, new long[]{10})); - result = service.executeCommandOnAllNodes(testTypes3, true, new long[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals(11L, result.get(0)); - - assertEquals((byte)12, service.executeCommandOnCoordinator(testTypes4, true, new byte[]{10})); - result = service.executeCommandOnAllNodes(testTypes4, true, new byte[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals((byte)12, result.get(0)); - - assertEquals((short)13, service.executeCommandOnCoordinator(testTypes5, true, new short[]{10})); - result = service.executeCommandOnAllNodes(testTypes5, true, new short[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals((short)13, result.get(0)); - - assertEquals('a', service.executeCommandOnCoordinator(testTypes6, true, new char[]{'a'})); - result = service.executeCommandOnAllNodes(testTypes6, true, new char[]{'a'}); - assertTrue(result != null && result.size() == 1); - assertEquals('a', result.get(0)); - - assertEquals(10.5, service.executeCommandOnCoordinator(testTypes7, true, new double[]{10})); - result = service.executeCommandOnAllNodes(testTypes7, true, new double[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals(10.5, result.get(0)); - - assertEquals((float)11.5, service.executeCommandOnCoordinator(testTypes8, true, new float[]{10})); - result = service.executeCommandOnAllNodes(testTypes8, true, new float[]{10}); - assertTrue(result != null && result.size() == 1); - assertEquals((float)11.5, result.get(0)); - - assertEquals(true, service.executeCommandOnCoordinator(testTypes9, true, new boolean[]{true})); - result = service.executeCommandOnAllNodes(testTypes9, true, new boolean[]{true}); - assertTrue(result != null && result.size() == 1); - assertEquals(true, result.get(0)); - - } - finally - { - if (service != null) - { - service.stop(); - } - } - } - - public static class MyService - { - private int value = 0; - - public int add(int i) - { - return value += i; - } - - @SuppressWarnings("unused") - private String getPrivateName() - { - return "name"; - } - - public String getName() - { - return "name"; - } - - public int total(int i) - { - return i; - } - - public int total(int i1, int i2) - { - return i1 + i2; - } - - public int total(int... values) - { - int total = 0; - for (int i : values) - { - total += i; - } - return total; - } - - public int total(String s, long l, int... values) - { - int total = 0; - if (values != null) - { - for (int i : values) - { - total += i; - } - } - return total; - } - - public int evaluate(int[] values) - { - int total = 0; - for (int i : values) - { - total += i; - } - return total; - } - - public int evaluate(List values) - { - int total = 0; - for (int i : values) - { - total += i; - } - return total; - } - - public String testTypes(String... values) - { - return values[0]; - } - - public boolean testTypes(boolean... values) - { - return values[0]; - } - - public char testTypes(char... values) - { - return values[0]; - } - - public double testTypes(double... values) - { - return values[0] + 0.5; - } - - public float testTypes(float... values) - { - return (float)(values[0] + 1.5); - } - - public int testTypes(int... values) - { - return values[0]; - } - - public long testTypes(long... values) - { - return values[0] + 1; - } - - public byte testTypes(byte... values) - { - return (byte)(values[0] + 2); - } - - public short testTypes(short... values) - { - return (short)(values[0] + 3); - } - } - - public void testExecOnCoordinator() throws Exception - { - InitParams params = new InitParams(); - ValueParam paramConf = new ValueParam(); - paramConf.setName(RPCServiceImpl.PARAM_JGROUPS_CONFIG); - paramConf.setValue("jar:/conf/portal/udp.xml"); - params.addParameter(paramConf); - - final List calledCommands = Collections.synchronizedList(new ArrayList()); - - RPCServiceImpl service1 = null; - RPCServiceImpl service2 = null; - try - { - service1 = new RPCServiceImpl(container.getContext(), params, configManager); - RemoteCommand service1Cmd = new RemoteCommand() - { - public String getId() - { - return "CoordinatorExecutedCommand"; - } - - public String execute(Serializable[] args) throws Throwable - { - calledCommands.add(Boolean.TRUE); - return "service 1"; - } - }; - service1.registerCommand(service1Cmd); - - service2 = new RPCServiceImpl(container.getContext(), params, configManager); - RemoteCommand service2Cmd = new RemoteCommand() - { - public String getId() - { - return "CoordinatorExecutedCommand"; - } - - public String execute(Serializable[] args) throws Throwable - { - calledCommands.add(Boolean.TRUE); - return "service 2"; - } - }; - service2.registerCommand(service2Cmd); - // starting services - service1.start(); - service2.start(); - - Object o = service1.executeCommandOnCoordinator(service1Cmd, true); - assertEquals("service 1", o); - - // it should be executed once - assertEquals(1, calledCommands.size()); - } - finally - { - if (service1 != null) - { - service1.stop(); - } - if (service2 != null) - { - service2.stop(); - } - } - } - - private static class MyListener implements TopologyChangeListener - { - - private boolean coordinatorHasChanged; - private boolean isCoordinator; - private int count; - - private CountDownLatch lock = new CountDownLatch(2); - - /** - * @see org.exoplatform.services.rpc.TopologyChangeListener#onChange(org.exoplatform.services.rpc.TopologyChangeEvent) - */ - public void onChange(TopologyChangeEvent event) - { - this.coordinatorHasChanged = event.isCoordinatorHasChanged(); - this.isCoordinator = event.isCoordinator(); - count++; - - lock.countDown(); - } - - public void waitTopologyChange() throws InterruptedException - { - lock.await(); - } - } -} diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/TransactionTest.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/TransactionTest.java deleted file mode 100644 index 2df5fa207..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/TransactionTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction; - -import junit.framework.TestCase; - -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.StandaloneContainer; - -import javax.naming.InitialContext; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; - -/** - * Created by The eXo Platform SAS .
Prerequisites: default-context-factory - * = org.exoplatform.services.naming.impl.SimpleContextFactory - * - * @author Gennady Azarenkov - * @version $Id: $ - */ -public class TransactionTest extends TestCase -{ - - private StandaloneContainer container; - - private TransactionService ts; - - public void setUp() throws Exception - { - ExoContainer topContainer = ExoContainerContext.getTopContainer(); - if(topContainer != null) { - topContainer.stop(); - } - StandaloneContainer.setConfigurationPath("src/test/resources/conf/standalone/test-configuration.xml"); - - container = StandaloneContainer.getInstance(); - - ts = (TransactionService)container.getComponentInstanceOfType(TransactionService.class); - // Needed to ensure that the TM is properly initialized before calling testUserTransactionFromJndi - // otherwise we can get a NPE - ts.getUserTransaction(); - } - - public void testUserTransactionBeforeResource() throws Exception - { - - UserTransaction ut = ts.getUserTransaction(); - ut.begin(); - - XAResourceTestImpl xares = new XAResourceTestImpl(ts); - ts.enlistResource(xares); - - xares.setFlag(5); - assertEquals(0, xares.getOldFlag()); - ts.delistResource(xares); - ut.commit(); - assertEquals(5, xares.getFlag()); - assertEquals(5, xares.getOldFlag()); - } - - public void testUserTransactionAfterResource() throws Exception - { - - XAResourceTestImpl xares = new XAResourceTestImpl(ts); - try - { - ts.enlistResource(xares); - fail("IllegalStateException is expected since it cannot be enlisted without an active tx"); - } - catch (IllegalStateException e) - { - // OK - } - - assertEquals(0, xares.getFlag()); - UserTransaction ut = ts.getUserTransaction(); - ut.begin(); - ts.enlistResource(xares); - xares.setFlag(5); - assertEquals(0, xares.getOldFlag()); - ut.commit(); - assertEquals(5, xares.getFlag()); - assertEquals(5, xares.getOldFlag()); - - try - { - ts.delistResource(xares); - fail("IllegalStateException is expected since it cannot be delisted without an active tx"); - } - catch (IllegalStateException e) - { - // OK - } - - } - - public void testUserTransactionRollback() throws Exception - { - XAResourceTestImpl xares = new XAResourceTestImpl(ts); - assertEquals(0, xares.getFlag()); - UserTransaction ut = ts.getUserTransaction(); - ut.begin(); - ts.enlistResource(xares); - xares.setFlag(5); - assertEquals(5, xares.getFlag()); - ts.delistResource(xares); - ut.rollback(); - assertEquals(0, xares.getFlag()); - assertEquals(0, xares.getOldFlag()); - - } - - public void testSimpleGlobalTransaction() throws Exception - { - XAResourceTestImpl xares = new XAResourceTestImpl(ts); - UserTransaction ut = ts.getUserTransaction(); - ut.begin(); - ts.enlistResource(xares); - assertEquals(0, xares.getFlag()); - xares.setFlag(1); - ut.commit(); - assertEquals(1, xares.getFlag()); - assertEquals(1, xares.getOldFlag()); - } - - public void test2GlobalTransactions() throws Exception - { - XAResourceTestImpl xares = new XAResourceTestImpl(ts); - TransactionManager tm = ts.getTransactionManager(); - tm.begin(); - ts.enlistResource(xares); - assertEquals(0, xares.getFlag()); - xares.setFlag(1); - Transaction tx = tm.suspend(); - assertEquals(1, xares.getFlag()); - - tm.begin(); - ts.enlistResource(xares); - xares.setFlag(2); - - // End work - tm.commit(); - - // Resume work with former transaction - tm.resume(tx); - - // Commit work recorded when associated with xid2 - tm.commit(); - assertEquals(2, xares.getFlag()); - assertEquals(2, xares.getOldFlag()); - } - -} diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/XAResourceTestImpl.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/XAResourceTestImpl.java deleted file mode 100644 index 464e39ed7..000000000 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/transaction/XAResourceTestImpl.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2009 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction; - -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import javax.transaction.Status; -import javax.transaction.xa.XAException; -import javax.transaction.xa.XAResource; -import javax.transaction.xa.Xid; - -/** - * Created by The eXo Platform SAS. - * - * @author Gennady - * Azarenkov - * @version $Id: $ - */ - -public class XAResourceTestImpl implements XAResource -{ - - private static Log log = ExoLogger.getLogger("exo.kernel.component.common.XAResourceTestImpl"); - - private int timeout = 5; - - private int oldFlag; - - private int flag = oldFlag = 0; - - private final TransactionService ts; - - public XAResourceTestImpl(TransactionService ts) - { - this.ts = ts; - } - - public void commit(Xid arg0, boolean arg1) throws XAException - { - oldFlag = flag; - log.info("Commit " + arg0); - } - - public void end(Xid arg0, int arg1) throws XAException - { - log.info("End " + arg0); - } - - public void forget(Xid arg0) throws XAException - { - log.info("Forget " + arg0); - } - - public int getTransactionTimeout() throws XAException - { - return timeout; - } - - public boolean isSameRM(XAResource arg0) throws XAException - { - return false; - } - - public int prepare(Xid arg0) throws XAException - { - log.info("Prepare " + arg0); - return Status.STATUS_PREPARED; - } - - public Xid[] recover(int arg0) throws XAException - { - log.info("recover " + arg0); - return null; - } - - public void rollback(Xid arg0) throws XAException - { - flag = oldFlag; - log.info("Rollback " + arg0); - } - - public boolean setTransactionTimeout(int arg0) throws XAException - { - this.timeout = arg0; - return true; - } - - public void start(Xid arg0, int arg1) throws XAException - { - log.info("Start " + arg0); - } - - public int getFlag() - { - return flag; - } - - public void setFlag(int flag) - { - this.flag = flag; - } - - public int getOldFlag() - { - return oldFlag; - } -} diff --git a/exo.kernel.component.common/src/test/resources/conf/portal/test-configuration.xml b/exo.kernel.component.common/src/test/resources/conf/portal/test-configuration.xml index 6ad01b362..e9a9ceb0a 100644 --- a/exo.kernel.component.common/src/test/resources/conf/portal/test-configuration.xml +++ b/exo.kernel.component.common/src/test/resources/conf/portal/test-configuration.xml @@ -27,16 +27,6 @@ org.exoplatform.services.scheduler.test.TestSchedulerService$MyComponent - - - org.exoplatform.services.net.NetService - org.exoplatform.services.net.impl.NetServiceImpl - - - - org.exoplatform.services.compress.CompressData - org.exoplatform.services.compress.CompressData - org.exoplatform.services.listener.ListenerService @@ -129,32 +119,6 @@ - - - tx.userTransaction - addPlugin - org.exoplatform.services.naming.BindReferencePlugin - - - bind-name - UserTransaction - - - class-name - javax.transaction.UserTransaction - - - factory - org.objectweb.jotm.UserTransactionFactory - - - - ref-addresses - ref-addresses - - - - diff --git a/exo.kernel.component.common/src/test/resources/conf/portal/udp.xml b/exo.kernel.component.common/src/test/resources/conf/portal/udp.xml deleted file mode 100644 index 0c35d1f29..000000000 --- a/exo.kernel.component.common/src/test/resources/conf/portal/udp.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.common/src/test/resources/conf/standalone/test-configuration.xml b/exo.kernel.component.common/src/test/resources/conf/standalone/test-configuration.xml index 5cc591a7a..8fd9f667f 100644 --- a/exo.kernel.component.common/src/test/resources/conf/standalone/test-configuration.xml +++ b/exo.kernel.component.common/src/test/resources/conf/standalone/test-configuration.xml @@ -53,32 +53,6 @@ - - - tx.userTransaction - addPlugin - org.exoplatform.services.naming.BindReferencePlugin - - - bind-name - UserTransaction - - - class-name - javax.transaction.UserTransaction - - - factory - org.objectweb.jotm.UserTransactionFactory - - - - ref-addresses - ref-addresses - - - - diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml deleted file mode 100644 index 37a09a6ac..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - - - 4.0.0 - - io.meeds.kernel - kernel-parent - 7.0.x-SNAPSHOT - - exo.kernel.component.ext.cache.impl.infinispan.v8 - Meeds:: PLF:: Kernel :: Cache Extension :: Infinispan Implementation - Infinispan Implementation of Cache Service for Exoplatform SAS 'eXo Kernel' project. - - 0.6 - - - - io.meeds.kernel - exo.kernel.commons.test - test - - - io.meeds.kernel - exo.kernel.component.cache - - - io.meeds.kernel - exo.kernel.component.common - - - org.jgroups - jgroups - - - - - org.infinispan - infinispan-core - - - org.jboss.spec.javax.transaction - jboss-transaction-api_1.1_spec - - - org.jboss.logging - jboss-logging - - - org.jgroups - jgroups - - - - - org.jboss.logging - jboss-logging - - - org.jboss.jbossts - jbossjta - - - org.jgroups - jgroups - runtime - - - io.meeds.kernel - exo.kernel.container - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true - - - - jgroups.bind_addr - 127.0.0.1 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - maven-antrun-plugin - - - prepare-test-policy - process-test-resources - - - Creating Access Policy for tests - - - - - - - - - - - - - - - - - run - - - - - - ant - ant-optional - 1.5.3-1 - - - - - - diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java deleted file mode 100644 index 25b2d5c74..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java +++ /dev/null @@ -1,752 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.services.cache.CacheInfo; -import org.exoplatform.services.cache.CacheListener; -import org.exoplatform.services.cache.CacheListenerContext; -import org.exoplatform.services.cache.CacheMode; -import org.exoplatform.services.cache.CachedObjectSelector; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ObjectCacheInfo; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.infinispan.AdvancedCache; -import org.infinispan.Cache; -import org.infinispan.container.entries.InternalCacheEntry; -import org.infinispan.context.Flag; -import org.infinispan.notifications.Listener; -import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; -import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * An {@link org.exoplatform.services.cache.ExoCache} implementation based on {@link Cache}. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public abstract class AbstractExoCache implements ExoCache -{ - - /** - * Logger. - */ - private static final Log LOG = ExoLogger.getLogger(AbstractExoCache.class); - - private final AtomicInteger hits = new AtomicInteger(0); - - private final AtomicInteger misses = new AtomicInteger(0); - - private String label; - - private String name; - - private boolean distributed; - - private boolean replicated; - - private boolean asynchronous; - - private boolean logEnabled; - - private final CopyOnWriteArrayList> listeners; - - protected final AdvancedCache cache; - - public AbstractExoCache(ExoCacheConfig config, Cache cache) - { - this.cache = cache.getAdvancedCache(); - this.listeners = new CopyOnWriteArrayList>(); - setDistributed(config.isDistributed()); - setLabel(config.getLabel()); - setName(config.getName()); - setLogEnabled(config.isLogEnabled()); - setReplicated(config.isRepicated()); - CacheMode cacheMode = config.getCacheMode(); - setAsynchronous(cacheMode != null && !cacheMode.isSync()); - cache.addListener(new CacheEventListener()); - } - - /** - * {@inheritDoc} - */ - public void addCacheListener(CacheListener listener) - { - if (listener == null) - { - throw new IllegalArgumentException("The listener cannot be null"); - } - listeners.add(new ListenerContext(listener, this)); - } - - /** - * {@inheritDoc} - */ - public void clearCache() - { - cache.withFlags(Flag.CACHE_MODE_LOCAL).clear(); - onClearCache(); - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public V get(Serializable name) - { - if (name == null) - { - return null; - } - final V result = cache.get(name); - if (result == null) - { - misses.incrementAndGet(); - } - else - { - hits.incrementAndGet(); - } - onGet((K)name, result); - return result; - } - - /** - * {@inheritDoc} - */ - public int getCacheHit() - { - return hits.get(); - } - - /** - * {@inheritDoc} - */ - public int getCacheMiss() - { - return misses.get(); - } - - /** - * {@inheritDoc} - */ - public int getCacheSize() - { - return cache.withFlags(Flag.CACHE_MODE_LOCAL).size(); - } - - /** - * {@inheritDoc} - */ - public List getCachedObjects() - { - Collection values = cache.withFlags(Flag.CACHE_MODE_LOCAL).values(); - if (values == null || values.isEmpty()) - { - return Collections.emptyList(); - } - else - { - return new ArrayList(values); - } - } - - /** - * {@inheritDoc} - */ - public String getLabel() - { - return label; - } - - /** - * {@inheritDoc} - */ - public String getName() - { - return name; - } - - /** - * {@inheritDoc} - */ - public boolean isDistributed() - { - return distributed; - } - - /** - * {@inheritDoc} - */ - public boolean isLogEnabled() - { - return logEnabled; - } - - /** - * {@inheritDoc} - */ - public boolean isReplicated() - { - return replicated; - } - - public void setAsynchronous(boolean asynchronous) { - this.asynchronous = asynchronous; - } - - public boolean isAsynchronous() { - return asynchronous; - } - - private void putOnlyAsync(K key, V value) - { - cache.withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES, Flag.FORCE_ASYNCHRONOUS).putAsync(key, value); - } - - - /** - * {@inheritDoc} - */ - public void put(final K key, final V value) throws IllegalArgumentException - { - if (key == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - else if (value == null) - { - // ignore null values - return; - } - if(LOG.isDebugEnabled() && cache.getDataContainer().containsKey(key)) { - InternalCacheEntry internalCacheEntry = cache.getDataContainer().get(key); - if(internalCacheEntry != null) { - Object oldValue = internalCacheEntry.getValue(); - if(oldValue != null) { - if(oldValue.equals(value)) { - LOG.debug("Need to optimize top layer cache management propably (depends on ValueClass.equals method pertinence). The same value putted into cache, cache = " + cache.getName() + ", key : class= " + key.getClass() + ", hashcode= " + key.hashCode() + "/ old hashcode: " + internalCacheEntry.getKey().hashCode()); - } else { - try { - value.getClass().getDeclaredMethod("equals"); - } catch (NoSuchMethodException e) { - LOG.debug("Need to implement equals method in " + value.getClass().getCanonicalName() + ". cache = " + cache.getName() + ", key : class= " + key.getClass() + ", hashcode= " + key.hashCode() + "/ old hashcode: " + internalCacheEntry.getKey().hashCode()); - } - } - } - } - } - putOnly(key, value, false); - onPut(key, value); - } - - @Override - public void putLocal(final K key, final V value) throws IllegalArgumentException { - if (key == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - else if (value == null) - { - // ignore null values - return; - } - - putOnly(key, value, true); - - onPutLocal(key, value); - } - - /** - * Only puts the data into the cache nothing more - */ - protected void putOnly(K key, V value, boolean isLocal) - { - if (isLocal) - { - if(isAsynchronous()) { - cache.withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES, Flag.FORCE_ASYNCHRONOUS).putAsync(key, value); - } else { - cache.withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES).put(key, value); - } - } - else - { - if(isAsynchronous()) { - cache.withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES, Flag.FORCE_ASYNCHRONOUS).putAsync(key, value); - } else { - cache.withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES).put(key, value); - } - } - } - - /** - * {@inheritDoc} - */ - public void putMap(final Map objs) throws IllegalArgumentException - { - if (objs == null) - { - throw new IllegalArgumentException("No null map accepted"); - } - for (Serializable name : objs.keySet()) - { - if (name == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - } - // Start transaction - if(cache.getTransactionManager() != null) { - cache.startBatch(); - } - try - { - // Make sure that the key and the value are valid - Map map = new LinkedHashMap(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(entry.getKey(), entry.getValue()); - } - cache.putAll(map); - if(cache.getTransactionManager() != null) { - cache.endBatch(true); - } - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e) //NOSONAR - { - if(cache.getTransactionManager() != null) { - cache.endBatch(false); - } - LOG.warn("An error occurs while executing the putMap method", e); - } - } - - /** - * {@inheritDoc} - */ - public void putAsyncMap(final Map objs) throws IllegalArgumentException - { - if (objs == null) - { - throw new IllegalArgumentException("No null map accepted"); - } - for (Serializable name : objs.keySet()) - { - if (name == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - } - try - { - // Make sure that the key and the value are valid - Map map = new LinkedHashMap(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(entry.getKey(), entry.getValue()); - } - cache.putAllAsync(map); - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e) //NOSONAR - { - LOG.warn("An error occurs while executing the putMap method", e); - } - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public V remove(final Serializable key) throws NullPointerException - { - if (key == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - V result = cache.remove(key); - onRemove((K)key, result); - return result; - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public void removeLocal(final Serializable key) throws NullPointerException - { - if (key == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - cache.withFlags(Flag.CACHE_MODE_LOCAL).removeAsync(key); - onRemove((K)key, null); - } - - /** - * {@inheritDoc} - */ - public List removeCachedObjects() - { - final List list = getCachedObjects(); - clearCache(); - return list; - } - - /** - * {@inheritDoc} - */ - public void select(CachedObjectSelector selector) throws Exception - { - if (selector == null) - { - throw new IllegalArgumentException("No null selector"); - } - for (Map.Entry entry : cache.withFlags(Flag.CACHE_MODE_LOCAL).entrySet()) - { - K key = entry.getKey(); - if (key == null) - { - continue; - } - final V value = entry.getValue(); - ObjectCacheInfo info = new ObjectCacheInfo() - { - public V get() - { - return value; - } - - public long getExpireTime() - { - // Cannot know: The expire time is managed by Infinispan itself - return -1; - } - }; - if (selector.select(key, info)) - { - selector.onSelect(this, key, info); - } - } - } - - /** - * {@inheritDoc} - */ - public void setDistributed(boolean distributed) - { - this.distributed = distributed; - } - - /** - * {@inheritDoc} - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * {@inheritDoc} - */ - public void setLogEnabled(boolean logEnabled) - { - this.logEnabled = logEnabled; - } - - /** - * {@inheritDoc} - */ - public void setName(String name) - { - this.name = name; - } - - /** - * {@inheritDoc} - */ - public void setReplicated(boolean replicated) - { - this.replicated = replicated; - } - - public void onExpire(K key, V obj) - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onExpire(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - public void onRemove(K key, V obj) - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onRemove(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - public void onPut(K key, V obj) - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - try - { - context.onPut(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - - public void onPutLocal(K key, V value) - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - try - { - context.onPutLocal(key, value); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - - public void onGet(K key, V obj) - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - try - { - context.onGet(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - - public void onClearCache() - { - if (listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - try - { - context.onClearCache(); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - - @Listener - public class CacheEventListener - { - /** - * Warning Infinispan triggers a CacheEntryEvictedEvent only at explicit eviction - * that is done lazily which is not exactly what we expect, we still use it to be - * able to use it with avoidValueReplication set to true. - */ - @CacheEntriesEvicted - public void cacheEntryEvicted(CacheEntriesEvictedEvent evt) - { - if (evt.isPre()) - { - for (Map.Entry entry : evt.getEntries().entrySet()) - { - onExpire(entry.getKey(), entry.getValue()); - } - } - } - - @CacheEntryRemoved - public void cacheEntryRemoved(CacheEntryRemovedEvent evt) - { - if (evt.isPre() && !evt.isOriginLocal()) - { - final K key = evt.getKey(); - final V value = evt.getValue(); - onRemove(key, value); - } - } - - @CacheEntryModified - public void cacheEntryModified(CacheEntryModifiedEvent evt) - { - if (!evt.isOriginLocal() && !evt.isPre()) - { - final K key = evt.getKey(); - final V value = evt.getValue(); - onPut(key, value); - } - } - - @CacheEntryCreated - public void CacheEntryCreated(CacheEntryCreatedEvent event) { - if (!event.isOriginLocal() && !event.isPre()) - { - final K key = event.getKey(); - final V value = event.getValue(); - onPut(key, value);; - } - } - } - - private static class ListenerContext implements CacheListenerContext, CacheInfo - { - - /** . */ - private final ExoCache cache; - - /** . */ - final CacheListener listener; - - public ListenerContext(CacheListener listener, ExoCache cache) - { - this.listener = listener; - this.cache = cache; - } - - public CacheInfo getCacheInfo() - { - return this; - } - - public String getName() - { - return cache.getName(); - } - - public int getMaxSize() - { - return cache.getMaxSize(); - } - - public long getLiveTime() - { - return cache.getLiveTime(); - } - - public int getSize() - { - return cache.getCacheSize(); - } - - void onExpire(K key, V obj) throws Exception - { - listener.onExpire(this, key, obj); - } - - void onRemove(K key, V obj) throws Exception - { - listener.onRemove(this, key, obj); - } - - void onPut(K key, V obj) throws Exception - { - listener.onPut(this, key, obj); - } - - void onPutLocal(K key, V obj) throws Exception - { - listener.onPutLocal(this, key, obj); - } - - void onGet(K key, V obj) throws Exception - { - listener.onGet(this, key, obj); - } - - void onClearCache() throws Exception - { - listener.onClearCache(this); - } - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreator.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreator.java deleted file mode 100644 index 8c2f9f4d8..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.infinispan.Cache; -import org.infinispan.configuration.cache.ConfigurationBuilder; - -import java.io.Serializable; -import java.util.Set; -import java.util.concurrent.Callable; - -/** - * This class is used to create the cache according to the given - * configuration {@link org.exoplatform.services.cache.ExoCacheConfig} - * - * @author Nicolas Filotto - * @version $Id$ - */ -public interface ExoCacheCreator -{ - - /** - * Creates an eXo cache according to the given configuration {@link org.exoplatform.services.cache.ExoCacheConfig} - * @param config the configuration of the cache to apply - * @param confBuilder the configuration builder of the infinispan cache - * @param cacheGetter a {@link Callable} instance from which we can get the cache - * @exception ExoCacheInitException if an exception happens while initializing the cache - */ - public ExoCache create(ExoCacheConfig config, ConfigurationBuilder confBuilder, - Callable> cacheGetter) throws ExoCacheInitException; - - /** - * Returns the type of {@link org.exoplatform.services.cache.ExoCacheConfig} expected by the creator - * @return the expected type - */ - public Class getExpectedConfigType(); - - /** - * Returns a set of all the implementations expected by the creator. This is mainly used to be backward compatible - * @return the expected by the creator - */ - public Set getExpectedImplementations(); -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreatorPlugin.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreatorPlugin.java deleted file mode 100644 index bd772095e..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheCreatorPlugin.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.container.component.BaseComponentPlugin; -import org.exoplatform.container.xml.InitParams; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class allows us to define new creators - * @author Nicolas Filotto - * @version $Id$ - */ -public class ExoCacheCreatorPlugin extends BaseComponentPlugin -{ - - /** - * The list of all the creators defined for this ComponentPlugin - */ - private final List creators; - - public ExoCacheCreatorPlugin(InitParams params) - { - creators = new ArrayList(); - List configs = params.getObjectParamValues(ExoCacheCreator.class); - for (int i = 0; i < configs.size(); i++) - { - ExoCacheCreator config = (ExoCacheCreator)configs.get(i); - creators.add(config); - } - } - - /** - * Returns all the creators defined for this ComponentPlugin - */ - public List getCreators() - { - return creators; - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryConfigPlugin.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryConfigPlugin.java deleted file mode 100644 index 8cbaf5e77..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryConfigPlugin.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.container.component.BaseComponentPlugin; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * This class is used to define custom configurations - * - * @author Nicolas Filotto - * @version $Id$ - */ -public class ExoCacheFactoryConfigPlugin extends BaseComponentPlugin -{ - - /** - * The map of all the creators defined for this ComponentPlugin - */ - private final Map configs; - - public ExoCacheFactoryConfigPlugin(InitParams params) - { - configs = new HashMap(); - for (Iterator iterator = params.getValueParamIterator(); iterator.hasNext();) - { - ValueParam vParam = iterator.next(); - configs.put(vParam.getName(), vParam.getValue()); - } - } - - /** - * Returns all the configurations defined for this ComponentPlugin - */ - public Map getConfigs() - { - return configs; - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java deleted file mode 100644 index a6c41c80a..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheFactory; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.exoplatform.services.cache.impl.infinispan.distributed.DistributedExoCache; -import org.exoplatform.services.cache.impl.infinispan.generic.GenericExoCacheCreator; -import org.exoplatform.services.ispn.DistributedCacheManager; -import org.exoplatform.services.ispn.Utils; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.infinispan.Cache; -import org.infinispan.configuration.cache.CacheMode; -import org.infinispan.configuration.cache.Configuration; -import org.infinispan.configuration.cache.ConfigurationBuilder; -import org.infinispan.configuration.global.GlobalConfiguration; -import org.infinispan.configuration.global.GlobalConfigurationBuilder; -import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; -import org.infinispan.configuration.parsing.ParserRegistry; -import org.infinispan.eviction.EvictionStrategy; -import org.infinispan.jmx.MBeanServerLookup; -import org.infinispan.manager.DefaultCacheManager; -import org.picocontainer.Startable; - -import java.io.InputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.Callable; - -import javax.management.MBeanServer; - -/** - * This class is the Infinispan implementation of the {@link org.exoplatform.services.cache.ExoCacheFactory} - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class ExoCacheFactoryImpl implements ExoCacheFactory, Startable { - - /** - * The logger - */ - private static final Log LOG = ExoLogger.getLogger(ExoCacheFactoryImpl.class); - - /** - * The initial parameter key that defines the full path of the configuration template - */ - private static final String CACHE_CONFIG_TEMPLATE_KEY = "cache.config.template"; - - /** - * The initial parameter key that defines the full path of the optional async configuration template - */ - private static final String CACHE_ASYNC_TEMPLATE_KEY = "cache.async.config.template"; - - /** - * The cache manager for the distributed cache - */ - private final DistributedCacheManager distributedCacheManager; - - /** - * The current {@link ExoContainerContext} - */ - private final ExoContainerContext ctx; - - /** - * The configuration manager that allows us to retrieve a configuration file in several different - * manners - */ - private final ConfigurationManager configManager; - - /** - * The {@link DefaultCacheManager} used for all sync cache regions - */ - private final DefaultCacheManager cacheManager; - - /** - * The {@link DefaultCacheManager} used for all async cache regions - */ - private DefaultCacheManager asyncCacheManager = null; - - /** - * The mapping between the configuration types and the creators - */ - private final Map, ExoCacheCreator> mappingConfigTypeCreators = - new HashMap, ExoCacheCreator>(); - - /** - * The mapping between the implementations and the creators. This is mainly used for backward compatibility - */ - private final Map mappingImplCreators = new HashMap(); - - /** - * The mapping between the cache names and the configuration paths - */ - private final Map mappingCacheNameConfig = new HashMap(); - - /** - * The async cache template path - */ - private final String asyncCacheTemplate; - - /** - * The mapping between the cluster name and the cache managers - */ - private final Map mappingGlobalConfigCacheManager = - new HashMap(); - - /** - * The default creator - */ - private final ExoCacheCreator defaultCreator = new GenericExoCacheCreator(); - - private static final MBeanServerLookup MBEAN_SERVER_LOOKUP = new MBeanServerLookup() - { - public MBeanServer getMBeanServer(Properties properties) - { - return ExoContainerContext.getTopContainer().getMBeanServer(); - } - }; - - public ExoCacheFactoryImpl(ExoContainerContext ctx, InitParams params, ConfigurationManager configManager) - throws ExoCacheInitException - { - this(ctx, getValueParam(params, CACHE_CONFIG_TEMPLATE_KEY), getValueParam(params, CACHE_ASYNC_TEMPLATE_KEY), configManager, null); - } - - public ExoCacheFactoryImpl(ExoContainerContext ctx, InitParams params, ConfigurationManager configManager, - DistributedCacheManager dcm) throws ExoCacheInitException - { - this(ctx, getValueParam(params, CACHE_CONFIG_TEMPLATE_KEY), getValueParam(params, CACHE_ASYNC_TEMPLATE_KEY), configManager, dcm); - } - - public ExoCacheFactoryImpl(ExoContainerContext ctx, String cacheConfigTemplate, String cacheAsyncConfigTemplate, ConfigurationManager configManager, - DistributedCacheManager dcm) throws ExoCacheInitException - { - this.distributedCacheManager = dcm; - this.ctx = ctx; - this.configManager = configManager; - if (cacheConfigTemplate == null) - { - throw new IllegalArgumentException("The parameter '" + CACHE_CONFIG_TEMPLATE_KEY + "' must be set"); - } - // Initialize the main cache manager - this.cacheManager = initCacheManager(cacheConfigTemplate); - - this.asyncCacheTemplate = cacheAsyncConfigTemplate; - } - - /** - * Initializes the {@link DefaultCacheManager} - * @throws ExoCacheInitException if the cache manager cannot be initialized - */ - private DefaultCacheManager initCacheManager(final String cacheConfigTemplate) throws ExoCacheInitException - { - InputStream is = null; - try - { - // Read the configuration file of the cache - is = configManager.getInputStream(cacheConfigTemplate); - } - catch (Exception e)//NOSONAR - { - throw new ExoCacheInitException("The configuration of the CacheManager cannot be loaded from '" - + cacheConfigTemplate + "'", e); - } - if (is == null) - { - throw new ExoCacheInitException("The configuration of the CacheManager cannot be found at '" - + cacheConfigTemplate + "'"); - } - GlobalConfigurationBuilder configBuilder; - Configuration config; - try - { - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Loads the configuration from the input stream - ConfigurationBuilderHolder holder = parser.parse(is); - configBuilder = holder.getGlobalConfigurationBuilder(); - config = holder.getDefaultConfigurationBuilder().build(); - } - catch (RuntimeException e) //NOSONAR - { - throw new ExoCacheInitException("Cannot parse the configuration '" + cacheConfigTemplate + "'", e); - } - configureCacheManager(configBuilder); - DefaultCacheManager cacheManager; - try - { - // Create the CacheManager from the new configuration - cacheManager = new DefaultCacheManager(configBuilder.build(), config); - } - catch (RuntimeException e) //NOSONAR - { - throw new ExoCacheInitException( - "Cannot initialize the CacheManager corresponding to the configuration '" + cacheConfigTemplate - + "'", e); - } - // Register the main cache manager - mappingGlobalConfigCacheManager.put(cacheManager.getCacheManagerConfiguration().transport().clusterName(), - cacheManager); - return cacheManager; - } - - /** - * Configure the cache manager - * - * @param configBuilder the configuration builder on which we applied all the required changes - * @throws ExoCacheInitException - */ - private void configureCacheManager(GlobalConfigurationBuilder configBuilder) throws ExoCacheInitException - { - GlobalConfiguration config = configBuilder.build(); - // Configure JGroups - configureJGroups(config, configBuilder); - // Configure the name of the cache manager - configBuilder.globalJmxStatistics().enable() - .cacheManagerName(config.globalJmxStatistics().cacheManagerName() + "_" + ctx.getName()). - // Configure the MBeanServerLookup - mBeanServerLookup(MBEAN_SERVER_LOOKUP); - } - - /** - * If some JGoups properties has been set, it will load the configuration and set - * the cluster name by adding as suffix the name of the {@link ExoContainerContext} - * - * @param config the global configuration from which the JGroups config will be extracted - * @param configBuilder the related configuration builder - * @throws ExoCacheInitException if any exception occurs while configuring JGroups - */ - private void configureJGroups(GlobalConfiguration config, GlobalConfigurationBuilder configBuilder) - throws ExoCacheInitException - { - if (loadJGroupsConfig(config, configBuilder)) - { - // The JGroups Config could be loaded which means that the configuration is for a cluster - configBuilder.transport().clusterName(config.transport().clusterName() + "-" + ctx.getName()); - } - } - - /** - * Load the JGroups configuration file thanks to the {@link ConfigurationManager} - * @param config the global configuration from which the JGroups config will be extracted - * @param configBuilder the related configuration builder - * @return true if the JGoups config could be loaded successfully, - * false if there were no JGroups config to load - * @throws ExoCacheInitException if the JGroups config could not be loaded - */ - private boolean loadJGroupsConfig(GlobalConfiguration config, GlobalConfigurationBuilder configBuilder) - throws ExoCacheInitException - { - return Utils.loadJGroupsConfig(configManager, config, configBuilder); - } - - /** - * To create a new cache instance according to the given configuration, we follow the steps below: - * - * We first try to find if a specific location of the cache configuration has been defined thanks - * to an external component plugin of type ExoCacheFactoryConfigPlugin. If so we use the default cache - * configuration defined in this file otherwise we use the default cache configuration defined in - * "${CACHE_CONFIG_TEMPLATE_KEY}" - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public ExoCache createCache(final ExoCacheConfig config) throws ExoCacheInitException - { - final String region = config.getName(); - String CacheConfig = mappingCacheNameConfig.get(region); - if(CacheConfig == null && config.isAsync() && asyncCacheTemplate !=null && asyncCacheManager == null) - { - //use async template if cache use async mode - this.asyncCacheManager = initCacheManager(asyncCacheTemplate); - } - final String customConfig = CacheConfig; - final ExoCache eXoCache; - final DefaultCacheManager cacheManager; - try - { - final ConfigurationBuilder confBuilder = new ConfigurationBuilder(); - if (customConfig != null) - { - // A custom configuration has been set - if (LOG.isInfoEnabled()) - LOG.info("A custom configuration has been set for the cache '" + region + "'."); - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Load the configuration - ConfigurationBuilderHolder holder = parser.parse(configManager.getInputStream(customConfig)); - GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); - // Configure JGroups and JMX since it could affect the state of the Global Config - configureCacheManager(configBuilder); - GlobalConfiguration gc = configBuilder.build(); - - // Check if a CacheManager with the same GlobalConfiguration exists - DefaultCacheManager currentCacheManager = - mappingGlobalConfigCacheManager.get(gc.transport().clusterName()); - if (currentCacheManager == null) - { - // Use a different cache manager name to prevent naming conflict - configBuilder.globalJmxStatistics().cacheManagerName( - gc.globalJmxStatistics().cacheManagerName() + "_" + region + "_" + ctx.getName()); - // No cache manager has been defined so far for this Cache Configuration - currentCacheManager = - new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder() - .build(), false); - for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) - { - currentCacheManager.defineConfiguration(entry.getKey(), entry.getValue().build()); - } - currentCacheManager.start(); - // We register this new cache manager - mappingGlobalConfigCacheManager.put(gc.transport().clusterName(), currentCacheManager); - } - cacheManager = currentCacheManager; - confBuilder.read(cacheManager.getDefaultCacheConfiguration()); - } - else if (config.isDistributed()) - { - // We expect a distributed cache - if (distributedCacheManager == null) - { - throw new IllegalArgumentException( - "The DistributedCacheManager has not been defined in the configuration," - + " please configure it at root container level if you want to use a distributed cache."); - } - return new DistributedExoCache(ctx, config, - distributedCacheManager.getCache(DistributedExoCache.CACHE_NAME)); - } - else - { - cacheManager = (config.isAsync() && asyncCacheManager != null) ? this.asyncCacheManager : this.cacheManager; - // No custom configuration has been found, a configuration template will be used - if (LOG.isInfoEnabled()) - LOG.info("The configuration template will be used for the cache '" + region + "'."); - confBuilder.read(cacheManager.getDefaultCacheConfiguration()); - if (!config.isRepicated()) - { - // The cache is local - confBuilder.clustering().cacheMode(CacheMode.LOCAL); - } - } - // Reset the configuration to avoid conflicts - resetConfiguration(confBuilder); - final ExoCacheCreator creator = getExoCacheCreator(config); - // Create the cache - eXoCache = creator.create(config, confBuilder, new Callable>() - { - public Cache call() throws Exception - { - cacheManager.defineConfiguration(region, confBuilder.build()); - // create and start the cache - return cacheManager.getCache(region); - } - }); - } - catch (Exception e) //NOSONAR - { - throw new ExoCacheInitException("The cache '" + region + "' could not be initialized", e); - } - return eXoCache; - } - - /** - * Add a list of creators to register - * @param plugin the plugin that contains the creators - */ - public void addCreator(ExoCacheCreatorPlugin plugin) - { - final List creators = plugin.getCreators(); - for (ExoCacheCreator creator : creators) - { - mappingConfigTypeCreators.put(creator.getExpectedConfigType(), creator); - Set implementations = creator.getExpectedImplementations(); - if (implementations == null) - { - throw new IllegalArgumentException("The set of implementations cannot be null"); - } - for (String imp : implementations) - { - mappingImplCreators.put(imp, creator); - } - } - } - - /** - * Add a list of custom configuration to register - * @param plugin the plugin that contains the configs - */ - public void addConfig(ExoCacheFactoryConfigPlugin plugin) - { - final Map configs = plugin.getConfigs(); - mappingCacheNameConfig.putAll(configs); - } - - @Override - public void start() { - // Nothing to start - } - - @Override - public void stop() { - if (cacheManager != null) { - cacheManager.stop(); - } - } - /** - * Returns the value of the ValueParam if and only if the value is not empty - */ - private static String getValueParam(InitParams params, String key) - { - if (params == null) - { - return null; - } - final ValueParam vp = params.getValueParam(key); - String result; - if (vp == null || (result = vp.getValue()) == null || (result = result.trim()).length() == 0) - { - return null; - } - return result; - } - - /** - * Returns the most relevant ExoCacheCreator according to the give configuration - */ - protected ExoCacheCreator getExoCacheCreator(ExoCacheConfig config) - { - ExoCacheCreator creator = mappingConfigTypeCreators.get(config.getClass()); - if (creator == null) - { - // No creator for this type has been found, let's try the implementation field - creator = mappingImplCreators.get(config.getImplementation()); - if (creator == null) - { - // No creator can be found, we will use the default creator - if (LOG.isInfoEnabled()) - LOG.info("No cache creator has been found for the cache '" + config.getName() - + "', the default one will be used."); - return defaultCreator; - } - } - if (LOG.isInfoEnabled()) - LOG.info("The cache '" + config.getName() + "' will be created with '" + creator.getClass() + "'."); - return creator; - } - - /** - * Clean the configuration template to prevent conflicts - */ - protected void resetConfiguration(ConfigurationBuilder confBuilder) - { - confBuilder.eviction().strategy(EvictionStrategy.NONE).size(-1).expiration() - .lifespan(-1L).maxIdle(-1L).wakeUpInterval(60000L); - } - -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java deleted file mode 100644 index 1e74abb46..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java +++ /dev/null @@ -1,1126 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan.distributed; - -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.management.annotations.Managed; -import org.exoplatform.management.annotations.ManagedDescription; -import org.exoplatform.management.annotations.ManagedName; -import org.exoplatform.services.cache.CacheInfo; -import org.exoplatform.services.cache.CacheListener; -import org.exoplatform.services.cache.CacheListenerContext; -import org.exoplatform.services.cache.CachedObjectSelector; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ObjectCacheInfo; -import org.exoplatform.services.ispn.AbstractMapper; -import org.exoplatform.services.ispn.DistributedCacheManager; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.infinispan.AdvancedCache; -import org.infinispan.Cache; -import org.infinispan.context.Flag; -import org.infinispan.distexec.mapreduce.Collector; -import org.infinispan.distexec.mapreduce.MapReduceTask; -import org.infinispan.distexec.mapreduce.Reducer; -import org.infinispan.notifications.Listener; -import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; -import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; - -import java.io.Externalizable; -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class DistributedExoCache implements ExoCache -{ - - /** - * Logger. - */ - private static final Log LOG = ExoLogger.getLogger(DistributedExoCache.class);//NOSONAR - - public static final String CACHE_NAME = "eXoCache"; - - private final AtomicInteger hits = new AtomicInteger(0); - - private final AtomicInteger misses = new AtomicInteger(0); - - private String label; - - private String name; - - private final String fullName; - - private boolean distributed; - - private boolean replicated; - - private boolean logEnabled; - - @SuppressWarnings("rawtypes") - private static final ConcurrentMap>> ALL_LISTENERS = - new ConcurrentHashMap>>(); - - protected final AdvancedCache, V> cache; - - @SuppressWarnings("unchecked") - public DistributedExoCache(ExoContainerContext ctx, ExoCacheConfig config, Cache cache) - { - this.fullName = ctx.getName() + "-" + config.getName(); - this.cache = (AdvancedCache, V>)cache.getAdvancedCache(); - setDistributed(config.isDistributed()); - setLabel(config.getLabel()); - setName(config.getName()); - setLogEnabled(config.isLogEnabled()); - setReplicated(config.isRepicated()); - } - - AdvancedCache, V> getCache() - { - return cache; - } - - /** - * @return the fullName - */ - String getFullName() - { - return fullName; - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("rawtypes") - public void addCacheListener(CacheListener listener) - { - if (listener == null) - { - throw new IllegalArgumentException("The listener cannot be null"); - } - List lListeners = getListeners(fullName); - if (lListeners == null) - { - lListeners = new CopyOnWriteArrayList(); - boolean alreadyAdded = false; - ConcurrentMap> listeners = getOrCreateListeners(); - if (listeners.isEmpty()) - { - synchronized (listeners) - { - if (listeners.isEmpty()) - { - // Ensure that the listener is added only once - cache.addListener(new CacheEventListener()); - listeners.put(fullName, lListeners); - alreadyAdded = true; - } - } - } - if (!alreadyAdded) - { - List oldValue = listeners.putIfAbsent(fullName, lListeners); - if (oldValue != null) - { - lListeners = oldValue; - } - } - } - lListeners.add(new ListenerContext(listener, this)); - } - - @SuppressWarnings("rawtypes") - private ConcurrentMap> getOrCreateListeners() - { - ConcurrentMap> listeners = ALL_LISTENERS.get(cache); - if (listeners == null) - { - listeners = new ConcurrentHashMap>(); - ConcurrentMap> oldValue = ALL_LISTENERS.putIfAbsent(cache, listeners); - if (oldValue != null) - { - listeners = oldValue; - } - } - return listeners; - } - - @SuppressWarnings("rawtypes") - private List getListeners(String fullName) - { - ConcurrentMap> listeners = ALL_LISTENERS.get(cache); - return listeners == null ? null : listeners.get(fullName); - } - - /** - * {@inheritDoc} - */ - public void clearCache() - { - MapReduceTask, V, Void, Void> task = new MapReduceTask, V, Void, Void>(cache); - task.mappedWith(new ClearCacheMapper(fullName)).reducedWith(new ClearCacheReducer()); - task.execute(); - onClearCache(); - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public V get(Serializable name) - { - if (name == null) - { - return null; - } - @SuppressWarnings("rawtypes") - final CacheKey key = new CacheKey(fullName, name); - final V result = cache.get(key); - if (result == null) - { - misses.incrementAndGet(); - } - else - { - hits.incrementAndGet(); - } - onGet(key, result); - return result; - } - - /** - * {@inheritDoc} - */ - public int getCacheHit() - { - return hits.get(); - } - - /** - * {@inheritDoc} - */ - public int getCacheMiss() - { - return misses.get(); - } - - /** - * {@inheritDoc} - */ - public int getCacheSize() - { - MapReduceTask, V, String, Integer> task = new MapReduceTask, V, String, Integer>(cache); - task.mappedWith(new GetSizeMapper(fullName)).reducedWith(new GetSizeReducer()); - Map map = task.execute(); - int sum = 0; - for (Integer i : map.values()) - { - sum += i; - } - return sum; - } - - /** - * {@inheritDoc} - */ - public List getCachedObjects() - { - MapReduceTask, V, String, List> task = - new MapReduceTask, V, String, List>(cache); - task.mappedWith(new GetCachedObjectsMapper(fullName)).reducedWith( - new GetCachedObjectsReducer()); - Map> map = task.execute(); - List result = new ArrayList(); - for (List vals : map.values()) - { - result.addAll(vals); - } - return result; - } - - /** - * {@inheritDoc} - */ - public String getLabel() - { - return label; - } - - /** - * {@inheritDoc} - */ - public String getName() - { - return name; - } - - /** - * {@inheritDoc} - */ - public boolean isDistributed() - { - return distributed; - } - - /** - * {@inheritDoc} - */ - public boolean isLogEnabled() - { - return logEnabled; - } - - /** - * {@inheritDoc} - */ - public boolean isReplicated() - { - return replicated; - } - - /** - * {@inheritDoc} - */ - public void put(final K key, final V value) throws IllegalArgumentException - { - if (key == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - else if (value == null) - { - // ignore null values - return; - } - putOnly(key, value); - onPut(key, value); - } - - /** - * Only puts the data into the cache nothing more - */ - protected void putOnly(K key, V value) - { - cache.withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES).put(new CacheKey(fullName, key), value); - } - - /** - * {@inheritDoc} - */ - public void putMap(final Map objs) throws IllegalArgumentException - { - if (objs == null) - { - throw new IllegalArgumentException("No null map accepted"); - } - for (Serializable name : objs.keySet()) - { - if (name == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - } - // Start transaction - cache.startBatch(); - try - { - // Wrap the key into a CacheKey and make sure that the key and the value - // are valid - Map, V> map = new LinkedHashMap, V>(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(new CacheKey(fullName, entry.getKey()), entry.getValue()); - } - cache.putAll(map); - cache.endBatch(true); - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e)//NOSONAR - { - cache.endBatch(false); - LOG.warn("An error occurs while executing the putMap method", e); - } - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public V remove(Serializable name) throws IllegalArgumentException - { - if (name == null) - { - throw new IllegalArgumentException("No null cache key accepted"); - } - @SuppressWarnings("rawtypes") - final CacheKey key = new CacheKey(fullName, name); - V result = cache.remove(key); - onRemove(key, result); - return result; - } - - /** - * {@inheritDoc} - */ - public List removeCachedObjects() - { - final List list = getCachedObjects(); - clearCache(); - return list; - } - - /** - * {@inheritDoc} - */ - public void select(CachedObjectSelector selector) throws Exception - { - if (selector == null) - { - throw new IllegalArgumentException("No null selector"); - } - MapReduceTask, V, K, V> task = new MapReduceTask, V, K, V>(cache); - task.mappedWith(new GetEntriesMapper(fullName)).reducedWith(new GetEntriesReducer()); - Map map = task.execute(); - - for (K key : map.keySet()) - { - if (key == null) - { - continue; - } - final V value = map.get(key); - ObjectCacheInfo info = new ObjectCacheInfo() - { - public V get() - { - return value; - } - - public long getExpireTime() - { - // Cannot know: The expire time is managed by Infinispan itself - return -1; - } - }; - if (selector.select(key, info)) - { - selector.onSelect(this, key, info); - } - } - } - - /** - * {@inheritDoc} - */ - public void setDistributed(boolean distributed) - { - this.distributed = distributed; - } - - /** - * {@inheritDoc} - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * {@inheritDoc} - */ - public void setLogEnabled(boolean logEnabled) - { - this.logEnabled = logEnabled; - } - - /** - * {@inheritDoc} - */ - public void setName(String name) - { - this.name = name; - } - - /** - * {@inheritDoc} - */ - public void setReplicated(boolean replicated) - { - this.replicated = replicated; - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - void onExpire(CacheKey key, V obj) - { - List listeners = getListeners(key.getFullName()); - if (listeners == null || listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onExpire(key.getKey(), obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - void onRemove(CacheKey key, V obj) - { - List listeners = getListeners(key.getFullName()); - if (listeners == null || listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onRemove(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - void onPut(CacheKey key, V obj) - { - onPut(key.getFullName(), key.getKey(), obj); - } - - public void onPut(K key, V obj) - { - onPut(fullName, key, obj); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - void onPut(String fullName, K key, V obj) - { - List listeners = getListeners(fullName); - if (listeners == null || listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onPut(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - void onGet(CacheKey key, V obj) - { - List listeners = getListeners(key.getFullName()); - if (listeners == null || listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onGet(key, obj); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - @SuppressWarnings("rawtypes") - public void onClearCache() - { - List listeners = getListeners(fullName); - if (listeners == null || listeners.isEmpty()) - { - return; - } - for (ListenerContext context : listeners) - { - try - { - context.onClearCache(); - } - catch (Exception e)//NOSONAR - { - if (LOG.isWarnEnabled()) - LOG.warn("Cannot execute the CacheListener properly", e); - } - } - } - - @Listener - public class CacheEventListener - { - /** - * Warning Infinispan triggers a CacheEntryEvictedEvent only at explicit eviction - * that is done lazily which is not exactly what we expect, we still use it to be - * able to use it with avoidValueReplication set to true. - */ - @CacheEntriesEvicted - public void cacheEntryEvicted(CacheEntriesEvictedEvent, V> evt) - { - if (evt.isPre()) - { - for (Map.Entry, V> entry : evt.getEntries().entrySet()) - { - onExpire(entry.getKey(), entry.getValue()); - } - } - } - - @CacheEntryRemoved - public void cacheEntryRemoved(CacheEntryRemovedEvent, V> evt) - { - if (evt.isPre() && !evt.isOriginLocal()) - { - final CacheKey key = evt.getKey(); - final V value = evt.getValue(); - onRemove(key, value); - } - } - - @CacheEntryModified - public void cacheEntryModified(CacheEntryModifiedEvent, V> evt) - { - if (!evt.isOriginLocal() && !evt.isPre()) - { - final CacheKey key = evt.getKey(); - final V value = evt.getValue(); - onPut(key, value); - } - } - - @CacheEntryCreated - public void cacheEntrCreated(CacheEntryCreatedEvent, V> evt) - { - if (!evt.isOriginLocal() && !evt.isPre()) - { - final CacheKey key = evt.getKey(); - final V value = evt.getValue(); - onPut(key, value); - } - } - } - - private static class ListenerContext implements CacheListenerContext, CacheInfo - { - - /** . */ - private final ExoCache cache; - - /** . */ - final CacheListener listener; - - public ListenerContext(CacheListener listener, ExoCache cache) - { - this.listener = listener; - this.cache = cache; - } - - public CacheInfo getCacheInfo() - { - return this; - } - - public String getName() - { - return cache.getName(); - } - - public int getMaxSize() - { - return cache.getMaxSize(); - } - - public long getLiveTime() - { - return cache.getLiveTime(); - } - - public int getSize() - { - return cache.getCacheSize(); - } - - void onExpire(K key, V obj) throws Exception - { - listener.onExpire(this, key, obj); - } - - void onRemove(K key, V obj) throws Exception - { - listener.onRemove(this, key, obj); - } - - void onPut(K key, V obj) throws Exception - { - listener.onPut(this, key, obj); - } - - void onGet(K key, V obj) throws Exception - { - listener.onGet(this, key, obj); - } - - void onClearCache() throws Exception - { - listener.onClearCache(this); - } - } - - public void setMaxSize(int max) - { - throw new UnsupportedOperationException("The configuration of the cache cannot not be modified"); - } - - public void setLiveTime(long period) - { - throw new UnsupportedOperationException("The configuration of the cache cannot not be modified"); - } - - @ManagedName("MaxEntries") - @ManagedDescription("Maximum number of entries in a cache instance. -1 means no limit.") - public int getMaxSize() - { - return Math.toIntExact(cache.getCacheConfiguration().eviction().maxEntries()); - } - - @ManagedName("Lifespan") - @ManagedDescription("Maximum lifespan of a cache entry, after which the entry is expired cluster-wide." - + " -1 means the entries never expire.") - public long getLiveTime() - { - return cache.getCacheConfiguration().expiration().lifespan(); - } - - @Managed - @ManagedName("MaxIdle") - @ManagedDescription("Maximum idle time a cache entry will be maintained in the cache. " - + "If the idle time is exceeded, the entry will be expired cluster-wide. -1 means the entries never expire.") - public long getMaxIdle() - { - return cache.getCacheConfiguration().expiration().maxIdle(); - } - - @Managed - @ManagedName("WakeUpInterval") - @ManagedDescription("Interval between subsequent eviction runs. If you wish to disable the periodic eviction " - + "process altogether, set wakeupInterval to -1.") - public long getWakeUpInterval() - { - return cache.getCacheConfiguration().expiration().wakeUpInterval(); - } - - public static class CacheKey implements Externalizable - { - private K key; - - private String fullName; - - public CacheKey() - { - } - - public CacheKey(String fullName, K key) - { - this.fullName = fullName; - this.key = key; - } - - /** - * @return the nested key - */ - K getKey() - { - return key; - } - - /** - * @return the fullName - */ - String getFullName() - { - return fullName; - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((fullName == null) ? 0 : fullName.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - @SuppressWarnings("rawtypes") - CacheKey other = (CacheKey)obj; - if (fullName == null) - { - if (other.fullName != null) - return false; - } - else if (!fullName.equals(other.fullName)) - return false; - if (key == null) - { - if (other.key != null) - return false; - } - else if (!key.equals(other.key)) - return false; - return true; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - return "CacheKey [fullName=" + fullName + ", key=" + key + "]"; - } - - /** - * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) - */ - public void writeExternal(ObjectOutput out) throws IOException - { - byte[] buf = fullName.getBytes("UTF-8"); - out.writeInt(buf.length); - out.write(buf); - out.writeObject(key); - } - - /** - * @see java.io.Externalizable#readExternal(java.io.ObjectInput) - */ - @SuppressWarnings("unchecked") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException - { - byte[] buf = new byte[in.readInt()]; - in.readFully(buf); - fullName = new String(buf, "UTF-8"); - key = (K)in.readObject(); - } - } - - private abstract static class AbstractExoCacheMapper extends - AbstractMapper, V, KOut, VOut> implements Externalizable - { - /** - * The full name of the cache instance - */ - private String fullName; - - public AbstractExoCacheMapper() - { - } - - public AbstractExoCacheMapper(String fullName) - { - this.fullName = fullName; - } - - /** - * The serial version UID - */ - private static final long serialVersionUID = 7962676854308932222L; - - /** - * @see org.exoplatform.services.ispn.AbstractMapper#isValid(java.lang.Object) - */ - @Override - protected boolean isValid(CacheKey key) - { - return fullName.equals(key.getFullName()); - } - - /** - * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) - */ - public void writeExternal(ObjectOutput out) throws IOException - { - byte[] buf = fullName.getBytes("UTF-8"); - out.writeInt(buf.length); - out.write(buf); - } - - /** - * @see java.io.Externalizable#readExternal(java.io.ObjectInput) - */ - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException - { - byte[] buf = new byte[in.readInt()]; - in.readFully(buf); - fullName = new String(buf, "UTF-8"); - } - } - - public static class GetSizeMapper extends AbstractExoCacheMapper - { - - public GetSizeMapper() - { - } - - public GetSizeMapper(String fullName) - { - super(fullName); - } - - /** - * {@inheritDoc} - */ - @Override - protected void _map(CacheKey key, V value, Collector collector) - { - collector.emit("total", Integer.valueOf(1)); - } - - } - - public static class GetSizeReducer implements Reducer - { - - /** - * The serial version UID - */ - private static final long serialVersionUID = -5264142863835473112L; - - /** - * @see org.infinispan.distexec.mapreduce.Reducer#reduce(java.lang.Object, java.util.Iterator) - */ - @Override - public Integer reduce(K reducedKey, Iterator iter) - { - int sum = 0; - while (iter.hasNext()) - { - Integer i = iter.next(); - sum += i; - } - return sum; - } - } - - public static class GetCachedObjectsMapper extends AbstractExoCacheMapper> - { - - public GetCachedObjectsMapper() - { - } - - public GetCachedObjectsMapper(String fullName) - { - super(fullName); - } - - /** - * {@inheritDoc} - */ - @Override - protected void _map(CacheKey key, V value, Collector> collector) - { - collector.emit("values", Collections.singletonList(value)); - } - - } - - public static class GetCachedObjectsReducer implements Reducer> - { - - /** - * The serial version UID - */ - private static final long serialVersionUID = 8069024420056440405L; - - /** - * @see org.infinispan.distexec.mapreduce.Reducer#reduce(java.lang.Object, java.util.Iterator) - */ - @Override - public List reduce(K reducedKey, Iterator> iter) - { - List values = new ArrayList(); - while (iter.hasNext()) - { - List vals = iter.next(); - values.addAll(vals); - } - return values; - } - } - - public static class ClearCacheMapper extends AbstractExoCacheMapper - { - - public ClearCacheMapper() - { - } - - public ClearCacheMapper(String fullName) - { - super(fullName); - } - - /** - * {@inheritDoc} - */ - @Override - protected void _map(CacheKey key, V value, Collector collector) - { - ExoContainer container = ExoContainerContext.getTopContainer(); - if (container == null) - { - LOG.error("The top container could not be found"); - return; - } - DistributedCacheManager dcm = - (DistributedCacheManager)container.getComponentInstanceOfType(DistributedCacheManager.class); - if (dcm == null) - { - LOG.error("The DistributedCacheManager could not be found at top container level, please configure it."); - return; - } - Cache, V> cache = dcm.getCache(CACHE_NAME); - cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.FAIL_SILENTLY).remove(key); - } - } - - public static class ClearCacheReducer implements Reducer - { - - /** - * The serial version UID - */ - private static final long serialVersionUID = -8111087186325793256L; - - /** - * @see org.infinispan.distexec.mapreduce.Reducer#reduce(java.lang.Object, java.util.Iterator) - */ - @Override - public Void reduce(Void reducedKey, Iterator iter) - { - return null; - } - } - - public static class GetEntriesMapper extends AbstractExoCacheMapper - { - public GetEntriesMapper() - { - } - - public GetEntriesMapper(String fullName) - { - super(fullName); - } - - /** - * {@inheritDoc} - */ - @Override - protected void _map(CacheKey key, V value, Collector collector) - { - collector.emit(key.getKey(), value); - } - } - - public static class GetEntriesReducer implements Reducer - { - - /** - * The serial version UID - */ - private static final long serialVersionUID = 5153826700048219537L; - - /** - * @see org.infinispan.distexec.mapreduce.Reducer#reduce(java.lang.Object, java.util.Iterator) - */ - @Override - public V reduce(K reducedKey, Iterator iter) - { - return iter == null || !iter.hasNext() ? null : iter.next(); - } - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheConfig.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheConfig.java deleted file mode 100644 index a2556e3bd..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan.generic; - -import org.exoplatform.services.cache.ExoCacheConfig; - -/** - * The {@link org.exoplatform.services.cache.ExoCacheConfig} for all the eviction algorithms - * available in infinispan - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class GenericExoCacheConfig extends ExoCacheConfig -{ - - private String strategy; - - private long maxIdle; - - private long wakeUpInterval; - - /** - * @return the strategy - */ - public String getStrategy() - { - return strategy; - } - - /** - * @param strategy the strategy to set - */ - public void setStrategy(String strategy) - { - this.strategy = strategy; - } - - /** - * @return the wakeUpInterval - */ - public long getWakeUpInterval() - { - return wakeUpInterval; - } - - /** - * @param wakeUpInterval the wakeUpInterval to set - */ - public void setWakeUpInterval(long wakeUpInterval) - { - this.wakeUpInterval = wakeUpInterval; - } - - /** - * @return the maxIdle - */ - public long getMaxIdle() - { - return maxIdle; - } - - /** - * @param maxIdle the maxIdle to set - */ - public void setMaxIdle(long maxIdle) - { - this.maxIdle = maxIdle; - } -} \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheCreator.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheCreator.java deleted file mode 100644 index 6e4a90a4b..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/generic/GenericExoCacheCreator.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan.generic; - -import org.exoplatform.management.annotations.Managed; -import org.exoplatform.management.annotations.ManagedDescription; -import org.exoplatform.management.annotations.ManagedName; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.exoplatform.services.cache.impl.infinispan.AbstractExoCache; -import org.exoplatform.services.cache.impl.infinispan.ExoCacheCreator; -import org.infinispan.Cache; -import org.infinispan.configuration.cache.ConfigurationBuilder; -import org.infinispan.eviction.EvictionStrategy; - -import java.io.Serializable; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.Callable; - -/** - * The generic {@link ExoCacheCreator} for all the expiration available in infinispan. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class GenericExoCacheCreator implements ExoCacheCreator -{ - - /** - * The default value for the eviction strategy - */ - protected String defaultStrategy = "LRU"; - - /** - * The default value for maxIdle - */ - protected long defaultMaxIdle = -1; - - /** - * The default value for wakeUpInterval - */ - protected long defaultWakeUpInterval = 5000; - - /** - * A set of all the implementations supported by this creator - */ - protected Set implementations; - - /** - * {@inheritDoc} - */ - public Set getExpectedImplementations() - { - return implementations; - } - - /** - * {@inheritDoc} - */ - public Class getExpectedConfigType() - { - return GenericExoCacheConfig.class; - } - - /** - * {@inheritDoc} - */ - public ExoCache create(ExoCacheConfig config, ConfigurationBuilder confBuilder, - Callable> cacheGetter) throws ExoCacheInitException - { - if (config instanceof GenericExoCacheConfig) - { - final GenericExoCacheConfig gConfig = (GenericExoCacheConfig)config; - return create(config, confBuilder, cacheGetter, gConfig.getStrategy(), gConfig.getMaxSize(), - gConfig.getLiveTime(), gConfig.getMaxIdle() == 0 ? defaultMaxIdle : gConfig.getMaxIdle(), - gConfig.getWakeUpInterval() == 0 ? defaultWakeUpInterval : gConfig.getWakeUpInterval()); - } - else - { - final long period = config.getLiveTime(); - return create(config, confBuilder, cacheGetter, - config.getImplementation() == null ? defaultStrategy : config.getImplementation(), config.getMaxSize(), - period > 0 ? period * 1000 : -1, defaultMaxIdle, defaultWakeUpInterval); - } - } - - /** - * Creates a new ExoCache instance with the relevant parameters - * @throws ExoCacheInitException If any exception occurs while creating the cache - */ - private ExoCache create(ExoCacheConfig config, ConfigurationBuilder confBuilder, - Callable> cacheGetter, String strategy, int maxEntries, long lifespan, long maxIdle, - long wakeUpInterval) throws ExoCacheInitException - { - EvictionStrategy es = - strategy == null || strategy.length() == 0 ? null : EvictionStrategy.valueOf(strategy - .toUpperCase(Locale.ENGLISH)); - if (es == null) - { - es = EvictionStrategy.LRU; - } - confBuilder.eviction().strategy(EvictionStrategy.valueOf(strategy)).maxEntries(maxEntries).expiration() - .lifespan(lifespan).maxIdle(maxIdle).wakeUpInterval(wakeUpInterval); - try - { - return new GenericExoCache(config, cacheGetter.call()); - } - catch (Exception e)//NOSONAR - { - throw new ExoCacheInitException("Cannot create the cache '" + config.getName() + "'", e); - } - } - - /** - * The Generic implementation of an ExoCache - */ - public static class GenericExoCache extends AbstractExoCache - { - - public GenericExoCache(ExoCacheConfig config, Cache cache) - { - super(config, cache); - } - - public void setMaxSize(int max) - { - throw new UnsupportedOperationException("The configuration of the cache cannot not be modified"); - } - - public void setLiveTime(long period) - { - throw new UnsupportedOperationException("The configuration of the cache cannot not be modified"); - } - - public int getMaxSize() - { - return Math.toIntExact(cache.getCacheConfiguration().eviction().maxEntries()); - } - - public long getLiveTime() - { - return cache.getCacheConfiguration().expiration().lifespan(); - } - - @Managed - @ManagedName("MaxIdle") - @ManagedDescription("Maximum idle time a cache entry will be maintained in the cache. " - + "If the idle time is exceeded, the entry will be expired cluster-wide. -1 means the entries never expire.") - public long getMaxIdle() - { - return cache.getCacheConfiguration().expiration().maxIdle(); - } - - @Managed - @ManagedName("WakeUpInterval") - @ManagedDescription("Interval between subsequent eviction runs. If you wish to disable the periodic eviction " - + "process altogether, set wakeupInterval to -1.") - public long getWakeUpInterval() - { - return cache.getCacheConfiguration().expiration().wakeUpInterval(); - } - } -} \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/AbstractMapper.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/AbstractMapper.java deleted file mode 100644 index ecd304554..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/AbstractMapper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.ispn; - -import org.infinispan.distexec.mapreduce.Collector; -import org.infinispan.distexec.mapreduce.Mapper; - -/** - * The main class of all the mappers. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public abstract class AbstractMapper implements Mapper -{ - - /** - * The serial version UID - */ - private static final long serialVersionUID = 7118530772747505976L; - - /** - * {@inheritDoc} - */ - @Override - public void map(KIn key, VIn value, Collector collector) - { - if (isValid(key)) - { - _map(key, value, collector); - } - } - - /** - * This method is in fact an internal mapping, it will be called by the map method in - * case the given key matches with the context - */ - protected abstract void _map(KIn key, VIn value, Collector collector); - - /** - * Indicates if the given key matches with the current context, indeed as the cache instances are - * shared it is needed to check each key to know if it is part of the targeted scope or not. - * - * @param key the key to check - * @return true if the key matches with the scope, false otherwise. - */ - protected abstract boolean isValid(KIn key); - -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java deleted file mode 100644 index 570c53652..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.ispn; - -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.util.TemplateConfigurationHelper; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.container.xml.PropertiesParam; -import org.exoplatform.container.xml.ValueParam; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.transaction.TransactionService; -import org.infinispan.Cache; -import org.infinispan.configuration.cache.ConfigurationBuilder; -import org.infinispan.configuration.global.GlobalConfigurationBuilder; -import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; -import org.infinispan.configuration.parsing.ParserRegistry; -import org.infinispan.manager.DefaultCacheManager; -import org.infinispan.manager.EmbeddedCacheManager; -import org.infinispan.transaction.lookup.TransactionManagerLookup; -import org.picocontainer.Startable; - -import java.util.Map; -import java.util.Map.Entry; - -import javax.transaction.TransactionManager; - -/** - * This class is used to allow to use infinispan in distribution mode with - * the ability to launch infinispan instances in standalone mode, in other - * words outside an application server. To make it possible we will need to share - * the same cache instance whatever the related {@link ExoContainer} because - * to be able to launch ispn instances in standalone mode we need to have a static - * configuration file. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class DistributedCacheManager implements Startable -{ - /** - * The logger - */ - private static final Log LOG = ExoLogger //NOSONAR - .getLogger("exo.kernel.component.ext.cache.impl.infinispan.v8.DistributedCacheManager");//NOSONAR - - /** - * The parameter name corresponding to the infinispan configuration - */ - private static final String CONFIG_FILE_PARAMETER_NAME = "infinispan-configuration"; - - /** - * The parameter name corresponding to the parameters to inject - * into the infinispan configuration file - */ - private static final String PARAMS_PARAMETER_NAME = "parameters"; - - /** - * The infinispan cache manager - */ - protected final EmbeddedCacheManager manager; - - /** - * Default constructor - */ - public DistributedCacheManager(String configurationFile, Map parameters, - ConfigurationManager configManager) - { - this.manager = init(configurationFile, parameters, configManager, null); - } - - /** - * Default constructor - */ - public DistributedCacheManager(InitParams params, ConfigurationManager configManager) - { - this(params, configManager, null); - } - - /** - * Default constructor - */ - public DistributedCacheManager(InitParams params, ConfigurationManager configManager, TransactionService ts) - { - ValueParam vp; - final String result; - if (params != null && (vp = params.getValueParam(CONFIG_FILE_PARAMETER_NAME)) != null - && (result = vp.getValue()) != null && !result.isEmpty()) - { - PropertiesParam pp = params.getPropertiesParam(PARAMS_PARAMETER_NAME); - this.manager = - init(result, pp == null ? null : pp.getProperties(), configManager, - ts == null ? null : ts.getTransactionManager()); - } - else - { - throw new IllegalArgumentException("The parameter '" + CONFIG_FILE_PARAMETER_NAME + "' must be set"); - } - } - - /** - * Initializes and created the CacheManager - * @param configurationFile the path of the configuration file - * @param parameters the parameters to inject into the configuration file - * @param configManager the configuration manager used to get the configuration file - * @param tm the transaction manager - * @return the CacheManager initialized - */ - private EmbeddedCacheManager init(final String configurationFile, final Map parameters, - final ConfigurationManager configManager, final TransactionManager tm) - { - try - { - if (configurationFile == null || configurationFile.isEmpty()) - { - throw new IllegalArgumentException("The parameter 'configurationFile' must be set"); - } - if (LOG.isDebugEnabled()) - { - LOG.debug("The configuration file of the DistributedCacheManager will be loaded from " + configurationFile); - } - final TemplateConfigurationHelper helper = - new TemplateConfigurationHelper(new String[]{"^.*"}, new String[]{}, configManager); - if (LOG.isDebugEnabled() && parameters != null && !parameters.isEmpty()) - { - LOG.debug("The parameters to use while processing the configuration file are " + parameters); - } - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Load the configuration - ConfigurationBuilderHolder holder = parser.parse(helper.fillTemplate(configurationFile, parameters)); - GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); - Utils.loadJGroupsConfig(configManager, configBuilder.build(), configBuilder); - // Create the CacheManager from the new configuration - EmbeddedCacheManager manager = - new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder().build()); - TransactionManagerLookup tml = new TransactionManagerLookup() - { - public TransactionManager getTransactionManager() throws Exception - { - return tm; - } - }; - for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) - { - ConfigurationBuilder b = entry.getValue(); - if (tm != null) - { - b.transaction().transactionManagerLookup(tml); - } - manager.defineConfiguration(entry.getKey(), b.build()); - } - for( String cacheName : manager.getCacheNames()) - { - manager.getCache(cacheName); - } - return manager; - } - catch (Exception e)//NOSONAR - { - throw new IllegalStateException( - "Could not initialize the cache manager corresponding to the configuration file " + configurationFile, e); - } - } - - /** - * Gives the cache corresponding to the given name if it doesn't exist - * a {@link NullPointerException} will be thrown - */ - public Cache getCache(String cacheName) - { - Cache cache = manager.getCache(cacheName); - if (cache == null) - { - throw new IllegalArgumentException("The expected cache named '" + cacheName - + "' has not been defined in the configuration of infinispan as named cache."); - } - return cache; - } - - /** - * @see org.picocontainer.Startable#start() - */ - @Override - public void start() - { - } - - /** - * @see org.picocontainer.Startable#stop() - */ - @Override - public void stop() - { - manager.stop(); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/Utils.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/Utils.java deleted file mode 100644 index c8b31d9f1..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/Utils.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.ispn; - -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.container.util.TemplateConfigurationHelper; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.infinispan.configuration.global.GlobalConfiguration; -import org.infinispan.configuration.global.GlobalConfigurationBuilder; -import org.infinispan.remoting.transport.jgroups.JGroupsTransport; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class Utils -{ - - private Utils() - { - } - - /** - * Load the JGroups configuration file thanks to the {@link ConfigurationManager} - * @param config the global configuration from which the JGroups config will be extracted - * @param configBuilder the related configuration builder - * @return true if the JGoups config could be loaded successfully, - * false if there were no JGroups config to load - * @throws IllegalStateException if the JGroups config could not be loaded - */ - public static boolean loadJGroupsConfig(ConfigurationManager cfm, GlobalConfiguration config, - GlobalConfigurationBuilder configBuilder) throws ExoCacheInitException - { - Properties properties = config.transport().properties(); - if (properties == null || !properties.containsKey(JGroupsTransport.CONFIGURATION_FILE)) - { - return false; - } - String filename = properties.getProperty(JGroupsTransport.CONFIGURATION_FILE); - InputStream inputStream = TemplateConfigurationHelper.getInputStream(cfm, filename); - - // inputStream still remains null, so file was not opened - if (inputStream == null) - { - throw new IllegalStateException("The jgroups configuration cannot be loaded from '" + filename + "'"); - } - try - { - // Set the jgroups configuration as XML - properties.setProperty(JGroupsTransport.CONFIGURATION_XML, - org.exoplatform.container.util.Utils.readStream(inputStream)); - } - catch (IOException e) - { - throw new IllegalStateException("The jgroups configuration cannot be read from '" + filename + "'", e); - } - // Remove the property corresponding to the configuration file - properties.remove(JGroupsTransport.CONFIGURATION_FILE); - configBuilder.transport().withProperties(properties); - return true; - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/GenericTransactionService.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/GenericTransactionService.java deleted file mode 100644 index 646ce67b5..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/GenericTransactionService.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.infinispan; - -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.services.transaction.impl.AbstractTransactionService; -import org.infinispan.transaction.lookup.TransactionManagerLookup; - -import javax.transaction.TransactionManager; - -/** - * @author Dmytro Katayev - * @version $Id: GenericTransactionService.java -1 $ - */ -public class GenericTransactionService extends AbstractTransactionService -{ - - /** - * TransactionManagerLookup. - */ - protected final TransactionManagerLookup tmLookup; - - /** - * JBossTransactionManagerLookup constructor. - * - * @param tmLookup TransactionManagerLookup - */ - public GenericTransactionService(TransactionManagerLookup tmLookup) - { - this(tmLookup, null); - } - - public GenericTransactionService(TransactionManagerLookup tmLookup, InitParams params) - { - super(params); - this.tmLookup = tmLookup; - } - - /** - * {@inheritDoc} - */ - public TransactionManager findTransactionManager() throws Exception - { - return tmLookup.getTransactionManager(); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossStandaloneJTAManagerLookup.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossStandaloneJTAManagerLookup.java deleted file mode 100644 index a9b62a7b0..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossStandaloneJTAManagerLookup.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2011 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.infinispan; - -import org.exoplatform.commons.utils.ClassLoading; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.transaction.TransactionService; -import org.infinispan.transaction.lookup.TransactionManagerLookup; - -import java.lang.reflect.Method; - -import javax.transaction.TransactionManager; -import javax.transaction.UserTransaction; - -/** - * This class is used to replace the one provided by default in ISPN 5.0 since - * it implicitly requires that ISPN is initialized before the rest which is actually - * the exact opposite. Indeed Arjuna accessors are initialized in the init method which is - * called at ISPN initialization but we expect to get the {@link TransactionManager} - * from it through the {@link TransactionService} before initializing the JCR so before - * initializing ISPN. - * - * The code below is a simple copy/paste of the code of - * {@link org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup} of ISPN 4. - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class JBossStandaloneJTAManagerLookup implements TransactionManagerLookup -{ - /** - * The logger - */ - private static final Log LOG = //NOSONAR - ExoLogger.getLogger("exo.jcr.component.core.JBossStandaloneJTAManagerLookup");//NOSONAR - - private Method manager, user; - - public JBossStandaloneJTAManagerLookup() - { - try - { - manager = loadClassStrict("com.arjuna.ats.jta.TransactionManager").getMethod("transactionManager"); - user = loadClassStrict("com.arjuna.ats.jta.UserTransaction").getMethod("userTransaction"); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException(e);//NOSONAR - } - catch (SecurityException e) - { - throw new RuntimeException(e);//NOSONAR - } - catch (NoSuchMethodException e) - { - throw new RuntimeException(e);//NOSONAR - } - } - - public TransactionManager getTransactionManager() throws Exception - { - TransactionManager tm = (TransactionManager)manager.invoke(null); - if (tm == null && LOG.isWarnEnabled()) - { - LOG.warn("The transaction manager could not be found"); - } - return tm; - } - - public UserTransaction getUserTransaction() throws Exception - { - UserTransaction ut = (UserTransaction)user.invoke(null); - if (ut == null && LOG.isWarnEnabled()) - { - LOG.warn("The user transaction could not be found"); - } - return ut; - } - - /** - * Loads the specified class using this class's classloader, or, if it is null (i.e. this class was - * loaded by the bootstrap classloader), the system classloader.
If loadtime instrumentation via - * GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap classloader.
- * - * @param classname name of the class to load - * @return the class - * @throws ClassNotFoundException - */ - private static Class loadClassStrict(String classname) throws ClassNotFoundException - { - return ClassLoading.loadClass(classname, JBossStandaloneJTAManagerLookup.class); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossTransactionsService.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossTransactionsService.java deleted file mode 100644 index 64a550154..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/transaction/infinispan/JBossTransactionsService.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.transaction.infinispan; - -import org.exoplatform.container.xml.InitParams; -import org.infinispan.transaction.lookup.TransactionManagerLookup; - -import javax.transaction.UserTransaction; - -/** - * Add the specific part for Arjuna - * - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class JBossTransactionsService extends GenericTransactionService -{ - - public JBossTransactionsService(TransactionManagerLookup tmLookup) - { - super(tmLookup); - } - - public JBossTransactionsService(TransactionManagerLookup tmLookup, InitParams params) - { - super(tmLookup, params); - } - - /** - * {@inheritDoc} - */ - @Override - protected UserTransaction findUserTransaction() throws Exception - { - return com.arjuna.ats.jta.UserTransaction.userTransaction(); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/cache-configuration-template.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/cache-configuration-template.xml deleted file mode 100644 index ca8d883b1..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/cache-configuration-template.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/configuration.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/configuration.xml deleted file mode 100644 index b9783cdb3..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/resources/conf/portal/configuration.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - org.exoplatform.services.cache.ExoCacheFactory - org.exoplatform.services.cache.impl.infinispan.ExoCacheFactoryImpl - - - cache.config.template - jar:/conf/portal/cache-configuration-template.xml - - - - diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestAbstractExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestAbstractExoCache.java deleted file mode 100644 index 5bc85214c..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestAbstractExoCache.java +++ /dev/null @@ -1,692 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import junit.framework.TestCase; - -import org.exoplatform.container.ExoContainer; -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.RootContainer; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.services.cache.CacheListener; -import org.exoplatform.services.cache.CacheListenerContext; -import org.exoplatform.services.cache.CacheService; -import org.exoplatform.services.cache.CachedObjectSelector; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheFactory; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.exoplatform.services.cache.ObjectCacheInfo; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestAbstractExoCache extends TestCase -{ - - PortalContainer container; - - CacheService service; - - AbstractExoCache cache; - - public TestAbstractExoCache(String name) - { - super(name); - } - - public void setUp() throws Exception - { - - ExoContainer topContainer = ExoContainerContext.getTopContainer(); - if(topContainer != null) { - topContainer.stop(); - } - RootContainer.setInstance(null); - ExoContainerContext.setCurrentContainer(null); - - this.container = PortalContainer.getInstance(); - this.service = container.getComponentInstanceOfType(CacheService.class); - this.cache = (AbstractExoCache)service.getCacheInstance("myCache"); - } - - public void testGet() throws Exception - { - cache.put(new MyKey("a"), "a"); - assertEquals("a", cache.get(new MyKey("a"))); - cache.put(new MyKey("a"), "c"); - assertEquals("c", cache.get(new MyKey("a"))); - cache.remove(new MyKey("a")); - assertEquals(null, cache.get(new MyKey("a"))); - assertEquals(null, cache.get(new MyKey("x"))); - - cache.clearCache(); - } - - public void testRemove() throws Exception - { - cache.put(new MyKey("a"), 1); - cache.put(new MyKey("b"), 2); - cache.put(new MyKey("c"), 3); - assertEquals(3, cache.getCacheSize()); - assertEquals(1, cache.remove(new MyKey("a"))); - assertEquals(2, cache.getCacheSize()); - assertEquals(2, cache.remove(new MyKey("b"))); - assertEquals(1, cache.getCacheSize()); - assertEquals(null, cache.remove(new MyKey("x"))); - assertEquals(1, cache.getCacheSize()); - - cache.clearCache(); - } - - public void testPutMap() throws Exception - { - Map values = new HashMap(); - values.put(new MyKey("a"), "a"); - values.put(new MyKey("b"), "b"); - assertEquals(0, cache.getCacheSize()); - cache.putMap(values); - assertEquals(2, cache.getCacheSize()); - values = new HashMap() - { - private static final long serialVersionUID = 1L; - - public Set> entrySet() - { - Set> set = new LinkedHashSet>(super.entrySet()); - set.add(new Entry() - { - - public Object setValue(Object paramV) - { - return null; - } - - public Object getValue() - { - throw new RuntimeException("An exception"); - } - - public Serializable getKey() - { - return "c"; - } - }); - return set; - } - }; - values.put(new MyKey("e"), "e"); - values.put(new MyKey("d"), "d"); - cache.putMap(values); - assertEquals(2, cache.getCacheSize()); - - cache.clearCache(); - } - - public void testGetCachedObjects() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - cache.put(new MyKey("d"), null); - assertEquals(3, cache.getCacheSize()); - List values = cache.getCachedObjects(); - assertEquals(3, values.size()); - assertTrue(values.contains("a")); - assertTrue(values.contains("b")); - assertTrue(values.contains("c")); - - cache.clearCache(); - } - - public void testRemoveCachedObjects() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - cache.put(new MyKey("d"), null); - assertEquals(3, cache.getCacheSize()); - List values = cache.removeCachedObjects(); - assertEquals(3, values.size()); - assertTrue(values.contains("a")); - assertTrue(values.contains("b")); - assertTrue(values.contains("c")); - assertEquals(0, cache.getCacheSize()); - - cache.clearCache(); - } - - public void testSelect() throws Exception - { - cache.put(new MyKey("a"), 1); - cache.put(new MyKey("b"), 2); - cache.put(new MyKey("c"), 3); - final AtomicInteger count = new AtomicInteger(); - CachedObjectSelector selector = new CachedObjectSelector() - { - - public void onSelect(ExoCache cache, Serializable key, - ObjectCacheInfo ocinfo) throws Exception - { - assertTrue(key.equals(new MyKey("a")) || key.equals(new MyKey("b")) || key.equals(new MyKey("c"))); - assertTrue(ocinfo.get().equals(1) || ocinfo.get().equals(2) || ocinfo.get().equals(3)); - count.incrementAndGet(); - } - - public boolean select(Serializable key, ObjectCacheInfo ocinfo) - { - return true; - } - }; - cache.select(selector); - assertEquals(3, count.intValue()); - - cache.clearCache(); - } - - public void testGetHitsNMisses() throws Exception - { - int hits = cache.getCacheHit(); - int misses = cache.getCacheMiss(); - cache.put(new MyKey("a"), "a"); - cache.get(new MyKey("a")); - cache.remove(new MyKey("a")); - cache.get(new MyKey("a")); - cache.get(new MyKey("z")); - assertEquals(1, cache.getCacheHit() - hits); - assertEquals(2, cache.getCacheMiss() - misses); - - cache.clearCache(); - } - - private ExoCacheFactory getExoCacheFactoryInstance() throws ExoCacheInitException - { - PortalContainer pc = PortalContainer.getInstance(); - return new ExoCacheFactoryImpl((ExoContainerContext)pc.getComponentInstanceOfType(ExoContainerContext.class), - "jar:/conf/portal/cache-configuration-template.xml", null, (ConfigurationManager)pc - .getComponentInstanceOfType(ConfigurationManager.class), null); - } - - public void testMultiThreading() throws Exception - { - final ExoCache cache = service.getCacheInstance("test-multi-threading"); - final int totalElement = 100; - final int totalTimes = 20; - int reader = 20; - int writer = 10; - int remover = 5; - int cleaner = 1; - final CountDownLatch startSignalWriter = new CountDownLatch(1); - final CountDownLatch startSignalOthers = new CountDownLatch(1); - final CountDownLatch doneSignal = new CountDownLatch(reader + writer + remover); - final List errors = Collections.synchronizedList(new ArrayList()); - for (int i = 0; i < writer; i++) - { - final int index = i; - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalWriter.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - if (index == 0 && j == 0) - { - // The cache is full, we can launch the others - startSignalOthers.countDown(); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - startSignalWriter.countDown(); - for (int i = 0; i < reader; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalOthers.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.get(new MyKey("key" + i)); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - for (int i = 0; i < remover; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalOthers.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.remove(new MyKey("key" + i)); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - doneSignal.await(); - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - assertEquals(totalElement, cache.getCacheSize()); - final CountDownLatch startSignal = new CountDownLatch(1); - final CountDownLatch doneSignal2 = new CountDownLatch(writer + cleaner); - for (int i = 0; i < writer; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignal.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal2.countDown(); - } - } - }; - thread.start(); - } - for (int i = 0; i < cleaner; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignal.await(); - for (int j = 0; j < totalTimes; j++) - { - sleep(150); - cache.clearCache(); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal2.countDown(); - } - } - }; - thread.start(); - } - cache.clearCache(); - assertEquals(0, cache.getCacheSize()); - if (!errors.isEmpty()) - { - for (Exception e : errors) - { - e.printStackTrace(); - } - throw errors.get(0); - } - cache.clearCache(); - } - - public static class MyCacheListener implements CacheListener - { - - public int clearCache; - - public int expire; - - public int get; - - public int put; - - public int remove; - - public void onClearCache(CacheListenerContext context) throws Exception - { - clearCache++; - } - - public void onExpire(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - expire++; - } - - public void onGet(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - get++; - } - - public void onPut(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - put++; - } - - public void onRemove(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - remove++; - } - } - - public static class MyKey implements Serializable - { - private static final long serialVersionUID = 1L; - - public String value; - - public MyKey(String value) - { - this.value = value; - } - - @Override - public boolean equals(Object paramObject) - { - return paramObject instanceof MyKey && ((MyKey)paramObject).value.equals(value); - } - - @Override - public int hashCode() - { - return value.hashCode(); - } - - @Override - public String toString() - { - return value; - } - } - - /** - * WARNING: For Linux distributions the following JVM parameter must be set to true: java.net.preferIPv4Stack - */ - @SuppressWarnings("unchecked") - public void testDistributedCache() throws Exception - { - // If the cache is still alive this test fails due to a TimeoutException. -// cache.cache.getCacheManager().stop(); - ExoCacheConfig config = new ExoCacheConfig(); - config.setName("MyCacheDistributed"); - config.setMaxSize(8); - config.setLiveTime(1); - config.setImplementation("LRU"); - config.setReplicated(true); - ExoCacheConfig config2 = new ExoCacheConfig(); - config2.setName("MyCacheDistributed2"); - config2.setMaxSize(8); - config2.setLiveTime(1); - config2.setImplementation("LRU"); - config2.setReplicated(true); - AbstractExoCache cache1 = - (AbstractExoCache)getExoCacheFactoryInstance().createCache(config); - MyCacheListener listener1 = new MyCacheListener(); - cache1.addCacheListener(listener1); - AbstractExoCache cache2 = - (AbstractExoCache)getExoCacheFactoryInstance().createCache(config); - MyCacheListener listener2 = new MyCacheListener(); - cache2.addCacheListener(listener2); - try - { - cache1.put(new MyKey("a"), "b"); - assertEquals(1, cache1.getCacheSize()); - assertEquals("b", cache2.get(new MyKey("a"))); - assertEquals(1, cache2.getCacheSize()); - assertEquals(1, listener1.put); - assertEquals(1, listener2.put); - assertEquals(0, listener1.get); - assertEquals(1, listener2.get); - cache2.put(new MyKey("b"), "c"); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals("c", cache1.get(new MyKey("b"))); - assertEquals(2, listener1.put); - assertEquals(2, listener2.put); - assertEquals(1, listener1.get); - assertEquals(1, listener2.get); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals(2, listener1.put); - assertEquals(2, listener2.put); - assertEquals(1, listener1.get); - assertEquals(1, listener2.get); - cache2.put(new MyKey("a"), "a"); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals("a", cache1.get(new MyKey("a"))); - assertEquals(3, listener1.put); - assertEquals(3, listener2.put); - assertEquals(2, listener1.get); - assertEquals(1, listener2.get); - cache2.remove(new MyKey("a")); - assertEquals(1, cache1.getCacheSize()); - assertEquals(1, cache2.getCacheSize()); - assertEquals(3, listener1.put); - assertEquals(3, listener2.put); - assertEquals(2, listener1.get); - assertEquals(1, listener2.get); - assertEquals(1, listener1.remove); - assertEquals(1, listener2.remove); - cache1.put(new MyKey("c"), "c"); - cache1.clearCache(); - assertEquals(0, cache1.getCacheSize()); - assertEquals(null, cache1.get(new MyKey("b"))); - assertEquals("c", cache2.get(new MyKey("b"))); - assertEquals("c", cache2.get(new MyKey("c"))); - assertEquals(2, cache2.getCacheSize()); - assertEquals(4, listener1.put); - assertEquals(4, listener2.put); - assertEquals(3, listener1.get); - assertEquals(3, listener2.get); - assertEquals(1, listener1.remove); - assertEquals(1, listener2.remove); - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - Map values = new HashMap(); - values.put(new MyKey("a"), "a"); - values.put(new MyKey("b"), "b"); - cache1.putMap(values); - assertEquals(2, cache1.getCacheSize()); - Thread.sleep(40); - assertEquals("a", cache2.get(new MyKey("a"))); - assertEquals("b", cache2.get(new MyKey("b"))); - assertEquals(3, cache2.getCacheSize()); - assertEquals(6, listener1.put); - assertEquals(6, listener2.put); - assertEquals(3, listener1.get); - assertEquals(5, listener2.get); - assertEquals(1, listener1.remove); - assertEquals(1, listener2.remove); - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - values = new HashMap() - { - private static final long serialVersionUID = 1L; - - public Set> entrySet() - { - Set> set = new LinkedHashSet>(super.entrySet()); - set.add(new Entry() - { - - public Object setValue(Object paramV) - { - return null; - } - - public Object getValue() - { - throw new RuntimeException("An exception"); - } - - public Serializable getKey() - { - return "c"; - } - }); - return set; - } - }; - values.put(new MyKey("e"), "e"); - values.put(new MyKey("d"), "d"); - cache1.putMap(values); - assertEquals(2, cache1.getCacheSize()); - assertEquals(3, cache2.getCacheSize()); - assertEquals(6, listener1.put); - assertEquals(6, listener2.put); - assertEquals(3, listener1.get); - assertEquals(5, listener2.get); - assertEquals(1, listener1.remove); - assertEquals(1, listener2.remove); - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - assertEquals(0, listener1.expire); - assertEquals(0, listener2.expire); - Thread.sleep(5600); - // The values are evicted lazily when we call it - cache1.get(new MyKey("a")); - cache1.get(new MyKey("b")); - cache2.get(new MyKey("a")); - cache2.get(new MyKey("b")); - cache2.get(new MyKey("c")); - assertEquals(0, cache1.getCacheSize()); - assertEquals(0, cache2.getCacheSize()); - assertEquals(6, listener1.put); - assertEquals(6, listener2.put); - assertEquals(5, listener1.get); - assertEquals(8, listener2.get); - assertEquals(1, listener1.remove); - assertEquals(1, listener2.remove); - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - } - finally - { - cache1.cache.getCacheManager().stop(); - cache2.cache.getCacheManager().stop(); - } - } - public void testPut() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - assertEquals(3, cache.getCacheSize()); - cache.put(new MyKey("a"), "c"); - assertEquals(3, cache.getCacheSize()); - cache.put(new MyKey("d"), "c"); - assertEquals(4, cache.getCacheSize()); - - cache.clearCache(); - } - - public void testClearCache() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - assertTrue(cache.getCacheSize() > 0); - cache.clearCache(); - assertTrue(cache.getCacheSize() == 0); - - cache.clearCache(); - } - -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheConfig.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheConfig.java deleted file mode 100644 index 37d6836d9..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.services.cache.ExoCacheConfig; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestExoCacheConfig extends ExoCacheConfig -{ - -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheCreator.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheCreator.java deleted file mode 100644 index b6545562d..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheCreator.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import org.exoplatform.services.cache.CacheListener; -import org.exoplatform.services.cache.CachedObjectSelector; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheInitException; -import org.infinispan.Cache; -import org.infinispan.configuration.cache.ConfigurationBuilder; - -import java.io.Serializable; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Callable; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestExoCacheCreator implements ExoCacheCreator -{ - - /** - * {@inheritDoc} - */ - @Override - public ExoCache create(ExoCacheConfig config, ConfigurationBuilder confBuilder, - Callable> cacheGetter) throws ExoCacheInitException - { - return new TestExoCache(); - } - - public Class getExpectedConfigType() - { - return TestExoCacheConfig.class; - } - - public Set getExpectedImplementations() - { - return Collections.singleton("TEST"); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public static class TestExoCache implements ExoCache - { - - public void addCacheListener(CacheListener listener) - { - } - - public int getCacheHit() - { - return 0; - } - - public int getCacheMiss() - { - return 0; - } - - public int getCacheSize() - { - return 0; - } - - public List getCachedObjects() - { - return null; - } - - public String getLabel() - { - return null; - } - - public long getLiveTime() - { - return 0; - } - - public int getMaxSize() - { - return 0; - } - - public String getName() - { - return "name"; - } - - public boolean isDistributed() - { - return false; - } - - public boolean isLogEnabled() - { - return false; - } - - public boolean isReplicated() - { - return false; - } - - public void select(CachedObjectSelector selector) throws Exception - { - - } - - public void setDistributed(boolean b) - { - - } - - public void setLabel(String s) - { - - } - - public void setLiveTime(long period) - { - - } - - public void setLogEnabled(boolean b) - { - - } - - public void setMaxSize(int max) - { - - } - - public void setName(String name) - { - - } - - public void setReplicated(boolean b) - { - - } - - public void clearCache() - { - - } - - public Object get(Serializable key) - { - return null; - } - - public void put(Serializable key, Object value) throws NullPointerException - { - - } - - public void putMap(Map objs) throws NullPointerException, IllegalArgumentException - { - - } - - public Object remove(Serializable key) throws NullPointerException - { - return null; - } - - public List removeCachedObjects() - { - return null; - } - - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheFactoryImpl.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheFactoryImpl.java deleted file mode 100644 index fbfcbcacb..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/TestExoCacheFactoryImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan; - -import junit.framework.TestCase; - -import org.exoplatform.container.PortalContainer; -import org.exoplatform.services.cache.CacheService; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.impl.infinispan.TestExoCacheCreator.TestExoCache; -import org.infinispan.configuration.cache.CacheMode; -import org.infinispan.manager.CacheContainer; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -@SuppressWarnings("rawtypes") -public class TestExoCacheFactoryImpl extends TestCase -{ - - CacheService service_; - - public TestExoCacheFactoryImpl(String name) - { - super(name); - } - - public void setUp() throws Exception - { - service_ = (CacheService)PortalContainer.getInstance().getComponentInstanceOfType(CacheService.class); - } - - public void testCacheFactory() - { - ExoCache cache = service_.getCacheInstance("myCache"); - assertTrue("expect an instance of AbstractExoCache", cache instanceof AbstractExoCache); - AbstractExoCache aCache = (AbstractExoCache)cache; - assertTrue("expect a local cache", - aCache.cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.LOCAL); - aCache.cache.stop(); - cache = service_.getCacheInstance("cacheDistributed"); - assertTrue("expect an instance of AbstractExoCache", cache instanceof AbstractExoCache); - aCache = (AbstractExoCache)cache; - assertTrue("expect a distributed cache", - aCache.cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.REPL_SYNC); - aCache.cache.stop(); - cache = service_.getCacheInstance("myCustomCache"); - assertTrue("expect an instance of AbstractExoCache", cache instanceof AbstractExoCache); - aCache = (AbstractExoCache)cache; - assertTrue("expect a distributed cache", - aCache.cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.REPL_SYNC); - aCache.cache.stop(); - } - - public void testExoCacheCreator() - { - ExoCache cache = service_.getCacheInstance("test-default-impl"); - assertTrue("expect an instance of AbstractExoCache", cache instanceof AbstractExoCache); - AbstractExoCache aCache = (AbstractExoCache)cache; - aCache.cache.stop(); - cache = service_.getCacheInstance("test-custom-impl-with-old-config"); - assertTrue("expect an instance of TestExoCache", cache instanceof TestExoCache); - cache = service_.getCacheInstance("test-custom-impl-with-new-config"); - assertTrue("expect an instance of TestExoCache", cache instanceof TestExoCache); - } - - public void testSameCacheManager() - { - ExoCache cache1 = service_.getCacheInstance("myCustomCache"); - assertTrue("expect an instance of AbstractExoCache", cache1 instanceof AbstractExoCache); - AbstractExoCache aCache1 = (AbstractExoCache)cache1; - CacheContainer cacheContainer1 = aCache1.cache.getCacheManager(); - - ExoCache cache2 = service_.getCacheInstance("myCustomCache-Bis"); - assertTrue("expect an instance of AbstractExoCache", cache2 instanceof AbstractExoCache); - AbstractExoCache aCache2 = (AbstractExoCache)cache2; - CacheContainer cacheContainer2 = aCache2.cache.getCacheManager(); - assertTrue("The CacheContainer should be the same", cacheContainer1 == cacheContainer2); - - ExoCache cache3 = service_.getCacheInstance("myCustomCache-Bis2"); - assertTrue("expect an instance of AbstractExoCache", cache3 instanceof AbstractExoCache); - AbstractExoCache aCache3 = (AbstractExoCache)cache3; - CacheContainer cacheContainer3 = aCache3.cache.getCacheManager(); - assertTrue("The CacheContainer should be the same", cacheContainer1 == cacheContainer3); - - aCache1.cache.stop(); - aCache2.cache.stop(); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/distributed/TestDistributedExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/distributed/TestDistributedExoCache.java deleted file mode 100644 index 632f16447..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/java/org/exoplatform/services/cache/impl/infinispan/distributed/TestDistributedExoCache.java +++ /dev/null @@ -1,858 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.services.cache.impl.infinispan.distributed; - -import junit.framework.TestCase; - -import org.exoplatform.container.ExoContainerContext; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.services.cache.CacheListener; -import org.exoplatform.services.cache.CacheListenerContext; -import org.exoplatform.services.cache.CacheService; -import org.exoplatform.services.cache.CachedObjectSelector; -import org.exoplatform.services.cache.ExoCache; -import org.exoplatform.services.cache.ExoCacheConfig; -import org.exoplatform.services.cache.ExoCacheFactory; -import org.exoplatform.services.cache.ObjectCacheInfo; -import org.exoplatform.services.cache.impl.infinispan.ExoCacheFactoryImpl; -import org.exoplatform.services.ispn.DistributedCacheManager; -import org.infinispan.affinity.KeyAffinityService; -import org.infinispan.affinity.KeyAffinityServiceFactory; -import org.infinispan.affinity.KeyGenerator; -import org.infinispan.distribution.DistributionManager; -import org.junit.Ignore; -import org.junit.Test; - - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Nicolas Filotto - * @version $Id$ - * - */ -public class TestDistributedExoCache extends TestCase -{ - - CacheService service; - - DistributedExoCache cache; - - DistributedExoCache cache2; - - public TestDistributedExoCache(String name) - { - super(name); - } - - public void setUp() throws Exception - { - this.service = (CacheService)PortalContainer.getInstance().getComponentInstanceOfType(CacheService.class); - this.cache = (DistributedExoCache)service.getCacheInstance("cache-distributed"); - this.cache2 = (DistributedExoCache)service.getCacheInstance("cache-distributed2"); - cache2.put(new MyKey("a"), "a"); - } - - protected void tearDown() throws Exception - { - cache.clearCache(); - cache2.clearCache(); - } - - public void testPut() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - assertEquals(3, cache.getCacheSize()); - cache.put(new MyKey("a"), "c"); - assertEquals(3, cache.getCacheSize()); - cache.put(new MyKey("d"), "c"); - assertEquals(4, cache.getCacheSize()); - } - - public void testClearCache() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - assertTrue(cache.getCacheSize() > 0); - cache.clearCache(); - assertTrue(cache.getCacheSize() == 0); - } - - public void testGet() throws Exception - { - cache.put(new MyKey("a"), "a"); - assertEquals("a", cache.get(new MyKey("a"))); - cache.put(new MyKey("a"), "c"); - assertEquals("c", cache.get(new MyKey("a"))); - cache.remove(new MyKey("a")); - assertEquals(null, cache.get(new MyKey("a"))); - assertEquals(null, cache.get(new MyKey("x"))); - } - - public void testRemove() throws Exception - { - cache.put(new MyKey("a"), 1); - cache.put(new MyKey("b"), 2); - cache.put(new MyKey("c"), 3); - assertEquals(3, cache.getCacheSize()); - assertEquals(1, cache.remove(new MyKey("a"))); - assertEquals(2, cache.getCacheSize()); - assertEquals(2, cache.remove(new MyKey("b"))); - assertEquals(1, cache.getCacheSize()); - assertEquals(null, cache.remove(new MyKey("x"))); - assertEquals(1, cache.getCacheSize()); - } - - public void testPutMap() throws Exception - { - Map values = new HashMap(); - values.put(new MyKey("a"), "a"); - values.put(new MyKey("b"), "b"); - assertEquals(0, cache.getCacheSize()); - cache.putMap(values); - assertEquals(2, cache.getCacheSize()); - values = new HashMap() - { - private static final long serialVersionUID = 1L; - - public Set> entrySet() - { - Set> set = new LinkedHashSet>(super.entrySet()); - set.add(new Entry() - { - - public Object setValue(Object paramV) - { - return null; - } - - public Object getValue() - { - throw new RuntimeException("An exception"); - } - - public Serializable getKey() - { - return "c"; - } - }); - return set; - } - }; - values.put(new MyKey("e"), "e"); - values.put(new MyKey("d"), "d"); - cache.putMap(values); - assertEquals(2, cache.getCacheSize()); - } - - public void testGetCachedObjects() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - cache.put(new MyKey("d"), null); - assertEquals(3, cache.getCacheSize()); - List values = cache.getCachedObjects(); - assertEquals(3, values.size()); - assertTrue(values.contains("a")); - assertTrue(values.contains("b")); - assertTrue(values.contains("c")); - } - - public void testRemoveCachedObjects() throws Exception - { - cache.put(new MyKey("a"), "a"); - cache.put(new MyKey("b"), "b"); - cache.put(new MyKey("c"), "c"); - cache.put(new MyKey("d"), null); - assertEquals(3, cache.getCacheSize()); - List values = cache.removeCachedObjects(); - assertEquals(3, values.size()); - assertTrue(values.contains("a")); - assertTrue(values.contains("b")); - assertTrue(values.contains("c")); - assertEquals(0, cache.getCacheSize()); - } - - public void testSelect() throws Exception - { - cache.put(new MyKey("a"), 1); - cache.put(new MyKey("b"), 2); - cache.put(new MyKey("c"), 3); - final AtomicInteger count = new AtomicInteger(); - CachedObjectSelector selector = new CachedObjectSelector() - { - - public void onSelect(ExoCache cache, Serializable key, - ObjectCacheInfo ocinfo) throws Exception - { - assertTrue(key.equals(new MyKey("a")) || key.equals(new MyKey("b")) || key.equals(new MyKey("c"))); - assertTrue(ocinfo.get().equals(1) || ocinfo.get().equals(2) || ocinfo.get().equals(3)); - count.incrementAndGet(); - } - - public boolean select(Serializable key, ObjectCacheInfo ocinfo) - { - return true; - } - }; - cache.select(selector); - assertEquals(3, count.intValue()); - } - - public void testGetHitsNMisses() throws Exception - { - int hits = cache.getCacheHit(); - int misses = cache.getCacheMiss(); - cache.put(new MyKey("a"), "a"); - cache.get(new MyKey("a")); - cache.remove(new MyKey("a")); - cache.get(new MyKey("a")); - cache.get(new MyKey("z")); - assertEquals(1, cache.getCacheHit() - hits); - assertEquals(2, cache.getCacheMiss() - misses); - } - - public void testMultiThreading() throws Exception - { - final int totalElement = 100; - final int totalTimes = 20; - int reader = 20; - int writer = 10; - int remover = 5; - int cleaner = 1; - final CountDownLatch startSignalWriter = new CountDownLatch(1); - final CountDownLatch startSignalOthers = new CountDownLatch(1); - final CountDownLatch doneSignal = new CountDownLatch(reader + writer + remover); - final List errors = Collections.synchronizedList(new ArrayList()); - for (int i = 0; i < writer; i++) - { - final int index = i; - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalWriter.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - if (index == 0 && j == 0) - { - // The cache is full, we can launch the others - startSignalOthers.countDown(); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - startSignalWriter.countDown(); - for (int i = 0; i < reader; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalOthers.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.get(new MyKey("key" + i)); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - for (int i = 0; i < remover; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignalOthers.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.remove(new MyKey("key" + i)); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal.countDown(); - } - } - }; - thread.start(); - } - doneSignal.await(); - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - assertEquals(totalElement, cache.getCacheSize()); - final CountDownLatch startSignal = new CountDownLatch(1); - final CountDownLatch doneSignal2 = new CountDownLatch(writer + cleaner); - for (int i = 0; i < writer; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignal.await(); - for (int j = 0; j < totalTimes; j++) - { - for (int i = 0; i < totalElement; i++) - { - cache.put(new MyKey("key" + i), "value" + i); - } - sleep(50); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal2.countDown(); - } - } - }; - thread.start(); - } - for (int i = 0; i < cleaner; i++) - { - Thread thread = new Thread() - { - public void run() - { - try - { - startSignal.await(); - for (int j = 0; j < totalTimes; j++) - { - sleep(150); - cache.clearCache(); - } - } - catch (Exception e) - { - errors.add(e); - } - finally - { - doneSignal2.countDown(); - } - } - }; - thread.start(); - } - cache.clearCache(); - assertEquals(0, cache.getCacheSize()); - if (!errors.isEmpty()) - { - for (Exception e : errors) - { - e.printStackTrace(); - } - throw errors.get(0); - } - } - - public static class MyCacheListener implements CacheListener - { - - public int clearCache; - - public int expire; - - public int get; - - public int put; - - public int remove; - - public void onClearCache(CacheListenerContext context) throws Exception - { - clearCache++; - } - - public void onExpire(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - expire++; - } - - public void onGet(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - get++; - } - - public void onPut(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - put++; - } - - public void onRemove(CacheListenerContext context, Serializable key, Object obj) throws Exception - { - remove++; - } - } - - public static class MyKey implements Serializable - { - private static final long serialVersionUID = 1L; - - public Object value; - - public String displayValue; - - public MyKey() - { - } - - public MyKey(Object value) - { - this.value = value; - } - - public MyKey(String displayValue, Object value) - { - this.displayValue = displayValue; - this.value = value; - } - - @Override - public boolean equals(Object paramObject) - { - return paramObject instanceof MyKey && ((MyKey)paramObject).value.equals(value); - } - - @Override - public int hashCode() - { - return value.hashCode(); - } - - @Override - public String toString() - { - return displayValue == null ? value.toString() : displayValue; - } - } - - public static class MyKeyGenerator implements KeyGenerator> - { - - public static final Random rnd = new Random(); - - private String fullName; - - public MyKeyGenerator(String fullName) - { - this.fullName = fullName; - } - - @Override - public DistributedExoCache.CacheKey getKey() - { - return new DistributedExoCache.CacheKey(fullName, new MyKey(rnd.nextLong())); - } - } - - /** - * WARNING: For Linux distributions the following JVM parameter must be set to true: java.net.preferIPv4Stack. - * - * @throws Exception - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testDistributedCache() throws Exception - { - PortalContainer pc = PortalContainer.getInstance(); - ExoCacheConfig config = new ExoCacheConfig(); - config.setName("MyCacheDistributed"); - config.setMaxSize(5); - config.setLiveTime(1); - config.setImplementation("LRU"); - config.setDistributed(true); - Map params = new HashMap(); - params.put("infinispan-num-owners", "1"); - ConfigurationManager cm = (ConfigurationManager)pc.getComponentInstanceOfType(ConfigurationManager.class); - DistributedCacheManager dcm2 = - new DistributedCacheManager("jar:/conf/portal/distributed-cache-configuration.xml", params, cm); - - DistributedExoCache cache1 = - (DistributedExoCache)((ExoCacheFactory)pc - .getComponentInstanceOfType(ExoCacheFactory.class)).createCache(config); - DistributionManager dm = cache1.getCache().getDistributionManager(); - DistributedExoCache cache2 = - (DistributedExoCache)new ExoCacheFactoryImpl( - (ExoContainerContext)pc.getComponentInstanceOfType(ExoContainerContext.class), - "jar:/conf/portal/cache-configuration-template.xml", null, cm, dcm2).createCache(config); - KeyAffinityService kas1 = - KeyAffinityServiceFactory.newLocalKeyAffinityService(cache1.getCache(), - new MyKeyGenerator(cache1.getFullName()), Executors.newSingleThreadExecutor(), 100); - KeyAffinityService kas2 = - KeyAffinityServiceFactory.newLocalKeyAffinityService(cache2.getCache(), - new MyKeyGenerator(cache1.getFullName()), Executors.newSingleThreadExecutor(), 100); - - try - { - Object a, b, c; - for (int i = 0; i < 2; i++) - { - if (i == 0) - { - a = - new MyKey("a", ((DistributedExoCache.CacheKey)kas1.getKeyForAddress(cache1.getCache() - .getRpcManager().getAddress())).getKey().value); - } - else - { - a = - new MyKey("a", ((DistributedExoCache.CacheKey)kas2.getKeyForAddress(cache2.getCache() - .getRpcManager().getAddress())).getKey().value); - } - for (int j = 0; j < 2; j++) - { - if (j == 0) - { - b = - new MyKey("b", ((DistributedExoCache.CacheKey)kas1.getKeyForAddress(cache1.getCache() - .getRpcManager().getAddress())).getKey().value); - } - else - { - b = - new MyKey("b", ((DistributedExoCache.CacheKey)kas2.getKeyForAddress(cache2.getCache() - .getRpcManager().getAddress())).getKey().value); - } - for (int k = 0; k < 2; k++) - { - if (k == 0) - { - c = - new MyKey("c", ((DistributedExoCache.CacheKey)kas1.getKeyForAddress(cache1.getCache() - .getRpcManager().getAddress())).getKey().value); - } - else - { - c = - new MyKey("c", ((DistributedExoCache.CacheKey)kas2.getKeyForAddress(cache2.getCache() - .getRpcManager().getAddress())).getKey().value); - } - checkUseCase(cache1, cache2, dm, a, b, c); - } - } - } - } - finally - { - dcm2.stop(); - } - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private void checkUseCase(DistributedExoCache cache1, - DistributedExoCache cache2, DistributionManager dm, Object a, Object b, Object c) - throws InterruptedException - { - MyCacheListener listener1 = new MyCacheListener(); - cache1.addCacheListener(listener1); - MyCacheListener listener2 = new MyCacheListener(); - cache2.addCacheListener(listener2); - boolean isALocal = dm.getLocality(new DistributedExoCache.CacheKey(cache1.getFullName(), new MyKey(a))).isLocal(); - boolean isBLocal = dm.getLocality(new DistributedExoCache.CacheKey(cache1.getFullName(), new MyKey(b))).isLocal(); - boolean isCLocal = dm.getLocality(new DistributedExoCache.CacheKey(cache1.getFullName(), new MyKey(c))).isLocal(); - MyKey key = new MyKey(a); - cache1.put(key, "b"); - assertEquals(1, cache1.getCacheSize()); - assertEquals("b", cache2.get(new MyKey(a))); - assertEquals(1, cache2.getCacheSize()); - - int put1 = 1; - int put2 = isALocal ? 0 : 1; - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(0, listener1.get); - assertEquals(1, listener2.get); - - MyKey key2 = new MyKey(b); - cache2.put(key2, "c"); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals("c", cache1.get(new MyKey(b))); - - put1 += isBLocal ? 1 : 0; - put2++; - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(1, listener1.get); - assertEquals(1, listener2.get); - - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(1, listener1.get); - assertEquals(1, listener2.get); - - key = new MyKey(a); - cache2.put(key, "a"); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals("a", cache1.get(new MyKey(a))); - - put1 += isALocal ? 1 : 0; - put2++; - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(2, listener1.get); - assertEquals(1, listener2.get); - - key = new MyKey(a); - cache2.remove(key); - assertEquals(1, cache1.getCacheSize()); - assertEquals(1, cache2.getCacheSize()); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(2, listener1.get); - assertEquals(1, listener2.get); - - int remove1 = isALocal ? 1 : 0; - int remove2 = 1; - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - key = new MyKey(c); - cache1.put(key, "c"); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - assertEquals("c", cache2.get(new MyKey(c))); - - put1++; - put2 += isCLocal ? 0 : 1; - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(2, listener1.get); - assertEquals(2, listener2.get); - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - assertEquals(0, listener1.clearCache); - assertEquals(0, listener2.clearCache); - - cache1.clearCache(); - assertEquals(0, cache1.getCacheSize()); - assertNull(cache1.get(new MyKey(b))); - assertNull(cache1.get(new MyKey(c))); - assertNull(cache2.get(new MyKey(b))); - assertNull(cache2.get(new MyKey(c))); - assertEquals(0, cache2.getCacheSize()); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(4, listener1.get); - assertEquals(4, listener2.get); - - // Since the clear cache map/reduce can only find cache1, - // the remove calls will be applied to cache1 so cache2 - // will be notified on its entries, this is due to the - // hack used to apply modifications within a map/reduce - remove2 += (isBLocal ? 0 : 1) + (isCLocal ? 0 : 1); - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - - Map values = new HashMap(); - key = new MyKey(a); - key2 = new MyKey(b); - values.put(key, "a"); - values.put(key2, "b"); - cache1.putMap(values); - assertEquals(2, cache1.getCacheSize()); - Thread.sleep(40); - assertEquals("a", cache1.get(new MyKey(a))); - assertEquals("b", cache1.get(new MyKey(b))); - assertEquals("a", cache2.get(new MyKey(a))); - assertEquals("b", cache2.get(new MyKey(b))); - assertEquals(2, cache2.getCacheSize()); - - put1 += 2; - put2 += (isALocal ? 0 : 1) + (isBLocal ? 0 : 1); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(6, listener1.get); - assertEquals(6, listener2.get); - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - - values = new HashMap() - { - private static final long serialVersionUID = 1L; - - public Set> entrySet() - { - Set> set = new LinkedHashSet>(super.entrySet()); - set.add(new Entry() - { - - public Object setValue(Object paramV) - { - return null; - } - - public Object getValue() - { - throw new RuntimeException("An exception"); - } - - public Serializable getKey() - { - return "c"; - } - }); - return set; - } - }; - values.put(new MyKey("e"), "e"); - values.put(new MyKey("d"), "d"); - cache1.putMap(values); - assertEquals(2, cache1.getCacheSize()); - assertEquals(2, cache2.getCacheSize()); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(6, listener1.get); - assertEquals(6, listener2.get); - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - assertEquals(1, listener1.clearCache); - assertEquals(0, listener2.clearCache); - - assertEquals(0, listener1.expire); - assertEquals(0, listener2.expire); - - cache2.clearCache(); - assertEquals(0, cache1.getCacheSize()); - assertEquals(0, cache2.getCacheSize()); - - assertEquals(put1, listener1.put); - assertEquals(put2, listener2.put); - - assertEquals(6, listener1.get); - assertEquals(6, listener2.get); - - // Since the clear cache map/reduce can only find cache1, - // the remove calls will be applied to cache1 so cache2 - // will be notified on its entries, this is due to the - // hack used to apply modifications within a map/reduce - remove2 += (isALocal ? 0 : 1) + (isBLocal ? 0 : 1); - - assertEquals(remove1, listener1.remove); - assertEquals(remove2, listener2.remove); - - assertEquals(1, listener1.clearCache); - assertEquals(1, listener2.clearCache); - - assertEquals(0, listener1.expire); - assertEquals(0, listener2.expire); - } -} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/configuration.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/configuration.xml deleted file mode 100644 index f65a8b475..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/configuration.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - org.exoplatform.services.ispn.DistributedCacheManager - - - infinispan-configuration - jar:/conf/portal/distributed-cache-configuration.xml - - - parameters - The parameters of the configuration - - - - - diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/jgroups/udp.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/jgroups/udp.xml deleted file mode 100644 index 6eccfebf1..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/jgroups/udp.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/cache-configuration-template.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/cache-configuration-template.xml deleted file mode 100644 index 4df9457bc..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/cache-configuration-template.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration-template.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration-template.xml deleted file mode 100644 index 41abb89de..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration-template.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration.xml deleted file mode 100644 index 5bec6064f..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/distributed-cache-configuration.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/test-configuration.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/test-configuration.xml deleted file mode 100644 index 3945a3a62..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/conf/portal/test-configuration.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - - - - org.exoplatform.services.cache.CacheService - org.exoplatform.services.cache.impl.CacheServiceImpl - - - - cache.config.default - The default cache configuration - - default - 10 - 2 - - - - cache-distributed - The default cache configuration - - cache-distributed - 5 - 2 - true - - - - cache-distributed2 - The default cache configuration - - cache-distributed2 - 5 - 2 - true - - - test-multi-threading - The default cache configuration - - test-multi-threading - NONE - -1 - -1 - - - - cacheDistributed - The default cache configuration - - cacheDistributed - 5 - 2 - true - - - - test-default-impl - The default cache configuration - - test-default-impl - 5 - 2 - - - - test-custom-impl-with-old-config - The default cache configuration - - test-custom-impl-with-old-config - 5 - 2 - TEST - - - - test-custom-impl-with-new-config - The default cache configuration - - test-custom-impl-with-new-config - 5 - 2 - - - - - - org.exoplatform.services.cache.ExoCacheFactory - org.exoplatform.services.cache.impl.infinispan.ExoCacheFactoryImpl - - - cache.config.template - jar:/conf/portal/cache-configuration-template.xml - - - - - - org.exoplatform.services.cache.ExoCacheFactory - - addConfig - addConfig - org.exoplatform.services.cache.impl.infinispan.ExoCacheFactoryConfigPlugin - add Custom Configurations - - - myCustomCache - jar:/conf/portal/distributed-cache-configuration-template.xml - - - myCustomCache-Bis - classpath:/conf/portal/distributed-cache-configuration-template.xml - - - - - addCreator - addCreator - org.exoplatform.services.cache.impl.infinispan.ExoCacheCreatorPlugin - add Exo Cache Creator - - - Test - The cache creator for testing purpose - - - - GENERIC - The generic cache creator - - - - - NONE - - - FIFO - - - LRU - - - UNORDERED - - - LIRS - - - - LRU - -1 - 500 - - - - - - diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/test.policy b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/test.policy deleted file mode 100644 index 28ff5d11a..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/test.policy +++ /dev/null @@ -1,30 +0,0 @@ -grant codeBase "@MAVEN_REPO@-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@TEST_CLASSES@-"{ -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.commons.test/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.commons/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.container/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.component.cache/-"{ - permission java.security.AllPermission; -}; - -grant codeBase "@MAIN_CLASSES@../../../exo.kernel.component.ext.cache.impl.infinispan.v8/-"{ - permission java.security.AllPermission; -}; diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/tsm-excludes.properties b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/tsm-excludes.properties deleted file mode 100644 index 9a2417667..000000000 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/test/resources/tsm-excludes.properties +++ /dev/null @@ -1 +0,0 @@ -org.exoplatform.services.cache.impl.infinispan.distributed.TestDistributedExoCache.testDistributedCache=stop \ No newline at end of file diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java b/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java deleted file mode 100644 index 223b0aac0..000000000 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.container.util; - -import org.exoplatform.container.configuration.ConfigurationManager; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Pattern; - -/** - * Builds configuration from template using map of template-variables -- value. - * Class provides extra functionality for filtering parameters by pattern, excluding - * unnecessary parameters. - * - * @author Nikolay Zamosenchuk - * @version $Id: TemplateConfigurationHelper.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class TemplateConfigurationHelper -{ - - private static final Log LOG = ExoLogger.getLogger("exo.kernel.container.TemplateConfigurationHelper"); - - // list with include-patterns - private List includes = new ArrayList(); - - // list with exclude-patterns - private List excludes = new ArrayList(); - - private ConfigurationManager cfm; - - /** - * Creates instance of template configuration helper with given lists of filtering - * patterns. Parameter will be included only if it matches any include-pattern and - * doesn't match any exclude-pattern. I.e. You can include "extended-*" and exclude - * "extended-type". Please refer to Java regexp documentation. Filtering for this - * example, should be defined as following: - * include: "^extended-.*" - * exclude: "^extended-type" - * - * @param includes Array with string representation of include reg-exp patterns - * @param excludes Array with string representation of exclude reg-exp patterns - * @param cfm instance for looking up resources - */ - public TemplateConfigurationHelper(String[] includes, String[] excludes, ConfigurationManager cfm) - { - super(); - this.cfm = cfm; - // compile include patterns - for (String regex : includes) - { - this.includes.add(Pattern.compile(regex)); - } - // compile exclude patterns - for (String regex : excludes) - { - this.excludes.add(Pattern.compile(regex)); - } - } - - /** - * Reads configuration file from a stream and replaces all the occurrences of template-variables - * (like : "${parameter.name}") with values provided in the map. - * - * @param inputStream - * @param parameters - * @return - * @throws IOException - */ - public InputStream fillTemplate(InputStream inputStream, Map parameters) throws IOException - { - if (inputStream == null || parameters == null || parameters.size() == 0) - { - return inputStream; - } - // parameters filtering - Map preparedParams = prepareParameters(parameters); - // read stream - String configuration = Utils.readStream(inputStream); - for (Entry entry : preparedParams.entrySet()) - { - configuration = configuration.replace(entry.getKey(), entry.getValue()); - } - // create new stream - InputStream configurationStream = new ByteArrayInputStream(configuration.getBytes()); - return configurationStream; - } - - /** - * Reads configuration file from a stream and replaces all the occurrences of template-variables - * (like : "${parameter.name}") with values provided in the map. - * - * @param filename - * @param parameters - * @return - * @throws IOException - */ - public InputStream fillTemplate(String filename, Map parameters) throws IOException - { - InputStream inputStream = getInputStream(cfm, filename); - // inputStream still remains null, so file was not opened - if (inputStream == null) - { - throw new IOException("Can't find or open file:" + filename); - } - return fillTemplate(inputStream, parameters); - } - - /** - * Tries first to get the file content using the configuration manager, if it cannot - * be found it will then try to get it from the context class loader of the current thread, - * if it cannot be found it will try to get it from the class loader of the current class and - * finally it still cannot be found it will try to use the file name as a file path. - * @param cfm the configuration manager from which we want to try to find the file content - * @param filename the name of the file to found - * @return the {@link InputStream} corresponding to the file content if it can be found - * null otherwise - */ - public static InputStream getInputStream(ConfigurationManager cfm, String filename) - { - InputStream inputStream = null; - // try to get using configuration manager - try - { - inputStream = cfm.getInputStream(filename); - } - catch (Exception e) - { - if (LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } - - // try to get resource by class loader - if (inputStream == null) - { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - inputStream = cl == null ? null : cl.getResourceAsStream(filename); - } - - // check system class loader - if (inputStream == null) - { - inputStream = TemplateConfigurationHelper.class.getClassLoader().getResourceAsStream(filename); - } - - // try to get as file stream - if (inputStream == null) - { - try - { - inputStream = new FileInputStream(filename); - } - catch (IOException e) - { - if (LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } - } - return inputStream; - } - - /** - * Checks if String mathes to any pattern from the list - * - * @param patterns - * @param parameter - * @return - */ - private boolean matches(List patterns, String parameter) - { - for (Pattern pattern : patterns) - { - if (pattern.matcher(parameter).matches()) - { - // string matched - return true; - } - } - return false; - } - - /** - * Filters the map of parameters, leaving only those than matches filtering regular expressions. - * Also adds "${}" to the parameter key:
- * I.e. such map provided on input: - * - * "foo-cache.loader":"org.exoplatform" - * "foo-configuration":"/conf/test.xml" - * "max-volatile-size":"100Kb" - * - * the output will be like: - * - * "${foo-cache.loader}":"org.exoplatform" - * - * Other will be ignored (depending on includes/excludes lists provided in constructor). - * - * @param parameters - * @return - */ - protected Map prepareParameters(Map parameters) - { - Map map = new HashMap(); - for (Entry entry : parameters.entrySet()) - { - if (matches(includes, entry.getKey()) && !matches(excludes, entry.getKey())) - { - map.put("${" + entry.getKey() + "}", entry.getValue()); - } - } - return map; - } -} diff --git a/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestContainerUtil.java b/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestContainerUtil.java index 9d057a228..f27cac2a5 100644 --- a/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestContainerUtil.java +++ b/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestContainerUtil.java @@ -50,27 +50,6 @@ protected void tearDown() throws Exception { Thread.currentThread().setContextClassLoader(oldCLoader); } - public void testJBossAS6CL() throws Exception { - Thread.currentThread().setContextClassLoader(new JBossAS6MockClassLoader()); - Collection urls = ContainerUtil.getConfigurationURL("conf/configuration.xml"); - assertNotNull(urls); - assertEquals(3, urls.size()); - } - - private static class JBossAS6MockClassLoader extends ClassLoader { - - @Override - public Enumeration getResources(String name) throws IOException { - List urls = new ArrayList(); - urls.add(new URL("file:///GateIn-JBoss6/server/default/deploy/gatein.ear/lib/exo.portal.webui.portal.jar/conf/configuration.xml")); - urls.add(new URL("file:///GateIn-JBoss6/server/default/deploy/gatein.ear/lib/exo.core.component.xml-processing/conf/configuration.xml")); - urls.add(new URL("file:///GateIn-JBoss6/server/default/deploy/gatein-sample-extension.ear/sample-ext.war/WEB-INF/conf/configuration.xml")); - urls.add(new URL("file:///GateIn-JBoss6/server/default/deploy/gatein.ear/lib/exo.kernel.commons.jar/conf/configuration.xml")); - return Collections.enumeration(urls); - } - - } - public void testGetServletContextName() { final AtomicReference scn = new AtomicReference("myContextName"); final AtomicReference scp = new AtomicReference("/myContextPath"); diff --git a/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestTemplateConfigurationHelper.java b/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestTemplateConfigurationHelper.java deleted file mode 100644 index 5b64c4620..000000000 --- a/exo.kernel.container/src/test/java/org/exoplatform/container/util/TestTemplateConfigurationHelper.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.container.util; - -import junit.framework.TestCase; - -import org.exoplatform.container.configuration.ConfigurationManagerImpl; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Nikolay Zamosenchuk - * @version $Id: TestTemplateHelper.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class TestTemplateConfigurationHelper extends TestCase -{ - - public void testFilters() - { - // create helper with predefined include and exclude patterns - TemplateConfigurationHelper helper = - new TemplateConfigurationHelper(new String[]{"^foo-.*", "^jgroups-configuration"}, - new String[]{"^foo-configuration"}, new ConfigurationManagerImpl()); - Map parameters = new HashMap(); - parameters.put("foo-configuration", ""); - parameters.put("foo-cache.loader", ""); - parameters.put("foo-clustername", ""); - parameters.put("max-volatile-size", ""); - Map preparedParameters = helper.prepareParameters(parameters); - assertEquals(2, preparedParameters.size()); - // "foo-configuration" and "max-volatile-size" should be excluded - assertFalse(preparedParameters.containsKey("${foo-configuration}")); - assertFalse(preparedParameters.containsKey("${max-volatile-size}")); - assertTrue(preparedParameters.containsKey("${foo-cache.loader}")); - assertTrue(preparedParameters.containsKey("${foo-clustername}")); - } - - public void testFilters2() - { - // create helper with predefined include and exclude patterns - TemplateConfigurationHelper helper = - new TemplateConfigurationHelper(new String[]{"^foo-.*", "^jgroups-configuration"}, - new String[]{"^foo-configuration"}, new ConfigurationManagerImpl()); - Map parameters = new HashMap(); - parameters.put("jgroups-configuration", ""); - parameters.put("foo-cache.loader", ""); - parameters.put("foo-clustername", ""); - parameters.put("max-volatile-size", ""); - Map preparedParameters = helper.prepareParameters(parameters); - assertEquals(3, preparedParameters.size()); - // "foo-configuration" and "max-volatile-size" should be excluded - assertFalse(preparedParameters.containsKey("${max-volatile-size}")); - assertTrue(preparedParameters.containsKey("${foo-cache.loader}")); - assertTrue(preparedParameters.containsKey("${foo-clustername}")); - } - - public void testTemplating() throws IOException - { - TemplateConfigurationHelper helper = - new TemplateConfigurationHelper(new String[]{"^foo-.*", "^jgroups-configuration"}, - new String[]{"^foo-configuration"}, new ConfigurationManagerImpl()); - String template = "configuration in any format, containing ${foo-template-variable} and many others"; - String expectedConfig = "configuration in any format, containing pretty good parameter and many others"; - - InputStream templateStream = new ByteArrayInputStream(template.getBytes()); - - Map parameters = new HashMap(); - parameters.put("foo-template-variable", "pretty good parameter"); - - InputStream configStream = helper.fillTemplate(templateStream, parameters); - String config = Utils.readStream(configStream); - assertTrue(expectedConfig.equals(config)); - } -} diff --git a/pom.xml b/pom.xml index c18dfc898..645128bed 100644 --- a/pom.xml +++ b/pom.xml @@ -64,8 +64,6 @@ exo.kernel.commons.test exo.kernel.component.common exo.kernel.component.cache - exo.kernel.component.ext.cache.impl.infinispan.v8 - exo.kernel.component.command @@ -118,16 +116,6 @@ exo.kernel.component.cache ${project.version} - - ${project.groupId} - exo.kernel.component.ext.cache.impl.infinispan.v8 - ${project.version} - - - ${project.groupId} - exo.kernel.component.command - ${project.version} - ${project.groupId} exo.kernel.container