Return-Path: X-Original-To: apmail-geode-commits-archive@minotaur.apache.org Delivered-To: apmail-geode-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id C8866183F0 for ; Wed, 17 Feb 2016 18:24:13 +0000 (UTC) Received: (qmail 39092 invoked by uid 500); 17 Feb 2016 18:24:08 -0000 Delivered-To: apmail-geode-commits-archive@geode.apache.org Received: (qmail 39065 invoked by uid 500); 17 Feb 2016 18:24:08 -0000 Mailing-List: contact commits-help@geode.incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@geode.incubator.apache.org Delivered-To: mailing list commits@geode.incubator.apache.org Received: (qmail 39056 invoked by uid 99); 17 Feb 2016 18:24:08 -0000 Received: from Unknown (HELO spamd1-us-west.apache.org) (209.188.14.142) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 17 Feb 2016 18:24:08 +0000 Received: from localhost (localhost [127.0.0.1]) by spamd1-us-west.apache.org (ASF Mail Server at spamd1-us-west.apache.org) with ESMTP id 0A60CC28B9 for ; Wed, 17 Feb 2016 18:24:08 +0000 (UTC) X-Virus-Scanned: Debian amavisd-new at spamd1-us-west.apache.org X-Spam-Flag: NO X-Spam-Score: -3.226 X-Spam-Level: X-Spam-Status: No, score=-3.226 tagged_above=-999 required=6.31 tests=[KAM_ASCII_DIVIDERS=0.8, KAM_LAZY_DOMAIN_SECURITY=1, RCVD_IN_DNSWL_HI=-5, RCVD_IN_MSPIKE_H3=-0.01, RCVD_IN_MSPIKE_WL=-0.01, RP_MATCHES_RCVD=-0.006] autolearn=disabled Received: from mx2-lw-eu.apache.org ([10.40.0.8]) by localhost (spamd1-us-west.apache.org [10.40.0.7]) (amavisd-new, port 10024) with ESMTP id 1KhSy22gkcwW for ; Wed, 17 Feb 2016 18:23:46 +0000 (UTC) Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by mx2-lw-eu.apache.org (ASF Mail Server at mx2-lw-eu.apache.org) with SMTP id 4C9A060DE4 for ; Wed, 17 Feb 2016 18:23:08 +0000 (UTC) Received: (qmail 32246 invoked by uid 99); 17 Feb 2016 18:23:06 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 17 Feb 2016 18:23:06 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 76AA0E0577; Wed, 17 Feb 2016 18:23:06 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: abaker@apache.org To: commits@geode.incubator.apache.org Date: Wed, 17 Feb 2016 18:23:52 -0000 Message-Id: <5b766b2ee16140e18dcb32e804b93391@git.apache.org> In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: [48/51] [partial] incubator-geode git commit: GEODE-917: rename gemfire subprojects to geode http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadOnlyAccess.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadOnlyAccess.java b/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadOnlyAccess.java deleted file mode 100644 index 6f54067..0000000 --- a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadOnlyAccess.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules.hibernate.internal; - -import org.hibernate.cache.CacheException; -import org.hibernate.cache.access.SoftLock; - -public class ReadOnlyAccess extends Access { - - public ReadOnlyAccess(GemFireEntityRegion region) { - super(region); - } - - @Override - public boolean insert(Object key, Object value, Object version) - throws CacheException { - throw new UnsupportedOperationException( - "insert not supported on read only access"); - } - - @Override - public boolean update(Object key, Object value, Object currentVersion, - Object previousVersion) throws CacheException { - throw new UnsupportedOperationException( - "update not supported on read only access"); - } - - @Override - public boolean afterInsert(Object key, Object value, Object version) - throws CacheException { - throw new UnsupportedOperationException( - "insert not supported on read only access"); - } - - @Override - public boolean afterUpdate(Object key, Object value, Object currentVersion, - Object previousVersion, SoftLock lock) throws CacheException { - throw new UnsupportedOperationException( - "update not supported on read only access"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadWriteAccess.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadWriteAccess.java b/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadWriteAccess.java deleted file mode 100644 index 3c80174..0000000 --- a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/ReadWriteAccess.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules.hibernate.internal; - -import org.hibernate.cache.CacheException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ReadWriteAccess extends Access { - - private Logger log = LoggerFactory.getLogger(getClass()); - - public ReadWriteAccess(GemFireEntityRegion region) { - super(region); - } - - @Override - public boolean update(Object key, Object value, Object currentVersion, - Object previousVersion) throws CacheException { - return super.update(key, value, currentVersion, previousVersion); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/RegionFactoryDelegate.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/RegionFactoryDelegate.java b/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/RegionFactoryDelegate.java deleted file mode 100644 index 76fdf77..0000000 --- a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/RegionFactoryDelegate.java +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules.hibernate.internal; - -import java.util.Iterator; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheFactory; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.GemFireCache; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionShortcut; -import com.gemstone.gemfire.cache.client.ClientRegionShortcut; -import com.gemstone.gemfire.cache.execute.FunctionService; -import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; -import com.gemstone.gemfire.modules.hibernate.GemFireCacheProvider; -import com.gemstone.gemfire.modules.util.BootstrappingFunction; -import com.gemstone.gemfire.modules.util.CreateRegionFunction; -import com.gemstone.gemfire.modules.util.RegionConfiguration; - -public class RegionFactoryDelegate { - - private static final String LOG_FILE = "log-file"; - - private static final String CACHE_XML_FILE = "cache-xml-file"; - - private static final String DEFAULT_REGION_TYPE = RegionShortcut.REPLICATE_HEAP_LRU.name(); - - private static final String CLIENT_DEFAULT_REGION_TYPE = ClientRegionShortcut.PROXY.name(); - - protected final Properties gemfireProperties; - protected final Properties regionProperties; - - protected Logger log = LoggerFactory.getLogger(getClass()); - - private Cache cache; - - public RegionFactoryDelegate(Properties gemfireProperties, Properties regionProperties) { - this.gemfireProperties = gemfireProperties; - this.regionProperties = regionProperties; - } - - public GemFireCache startCache() { - log.info("Creating a GemFire cache"); - checkExistingCache(); - cache = new CacheFactory(gemfireProperties).create(); - log.debug("GemFire cache creation completed"); - FunctionService.onMembers(this.cache.getDistributedSystem()).execute(new BootstrappingFunction()).getResult(); - FunctionService.registerFunction(new CreateRegionFunction(cache)); - return cache; - } - - /** - * When hibernate module is running within servlet container, we should - * check if http module is being used and make sure that we use - * same cache-xml and log-file properties. - */ - protected void checkExistingCache() { - Cache existingCache = GemFireCacheImpl.getInstance(); - if (existingCache == null) { - return; - } - Properties existingProps = existingCache.getDistributedSystem().getProperties(); - String cacheXML = existingProps.getProperty(CACHE_XML_FILE); - String logFile = existingProps.getProperty(LOG_FILE, ""); - this.gemfireProperties.setProperty(CACHE_XML_FILE, cacheXML); - this.gemfireProperties.setProperty(LOG_FILE, logFile); - log.info("Existing GemFire cache detected. Using same "+CACHE_XML_FILE+":"+cacheXML+ - " and "+LOG_FILE+":"+logFile+" as existing cache"); - } - - public Region createRegion(String regionName) { - Region r = cache.getRegion(regionName); - if (r != null) { - // for the peer-to-peer case, for now we assume that - // cache.xml will be the same for all peers - // TODO validate regions without this assumption - return r; - } - String regionType = getRegionType(regionName); - boolean isLocalRegion = regionType.contains("LOCAL") ? true : false; - RegionConfiguration regionConfig = new RegionConfiguration(); - regionConfig.setRegionName(regionName); - regionConfig.setRegionAttributesId(regionType); - regionConfig.setCacheWriterName(EntityRegionWriter.class.getCanonicalName()); - com.gemstone.gemfire.cache.RegionFactory rFactory = this.cache - .createRegionFactory(RegionShortcut.valueOf(regionType)); - rFactory.setCacheWriter(new EntityRegionWriter()); - if (isLocalRegion) { - rFactory.setDataPolicy(DataPolicy.REPLICATE); - } - r = rFactory.create(regionName); - // create same region on peers - if (!isLocalRegion) { - FunctionService.onMembers(this.cache.getDistributedSystem()) - .withArgs(regionConfig).execute(CreateRegionFunction.ID).getResult(); - } - return r; - } - - /** - * returns the type of region to create by consulting the properties specified - * in hibernate.cfg.xml - * - * @see #createRegion(String) - * @param regionName - * @return string representation of {@link RegionShortcut} - * @see GemFireCacheProvider - */ - protected String getRegionType(String regionName) { - String rType = getOverridenRegionType(regionName); - if (rType != null) { - return rType.toUpperCase(); - } - rType = regionProperties - .getProperty("gemfire.default-region-attributes-id"); - if (rType == null) { - rType = DEFAULT_REGION_TYPE; - } - return rType.toUpperCase(); - } - - private String getOverridenRegionType(String regionName) { - String rType = null; - Iterator it = regionProperties.keySet().iterator(); - while (it.hasNext()) { - String current = (String)it.next(); - if (current.contains(regionName)) { - rType = regionProperties.getProperty(current); - break; - } - } - return rType; - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/TransactionalAccess.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/TransactionalAccess.java b/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/TransactionalAccess.java deleted file mode 100644 index f12eab9..0000000 --- a/extensions/gemfire-modules-hibernate/src/main/java/com/gemstone/gemfire/modules/hibernate/internal/TransactionalAccess.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.gemstone.gemfire.modules.hibernate.internal; - -public class TransactionalAccess extends Access { - - public TransactionalAccess(GemFireEntityRegion region) { - super(region); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Event.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Event.java b/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Event.java deleted file mode 100644 index 962c083..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Event.java +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules; - -import java.util.Date; - -public class Event { - private Long id; - - private String title; - private Date date; - private int i; - - public Event() {} - - public Long getId() { - return id; - } - - private void setId(Long id) { - this.id = id; - } - - public Date getDate() { - return date; - } - - public Integer getVersion() { - return i; - } - - public void setVersion(int i) { - this.i = i; - } - - public void setDate(Date date) { - this.date = date; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - b.append("Event:id:"+id+" title:"+title+" date:"+date); - return b.toString(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/HibernateJUnitTest.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/HibernateJUnitTest.java b/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/HibernateJUnitTest.java deleted file mode 100644 index 9a86f10..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/HibernateJUnitTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules; - -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.Region.Entry; -import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; -import com.gemstone.gemfire.modules.Owner.Status; -import com.gemstone.gemfire.test.junit.categories.IntegrationTest; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.AnnotationConfiguration; -import org.hibernate.cfg.Configuration; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import static org.junit.Assert.assertEquals; - -@Category(IntegrationTest.class) -public class HibernateJUnitTest { - - private Logger log = LoggerFactory.getLogger(getClass()); - - //private static final String jdbcURL = "jdbc:hsqldb:hsql://localhost/test"; - private static final String jdbcURL = "jdbc:hsqldb:mem:test"; - - static File tmpDir; - - static String gemfireLog; - - @Before - public void setUp() throws Exception { - // Create a per-user scratch directory - tmpDir = new File(System.getProperty("java.io.tmpdir"), - "gemfire_modules-" + System.getProperty("user.name")); - tmpDir.mkdirs(); - tmpDir.deleteOnExit(); - - gemfireLog = tmpDir.getPath() + - System.getProperty("file.separator") + "gemfire_modules.log"; - } - - public static SessionFactory getSessionFactory(Properties overrideProps) { - System.setProperty("gemfire.home", "GEMFIREHOME"); - Configuration cfg = new Configuration(); - cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); - cfg.setProperty("hibernate.connection.driver_class", - "org.hsqldb.jdbcDriver"); - // cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test"); - cfg.setProperty("hibernate.connection.url", jdbcURL); - cfg.setProperty("hibernate.connection.username", "sa"); - cfg.setProperty("hibernate.connection.password", ""); - cfg.setProperty("hibernate.connection.pool_size", "1"); - cfg.setProperty("hibernate.connection.autocommit", "true"); - cfg.setProperty("hibernate.hbm2ddl.auto", "update"); - - cfg.setProperty("hibernate.cache.region.factory_class", - "com.gemstone.gemfire.modules.hibernate.GemFireRegionFactory"); - cfg.setProperty("hibernate.show_sql", "true"); - cfg.setProperty("hibernate.cache.use_query_cache", "true"); - //cfg.setProperty("gemfire.mcast-port", AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS)+""); - cfg.setProperty("gemfire.mcast-port", "0"); - cfg.setProperty("gemfire.statistic-sampling-enabled", "true"); - cfg.setProperty("gemfire.log-file", gemfireLog); - cfg.setProperty("gemfire.writable-working-dir", tmpDir.getPath()); - //cfg.setProperty("gemfire.statistic-archive-file", "plugin-stats-file.gfs"); - //cfg.setProperty("gemfire.default-client-region-attributes-id", "CACHING_PROXY"); - //cfg.setProperty("gemfire.cache-topology", "client-server"); - //cfg.setProperty("gemfire.locators", "localhost[5432]"); - //cfg.setProperty("gemfire.log-level", "fine"); - // cfg.setProperty("", ""); - cfg.addClass(Person.class); - cfg.addClass(Event.class); - if (overrideProps != null) { - Iterator it = overrideProps.keySet().iterator(); - while (it.hasNext()) { - String key = (String)it.next(); - cfg.setProperty(key, overrideProps.getProperty(key)); - } - } - return cfg.buildSessionFactory(); - } - - @Test - public void testpreload() { - log.info("SWAP:creating session factory In hibernateTestCase"); - - Session session = getSessionFactory(null).openSession(); - log.info("SWAP:session opened"); - session.beginTransaction(); - Event theEvent = new Event(); - theEvent.setTitle("title"); - theEvent.setDate(new Date()); - session.save(theEvent); - Long id = theEvent.getId(); - session.getTransaction().commit(); - session.beginTransaction(); - Event ev = (Event)session.get(Event.class, id); - log.info("SWAP:load complete: " + ev); - session.getTransaction().commit(); - } - - @Test - public void testNothing() throws Exception { - java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.ALL); - log.info("SWAP:creating session factory In hibernateTestCase"); - - Session session = getSessionFactory(null).openSession(); - log.info("SWAP:session opened"); - // session.setFlushMode(FlushMode.COMMIT); - session.beginTransaction(); - Event theEvent = new Event(); - theEvent.setTitle("title"); - theEvent.setDate(new Date()); - //session.save(theEvent); - session.persist(theEvent); - Long id = theEvent.getId(); - session.getTransaction().commit(); - log.info("commit complete...doing load"); - session.beginTransaction(); - Event ev = (Event)session.load(Event.class, id); - log.info("load complete: " + ev); - log.trace("SWAP"); - ev.setTitle("newTitle"); - session.save(ev); - log.info("commit"); - session.getTransaction().commit(); - log.info("save complete " + ev); - - session.beginTransaction(); - ev = (Event)session.load(Event.class, id); - log.info("load complete: " + ev); - ev.setTitle("newTitle2"); - session.save(ev); - log.info("commit"); - session.getTransaction().commit(); - log.info("save complete " + ev); - - ev = (Event)session.load(Event.class, id); - log.info("second load " + ev); - session.flush(); - session.close(); - log.info("flush complete session:" + session); - - for (int i=0; i<5; i++) { - session = getSessionFactory(null).openSession(); - log.info("doing get "+id); - // ev = (Event) session.load(Event.class, id); - ev = (Event)session.get(Event.class, id); - log.info("third load " + ev); - } - printExistingDB(); - Iterator it = GemFireCacheImpl.getInstance().rootRegions().iterator(); - while (it.hasNext()) { - Region r = (Region)it.next(); - System.out.println("Region:"+r); - Iterator enIt = r.entrySet().iterator(); - while (enIt.hasNext()) { - Region.Entry re = (Entry)enIt.next(); - System.out.println("key:"+re.getKey()+" value:"+re.getValue()); - } - } - Thread.sleep(3000); - //System.in.read(); - // try direct data - - } - - public void _testInvalidation() { - Session s = getSessionFactory(null).openSession(); - } - - static Long personId; - - @Test - public void testRelationship() throws Exception { - //java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.ALL); - Properties props = new Properties(); - props.put("gemfire.topology", "client-server"); - Session session = getSessionFactory(null).openSession(); - session.beginTransaction(); - - Person thePerson = new Person(); - thePerson.setFirstname("foo"); - thePerson.setLastname("bar"); - thePerson.setAge(1); - thePerson.setId(99L); - session.save(thePerson); - personId = thePerson.getId(); - log.info("person saved"); - - Event theEvent = new Event(); - theEvent.setTitle("title"); - theEvent.setDate(new Date()); - session.save(theEvent); - Long eventId = theEvent.getId(); - log.info("event saved"); - - Event theEvent2 = new Event(); - theEvent2.setTitle("title2"); - theEvent2.setDate(new Date()); - session.save(theEvent2); - Long eventId2 = theEvent2.getId(); - log.info("event2 saved"); - session.getTransaction().commit(); - - session.beginTransaction(); - Person aPerson = (Person) session.load(Person.class, personId); - Event anEvent = (Event) session.load(Event.class, eventId); - Event anEvent2 = (Event) session.load(Event.class, eventId2); - log.info("adding event to person"); - aPerson.getE().add(anEvent); - aPerson.getE().add(anEvent2); - log.info("calling commit"); - - session.getTransaction().commit(); - log.info("commit complete"); - session.close(); - log.info("opening new session"); - session = getSessionFactory(null).openSession(); - log.info("SWAP:loading person"); - aPerson = (Person)session.load(Person.class, personId); - log.info("loading events"); - Iterator e = aPerson.getE().iterator(); - while (e.hasNext()) { - e.next(); - } - session.close(); - log.info("opening new session"); - session = getSessionFactory(null).openSession(); - log.info("SWAP:loading person"); - aPerson = (Person)session.load(Person.class, personId); - log.info("loading events"); - e = aPerson.getE().iterator(); - while (e.hasNext()) { - e.next(); - } - - log.info(aPerson.getE()+""); - session.close(); - //System.in.read(); -// log.info("opening third session"); -// session = getSessionFactory().openSession(); -// log.info("loading person"); -// aPerson = (Person)session.load(Person.class, personId); -// log.info("loading events"); -// log.info(aPerson.getEvents()+""); - } - - public void _testQueryCache() throws Exception { - Session session = getSessionFactory(null).openSession(); - Query q = session.createQuery("from Event"); - q.setCacheable(true); - List l = q.list(); - log.info("list:"+l); -// log.info("Sleeping for 10 seconds"); -// Thread.sleep(10000); - l = q.list(); - log.info("list2:"+l); - log.info("updating an event"); - session.beginTransaction(); - Event e = (Event)l.get(0); - e.setDate(new Date()); - session.saveOrUpdate(e); - session.getTransaction().commit(); - l = q.list(); - log.info("list3:"+l); - } - - @Test - public void testInsert() { - Session session = getSessionFactory(null).openSession(); - Region r = GemFireCacheImpl.getExisting().getRegion(Person.class.getCanonicalName()); - int initSize = r.size(); - session.beginTransaction(); - log.info("SWAP: Saving Person"); - Person p = new Person(); - p.setId(10L); - p.setFirstname("foo"); - p.setLastname("bar"); - session.saveOrUpdate("Person", p); - session.getTransaction().commit(); - assertEquals(1, session.getStatistics().getEntityCount()); - assertEquals(initSize+1, r.size()); - - session.beginTransaction(); - p.setAge(1); - session.saveOrUpdate(p); - session.getTransaction().commit(); - assertEquals(1, session.getStatistics().getEntityCount()); - } - - @Test - public void testNormalRegion() { - Properties props = new Properties(); - props.setProperty("gemfire.default-region-attributes-id", "LOCAL"); - Session session = getSessionFactory(props).openSession(); - session.beginTransaction(); - Event theEvent = new Event(); - theEvent.setTitle("title"); - theEvent.setDate(new Date()); - session.save(theEvent); - Long id = theEvent.getId(); - session.getTransaction().commit(); - session.beginTransaction(); - Event ev = (Event)session.load(Event.class, id); - ev.setTitle("newTitle"); - session.save(ev); - session.getTransaction().commit(); - } - - private void printExistingDB() throws SQLException { - try { - Class.forName("org.hsqldb.jdbc.JDBCDriver"); - } - catch (Exception e) { - System.err.println("ERROR: failed to load HSQLDB JDBC driver."); - e.printStackTrace(); - return; - } - - Connection c = DriverManager.getConnection(jdbcURL, "SA", ""); - log.info("issuing query..."); - ResultSet rs = c.createStatement().executeQuery("select * from events"); - int col = rs.getMetaData().getColumnCount(); - while (rs.next()) { - StringBuilder b = new StringBuilder(); - for (int i = 1; i <= col; i++) { - b.append(" col:" + i + ":" + rs.getString(i)); - } - log.info("Query result:" + b.toString()); - } - } - - @Test - public void testEnum() { - AnnotationConfiguration cfg = new AnnotationConfiguration(); - cfg.addAnnotatedClass(Owner.class); - cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); - cfg.setProperty("hibernate.connection.driver_class", - "org.hsqldb.jdbcDriver"); - cfg.setProperty("hibernate.connection.url", jdbcURL); - cfg.setProperty("hibernate.connection.username", "sa"); - cfg.setProperty("hibernate.connection.password", ""); - cfg.setProperty("hibernate.connection.pool_size", "1"); - cfg.setProperty("hibernate.connection.autocommit", "true"); - cfg.setProperty("hibernate.hbm2ddl.auto", "update"); - - cfg.setProperty("hibernate.cache.region.factory_class", - "com.gemstone.gemfire.modules.hibernate.GemFireRegionFactory"); - cfg.setProperty("hibernate.show_sql", "true"); - cfg.setProperty("hibernate.cache.use_query_cache", "true"); - cfg.setProperty("gemfire.statistic-sampling-enabled", "true"); - cfg.setProperty("gemfire.log-file", gemfireLog); - cfg.setProperty("gemfire.writable-working-dir", tmpDir.getPath()); - cfg.setProperty("gemfire.mcast-port", "0"); - //cfg.setProperty("gemfire.cache-topology", "client-server"); - - SessionFactory sf = cfg.buildSessionFactory(); - Session session = sf.openSession(); - session.beginTransaction(); - Owner o = new Owner(); - o.setAddress("addr"); - o.setCity("pdx"); - o.setStatus(Status.PREMIUM); - session.save(o); - long id = o.getId(); - log.info("testEnum:commiting tx"); - session.getTransaction().commit(); - session.close(); - - session = sf.openSession(); - Owner o1 = (Owner) session.load(Owner.class, id); - log.info("loaded:"+o); - assertEquals(o.getAddress(), o1.getAddress()); - assertEquals(o.getCity(), o1.getCity()); - assertEquals(o.getStatus(), o1.getStatus()); - o1.setAddress("address2"); - session.save(o1); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Owner.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Owner.java b/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Owner.java deleted file mode 100644 index 92ef56f..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Owner.java +++ /dev/null @@ -1,186 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -import org.hibernate.annotations.Entity; - - -/** - * Simple JavaBean domain object representing an owner. - * - * @author Ken Krebs - * @author Juergen Hoeller - * @author Sam Brannen - */ -@javax.persistence.Entity -@Entity -public class Owner { - private static final long serialVersionUID = 4315791692556052565L; - - @Column(name="address") - private String address; - - private String city; - - private String telephone; - -// private Set pets; - @Id - @GeneratedValue - private Long id; - - private long versionNum = -1; - - public enum Status { - NORMAL, PREMIUM - }; - - @Enumerated - private Status status = Status.NORMAL; - - private void setId(Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - - public String getAddress() { - return this.address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getCity() { - return this.city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getTelephone() { - return this.telephone; - } - - public void setTelephone(String telephone) { - this.telephone = telephone; - } - - public long getVersionNum() { - return versionNum; - } - - public void setVersionNum(long versionNum) { - this.versionNum = versionNum; - } - - public Status getStatus() { - return this.status; - } - - public void setStatus(Status state) { - if (state != null) { - this.status = state; - } - } - -// protected void setPetsInternal(Set pets) { -// this.pets = pets; -// } -// -// protected Set getPetsInternal() { -// if (this.pets == null) { -// this.pets = new HashSet(); -// } -// return this.pets; -// } -// -// public List getPets() { -// List sortedPets = new ArrayList(getPetsInternal()); -// PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", -// true, true)); -// return Collections.unmodifiableList(sortedPets); -// } -// -// public void addPet(Pet pet) { -// getPetsInternal().add(pet); -// pet.setOwner(this); -// } -// -// /** -// * Return the Pet with the given name, or null if none found for this Owner. -// * -// * @param name -// * to test -// * @return true if pet name is already in use -// */ -// public Pet getPet(String name) { -// return getPet(name, false); -// } -// -// /** -// * Return the Pet with the given name, or null if none found for this Owner. -// * -// * @param name -// * to test -// * @return true if pet name is already in use -// */ -// public Pet getPet(String name, boolean ignoreNew) { -// name = name.toLowerCase(); -// for (Pet pet : getPetsInternal()) { -// if (!ignoreNew || !pet.isNew()) { -// String compName = pet.getName(); -// compName = compName.toLowerCase(); -// if (compName.equals(name)) { -// return pet; -// } -// } -// } -// return null; -// } -// -// @Override -// public String toString() { -// return new ToStringCreator(this).append("id", this.getId()) -// .append("new", this.isNew()) -// .append("lastName", this.getLastName()) -// .append("firstName", this.getFirstName()) -// .append("address", this.address).append("city", this.city) -// .append("telephone", this.telephone) -// .append("version", this.versionNum) -// .append("status", this.status) -// -// .toString(); -// } -} - http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Person.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Person.java b/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Person.java deleted file mode 100644 index 559363d..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/Person.java +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules; - -import java.util.HashSet; -import java.util.Set; - -public class Person { - private Long id; - private int age; - private String firstname; - private String lastname; - - private Set e = new HashSet(); - - public Person() {} - - public void setId(Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - - public void setAge(int age) { - this.age = age; - } - - public int getAge() { - return age; - } - - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - public String getFirstname() { - return firstname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - public String getLastname() { - return lastname; - } - - public void setE(Set events) { - this.e = events; - } - - public Set getE() { - return e; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/SecondVMTest.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/SecondVMTest.java b/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/SecondVMTest.java deleted file mode 100644 index e3b6480..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/java/com/gemstone/gemfire/modules/SecondVMTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package com.gemstone.gemfire.modules; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Properties; -import java.util.logging.Level; - -import com.gemstone.gemfire.test.junit.categories.IntegrationTest; -import junit.framework.TestCase; - -import org.hibernate.Session; -import org.junit.Ignore; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheFactory; -import com.gemstone.gemfire.cache.GemFireCache; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.Region.Entry; -import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; - -@Ignore("Can this test be deleted?") -@Category(IntegrationTest.class) -public class SecondVMTest extends TestCase { - - private Logger log = LoggerFactory.getLogger(getClass()); - - public void testNoop() { - - } - public void _testStartEmptyVM() throws IOException { - Properties gemfireProperties = new Properties(); - gemfireProperties.setProperty("mcast-port", "5555"); - gemfireProperties.setProperty("log-level", "fine"); - Cache cache = new CacheFactory(gemfireProperties).create(); - System.in.read(); - Iterator it = cache.rootRegions().iterator(); - while (it.hasNext()) { - Region r = (Region)it.next(); - System.out.println("Region:"+r); - Iterator enIt = r.entrySet().iterator(); - while (enIt.hasNext()) { - Region.Entry re = (Entry)enIt.next(); - System.out.println("key:"+re.getKey()+" value:"+re.getValue()); - } - } - } - - public void _testStartVM() throws Exception { - java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.ALL); - Session session = HibernateJUnitTest.getSessionFactory(null).openSession(); - log.info("SWAP:new session open"); - long id = 1; - log.info("loading new person:"+(id)); - GemFireCache cache = GemFireCacheImpl.getInstance(); - Iterator> rSet = cache.rootRegions().iterator(); - while (rSet.hasNext()) { - Region r = rSet.next(); - log.info("SWAP:Region "+r); - Iterator keySet = r.keySet().iterator(); - while (keySet.hasNext()) { - log.info("key:"+keySet.next()); - } - } - log.info("loading new person:"+(id)); - session.beginTransaction(); - Person p = (Person)session.load(Person.class, id); - p.setFirstname("SecondVMfirstname"+id); - log.info("loading events"); - log.info(p.getE()+""); - session.getTransaction().commit(); - //System.in.read(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Event.hbm.xml ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Event.hbm.xml b/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Event.hbm.xml deleted file mode 100644 index 3ec08c9..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Event.hbm.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Person.hbm.xml ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Person.hbm.xml b/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Person.hbm.xml deleted file mode 100644 index 7c28734..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/resources/com/gemstone/gemfire/modules/Person.hbm.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-hibernate/src/test/resources/log4j.properties ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-hibernate/src/test/resources/log4j.properties b/extensions/gemfire-modules-hibernate/src/test/resources/log4j.properties deleted file mode 100644 index c136990..0000000 --- a/extensions/gemfire-modules-hibernate/src/test/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml! -# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J. -#log4j.rootLogger=DEBUG, stdout, logfile -log4j.rootLogger=DEBUG, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n - -#log4j.appender.logfile=org.apache.log4j.RollingFileAppender -#log4j.appender.logfile.MaxFileSize=512KB -## Keep three backup files. -#log4j.appender.logfile.MaxBackupIndex=3 -## Pattern to output: date priority [category] - message -#log4j.appender.logfile.layout=org.apache.log4j.PatternLayout -#log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-session/build.gradle ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-session/build.gradle b/extensions/gemfire-modules-session/build.gradle deleted file mode 100644 index 45c6445..0000000 --- a/extensions/gemfire-modules-session/build.gradle +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -dependencies { - compile project(':extensions/gemfire-modules') - compile project(':gemfire-core') - - testCompile 'javax.servlet:javax.servlet-api:' + project.'javax.servlet-api.version' - testCompile 'org.slf4j:slf4j-api:' + project.'slf4j-api.version' - testCompile('com.mockrunner:mockrunner-servlet:' + project.'mockrunner.version') { - exclude group: 'jboss' - } - testCompile(group: 'org.eclipse.jetty', name: 'jetty-http', version: project.'jetty.version', classifier: 'tests') - testCompile(group: 'org.eclipse.jetty', name: 'jetty-servlet', version: project.'jetty.version', classifier: 'tests') - - testCompile project(path: ':gemfire-junit') -} - -jar { - include '**/session/filter/**/*' - include '**/session/installer/**/*' - includeEmptyDirs = false - - manifest { - attributes 'Main-Class': 'com.gemstone.gemfire.modules.session.installer.Installer' - } - baseName = 'gemfire-modules-session' -} - -task internalJar(type: Jar) { - from sourceSets.main.output - include '**/internal/**/*' - includeEmptyDirs = false - baseName = 'gemfire-modules-session' - classifier = 'internal' -} - -artifacts { - archives internalJar -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionCachingFilter.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionCachingFilter.java b/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionCachingFilter.java deleted file mode 100644 index 7490fdd..0000000 --- a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionCachingFilter.java +++ /dev/null @@ -1,652 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package com.gemstone.gemfire.modules.session.filter; - -import com.gemstone.gemfire.modules.session.internal.filter.GemfireHttpSession; -import com.gemstone.gemfire.modules.session.internal.filter.GemfireSessionManager; -import com.gemstone.gemfire.modules.session.internal.filter.SessionManager; -import com.gemstone.gemfire.modules.session.internal.filter.util.ThreadLocalSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.security.Principal; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Primary class which orchestrates everything. This is the class which gets - * configured in the web.xml. - */ -public class SessionCachingFilter implements Filter { - - /** - * Logger instance - */ - private static final Logger LOG = - LoggerFactory.getLogger(SessionCachingFilter.class.getName()); - - /** - * The filter configuration object we are associated with. If this value is - * null, this filter instance is not currently configured. - */ - private FilterConfig filterConfig = null; - - /** - * Some containers will want to instantiate multiple instances of this filter, - * but we only need one SessionManager - */ - private static SessionManager manager = null; - - /** - * Can be overridden during testing. - */ - private static AtomicInteger started = - new AtomicInteger( - Integer.getInteger("gemfire.override.session.manager.count", 1)); - - private static int percentInactiveTimeTriggerRebuild = - Integer.getInteger("gemfire.session.inactive.trigger.rebuild", 80); - - /** - * This latch ensures that at least one thread/instance has fired up the - * session manager before any other threads complete the init method. - */ - private static CountDownLatch startingLatch = new CountDownLatch(1); - - /** - * This request wrapper class extends the support class - * HttpServletRequestWrapper, which implements all the methods in the - * HttpServletRequest interface, as delegations to the wrapped request. You - * only need to override the methods that you need to change. You can get - * access to the wrapped request using the method getRequest() - */ - public static class RequestWrapper extends HttpServletRequestWrapper { - - private static final String URL_SESSION_IDENTIFIER = ";jsessionid="; - - private ResponseWrapper response; - - private boolean sessionFromCookie = false; - - private boolean sessionFromURL = false; - - private String requestedSessionId = null; - - private GemfireHttpSession session = null; - - private SessionManager manager; - - private HttpServletRequest outerRequest = null; - - /** - * Need to save this in case we need the original {@code RequestDispatcher} - */ - private HttpServletRequest originalRequest; - - public RequestWrapper(SessionManager manager, - HttpServletRequest request, - ResponseWrapper response) { - - super(request); - this.response = response; - this.manager = manager; - this.originalRequest = request; - - final Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (final Cookie cookie : cookies) { - if (cookie.getName().equalsIgnoreCase( - manager.getSessionCookieName()) && - cookie.getValue().endsWith("-GF")) { - requestedSessionId = cookie.getValue(); - sessionFromCookie = true; - - LOG.debug("Cookie contains sessionId: {}", - requestedSessionId); - } - } - } - - if (requestedSessionId == null) { - requestedSessionId = extractSessionId(); - LOG.debug("Extracted sessionId from URL {}", requestedSessionId); - if (requestedSessionId != null) { - sessionFromURL = true; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public HttpSession getSession() { - return getSession(true); - } - - /** - * Create our own sessions. TODO: Handle invalidated sessions - * - * @return a HttpSession - */ - @Override - public HttpSession getSession(boolean create) { - if (session != null && session.isValid()) { - session.setIsNew(false); - session.updateAccessTime(); - /* - * This is a massively gross hack. Currently, there is no way - * to actually update the last accessed time for a session, so - * what we do here is once we're into X% of the session's TTL - * we grab a new session from the container. - * - * (inactive * 1000) * (pct / 100) ==> (inactive * 10 * pct) - */ - if (session.getLastAccessedTime() - session.getCreationTime() > - (session.getMaxInactiveInterval() * 10 * percentInactiveTimeTriggerRebuild)) { - HttpSession nativeSession = super.getSession(); - session.failoverSession(nativeSession); - } - return session; - } - - if (requestedSessionId != null) { - session = (GemfireHttpSession) manager.getSession( - requestedSessionId); - if (session != null) { - session.setIsNew(false); - // This means we've failed over to another node - if (session.getNativeSession() == null) { - try { - ThreadLocalSession.set(session); - HttpSession nativeSession = super.getSession(); - session.failoverSession(nativeSession); - session.putInRegion(); - } finally { - ThreadLocalSession.remove(); - } - } - } - } - - if (session == null || !session.isValid()) { - if (create) { - try { - session = (GemfireHttpSession) manager.wrapSession(null); - ThreadLocalSession.set(session); - HttpSession nativeSession = super.getSession(); - if (session.getNativeSession() == null) { - session.setNativeSession(nativeSession); - } else { - assert (session.getNativeSession() == nativeSession); - } - session.setIsNew(true); - manager.putSession(session); - } finally { - ThreadLocalSession.remove(); - } - } else { - // create is false, and session is either null or not valid. - // The spec says return a null: - return null; - } - } - - if (session != null) { - addSessionCookie(response); - session.updateAccessTime(); - } - - return session; - } - - private void addSessionCookie(HttpServletResponse response) { - // Don't bother if the response is already committed - if (response.isCommitted()) { - return; - } - - // Get the existing cookies - Cookie[] cookies = getCookies(); - - Cookie cookie = new Cookie(manager.getSessionCookieName(), - session.getId()); - cookie.setPath("".equals(getContextPath()) ? "/" : getContextPath()); - // Clear out all old cookies and just set ours - response.addCookie(cookie); - - // Replace all other cookies which aren't JSESSIONIDs - if (cookies != null) { - for (Cookie c : cookies) { - if (manager.getSessionCookieName().equals(c.getName())) { - continue; - } - response.addCookie(c); - } - } - - } - - private String getCookieString(Cookie c) { - StringBuilder cookie = new StringBuilder(); - cookie.append(c.getName()).append("=").append(c.getValue()); - - if (c.getPath() != null) { - cookie.append("; ").append("Path=").append(c.getPath()); - } - if (c.getDomain() != null) { - cookie.append("; ").append("Domain=").append(c.getDomain()); - } - if (c.getSecure()) { - cookie.append("; ").append("Secure"); - } - - cookie.append("; HttpOnly"); - - return cookie.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isRequestedSessionIdFromCookie() { - return sessionFromCookie; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isRequestedSessionIdFromURL() { - return sessionFromURL; - } - - /** - * {@inheritDoc} - */ - @Override - public String getRequestedSessionId() { - if (requestedSessionId != null) { - return requestedSessionId; - } else { - return super.getRequestedSessionId(); - } - } - - /* - * Hmmm... not sure if this is right or even good to do. So, in some - * cases - for ex. using a Spring security filter, we have 3 possible - * wrappers to deal with - the original, this one and one created by - * Spring. When a servlet or JSP is forwarded to the original request - * is passed in, but then this (the wrapped) request is used by the JSP. - * In some cases, the outer wrapper also contains information relevant - * to the request - in this case security info. So here we allow access - * to that. There's probably a better way.... - */ - - /** - * {@inheritDoc} - */ - @Override - public Principal getUserPrincipal() { - if (outerRequest != null) { - return outerRequest.getUserPrincipal(); - } else { - return super.getUserPrincipal(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getRemoteUser() { - if (outerRequest != null) { - return outerRequest.getRemoteUser(); - } else { - return super.getRemoteUser(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isUserInRole(String role) { - if (outerRequest != null) { - return outerRequest.isUserInRole(role); - } else { - return super.isUserInRole(role); - } - } - - ////////////////////////////////////////////////////////////// - // Non-API methods - - void setOuterWrapper(HttpServletRequest outer) { - this.outerRequest = outer; - } - - ////////////////////////////////////////////////////////////// - // Private methods - private String extractSessionId() { - final int prefix = getRequestURL().indexOf(URL_SESSION_IDENTIFIER); - if (prefix != -1) { - final int start = prefix + URL_SESSION_IDENTIFIER.length(); - int suffix = getRequestURL().indexOf("?", start); - if (suffix < 0) { - suffix = getRequestURL().indexOf("#", start); - } - if (suffix <= prefix) { - return getRequestURL().substring(start); - } - return getRequestURL().substring(start, suffix); - } - return null; - } - } - - /** - * This response wrapper class extends the support class - * HttpServletResponseWrapper, which implements all the methods in the - * HttpServletResponse interface, as delegations to the wrapped response. You - * only need to override the methods that you need to change. You can get - * access to the wrapped response using the method getResponse() - */ - class ResponseWrapper extends HttpServletResponseWrapper { - - HttpServletResponse originalResponse; - - public ResponseWrapper(HttpServletResponse response) throws IOException { - super(response); - originalResponse = response; - } - - public HttpServletResponse getOriginalResponse() { - return originalResponse; - } - - @Override - public void setHeader(String name, String value) { - super.setHeader(name, value); - } - - @Override - public void setIntHeader(String name, int value) { - super.setIntHeader(name, value); - } - } - - - public SessionCachingFilter() { - } - - /** - * @param request The servlet request we are processing - * @param response The servlet response we are creating - * @param chain The filter chain we are processing - * @throws IOException if an input/output error occurs - * @throws ServletException if a servlet error occurs - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - HttpServletRequest httpReq = (HttpServletRequest) request; - HttpServletResponse httpResp = (HttpServletResponse) response; - - /** - * Early out if this isn't the right kind of request. We might see a - * RequestWrapper instance during a forward or include request. - */ - if (request instanceof RequestWrapper || - !(request instanceof HttpServletRequest)) { - LOG.debug("Handling already-wrapped request"); - chain.doFilter(request, response); - return; - } - - // Create wrappers for the request and response objects. - // Using these, you can extend the capabilities of the - // request and response, for example, allow setting parameters - // on the request before sending the request to the rest of the filter chain, - // or keep track of the cookies that are set on the response. - // - // Caveat: some servers do not handle wrappers very well for forward or - // include requests. - - ResponseWrapper wrappedResponse = new ResponseWrapper(httpResp); - final RequestWrapper wrappedRequest = - new RequestWrapper(manager, httpReq, wrappedResponse); - - Throwable problem = null; - - try { - chain.doFilter(wrappedRequest, wrappedResponse); - } catch (Throwable t) { - // If an exception is thrown somewhere down the filter chain, - // we still want to execute our after processing, and then - // rethrow the problem after that. - problem = t; - LOG.error("Exception processing filter chain", t); - } - - GemfireHttpSession session = - (GemfireHttpSession) wrappedRequest.getSession(false); - - // If there was a problem, we want to rethrow it if it is - // a known type, otherwise log it. - if (problem != null) { - if (problem instanceof ServletException) { - throw (ServletException) problem; - } - if (problem instanceof IOException) { - throw (IOException) problem; - } - sendProcessingError(problem, response); - } - - /** - * Commit any updates. What actually happens at that point is - * dependent on the type of attributes defined for use by the sessions. - */ - if (session != null) { - session.commit(); - } - } - - /** - * Return the filter configuration object for this filter. - */ - public FilterConfig getFilterConfig() { - return (this.filterConfig); - } - - /** - * Set the filter configuration object for this filter. - * - * @param filterConfig The filter configuration object - */ - public void setFilterConfig(FilterConfig filterConfig) { - this.filterConfig = filterConfig; - } - - /** - * Destroy method for this filter - */ - @Override - public void destroy() { - if (manager != null) { - manager.stop(); - } - } - - /** - * This is where all the initialization happens. - * - * @param config - * @throws ServletException - */ - @Override - public void init(final FilterConfig config) { - LOG.info("Starting Session Filter initialization"); - this.filterConfig = config; - - if (started.getAndDecrement() > 0) { - /** - * Allow override for testing purposes - */ - String managerClassStr = - config.getInitParameter("session-manager-class"); - - // Otherwise default - if (managerClassStr == null) { - managerClassStr = GemfireSessionManager.class.getName(); - } - - try { - manager = (SessionManager) Class.forName( - managerClassStr).newInstance(); - manager.start(config, this.getClass().getClassLoader()); - } catch (Exception ex) { - LOG.error("Exception creating Session Manager", ex); - } - - startingLatch.countDown(); - } else { - try { - startingLatch.await(); - } catch (InterruptedException iex) { - } - - LOG.debug("SessionManager and listener initialization skipped - " - + "already done."); - } - - LOG.info("Session Filter initialization complete"); - LOG.debug("Filter class loader {}", this.getClass().getClassLoader()); - } - - /** - * Return a String representation of this object. - */ - @Override - public String toString() { - if (filterConfig == null) { - return ("SessionCachingFilter()"); - } - StringBuilder sb = new StringBuilder("SessionCachingFilter("); - sb.append(filterConfig); - sb.append(")"); - return (sb.toString()); - - } - - - private void sendProcessingError(Throwable t, ServletResponse response) { - String stackTrace = getStackTrace(t); - - if (stackTrace != null && !stackTrace.equals("")) { - try { - response.setContentType("text/html"); - PrintStream ps = new PrintStream(response.getOutputStream()); - PrintWriter pw = new PrintWriter(ps); - pw.print( - "\n\nError\n\n\n"); //NOI18N - - // PENDING! Localize this for next official release - pw.print("

The resource did not process correctly

\n
\n");
-        pw.print(stackTrace);
-        pw.print("
\n"); //NOI18N - pw.close(); - ps.close(); - response.getOutputStream().close(); - } catch (Exception ex) { - } - } else { - try { - PrintStream ps = new PrintStream(response.getOutputStream()); - t.printStackTrace(ps); - ps.close(); - response.getOutputStream().close(); - } catch (Exception ex) { - } - } - } - - public static String getStackTrace(Throwable t) { - String stackTrace = null; - try { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - pw.close(); - sw.close(); - stackTrace = sw.getBuffer().toString(); - } catch (Exception ex) { - } - return stackTrace; - } - - /** - * Retrieve the SessionManager. This is only here so that tests can get access - * to the cache. - */ - public static SessionManager getSessionManager() { - return manager; - } - - /** - * Return the GemFire session which wraps a native session - * - * @param nativeSession the native session for which the corresponding GemFire - * session should be returned. - * @return the GemFire session or null if no session maps to the native - * session - */ - public static HttpSession getWrappingSession(HttpSession nativeSession) { - /* - * This is a special case where the GemFire session has been set as a - * ThreadLocal during session creation. - */ - GemfireHttpSession gemfireSession = (GemfireHttpSession) ThreadLocalSession.get(); - if (gemfireSession != null) { - gemfireSession.setNativeSession(nativeSession); - return gemfireSession; - } - return getSessionManager().getWrappingSession(nativeSession.getId()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionListener.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionListener.java b/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionListener.java deleted file mode 100644 index 7973bc5..0000000 --- a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/filter/SessionListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package com.gemstone.gemfire.modules.session.filter; - -import com.gemstone.gemfire.distributed.DistributedSystemDisconnectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; - -public class SessionListener implements HttpSessionListener { - - private static final Logger LOG = - LoggerFactory.getLogger(SessionListener.class.getName()); - - public void sessionCreated(HttpSessionEvent httpSessionEvent) { - } - - /** - * This will receive events from the container using the native sessions. - */ - public void sessionDestroyed(HttpSessionEvent event) { - String nativeId = event.getSession().getId(); - try { - String sessionId = SessionCachingFilter.getSessionManager().destroyNativeSession( - nativeId); - LOG.debug( - "Received sessionDestroyed event for native session {} (wrapped by {})", - nativeId, sessionId); - } catch (DistributedSystemDisconnectedException dex) { - LOG.debug("Cache disconnected - unable to destroy native session {0}", - nativeId); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/f6c4c2f9/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/installer/Installer.java ---------------------------------------------------------------------- diff --git a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/installer/Installer.java b/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/installer/Installer.java deleted file mode 100644 index 7ba5b34..0000000 --- a/extensions/gemfire-modules-session/src/main/java/com/gemstone/gemfire/modules/session/installer/Installer.java +++ /dev/null @@ -1,296 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package com.gemstone.gemfire.modules.session.installer; - -import com.gemstone.gemfire.modules.session.installer.args.Argument; -import com.gemstone.gemfire.modules.session.installer.args.ArgumentProcessor; -import com.gemstone.gemfire.modules.session.installer.args.ArgumentValues; -import com.gemstone.gemfire.modules.session.installer.args.UnknownArgumentHandler; -import com.gemstone.gemfire.modules.session.installer.args.UsageException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * - */ -public class Installer { - - private static final String GEMFIRE_FILTER_CLASS = - "com.gemstone.gemfire.modules.session.filter.SessionCachingFilter"; - - private static final String GEMFIRE_LISTENER_CLASS = - "com.gemstone.gemfire.modules.session.filter.SessionListener"; - - private ArgumentValues argValues; - - private static final Argument ARG_HELP = - new Argument("-h", false). - setDescription("Displays this help message."); - - private static Argument ARG_GEMFIRE_PARAMETERS = - new Argument("-p", false, "param=value"). - setDescription("Specific parameter for inclusion into the " - + "session filter definition as a regular " - + "init-param. Can be given multiple times."); - - private static Argument ARG_CACHE_TYPE = - new Argument("-t", false, "cache-type"). - setDescription( - "Type of cache. Must be one of 'peer-to-peer' or " - + "'client-server'. Default is peer-to-peer."). - setDefaults("peer-to-peer"); - - private static Argument ARG_WEB_XML_FILE = - new Argument("-w", true, "web.xml file"). - setDescription("The web.xml file to be modified."); - - - /** - * Class main method - * - * @param args Arguments passed in via the command line - * @throws Exception in the event of any errors - */ - public static void main(final String[] args) throws Exception { - new Installer(args).process(); - } - - public static void log(String message) { - System.err.println(message); - } - - - public Installer(String[] args) throws Exception { - final ArgumentProcessor processor = new ArgumentProcessor("Installer"); - - argValues = null; - try { - // These are ordered so as to keep the options alphabetical - processor.addArgument(ARG_HELP); - processor.addArgument(ARG_GEMFIRE_PARAMETERS); - processor.addArgument(ARG_CACHE_TYPE); - processor.addArgument(ARG_WEB_XML_FILE); - - processor.setUnknownArgumentHandler(new UnknownArgumentHandler() { - @Override - public void handleUnknownArgument( - final String form, final String[] params) { - log("Unknown argument being ignored: " - + form + " (" + params.length + " params)"); - log("Use '-h' argument to display usage"); - } - }); - argValues = processor.process(args); - - if (argValues.isDefined(ARG_HELP)) { - final UsageException usageException = - new UsageException("Usage requested by user"); - usageException.setUsage(processor.getUsage()); - throw (usageException); - } - - } catch (UsageException ux) { - final StringBuilder error = new StringBuilder(); - error.append("\nERROR: "); - error.append(ux.getMessage()); - error.append("\n"); - if (ux.getUsage() != null) { - error.append(ux.getUsage()); - } - log(error.toString()); - System.exit(2); - } - - } - - - /** - * The main entry point for processing - * - * @throws Exception if any errors occur. - */ - public void process() throws Exception { - String argInputFile = argValues.getFirstResult(ARG_WEB_XML_FILE); - - ByteArrayOutputStream output = new ByteArrayOutputStream(); - InputStream input = new FileInputStream(argInputFile); - - processWebXml(input, output); - input.close(); - - System.out.println(output.toString()); - } - - - private void processWebXml(final InputStream webXml, - final OutputStream out) throws Exception { - - Document doc = createWebXmlDoc(webXml); - mangleWebXml(doc); - - streamXML(doc, out); - } - - - private Document createWebXmlDoc(final InputStream webXml) - throws Exception { - Document doc; - final DocumentBuilderFactory factory = - DocumentBuilderFactory.newInstance(); - final DocumentBuilder builder = factory.newDocumentBuilder(); - doc = builder.parse(webXml); - - return doc; - } - - - private Document mangleWebXml(final Document doc) { - final Element docElement = doc.getDocumentElement(); - final NodeList nodelist = docElement.getChildNodes(); - Node firstFilter = null; - Node displayElement = null; - Node afterDisplayElement = null; - - for (int i = 0; i < nodelist.getLength(); i++) { - final Node node = nodelist.item(i); - final String name = node.getNodeName(); - if ("display-name".equals(name)) { - displayElement = node; - } else { - if ("filter".equals(name)) { - if (firstFilter == null) { - firstFilter = node; - } - } - if (displayElement != null && afterDisplayElement == null) { - afterDisplayElement = node; - } - } - } - - Node initParam; - final Element filter = doc.createElement("filter"); - append(doc, filter, "filter-name", "gemfire-session-filter"); - append(doc, filter, "filter-class", GEMFIRE_FILTER_CLASS); - - // Set the type of cache - initParam = append(doc, filter, "init-param", null); - append(doc, initParam, "param-name", "cache-type"); - append(doc, initParam, "param-value", - argValues.getFirstResult(ARG_CACHE_TYPE)); - - - if (argValues.isDefined(ARG_GEMFIRE_PARAMETERS)) { - for (String[] val : argValues.getAllResults(ARG_GEMFIRE_PARAMETERS)) { - String gfParam = val[0]; - int idx = gfParam.indexOf("="); - initParam = append(doc, filter, "init-param", null); - append(doc, initParam, "param-name", gfParam.substring(0, idx)); - append(doc, initParam, "param-value", gfParam.substring(idx + 1)); - } - } - - Node first = firstFilter; - if (first == null) { - if (afterDisplayElement != null) { - first = afterDisplayElement; - } - } - if (first == null) { - first = docElement.getFirstChild(); - } - docElement.insertBefore(filter, first); - final Element filterMapping = doc.createElement("filter-mapping"); - append(doc, filterMapping, "filter-name", "gemfire-session-filter"); - append(doc, filterMapping, "url-pattern", "/*"); - append(doc, filterMapping, "dispatcher", "FORWARD"); - append(doc, filterMapping, "dispatcher", "INCLUDE"); - append(doc, filterMapping, "dispatcher", "REQUEST"); - append(doc, filterMapping, "dispatcher", "ERROR"); - final Element contextListener = doc.createElement("listener"); - append(doc, contextListener, "listener-class", GEMFIRE_LISTENER_CLASS); - docElement.insertBefore(filterMapping, after(docElement, "filter")); - docElement.insertBefore(contextListener, - after(docElement, "filter-mapping")); - return doc; - } - - private Node after(final Node parent, final String nodeName) { - final NodeList nodelist = parent.getChildNodes(); - int index = -1; - for (int i = 0; i < nodelist.getLength(); i++) { - final Node node = nodelist.item(i); - final String name = node.getNodeName(); - if (nodeName.equals(name)) { - index = i; - } - } - if (index == -1) - return null; - if (nodelist.getLength() > (index + 1)) { - return nodelist.item(index + 1); - } - return null; - } - - private Node append(final Document doc, final Node parent, - final String element, - final String value) { - final Element child = doc.createElement(element); - if (value != null) - child.setTextContent(value); - parent.appendChild(child); - return child; - } - - private void streamXML(final Document doc, final OutputStream out) { - try {// Use a Transformer for output - final TransformerFactory tFactory = TransformerFactory.newInstance(); - final Transformer transformer = tFactory.newTransformer(); - if (doc.getDoctype() != null) { - final String systemId = doc.getDoctype().getSystemId(); - final String publicId = doc.getDoctype().getPublicId(); - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemId); - } - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", - "4"); - final DOMSource source = new DOMSource(doc); - final StreamResult result = new StreamResult(out); - transformer.transform(source, result); - } catch (final Exception e) { - e.printStackTrace(); - } - } - -}