tomee-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rmannibu...@apache.org
Subject svn commit: r1208817 - in /openejb/trunk/openejb: container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ examples/ examples/reload-persistence-unit-properties/ examples/reload-persistence-unit-properties/src/ examples/reload-persist...
Date Wed, 30 Nov 2011 21:52:19 GMT
Author: rmannibucau
Date: Wed Nov 30 21:52:15 2011
New Revision: 1208817

URL: http://svn.apache.org/viewvc?rev=1208817&view=rev
Log:
adding more properties to the mbean managing the (re)creation of the entitymanager and an
example of such a feature

Added:
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/README.md
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/pom.xml
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/Person.java
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/PersonManager.java
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/persistence.xml
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/
    openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/CacheActivationTest.java
Modified:
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ReloadableEntityManagerFactory.java
    openejb/trunk/openejb/examples/pom.xml

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ReloadableEntityManagerFactory.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ReloadableEntityManagerFactory.java?rev=1208817&r1=1208816&r2=1208817&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ReloadableEntityManagerFactory.java
(original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ReloadableEntityManagerFactory.java
Wed Nov 30 21:52:15 2011
@@ -8,14 +8,35 @@ import org.apache.openejb.persistence.Pe
 import org.apache.openejb.util.LogCategory;
 import org.apache.openejb.util.Logger;
 
-import javax.management.*;
+import javax.management.Description;
+import javax.management.MBean;
+import javax.management.MBeanServer;
+import javax.management.ManagedAttribute;
+import javax.management.ManagedOperation;
+import javax.management.ObjectName;
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.CompositeDataSupport;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
+import javax.management.openmbean.SimpleType;
+import javax.management.openmbean.TabularData;
+import javax.management.openmbean.TabularDataSupport;
+import javax.management.openmbean.TabularType;
 import javax.persistence.Cache;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.PersistenceUnitUtil;
+import javax.persistence.SharedCacheMode;
+import javax.persistence.ValidationMode;
 import javax.persistence.criteria.CriteriaBuilder;
 import javax.persistence.metamodel.Metamodel;
-import java.lang.management.ManagementFactory;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 
@@ -95,17 +116,27 @@ public class ReloadableEntityManagerFact
 
     private ObjectName generateObjectName() {
         ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management");
-        jmxName.set("J2EEServer", "openejb");
         jmxName.set("ObjectType", "persistence-unit");
         jmxName.set("PersistenceUnit", getPUname());
         objectName = jmxName.build();
+
+        MBeanServer server = LocalMBeanServer.get();
+        if (server.isRegistered(objectName)) { // if 2 pu have the same name...a bit uglier
but unique
+            jmxName.set("PersistenceUnit", getPUname() + "(" + getId() + ")");
+            objectName = jmxName.build();
+        }
+
         return objectName;
     }
 
-    public String getPUname() {
+    private String getPUname() {
         return entityManagerFactoryCallable.getUnitInfo().getPersistenceUnitName();
     }
 
+    private String getId() {
+        return entityManagerFactoryCallable.getUnitInfo().getId();
+    }
+
     private Object mBeanify() {
         return new DynamicMBeanWrapper(new JMXReloadableEntityManagerFactory(this));
     }
@@ -136,6 +167,39 @@ public class ReloadableEntityManagerFact
         }
     }
 
+    public synchronized void setSharedCacheMode(SharedCacheMode mode) {
+        entityManagerFactoryCallable.getUnitInfo().setSharedCacheMode(mode);
+    }
+
+    public synchronized void setValidationMode(ValidationMode mode) {
+        entityManagerFactoryCallable.getUnitInfo().setValidationMode(mode);
+    }
+
+    public synchronized void setProvider(String providerRaw) {
+        final String provider = providerRaw.trim();
+        String newProvider;
+        if ("hibernate".equals(provider)) {
+            newProvider = "org.hibernate.ejb.HibernatePersistence";
+        } else if ("openjpa".equals(provider)) {
+            newProvider = "org.apache.openjpa.persistence.PersistenceProviderImpl";
+        } else if ("eclipse".equals(provider)) {
+            newProvider = "oracle.toplink.essentials.PersistenceProvider";
+        } else {
+            newProvider = provider;
+        }
+
+        try {
+            classLoader.loadClass(newProvider);
+            entityManagerFactoryCallable.getUnitInfo().setPersistenceProviderClassName(newProvider);
+        } catch (ClassNotFoundException e) {
+            LOGGER.error("can't load new provider " + newProvider, e);
+        }
+    }
+
+    public synchronized void setTransactionType(PersistenceUnitTransactionType type) {
+        entityManagerFactoryCallable.getUnitInfo().setTransactionType(type);
+    }
+
     public synchronized void setProperty(String key, String value) {
         PersistenceUnitInfoImpl unitInfo = entityManagerFactoryCallable.getUnitInfo();
         if (unitInfo.getProperties() == null) {
@@ -159,6 +223,58 @@ public class ReloadableEntityManagerFact
         return new Properties();
     }
 
+    public List<String> getMappingFiles() {
+        return entityManagerFactoryCallable.getUnitInfo().getMappingFileNames();
+    }
+
+    public void addMappingFile(String file) {
+        if (new File(file).exists()) {
+            entityManagerFactoryCallable.getUnitInfo().addMappingFileName(file);
+        } else {
+            LOGGER.error("file " + file + " doesn't exists");
+        }
+    }
+
+    public void removeMappingFile(String file) {
+        entityManagerFactoryCallable.getUnitInfo().getMappingFileNames().remove(file);
+    }
+
+    public List<URL> getJarFileUrls() {
+        return entityManagerFactoryCallable.getUnitInfo().getJarFileUrls();
+    }
+
+    public void addJarFileUrls(String file) {
+        if (new File(file).exists()) { // should we test real urls?
+            try {
+                entityManagerFactoryCallable.getUnitInfo().getJarFileUrls().add(new URL(file));
+            } catch (MalformedURLException e) {
+                LOGGER.error("url " + file + " is malformed");
+            }
+        } else {
+            LOGGER.error("url " + file + " is not correct");
+        }
+    }
+
+    public void removeJarFileUrls(String file) {
+        try {
+            entityManagerFactoryCallable.getUnitInfo().getJarFileUrls().remove(new URL(file));
+        } catch (MalformedURLException e) {
+            LOGGER.error("url " + file + " is malformed");
+        }
+    }
+
+    public List<String> getManagedClasses() {
+        return entityManagerFactoryCallable.getUnitInfo().getManagedClassNames();
+    }
+
+    public void addManagedClasses(String clazz) {
+        entityManagerFactoryCallable.getUnitInfo().getManagedClassNames().add(clazz);
+    }
+
+    public void removeManagedClasses(String clazz) {
+        entityManagerFactoryCallable.getUnitInfo().getManagedClassNames().remove(clazz);
+    }
+
     @MBean
     @Description("represents a persistence unit managed by OpenEJB")
     public static class JMXReloadableEntityManagerFactory {
@@ -175,6 +291,23 @@ public class ReloadableEntityManagerFact
         }
 
         @ManagedOperation
+        @Description("change the current JPA provider")
+        public void setProvider(String provider) {
+            reloadableEntityManagerFactory.setProvider(provider);
+        }
+
+        @ManagedOperation
+        @Description("change the current transaction type")
+        public void setTransactionType(String type) {
+            try {
+                PersistenceUnitTransactionType tt = PersistenceUnitTransactionType.valueOf(type.toUpperCase());
+                reloadableEntityManagerFactory.setTransactionType(tt);
+            } catch (Exception iae) {
+                // ignored
+            }
+        }
+
+        @ManagedOperation
         @Description("create or modify a property of the persistence unit")
         public void setProperty(String key, String value) {
             reloadableEntityManagerFactory.setProperty(key, value);
@@ -186,10 +319,178 @@ public class ReloadableEntityManagerFact
             reloadableEntityManagerFactory.removeProperty(key);
         }
 
+        @ManagedOperation
+        @Description("add a mapping file")
+        public void addMappingFile(String file) {
+            reloadableEntityManagerFactory.addMappingFile(file);
+        }
+
+        @ManagedOperation
+        @Description("remove a mapping file")
+        public void removeMappingFile(String file) {
+            reloadableEntityManagerFactory.removeMappingFile(file);
+        }
+
+        @ManagedOperation
+        @Description("add a managed class")
+        public void addManagedClass(String clazz) {
+            reloadableEntityManagerFactory.addManagedClasses(clazz);
+        }
+
+        @ManagedOperation
+        @Description("remove a managed class")
+        public void removeManagedClass(String clazz) {
+            reloadableEntityManagerFactory.removeManagedClasses(clazz);
+        }
+
+        @ManagedOperation
+        @Description("add a jar file")
+        public void addJarFile(String file) {
+            reloadableEntityManagerFactory.addJarFileUrls(file);
+        }
+
+        @ManagedOperation
+        @Description("remove a jar file")
+        public void removeJarFile(String file) {
+            reloadableEntityManagerFactory.removeJarFileUrls(file);
+        }
+
+        @ManagedOperation
+        @Description("change the shared cache mode if possible (value is ok)")
+        public void setSharedCacheMode(String value) {
+            try {
+                SharedCacheMode mode = SharedCacheMode.valueOf(value.trim().toUpperCase());
+                reloadableEntityManagerFactory.setSharedCacheMode(mode);
+            } catch (Exception iae) {
+                // ignored
+            }
+        }
+
+        @ManagedOperation
+        @Description("change the validation mode if possible (value is ok)")
+        public void setValidationMode(String value) {
+            try {
+                ValidationMode mode = ValidationMode.valueOf(value.trim().toUpperCase());
+                reloadableEntityManagerFactory.setValidationMode(mode);
+            } catch (Exception iae) {
+                // ignored
+            }
+        }
+
+        @ManagedAttribute
+        @Description("get all properties")
+        public TabularData getProperties() {
+            return tabularData("properties", "properties type",
+                    "Property of " + reloadableEntityManagerFactory.getPUname(),
+                    reloadableEntityManagerFactory.getUnitProperties());
+        }
+
         @ManagedAttribute
-        @Description("get all properties colon separated")
-        public String getProperties() {
-            return reloadableEntityManagerFactory.getUnitProperties().toString();
+        @Description("get all mapping files")
+        public TabularData getMappingFiles() {
+            return tabularData("mappingfile", "mapping file type",
+                    "Mapping file of " + reloadableEntityManagerFactory.getPUname(),
+                    reloadableEntityManagerFactory.getMappingFiles(), Info.FILE);
+        }
+
+        @ManagedAttribute
+        @Description("get all jar files")
+        public TabularData getJarFiles() {
+            return tabularData("jarfile", "jar file type",
+                    "Jar file of " + reloadableEntityManagerFactory.getPUname(),
+                    reloadableEntityManagerFactory.getJarFileUrls(), Info.URL);
+        }
+
+        @ManagedAttribute
+        @Description("get all managed classes")
+        public TabularData getManagedClasses() {
+            return tabularData("managedclass", "managed class type",
+                    "Managed class of " + reloadableEntityManagerFactory.getPUname(),
+                    reloadableEntityManagerFactory.getManagedClasses(), Info.CLASS);
+        }
+
+        private TabularData tabularData(String typeName, String typeDescription, String description,
List<?> list, Info info) {
+            String[] names = new String[list.size()];
+            Object[] values= new Object[names.length];
+            int i = 0;
+            for (Object o : list) {
+                names[i] = o.toString();
+                values[i++] = info.info(reloadableEntityManagerFactory.classLoader, o);
+            }
+            return tabularData(typeName, typeDescription, names, values);
+        }
+
+        private static TabularData tabularData(String typeName, String typeDescription, String
description, Properties properties) {
+            String[] names = properties.keySet().toArray(new String[properties.size()]);
+            Object[] values = new Object[names.length];
+            for (int i = 0; i < values.length; i++) {
+                values[i] = properties.get(names[i]);
+            }
+            return tabularData(typeName, typeDescription, names, values);
+        }
+
+        private static TabularData tabularData(String typeName, String typeDescription, String[]
names, Object[] values) {
+            if (names.length == 0) {
+                return null;
+            }
+
+            OpenType<?>[] types = new OpenType<?>[names.length];
+            for (int i = 0; i < types.length; i++) {
+                types[i] = SimpleType.STRING;
+            }
+
+            try {
+                CompositeType ct = new CompositeType(typeName, typeDescription, names, names,
types);
+                TabularType type = new TabularType(typeName, typeDescription, ct, names);
+                TabularDataSupport data = new TabularDataSupport(type);
+
+                CompositeData line = new CompositeDataSupport(ct, names, values);
+                data.put(line);
+
+                return data;
+            } catch (OpenDataException e) {
+                return null;
+            }
+        }
+
+        private enum Info {
+            URL, NONE, FILE, CLASS;
+
+            public String info(ClassLoader cl, Object o) {
+                switch (this) {
+                    case URL:
+                        try {
+                            if (((URL) o).openConnection().getContentLength() > 0) {
+                                return "valid";
+                            }
+                        } catch (IOException e) {
+                            // ignored
+                        }
+                        return "not valid";
+
+                    case FILE:
+                        File file;
+                        if (o instanceof String) {
+                            file = new File((String) o);
+                        } else if (o instanceof File) {
+                            file = (File) o;
+                        } else {
+                            return "unknown";
+                        }
+                        return "exist? " + file.exists();
+
+                    case CLASS:
+                        try {
+                            cl.loadClass((String) o);
+                            return "loaded";
+                        } catch (ClassNotFoundException e) {
+                            return "unloadable";
+                        }
+
+                    default:
+                        return "-";
+                }
+            }
         }
     }
 }

Modified: openejb/trunk/openejb/examples/pom.xml
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/pom.xml?rev=1208817&r1=1208816&r2=1208817&view=diff
==============================================================================
--- openejb/trunk/openejb/examples/pom.xml (original)
+++ openejb/trunk/openejb/examples/pom.xml Wed Nov 30 21:52:15 2011
@@ -93,6 +93,7 @@
     <module>cdi-alternative-and-stereotypes</module>
     <module>cdi-events</module>
     <module>dynamic-proxy-to-access-mbean</module>
+    <module>reload-persistence-unit-properties</module>
   </modules>
   <profiles>
     <profile>

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/README.md
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/README.md?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/README.md (added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/README.md Wed Nov 30
21:52:15 2011
@@ -0,0 +1,52 @@
+Title: Reload Persistence Unit Properties
+
+This example aims to simulate a benchmark campaign on JPA.
+
+First you'll run your application then you'll realize you could need L2 cache to respect
your SLA.
+
+So you change your persistence.xml configuration, then restart your application,
+you wait a bit because you are using OpenEJB ;)...but you wait...
+
+So to try to go faster on long campaign simply change your configuration at runtime to test
it then when it works change
+your configuration file to keep the modification.
+
+To do it we can simply use JMX.
+
+OpenEJB automatically register one MBeans by entitymanager (persistence unit).
+
+It allows you mainly to change your persistence unit properties even if more is possible.
+
+## The test itself
+
+The test is simple: we persist an entity, we query it three times without cache then we activate
cache and realize
+running again our queries that one is enough to do the same.
+
+# The output
+
+In the ouput we find the 3 parts described just before.
+
+    INFO - TEST, data initialization
+    DEBUG - <t 1523828380, conn 93608538> executing stmnt 1615782385 CREATE TABLE Person
(id BIGINT NOT NULL, name VARCHAR(255), PRIMARY KEY (id))
+    DEBUG - <t 1523828380, conn 93608538> [1 ms] spent
+    DEBUG - <t 1523828380, conn 1506565411> executing prepstmnt 668144844 INSERT INTO
Person (id, name) VALUES (?, ?) [params=?, ?]
+    DEBUG - <t 1523828380, conn 1506565411> [0 ms] spent
+    INFO - TEST, end of data initialization
+
+
+    INFO - TEST, doing some queries without cache
+    DEBUG - <t 1523828380, conn 1506565411> executing prepstmnt 1093240870 SELECT t0.name
FROM Person t0 WHERE t0.id = ? [params=?]
+    DEBUG - <t 1523828380, conn 1506565411> [0 ms] spent
+    DEBUG - <t 1523828380, conn 1506565411> executing prepstmnt 1983702821 SELECT t0.name
FROM Person t0 WHERE t0.id = ? [params=?]
+    DEBUG - <t 1523828380, conn 1506565411> [0 ms] spent
+    DEBUG - <t 1523828380, conn 1506565411> executing prepstmnt 1178041898 SELECT t0.name
FROM Person t0 WHERE t0.id = ? [params=?]
+    DEBUG - <t 1523828380, conn 1506565411> [1 ms] spent
+    INFO - TEST, queries without cache done
+
+
+    INFO - TEST, doing some queries with cache
+    DEBUG - <t 1523828380, conn 1506565411> executing prepstmnt 1532943889 SELECT t0.name
FROM Person t0 WHERE t0.id = ? [params=?]
+    DEBUG - <t 1523828380, conn 1506565411> [0 ms] spent
+    INFO - TEST, queries with cache done
+
+
+

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/pom.xml
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/pom.xml?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/pom.xml (added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/pom.xml Wed Nov 30 21:52:15
2011
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Licensed to the Apache Software Foundation (ASF) under one or more
+    contributor license agreements.  See the NOTICE file distributed with
+    this work for additional information regarding copyright ownership.
+    The ASF licenses this file to You under the Apache License, Version 2.0
+    (the "License"); you may not use this file except in compliance with
+    the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+
+<!-- $Rev: 1178411 $ $Date: 2011-10-03 15:35:26 +0200 (lun. 03 oct. 2011) $ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.superbiz</groupId>
+  <artifactId>reload-persistence-unit-properties</artifactId>
+  <packaging>jar</packaging>
+  <version>1.1-SNAPSHOT</version>
+  <name>OpenEJB :: Examples :: Reloadable Persistence Unit Properties</name>
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+  </properties>
+  <build>
+    <defaultGoal>install</defaultGoal>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <version>2.3.2</version>
+        <configuration>
+          <source>1.6</source>
+          <target>1.6</target>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+  <repositories>
+    <repository>
+      <id>apache-m2-snapshot</id>
+      <name>Apache Snapshot Repository</name>
+      <url>http://repository.apache.org/snapshots</url>
+    </repository>
+  </repositories>
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.openejb</groupId>
+      <artifactId>javaee-api</artifactId>
+      <version>6.0-3-SNAPSHOT</version>
+      <scope>provided</scope>
+    </dependency>
+
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>4.8.1</version>
+      <scope>test</scope>
+    </dependency>
+    <!--
+    The <scope>test</scope> guarantees that non of your runtime
+    code is dependent on any OpenEJB classes.
+    -->
+    <dependency>
+      <groupId>org.apache.openejb</groupId>
+      <artifactId>openejb-core</artifactId>
+      <version>4.0.0-beta-2-SNAPSHOT</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+  <!--
+  This section allows you to configure where to publish libraries for sharing.
+  It is not required and may be deleted.  For more information see:
+  http://maven.apache.org/plugins/maven-deploy-plugin/
+  -->
+  <distributionManagement>
+    <repository>
+      <id>localhost</id>
+      <url>file://${basedir}/target/repo/</url>
+    </repository>
+    <snapshotRepository>
+      <id>localhost</id>
+      <url>file://${basedir}/target/snapshot-repo/</url>
+    </snapshotRepository>
+  </distributionManagement>
+</project>

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/Person.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/Person.java?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/Person.java
(added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/Person.java
Wed Nov 30 21:52:15 2011
@@ -0,0 +1,38 @@
+package org.superbiz.reloadable.pu;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author rmannibucau
+ */
+@Entity
+public class Person {
+    @Id private long id;
+    private String name;
+
+    public Person() {
+        // no-op
+    }
+
+    public Person(long id, String name) {
+        this.id = id;
+        this.name = name;
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public void setId(long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+}

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/PersonManager.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/PersonManager.java?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/PersonManager.java
(added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/java/org/superbiz/reloadable/pu/PersonManager.java
Wed Nov 30 21:52:15 2011
@@ -0,0 +1,29 @@
+package org.superbiz.reloadable.pu;
+
+import javax.ejb.Singleton;
+import javax.ejb.TransactionAttribute;
+import javax.ejb.TransactionAttributeType;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+/**
+ * @author rmannibucau
+ */
+@Singleton
+public class PersonManager {
+    private static int ID = 0;
+
+    @PersistenceContext
+    private EntityManager em;
+
+    public Person createUser(String name) {
+        Person user = new Person(ID++, name);
+        em.persist(user);
+        return user;
+    }
+
+    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
+    public Person search(long id) {
+        return em.find(Person.class, id);
+    }
+}

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/persistence.xml
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/persistence.xml?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/persistence.xml
(added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/main/resources/META-INF/persistence.xml
Wed Nov 30 21:52:15 2011
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<persistence xmlns="http://java.sun.com/xml/ns/persistence"
+             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
+             version="2.0">
+  <persistence-unit name="reloadable">
+    <jta-data-source>My Default DataSource</jta-data-source>
+    <class>org.superbiz.reloadable.pu.Person</class>
+    <properties>
+      <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
+      <property name="openjpa.Log" value="SQL=TRACE"/>
+    </properties>
+  </persistence-unit>
+</persistence>

Added: openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/CacheActivationTest.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/CacheActivationTest.java?rev=1208817&view=auto
==============================================================================
--- openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/CacheActivationTest.java
(added)
+++ openejb/trunk/openejb/examples/reload-persistence-unit-properties/src/test/java/org/superbiz/reloadable/pu/CacheActivationTest.java
Wed Nov 30 21:52:15 2011
@@ -0,0 +1,113 @@
+package org.superbiz.reloadable.pu;
+
+import org.apache.log4j.ConsoleAppender;
+import org.apache.log4j.SimpleLayout;
+import org.apache.log4j.varia.NullAppender;
+import org.apache.openjpa.persistence.StoreCacheImpl;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ejb.EJB;
+import javax.ejb.embeddable.EJBContainer;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.naming.NamingException;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.PersistenceUnit;
+import java.lang.management.ManagementFactory;
+import java.util.Properties;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertNull;
+
+/**
+ * @author rmannibucau
+ */
+public class CacheActivationTest {
+    private static final Logger LOGGER = LoggerFactory.getLogger(CacheActivationTest.class);
+
+    private static EJBContainer container;
+
+    @EJB
+    private PersonManager mgr;
+
+    @PersistenceUnit
+    private EntityManagerFactory emf;
+
+    @BeforeClass
+    public static void start() {
+        // customizing logs to print mainly sql queries
+        Properties p = new Properties();
+        p.put("openejb.nobanner", "false");
+        p.put("log4j.rootLogger", "error, N");
+        p.put("log4j.category.OpenEJB.options", "error");
+        p.put("log4j.category.OpenEJB.options", "error");
+        p.put("log4j.category.OpenEJB.server", "error");
+        p.put("log4j.category.OpenEJB.startup", "error");
+        p.put("log4j.category.OpenEJB.startup.service", "error");
+        p.put("log4j.category.OpenEJB.startup.config", "error");
+        p.put("log4j.category.openjpa.jdbc.SQL", "debug, C"); // we want sql queries
+        p.put("log4j.category.openjpa.Enhance", "error");
+        p.put("log4j.category.org.superbiz", "info, C"); // we want our own logs
+        p.put("log4j.appender.N", NullAppender.class.getName());
+        p.put("log4j.appender.C", ConsoleAppender.class.getName());
+        p.put("log4j.appender.C.layout", SimpleLayout.class.getName());
+
+        // finally starting the container
+        container = EJBContainer.createEJBContainer(p);
+    }
+
+    @Before
+    public void inject() throws NamingException {
+        container.getContext().bind("inject", this);
+    }
+
+    @AfterClass
+    public static void shutdown() {
+        if (container != null) {
+            container.close();
+        }
+    }
+
+    @Test
+    public void activeCacheAtRuntime() throws Exception {
+        LOGGER.info("TEST, data initialization");
+        final Person person = mgr.createUser("user #1");
+        final long personId = person.getId();
+        LOGGER.info("TEST, end of data initialization\n\n");
+
+        assertNull(((StoreCacheImpl) emf.getCache()).getDelegate());
+        LOGGER.info("TEST, doing some queries without cache");
+        query(personId);
+        LOGGER.info("TEST, queries without cache done\n\n");
+
+        activateCache();
+
+        assertNotNull(((StoreCacheImpl) emf.getCache()).getDelegate());
+        LOGGER.info("TEST, doing some queries with cache");
+        query(personId);
+        LOGGER.info("TEST, queries with cache done\n\n");
+    }
+
+    private void activateCache() throws Exception {
+        ObjectName on = new ObjectName("openejb.management:ObjectType=persistence-unit,PersistenceUnit=reloadable");
+        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+        server.invoke(on, "setProperty", new Object[] { "openjpa.DataCache", "true" }, null);
+        server.invoke(on, "setProperty", new Object[] { "openjpa.RemoteCommitProvider", "sjvm"
}, null);
+        server.invoke(on, "setSharedCacheMode", new Object[] { "ALL" }, null);
+        server.invoke(on, "reload", new Object[0], null);
+    }
+
+    private void query(long personId) {
+        for (int i = 0; i < 3; i++) { // some multiple time to get if cache works or not
+            Person found = mgr.search(personId);
+            assertNotNull(found);
+            assertEquals(personId,  found.getId());
+        }
+    }
+}



Mime
View raw message