You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by zo...@apache.org on 2010/05/30 19:00:07 UTC
svn commit: r949534 [1/2] - in /incubator/aries/trunk/samples/blog: ./
blog-itests/ blog-itests/src/test/java/org/apache/aries/samples/blog/itests/
blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/
blog-persistence-jdb...
Author: zoe
Date: Sun May 30 17:00:06 2010
New Revision: 949534
URL: http://svn.apache.org/viewvc?rev=949534&view=rev
Log:
ARIES-313 Adding JDBC blog tests
Added:
incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleTest.java
incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java
incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java
Modified:
incubator/aries/trunk/samples/blog/blog-itests/pom.xml
incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractIntegrationTest.java
incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java
incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/resources/OSGI-INF/blueprint/blueprint.xml
incubator/aries/trunk/samples/blog/pom.xml
Modified: incubator/aries/trunk/samples/blog/blog-itests/pom.xml
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-itests/pom.xml?rev=949534&r1=949533&r2=949534&view=diff
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-itests/pom.xml (original)
+++ incubator/aries/trunk/samples/blog/blog-itests/pom.xml Sun May 30 17:00:06 2010
@@ -84,6 +84,25 @@
<artifactId>org.apache.aries.samples.blog.persistence.jpa</artifactId>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.aries.samples.blog</groupId>
+ <artifactId>org.apache.aries.samples.blog.persistence.jdbc</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.aries.samples.blog</groupId>
+ <artifactId>org.apache.aries.samples.blog.datasource</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.aries.samples.blog</groupId>
+ <artifactId>org.apache.aries.samples.blog.jdbc.eba</artifactId>
+ <scope>test</scope>
+ <type>eba</type>
+ </dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
@@ -351,12 +370,6 @@
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.aries.samples.blog</groupId>
- <artifactId>org.apache.aries.samples.blog.datasource</artifactId>
- <scope>test</scope>
- </dependency>
-
</dependencies>
<build>
Modified: incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractIntegrationTest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractIntegrationTest.java?rev=949534&r1=949533&r2=949534&view=diff
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractIntegrationTest.java (original)
+++ incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractIntegrationTest.java Sun May 30 17:00:06 2010
@@ -28,6 +28,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@@ -39,9 +40,14 @@ import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
+import org.ops4j.pax.url.mvn.Handler;
+import org.ops4j.pax.url.mvn.ServiceConstants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
@@ -212,5 +218,63 @@ public abstract class AbstractIntegratio
return conn;
}
+
+ protected <T> T getOsgiService(Class<T> type, long timeout) {
+ return getOsgiService(type, null, timeout);
+ }
+
+ protected <T> T getOsgiService(Class<T> type) {
+ return getOsgiService(type, null, DEFAULT_TIMEOUT);
+ }
+
+ protected <T> T getOsgiService(Class<T> type, String filter, long timeout) {
+ return getOsgiService(null, type, filter, timeout);
+ }
+
+ protected <T> T getOsgiService(BundleContext bc, Class<T> type,
+ String filter, long timeout) {
+ ServiceTracker tracker = null;
+ try {
+ String flt;
+ if (filter != null) {
+ if (filter.startsWith("(")) {
+ flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")"
+ + filter + ")";
+ } else {
+ flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")("
+ + filter + "))";
+ }
+ } else {
+ flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
+ }
+ Filter osgiFilter = FrameworkUtil.createFilter(flt);
+ tracker = new ServiceTracker(bc == null ? bundleContext : bc, osgiFilter,
+ null);
+ tracker.open();
+
+ // add tracker to the list of trackers we close at tear down
+ srs.add(tracker);
+ Object x = tracker.waitForService(timeout);
+ Object svc = type.cast(x);
+ if (svc == null) {
+ throw new RuntimeException("Gave up waiting for service " + flt);
+ }
+ return type.cast(svc);
+ } catch (InvalidSyntaxException e) {
+ throw new IllegalArgumentException("Invalid filter", e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static URL getUrlToEba(String groupId, String artifactId) throws MalformedURLException {
+ String artifactVersion = getArtifactVersion(groupId, artifactId);
+
+ // Need to use handler from org.ops4j.pax.url.mvn
+ URL urlToEba = new URL(null,
+ ServiceConstants.PROTOCOL + ":" + groupId + "/" +artifactId + "/"
+ + artifactVersion + "/eba", new Handler());
+ return urlToEba;
+ }
}
Added: incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleTest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleTest.java?rev=949534&view=auto
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleTest.java (added)
+++ incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleTest.java Sun May 30 17:00:06 2010
@@ -0,0 +1,162 @@
+/*
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.samples.blog.itests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages;
+import static org.ops4j.pax.exam.CoreOptions.equinox;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.systemProperty;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
+
+import java.net.HttpURLConnection;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.JUnit4TestRunner;
+import org.osgi.framework.Bundle;
+
+@RunWith(JUnit4TestRunner.class)
+public class JdbcBlogSampleTest extends AbstractIntegrationTest {
+
+ @Test
+ public void test() throws Exception {
+
+ Bundle bapi = getInstalledBundle("org.apache.aries.samples.blog.api");
+ assertNotNull(bapi);
+ bapi.start();
+
+ Bundle bweb = getInstalledBundle("org.apache.aries.samples.blog.web");
+ assertNotNull(bweb);
+ bweb.start();
+
+ Bundle bbiz = getInstalledBundle("org.apache.aries.samples.blog.biz");
+ assertNotNull(bbiz);
+ bbiz.start();
+
+ Bundle bper = getInstalledBundle("org.apache.aries.samples.blog.persistence.jdbc");
+ assertNotNull(bper);
+ bper.start();
+
+ Bundle bds = getInstalledBundle("org.apache.aries.samples.blog.datasource");
+ Bundle txs = getInstalledBundle("org.apache.aries.transaction.manager");
+
+ waitForServices(bbiz, "org.apache.aries.samples.api.BloggingService");
+ waitForServices(bper, "org.apache.aries.samples.api.BloggingService");
+ waitForServices(bds, "java.sql.XADataSource");
+ waitForServices(txs, "javax.transaction.TransactionManager");
+
+ if (!isServiceRegistered(bbiz)) {
+ System.out.println("ZZZZZ No services registered for "
+ + bbiz.getSymbolicName());
+ }
+
+ if (!isServiceRegistered(bper)) {
+ System.out.println("ZZZZZ No services registered for "
+ + bper.getSymbolicName());
+ }
+
+ if (!isServiceRegistered(bds)) {
+ System.out.println("ZZZZZ No services registered for "
+ + bds.getSymbolicName());
+ }
+
+ if (!isServiceRegistered(txs)) {
+ System.out.println("ZZZZZ No services registered for "
+ + txs.getSymbolicName());
+ }
+
+ System.out.println("ZZZZZ in test and trying to get connection....");
+ HttpURLConnection conn = makeConnection("http://localhost:8080/org.apache.aries.samples.blog.web/ViewBlog");
+ String response = getHTTPResponse(conn);
+ System.out.println("ZZZZZ " + response);
+ System.out.println("ZZZZZ " + conn.getResponseCode());
+ System.out.println("ZZZZZ " + HttpURLConnection.HTTP_OK);
+
+ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+
+ assertTrue("The response did not contain the expected content",
+ response.contains("Blog home"));
+ }
+
+ @org.ops4j.pax.exam.junit.Configuration
+ public static Option[] configuration() {
+ Option[] options = options(
+ bootDelegationPackages("javax.transaction",
+ "javax.transaction.*"),
+ vmOption("-Dorg.osgi.framework.system.packages=javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.c
allback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.
xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,
org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers,javax.transaction;partial=true;mandatory:=partial,javax.transaction.xa;partial=true;mandatory:=partial"),
+ // Log
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-api"),
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-service"),
+ // Felix mvn url handler - do we need this?
+ mavenBundle("org.ops4j.pax.url", "pax-url-mvn"),
+
+ // this is how you set the default log level when using pax
+ // logging (logProfile)
+ systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level")
+ .value("DEBUG"),
+
+ // Bundles
+ mavenBundle("org.eclipse.equinox", "cm"),
+ mavenBundle("org.eclipse.osgi", "services"),
+
+ mavenBundle("org.ops4j.pax.web", "pax-web-extender-war"),
+ mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle"),
+ mavenBundle("org.ops4j.pax.web", "pax-web-jsp"),
+ mavenBundle("org.apache.derby", "derby"),
+ mavenBundle("org.apache.geronimo.specs", "geronimo-jpa_2.0_spec"),
+
+ mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec"),
+ mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.5_spec"),
+ mavenBundle("org.apache.geronimo.components", "geronimo-transaction"),
+ mavenBundle("org.apache.openjpa", "openjpa"),
+ mavenBundle("commons-lang", "commons-lang"),
+ mavenBundle("commons-collections", "commons-collections"),
+ mavenBundle("commons-pool", "commons-pool"),
+ mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.serp"),
+ mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint" ),
+ mavenBundle("org.apache.aries", "org.apache.aries.util" ),
+ mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.install" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.api" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.management" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.api" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.blueprint.aries" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container.context" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.manager" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.blueprint" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.wrappers" ),
+ mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.datasource" ),
+ mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.api" ).noStart(),
+ mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.web" ).noStart(),
+ mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.biz" ).noStart(),
+ mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.persistence.jdbc" ).noStart(),
+ mavenBundle("asm", "asm-all" ),
+ equinox().version("3.5.0")
+ );
+ options = updateOptions(options);
+ return options;
+ }
+
+}
Added: incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java?rev=949534&view=auto
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java (added)
+++ incubator/aries/trunk/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java Sun May 30 17:00:06 2010
@@ -0,0 +1,164 @@
+/*
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.samples.blog.itests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages;
+import static org.ops4j.pax.exam.CoreOptions.equinox;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.systemProperty;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import org.apache.aries.application.management.AriesApplication;
+import org.apache.aries.application.management.AriesApplicationContext;
+import org.apache.aries.application.management.AriesApplicationManager;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.JUnit4TestRunner;
+import org.osgi.framework.Bundle;
+
+@RunWith(JUnit4TestRunner.class)
+public class JdbcBlogSampleWithEbaTest extends AbstractIntegrationTest {
+
+ @Test
+ public void test() throws Exception {
+
+ URL urlToEba = getUrlToEba("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.jdbc.eba");
+
+ AriesApplicationManager manager = getOsgiService(AriesApplicationManager.class);
+ AriesApplication app = manager.createApplication(urlToEba);
+ AriesApplicationContext ctx = manager.install(app);
+ ctx.start();
+
+ Bundle bapi = getInstalledBundle("org.apache.aries.samples.blog.api");
+ assertNotNull(bapi);
+ bapi.start();
+
+ Bundle bweb = getInstalledBundle("org.apache.aries.samples.blog.web");
+ assertNotNull(bweb);
+ bweb.start();
+
+ Bundle bbiz = getInstalledBundle("org.apache.aries.samples.blog.biz");
+ assertNotNull(bbiz);
+ bbiz.start();
+
+ Bundle bper = getInstalledBundle("org.apache.aries.samples.blog.persistence.jdbc");
+ assertNotNull(bper);
+ bper.start();
+
+ Bundle txs = getInstalledBundle("org.apache.aries.transaction.manager");
+
+ waitForServices(bbiz, "org.apache.aries.samples.api.BloggingService");
+ waitForServices(bper, "org.apache.aries.samples.api.BloggingService");
+ waitForServices(txs, "javax.transaction.TransactionManager");
+
+ if (!isServiceRegistered(bbiz)) {
+ System.out.println("ZZZZZ No services registered for "
+ + bbiz.getSymbolicName());
+ }
+
+ if (!isServiceRegistered(bper)) {
+ System.out.println("ZZZZZ No services registered for "
+ + bper.getSymbolicName());
+ }
+
+ if (!isServiceRegistered(txs)) {
+ System.out.println("ZZZZZ No services registered for "
+ + txs.getSymbolicName());
+ }
+
+ System.out.println("ZZZZZ in test and trying to get connection....");
+ HttpURLConnection conn = makeConnection("http://localhost:8080/org.apache.aries.samples.blog.web/ViewBlog");
+ String response = getHTTPResponse(conn);
+ System.out.println("ZZZZZ " + response);
+ System.out.println("ZZZZZ " + conn.getResponseCode());
+ System.out.println("ZZZZZ " + HttpURLConnection.HTTP_OK);
+
+ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
+
+ assertTrue("The response did not contain the expected content",
+ response.contains("Blog home"));
+
+ ctx.stop();
+ manager.uninstall(ctx);
+ }
+
+ @org.ops4j.pax.exam.junit.Configuration
+ public static Option[] configuration() {
+ Option[] options = options(
+ bootDelegationPackages("javax.transaction",
+ "javax.transaction.*"),
+ vmOption("-Dorg.osgi.framework.system.packages=javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.c
allback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.
xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,
org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers,javax.transaction;partial=true;mandatory:=partial,javax.transaction.xa;partial=true;mandatory:=partial"),
+ // Log
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-api"),
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-service"),
+ // Felix mvn url handler - do we need this?
+ mavenBundle("org.ops4j.pax.url", "pax-url-mvn"),
+
+ // this is how you set the default log level when using pax
+ // logging (logProfile)
+ systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level")
+ .value("DEBUG"),
+
+ // Bundles
+ mavenBundle("org.eclipse.equinox", "cm"),
+ mavenBundle("org.eclipse.osgi", "services"),
+
+ mavenBundle("org.ops4j.pax.web", "pax-web-extender-war"),
+ mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle"),
+ mavenBundle("org.ops4j.pax.web", "pax-web-jsp"),
+ mavenBundle("org.apache.derby", "derby"),
+ mavenBundle("org.apache.geronimo.specs", "geronimo-jpa_2.0_spec"),
+
+ mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec"),
+ mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.5_spec"),
+ mavenBundle("org.apache.geronimo.components", "geronimo-transaction"),
+ mavenBundle("org.apache.openjpa", "openjpa"),
+ mavenBundle("commons-lang", "commons-lang"),
+ mavenBundle("commons-collections", "commons-collections"),
+ mavenBundle("commons-pool", "commons-pool"),
+ mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.serp"),
+ mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint" ),
+ mavenBundle("org.apache.aries", "org.apache.aries.util" ),
+ mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.install" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.api" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.management" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime" ),
+ mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.api" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.blueprint.aries" ),
+ mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container.context" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.manager" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.blueprint" ),
+ mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.wrappers" ),
+ mavenBundle("asm", "asm-all" ),
+ equinox().version("3.5.0")
+ );
+ options = updateOptions(options);
+ return options;
+ }
+
+}
Modified: incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java?rev=949534&r1=949533&r2=949534&view=diff
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java (original)
+++ incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java Sun May 30 17:00:06 2010
@@ -1,659 +1,728 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.aries.samples.blog.persistence.jdbc;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import javax.sql.DataSource;
-
-import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService;
-import org.apache.aries.samples.blog.persistence.jdbc.entity.AuthorImpl;
-import org.apache.aries.samples.blog.persistence.jdbc.entity.EntryImpl;
-
-/**
- * This class is the implementation of the blogPersistenceService
- */
-public class BlogPersistenceServiceImpl implements BlogPersistenceService {
- private DataSource dataSource;
-
-
- /**
- * set data source
- */
- public void setDataSource(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- /**
- * Create an author record
- *
- * @param a
- * The author object to be created
- * @throws ParseException
- * @throws ParseException
- */
- public void createAuthor(String email, Date dob, String name,
- String displayName, String bio) {
-
-
- try {
- Connection connection = dataSource.getConnection();
- String sql = "INSERT INTO AUTHOR VALUES (?,?,?,?,?)";
-
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ppsm.setString(1, email);
- ppsm.setString(2, bio);
- ppsm.setString(3, displayName);
- if (dob != null)
- ppsm.setDate(4, new java.sql.Date(dob.getTime()));
- else
- ppsm.setDate(4, null);
- ppsm.setString(5, name);
- int insertRows = ppsm.executeUpdate();
- ppsm.close();
- connection.close();
-
- if (insertRows != 1)
- throw new IllegalArgumentException("The Author " + email
- + " cannot be inserted.");
- } catch (SQLException e) {
- e.printStackTrace();
- throw new IllegalArgumentException(e.getMessage());
- }
-
- }
-
- /**
- * Create a blog entry record
- *
- * @param a
- * The author
- * @param title
- * The title of the post
- * @param blogText
- * The text of the post
- * @param tags
- *
- */
- public void createBlogPost(String authorEmail, String title, String blogText,
- List<String> tags) {
-
- AuthorImpl a = getAuthor(authorEmail);
-
- if(title == null) title = "";
- Date publishDate = new Date(System.currentTimeMillis());
- if(tags == null) tags = new ArrayList<String>();
-
-
- try {
- Connection connection = dataSource.getConnection();
- // let's find the max id from the blogentry table
- String sql = "SELECT max(id) FROM BLOGENTRY";
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ResultSet rs = ppsm.executeQuery();
- // we only expect to have one row returned
- rs.next();
-
- long max_id = rs.getLong(1);
- ppsm.close();
-
- long post_id = max_id + 1;
- sql = "INSERT INTO BLOGENTRY VALUES (?,?,?,?,?,?)";
-
- ppsm = connection.prepareStatement(sql);
- ppsm.setLong(1, post_id);
- ppsm.setString(2, blogText);
- if (publishDate != null)
- ppsm
- .setDate(3, new java.sql.Date(publishDate
- .getTime()));
- else
- ppsm.setDate(3, null);
- ppsm.setString(4, title);
-
- ppsm.setDate(5, null);
- ppsm.setString(6, a.getEmail());
- int rows = ppsm.executeUpdate();
- if (rows != 1)
- throw new IllegalArgumentException(
- "The blog entry record cannot be inserted: "
- + blogText);
- ppsm.close();
-
- // insert a row in the relationship table
-
- sql = "INSERT INTO Author_BlogEntry VALUES (?,?)";
- ppsm = connection.prepareStatement(sql);
- ppsm.setString(1, a.getEmail());
- ppsm.setLong(2, post_id);
-
- rows = ppsm.executeUpdate();
- ppsm.close();
- connection.close();
-
- if (rows != 1)
- throw new IllegalArgumentException(
- "The Author_BlogEntry record cannot be inserted: "
- + a.getEmail() + " , " + post_id);
-
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- }
-
- }
-
- /**
- * Find the blog entry record with the specified title
- *
- * @param The title to be searched
- * @return The blogEntry record
- */
- public EntryImpl findBlogEntryByTitle(String title) {
-
- EntryImpl be = null;
-
- String sql = "SELECT * FROM BlogEntry e WHERE e.title = '" + title
- + "'";
-
- List<EntryImpl> blogEntries = findBlogs(sql);
-
- // just return the first blog entry for the time being
- if ((blogEntries != null) && (blogEntries.size() > 0))
- be = blogEntries.get(0);
- return be;
- }
-
- /**
- * Return all author records in the Author table
- *
- * @return the list of Author records
- */
- public List<AuthorImpl> getAllAuthors() {
- String sql = "SELECT * FROM Author";
-
- List<AuthorImpl> list = findAuthors(sql);
-
- return list;
- }
-
- /**
- * Return all blog entry records from BlogEntry table with the most recent
- * published blog entries first
- *
- * @return a list of blogEntry object
- */
- public List<EntryImpl> getAllBlogEntries() {
- String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC";
-
- List<EntryImpl> list = findBlogs(sql);
-
- return list;
- }
-
- /**
- * Return the number of the blog entry records
- *
- * @return the number of the blog Entry records
- */
- public int getNoOfBlogEntries() {
-
- int count = 0;
-
- String sql = "SELECT count(*) FROM BLOGENTRY";
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ResultSet rs = ppsm.executeQuery();
- // we only expect to have one row returned
- rs.next();
- count = rs.getInt(1);
- ppsm.close();
- connection.close();
-
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- }
- return count;
- }
-
- /**
- * Return the portion of blog Entries
- *
- * @param firstPostIndex
- * The index of the first blog entry to be returned
- * @param noOfPosts
- * The number of blog entry to be returned
- * @return The list of the blog entry record
- */
- public List<EntryImpl> getBlogEntries(int firstPostIndex, int noOfPosts) {
- String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC";
- List<EntryImpl> emptyList = new ArrayList<EntryImpl>();
- List<EntryImpl> blogs = findBlogs(sql);
- // we only return a portion of the list
- if (blogs == null)
- return emptyList;
- // We need to make sure we won't throw IndexOutOfBoundException if the
- // supplied
- // index is out of the list range
- int maximumIndex = blogs.size();
- // if the first index is minus or greater than the last item index of
- // the list, return an empty list
- if ((firstPostIndex < 0) || (noOfPosts <= 0)
- || (firstPostIndex > maximumIndex))
- return emptyList;
- // return the required number of the blog entries or the available blog
- // entries
- int lastIndex = noOfPosts + firstPostIndex;
- // we need to make sure we return the blog entries at most up to the
- // final record
-
- return (blogs.subList(firstPostIndex,
- (lastIndex > maximumIndex) ? maximumIndex : lastIndex));
-
- }
-
- /**
- * Return the author with the specified email address
- *
- * @param emailAddress
- * The email address
- * @return The author record
- */
- public AuthorImpl getAuthor(String emailAddress) {
- String sql = "SELECT * FROM AUTHOR a where a.email='" + emailAddress
- + "'";
- List<AuthorImpl> authors = findAuthors(sql);
-
- if (authors.size() == 0)
- return null;
- else if (authors.size() > 1)
- throw new IllegalArgumentException(
- "Email address should be unique per author");
-
- return authors.get(0); // just return the first author
- }
-
- /**
- * Return the blog entries modified between the date range of [start, end]
- *
- * @param start
- * The start date
- * @param end
- * The end date
- * @return The list of blog entries
- */
- public List<EntryImpl> getBlogEntriesModifiedBetween(Date start, Date end) {
-
- // String sql = "SELECT * FROM BlogEntry b WHERE (b.updatedDate >= " +
- // startTS +" AND b.updatedDate <= " + endTS + ") OR (b.publishDate >= "
- // +startTS + " AND b.publishDate <= " + endTS +
- // ") ORDER BY b.publishDate ASC";
- String sql = "SELECT * FROM BlogEntry b WHERE (Date(b.updatedDate) BETWEEN '"
- + start
- + "' AND '"
- + end
- + "') OR (Date(b.publishDate) BETWEEN '"
- + start
- + "' AND '"
- + end + "') ORDER BY b.publishDate ASC";
-
- return findBlogs(sql);
-
- }
-
- /**
- * Return a list of blog entries belonging to the author with the specified
- * email address
- *
- * @param emailAddress
- * the author's email address
- * @return The list of blog entries
- */
- public List<EntryImpl> getBlogsForAuthor(String emailAddress) {
-
- String sql = "SELECT * FROM BlogEntry b WHERE b.AUTHOR_EMAIL='"
- + emailAddress + "'";
- return findBlogs(sql);
- }
-
- /**
- * Update the author record
- *
- * @param email
- * The email associated with an author
- * @param dob
- * The author's date of birth
- * @param name
- * the author's name
- * @param displayName
- * The displayName
- * @param bio
- * The aouthor's bio
- */
- public void updateAuthor(String email, Date dob, String name,
- String displayName, String bio) {
-
-
- String sql = "UPDATE AUTHOR a SET bio = ?, displayName = ?, dob = ?, name =? WHERE email ='"
- + email + "'";
- int updatedRows = 0;
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ppsm.setString(1, bio);
- ppsm.setString(2, displayName);
- if (dob != null)
- ppsm.setDate(3, new java.sql.Date(dob.getTime()));
- else
- ppsm.setDate(3, null);
- ppsm.setString(4, name);
- updatedRows = ppsm.executeUpdate();
-
- ppsm.close();
- connection.close();
-
- if (updatedRows != 1)
- throw new IllegalArgumentException("The Author " + email
- + " cannot be updated.");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Update the blog entry record
- *
- *
- */
- public void updateBlogEntry(long id, String email, String title, String blogText, List<String> tags, Date updatedDate) {
-
- if (id == -1)
- throw new IllegalArgumentException(
- "Not a BlogEntry returned by this interface");
- EntryImpl b = getBlogEntryById(id);
- String sql_se = "SELECT * FROM BLOGENTRY bp WHERE bp.id = " + id;
- String email_old = null;
- // let's find out the email address for the blog post to see whether the
- // table Author_BlogEntry needs to be updated
- // if the email is updated, we need to update the table Author_BlogEntry
- // to reflect the change.
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql_se);
- ResultSet rs = ppsm.executeQuery();
- // there should be just one record
- rs.next();
- email_old = rs.getString("AUTHOR_EMAIL");
- ppsm.close();
- connection.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- }
- String sql = "UPDATE BLOGENTRY bp SET bp.blogText = ?, bp.publishDate = ?, bp.title = ?, bp.updatedDate = ?, bp.AUTHOR_EMAIL = ? where bp.id = "
- + id;
- int updatedRows = 0;
-
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ppsm.setString(1, blogText);
- if (b.getPublishDate() != null)
- ppsm
- .setDate(2, new java.sql.Date(b.getPublishDate()
- .getTime()));
- else
- ppsm.setDate(2, null);
- ppsm.setString(3, b.getTitle());
- if (b.getUpdatedDate() != null)
- ppsm
- .setDate(4, new java.sql.Date(b.getUpdatedDate()
- .getTime()));
- else
- ppsm.setDate(4, null);
-
- ppsm.setString(5, email);
- updatedRows = ppsm.executeUpdate();
-
- ppsm.close();
-
- connection.close();
-
- if (updatedRows != 1)
- throw new IllegalArgumentException("The Blog " + b.getId()
- + " cannot be updated.");
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- // if the email address is changed, we need to need to update the
- // relationship table Author_BlogEntry
- if ((email_old != null) && (!!!email_old.equals(email))) {
- // update the table Author_BlogEntry
- String sql_ab = "UDPATE Author_BlogEntry ab SET ab.AUTHOR_EMAIL = '"
- + email + "'";
- updatedRows = 0;
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql_ab);
- updatedRows = ppsm.executeUpdate();
- ppsm.close();
- connection.close();
- if (updatedRows != 1)
- throw new IllegalArgumentException(
- "The Author_BlogEntry with the postsID "
- + b.getId() + " cannot be updated.");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Delete the author record with the specified email address
- *
- * @param emailAddress
- * The author's email address
- *
- */
- public void removeAuthor(String emailAddress) {
-
- // we need to remove the author and its blog entries
-
- try {
- String sql = "DELETE FROM BLOGENTRY bp WHERE bp.AUTHOR_EMAIL = '"
- + emailAddress + "'";
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ppsm.executeUpdate();
- ppsm.close();
-
- // delete the records from Author_BlogEntry
- sql = "DELETE FROM Author_BlogEntry ab WHERE ab.AUTHOR_EMAIL = '"
- + emailAddress + "'";
- ppsm = connection.prepareStatement(sql);
- ppsm.executeUpdate();
- ppsm.close();
-
- // delete the author record
- sql = "DELETE FROM Author a WHERE a.EMAIL = '" + emailAddress + "'";
- ppsm = connection.prepareStatement(sql);
- ppsm.executeUpdate();
- ppsm.close();
- connection.close();
-
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- }
-
- }
-
- /**
- * Delete the blog entry record specified by the blogEntry
- *
- * @param blogEntry
- * the blog entry record to be deleted
- */
- public void removeBlogEntry(long id) {
- if (id == -1)
- throw new IllegalArgumentException(
- "Not a BlogEntry returned by this interface");
-
- try {
- String sql = "DELETE FROM BLOGENTRY bp WHERE bp.id = "
- + id;
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ppsm.executeUpdate();
- ppsm.close();
- // We also need to delete the records from Author_BlogEntry, as this
- // table is a kind of link between author and blogentry record
- sql = "DELETE FROM Author_BlogEntry ab WHERE ab.POSTS_ID = "
- + id;
- ppsm = connection.prepareStatement(sql);
- ppsm.executeUpdate();
- ppsm.close();
- connection.close();
-
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- }
-
- }
-
- /**
- * Return the blog entry record with the specified id
- *
- * @param postId
- * The blogEntry record id
- */
- public EntryImpl getBlogEntryById(long postId) {
- String sql = "SELECT * FROM BlogEntry b WHERE b.id = " + postId;
- List<EntryImpl> blogs = findBlogs(sql);
- if (blogs.size() == 0)
- return null;
- if (blogs.size() > 1)
- throw new IllegalArgumentException("Blog id is not unique");
- return blogs.get(0);
- }
-
- /**
- * Return a list of authors with the sql query
- *
- * @param sql
- * The SQL query
- * @return A list of author records
- */
- private List<AuthorImpl> findAuthors(String sql) {
- List<AuthorImpl> authorList = new ArrayList<AuthorImpl>();
-
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
-
- ResultSet ars = ppsm.executeQuery();
-
- while (ars.next()) {
- AuthorImpl ar = new AuthorImpl();
- ar.setBio(ars.getString("bio"));
- ar.setDisplayName(ars.getString("displayName"));
- ar.setDob(ars.getDate("dob"));
- String email = ars.getString("email");
- ar.setEmail(email);
- ar.setName(ars.getString("name"));
-
- // let's find the blog entries for the author
- String sql_be = "SELECT * FROM BLOGENTRY be WHERE be.AUTHOR_EMAIL = '"
- + email + "'";
- PreparedStatement ppsm2 = connection.prepareStatement(sql_be);
- ResultSet rs = ppsm2.executeQuery();
-
- List<EntryImpl> blogs = new ArrayList<EntryImpl>();
- while (rs.next()) {
- EntryImpl blog = new EntryImpl();
- blog.setAuthor(ar);
- blog.setId(rs.getLong("id"));
- blog.setBlogText(rs.getString("blogText"));
- blog.setPublishDate(rs.getDate("publishDate"));
- blog.setTitle(rs.getString("title"));
- blog.setUpdatedDate(rs.getDate("updatedDate"));
- blogs.add(blog);
- }
- ar.setEntries(blogs);
- authorList.add(ar);
- ppsm2.close();
- }
- ppsm.close();
- connection.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return authorList;
- }
-
- /**
- * Return a list of blog entries with the sql query
- *
- * @param sql
- * The sql query to be executed
- * @return a list of blogEntry records
- */
- private List<EntryImpl> findBlogs(String sql) {
- List<EntryImpl> blogEntryList = new ArrayList<EntryImpl>();
-
- try {
- Connection connection = dataSource.getConnection();
- PreparedStatement ppsm = connection.prepareStatement(sql);
- ResultSet blogrs = ppsm.executeQuery();
-
- while (blogrs.next()) {
- EntryImpl be = new EntryImpl();
- be.setId(blogrs.getLong("id"));
- be.setBlogText(blogrs.getString("blogText"));
- be.setPublishDate(blogrs.getDate("publishDate"));
- be.setTitle(blogrs.getString("title"));
- be.setUpdatedDate(blogrs.getDate("updatedDate"));
- // find the author email address
- String author_email = blogrs.getString("AUTHOR_EMAIL");
- String author_sql = "SELECT * FROM Author a WHERE a.email ='"
- + author_email + "'";
- List<AuthorImpl> authors = findAuthors(author_sql);
- // there should be just one entry, as email is the primary key
- // for the Author table
- if (authors.size() != 1)
- throw new IllegalArgumentException(
- "We got more than one author with the same email address. This is wrong");
- else
- be.setAuthor(authors.get(0));
- blogEntryList.add(be);
- }
- ppsm.close();
- connection.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return blogEntryList;
- }
-}
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.samples.blog.persistence.jdbc;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.sql.DataSource;
+
+import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService;
+import org.apache.aries.samples.blog.persistence.jdbc.entity.AuthorImpl;
+import org.apache.aries.samples.blog.persistence.jdbc.entity.EntryImpl;
+
+/**
+ * This class is the implementation of the blogPersistenceService
+ */
+public class BlogPersistenceServiceImpl implements BlogPersistenceService {
+ private DataSource dataSource;
+
+ private Statements statements;
+
+ public BlogPersistenceServiceImpl() {
+ this.statements = new Statements();
+ }
+
+ /**
+ * set data source
+ */
+ public void setDataSource(DataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ public void init() {
+ Statement s = null;
+ Connection connection = null;
+
+ try {
+ connection = dataSource.getConnection();
+
+ s = connection.createStatement();
+ String[] createStatments = this.statements
+ .getCreateSchemaStatements();
+ for (int i = 0; i < createStatments.length; i++) {
+ s.execute(createStatments[i]);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ } finally {
+ if (s != null) {
+ try {
+ s.close();
+ } catch (Throwable e) {
+ }
+ }
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (Throwable e) {
+ }
+ }
+ }
+ }
+
+ public void destroy() {
+ Statement s = null;
+ Connection connection = null;
+
+ try {
+ connection = dataSource.getConnection();
+
+ s = connection.createStatement();
+ String[] dropStatments = this.statements.getDropSchemaStatements();
+ for (int i = 0; i < dropStatments.length; i++) {
+ s.execute(dropStatments[i]);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ } finally {
+ if (s != null) {
+ try {
+ s.close();
+ } catch (Throwable e) {
+ }
+ }
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (Throwable e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Create an author record
+ *
+ * @param a
+ * The author object to be created
+ * @throws ParseException
+ * @throws ParseException
+ */
+ public void createAuthor(String email, Date dob, String name,
+ String displayName, String bio) {
+
+
+ try {
+ Connection connection = dataSource.getConnection();
+ String sql = "INSERT INTO AUTHOR VALUES (?,?,?,?,?)";
+
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ppsm.setString(1, email);
+ ppsm.setString(2, bio);
+ ppsm.setString(3, displayName);
+ if (dob != null)
+ ppsm.setDate(4, new java.sql.Date(dob.getTime()));
+ else
+ ppsm.setDate(4, null);
+ ppsm.setString(5, name);
+ int insertRows = ppsm.executeUpdate();
+ ppsm.close();
+ connection.close();
+
+ if (insertRows != 1)
+ throw new IllegalArgumentException("The Author " + email
+ + " cannot be inserted.");
+ } catch (SQLException e) {
+ e.printStackTrace();
+ throw new IllegalArgumentException(e.getMessage());
+ }
+
+ }
+
+ /**
+ * Create a blog entry record
+ *
+ * @param a
+ * The author
+ * @param title
+ * The title of the post
+ * @param blogText
+ * The text of the post
+ * @param tags
+ *
+ */
+ public void createBlogPost(String authorEmail, String title, String blogText,
+ List<String> tags) {
+
+ AuthorImpl a = getAuthor(authorEmail);
+
+ if(title == null) title = "";
+ Date publishDate = new Date(System.currentTimeMillis());
+ if(tags == null) tags = new ArrayList<String>();
+
+
+ try {
+ Connection connection = dataSource.getConnection();
+ // let's find the max id from the blogentry table
+ String sql = "SELECT max(id) FROM BLOGENTRY";
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ResultSet rs = ppsm.executeQuery();
+ // we only expect to have one row returned
+ rs.next();
+
+ long max_id = rs.getLong(1);
+ ppsm.close();
+
+ long post_id = max_id + 1;
+ sql = "INSERT INTO BLOGENTRY VALUES (?,?,?,?,?,?)";
+
+ ppsm = connection.prepareStatement(sql);
+ ppsm.setLong(1, post_id);
+ ppsm.setString(2, blogText);
+ if (publishDate != null)
+ ppsm
+ .setDate(3, new java.sql.Date(publishDate
+ .getTime()));
+ else
+ ppsm.setDate(3, null);
+ ppsm.setString(4, title);
+
+ ppsm.setDate(5, null);
+ ppsm.setString(6, a.getEmail());
+ int rows = ppsm.executeUpdate();
+ if (rows != 1)
+ throw new IllegalArgumentException(
+ "The blog entry record cannot be inserted: "
+ + blogText);
+ ppsm.close();
+
+ // insert a row in the relationship table
+
+ sql = "INSERT INTO Author_BlogEntry VALUES (?,?)";
+ ppsm = connection.prepareStatement(sql);
+ ppsm.setString(1, a.getEmail());
+ ppsm.setLong(2, post_id);
+
+ rows = ppsm.executeUpdate();
+ ppsm.close();
+ connection.close();
+
+ if (rows != 1)
+ throw new IllegalArgumentException(
+ "The Author_BlogEntry record cannot be inserted: "
+ + a.getEmail() + " , " + post_id);
+
+ } catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Find the blog entry record with the specified title
+ *
+ * @param The title to be searched
+ * @return The blogEntry record
+ */
+ public EntryImpl findBlogEntryByTitle(String title) {
+
+ EntryImpl be = null;
+
+ String sql = "SELECT * FROM BlogEntry e WHERE e.title = '" + title
+ + "'";
+
+ List<EntryImpl> blogEntries = findBlogs(sql);
+
+ // just return the first blog entry for the time being
+ if ((blogEntries != null) && (blogEntries.size() > 0))
+ be = blogEntries.get(0);
+ return be;
+ }
+
+ /**
+ * Return all author records in the Author table
+ *
+ * @return the list of Author records
+ */
+ public List<AuthorImpl> getAllAuthors() {
+ String sql = "SELECT * FROM Author";
+
+ List<AuthorImpl> list = findAuthors(sql);
+
+ return list;
+ }
+
+ /**
+ * Return all blog entry records from BlogEntry table with the most recent
+ * published blog entries first
+ *
+ * @return a list of blogEntry object
+ */
+ public List<EntryImpl> getAllBlogEntries() {
+ String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC";
+
+ List<EntryImpl> list = findBlogs(sql);
+
+ return list;
+ }
+
+ /**
+ * Return the number of the blog entry records
+ *
+ * @return the number of the blog Entry records
+ */
+ public int getNoOfBlogEntries() {
+
+ int count = 0;
+
+ String sql = "SELECT count(*) FROM BLOGENTRY";
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ResultSet rs = ppsm.executeQuery();
+ // we only expect to have one row returned
+ rs.next();
+ count = rs.getInt(1);
+ ppsm.close();
+ connection.close();
+
+ } catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+ return count;
+ }
+
+ /**
+ * Return the portion of blog Entries
+ *
+ * @param firstPostIndex
+ * The index of the first blog entry to be returned
+ * @param noOfPosts
+ * The number of blog entry to be returned
+ * @return The list of the blog entry record
+ */
+ public List<EntryImpl> getBlogEntries(int firstPostIndex, int noOfPosts) {
+ String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC";
+ List<EntryImpl> emptyList = new ArrayList<EntryImpl>();
+ List<EntryImpl> blogs = findBlogs(sql);
+ // we only return a portion of the list
+ if (blogs == null)
+ return emptyList;
+ // We need to make sure we won't throw IndexOutOfBoundException if the
+ // supplied
+ // index is out of the list range
+ int maximumIndex = blogs.size();
+ // if the first index is minus or greater than the last item index of
+ // the list, return an empty list
+ if ((firstPostIndex < 0) || (noOfPosts <= 0)
+ || (firstPostIndex > maximumIndex))
+ return emptyList;
+ // return the required number of the blog entries or the available blog
+ // entries
+ int lastIndex = noOfPosts + firstPostIndex;
+ // we need to make sure we return the blog entries at most up to the
+ // final record
+
+ return (blogs.subList(firstPostIndex,
+ (lastIndex > maximumIndex) ? maximumIndex : lastIndex));
+
+ }
+
+ /**
+ * Return the author with the specified email address
+ *
+ * @param emailAddress
+ * The email address
+ * @return The author record
+ */
+ public AuthorImpl getAuthor(String emailAddress) {
+ String sql = "SELECT * FROM AUTHOR a where a.email='" + emailAddress
+ + "'";
+ List<AuthorImpl> authors = findAuthors(sql);
+
+ if (authors.size() == 0)
+ return null;
+ else if (authors.size() > 1)
+ throw new IllegalArgumentException(
+ "Email address should be unique per author");
+
+ return authors.get(0); // just return the first author
+ }
+
+ /**
+ * Return the blog entries modified between the date range of [start, end]
+ *
+ * @param start
+ * The start date
+ * @param end
+ * The end date
+ * @return The list of blog entries
+ */
+ public List<EntryImpl> getBlogEntriesModifiedBetween(Date start, Date end) {
+
+ // String sql = "SELECT * FROM BlogEntry b WHERE (b.updatedDate >= " +
+ // startTS +" AND b.updatedDate <= " + endTS + ") OR (b.publishDate >= "
+ // +startTS + " AND b.publishDate <= " + endTS +
+ // ") ORDER BY b.publishDate ASC";
+ String sql = "SELECT * FROM BlogEntry b WHERE (Date(b.updatedDate) BETWEEN '"
+ + start
+ + "' AND '"
+ + end
+ + "') OR (Date(b.publishDate) BETWEEN '"
+ + start
+ + "' AND '"
+ + end + "') ORDER BY b.publishDate ASC";
+
+ return findBlogs(sql);
+
+ }
+
+ /**
+ * Return a list of blog entries belonging to the author with the specified
+ * email address
+ *
+ * @param emailAddress
+ * the author's email address
+ * @return The list of blog entries
+ */
+ public List<EntryImpl> getBlogsForAuthor(String emailAddress) {
+
+ String sql = "SELECT * FROM BlogEntry b WHERE b.AUTHOR_EMAIL='"
+ + emailAddress + "'";
+ return findBlogs(sql);
+ }
+
+ /**
+ * Update the author record
+ *
+ * @param email
+ * The email associated with an author
+ * @param dob
+ * The author's date of birth
+ * @param name
+ * the author's name
+ * @param displayName
+ * The displayName
+ * @param bio
+ * The aouthor's bio
+ */
+ public void updateAuthor(String email, Date dob, String name,
+ String displayName, String bio) {
+
+
+ String sql = "UPDATE AUTHOR a SET bio = ?, displayName = ?, dob = ?, name =? WHERE email ='"
+ + email + "'";
+ int updatedRows = 0;
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ppsm.setString(1, bio);
+ ppsm.setString(2, displayName);
+ if (dob != null)
+ ppsm.setDate(3, new java.sql.Date(dob.getTime()));
+ else
+ ppsm.setDate(3, null);
+ ppsm.setString(4, name);
+ updatedRows = ppsm.executeUpdate();
+
+ ppsm.close();
+ connection.close();
+
+ if (updatedRows != 1)
+ throw new IllegalArgumentException("The Author " + email
+ + " cannot be updated.");
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Update the blog entry record
+ *
+ *
+ */
+ public void updateBlogEntry(long id, String email, String title, String blogText, List<String> tags, Date updatedDate) {
+
+ if (id == -1)
+ throw new IllegalArgumentException(
+ "Not a BlogEntry returned by this interface");
+ EntryImpl b = getBlogEntryById(id);
+ String sql_se = "SELECT * FROM BLOGENTRY bp WHERE bp.id = " + id;
+ String email_old = null;
+ // let's find out the email address for the blog post to see whether the
+ // table Author_BlogEntry needs to be updated
+ // if the email is updated, we need to update the table Author_BlogEntry
+ // to reflect the change.
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql_se);
+ ResultSet rs = ppsm.executeQuery();
+ // there should be just one record
+ rs.next();
+ email_old = rs.getString("AUTHOR_EMAIL");
+ ppsm.close();
+ connection.close();
+ } catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+ String sql = "UPDATE BLOGENTRY bp SET bp.blogText = ?, bp.publishDate = ?, bp.title = ?, bp.updatedDate = ?, bp.AUTHOR_EMAIL = ? where bp.id = "
+ + id;
+ int updatedRows = 0;
+
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ppsm.setString(1, blogText);
+ if (b.getPublishDate() != null)
+ ppsm
+ .setDate(2, new java.sql.Date(b.getPublishDate()
+ .getTime()));
+ else
+ ppsm.setDate(2, null);
+ ppsm.setString(3, b.getTitle());
+ if (b.getUpdatedDate() != null)
+ ppsm
+ .setDate(4, new java.sql.Date(b.getUpdatedDate()
+ .getTime()));
+ else
+ ppsm.setDate(4, null);
+
+ ppsm.setString(5, email);
+ updatedRows = ppsm.executeUpdate();
+
+ ppsm.close();
+
+ connection.close();
+
+ if (updatedRows != 1)
+ throw new IllegalArgumentException("The Blog " + b.getId()
+ + " cannot be updated.");
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+
+ // if the email address is changed, we need to need to update the
+ // relationship table Author_BlogEntry
+ if ((email_old != null) && (!!!email_old.equals(email))) {
+ // update the table Author_BlogEntry
+ String sql_ab = "UDPATE Author_BlogEntry ab SET ab.AUTHOR_EMAIL = '"
+ + email + "'";
+ updatedRows = 0;
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql_ab);
+ updatedRows = ppsm.executeUpdate();
+ ppsm.close();
+ connection.close();
+ if (updatedRows != 1)
+ throw new IllegalArgumentException(
+ "The Author_BlogEntry with the postsID "
+ + b.getId() + " cannot be updated.");
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * Delete the author record with the specified email address
+ *
+ * @param emailAddress
+ * The author's email address
+ *
+ */
+ public void removeAuthor(String emailAddress) {
+
+ // we need to remove the author and its blog entries
+
+ try {
+ String sql = "DELETE FROM BLOGENTRY bp WHERE bp.AUTHOR_EMAIL = '"
+ + emailAddress + "'";
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ppsm.executeUpdate();
+ ppsm.close();
+
+ // delete the records from Author_BlogEntry
+ sql = "DELETE FROM Author_BlogEntry ab WHERE ab.AUTHOR_EMAIL = '"
+ + emailAddress + "'";
+ ppsm = connection.prepareStatement(sql);
+ ppsm.executeUpdate();
+ ppsm.close();
+
+ // delete the author record
+ sql = "DELETE FROM Author a WHERE a.EMAIL = '" + emailAddress + "'";
+ ppsm = connection.prepareStatement(sql);
+ ppsm.executeUpdate();
+ ppsm.close();
+ connection.close();
+
+ } catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Delete the blog entry record specified by the blogEntry
+ *
+ * @param blogEntry
+ * the blog entry record to be deleted
+ */
+ public void removeBlogEntry(long id) {
+ if (id == -1)
+ throw new IllegalArgumentException(
+ "Not a BlogEntry returned by this interface");
+
+ try {
+ String sql = "DELETE FROM BLOGENTRY bp WHERE bp.id = "
+ + id;
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ppsm.executeUpdate();
+ ppsm.close();
+ // We also need to delete the records from Author_BlogEntry, as this
+ // table is a kind of link between author and blogentry record
+ sql = "DELETE FROM Author_BlogEntry ab WHERE ab.POSTS_ID = "
+ + id;
+ ppsm = connection.prepareStatement(sql);
+ ppsm.executeUpdate();
+ ppsm.close();
+ connection.close();
+
+ } catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Return the blog entry record with the specified id
+ *
+ * @param postId
+ * The blogEntry record id
+ */
+ public EntryImpl getBlogEntryById(long postId) {
+ String sql = "SELECT * FROM BlogEntry b WHERE b.id = " + postId;
+ List<EntryImpl> blogs = findBlogs(sql);
+ if (blogs.size() == 0)
+ return null;
+ if (blogs.size() > 1)
+ throw new IllegalArgumentException("Blog id is not unique");
+ return blogs.get(0);
+ }
+
+ /**
+ * Return a list of authors with the sql query
+ *
+ * @param sql
+ * The SQL query
+ * @return A list of author records
+ */
+ private List<AuthorImpl> findAuthors(String sql) {
+ List<AuthorImpl> authorList = new ArrayList<AuthorImpl>();
+
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+
+ ResultSet ars = ppsm.executeQuery();
+
+ while (ars.next()) {
+ AuthorImpl ar = new AuthorImpl();
+ ar.setBio(ars.getString("bio"));
+ ar.setDisplayName(ars.getString("displayName"));
+ ar.setDob(ars.getDate("dob"));
+ String email = ars.getString("email");
+ ar.setEmail(email);
+ ar.setName(ars.getString("name"));
+
+ // let's find the blog entries for the author
+ String sql_be = "SELECT * FROM BLOGENTRY be WHERE be.AUTHOR_EMAIL = '"
+ + email + "'";
+ PreparedStatement ppsm2 = connection.prepareStatement(sql_be);
+ ResultSet rs = ppsm2.executeQuery();
+
+ List<EntryImpl> blogs = new ArrayList<EntryImpl>();
+ while (rs.next()) {
+ EntryImpl blog = new EntryImpl();
+ blog.setAuthor(ar);
+ blog.setId(rs.getLong("id"));
+ blog.setBlogText(rs.getString("blogText"));
+ blog.setPublishDate(rs.getDate("publishDate"));
+ blog.setTitle(rs.getString("title"));
+ blog.setUpdatedDate(rs.getDate("updatedDate"));
+ blogs.add(blog);
+ }
+ ar.setEntries(blogs);
+ authorList.add(ar);
+ ppsm2.close();
+ }
+ ppsm.close();
+ connection.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return authorList;
+ }
+
+ /**
+ * Return a list of blog entries with the sql query
+ *
+ * @param sql
+ * The sql query to be executed
+ * @return a list of blogEntry records
+ */
+ private List<EntryImpl> findBlogs(String sql) {
+ List<EntryImpl> blogEntryList = new ArrayList<EntryImpl>();
+
+ try {
+ Connection connection = dataSource.getConnection();
+ PreparedStatement ppsm = connection.prepareStatement(sql);
+ ResultSet blogrs = ppsm.executeQuery();
+
+ while (blogrs.next()) {
+ EntryImpl be = new EntryImpl();
+ be.setId(blogrs.getLong("id"));
+ be.setBlogText(blogrs.getString("blogText"));
+ be.setPublishDate(blogrs.getDate("publishDate"));
+ be.setTitle(blogrs.getString("title"));
+ be.setUpdatedDate(blogrs.getDate("updatedDate"));
+ // find the author email address
+ String author_email = blogrs.getString("AUTHOR_EMAIL");
+ String author_sql = "SELECT * FROM Author a WHERE a.email ='"
+ + author_email + "'";
+ List<AuthorImpl> authors = findAuthors(author_sql);
+ // there should be just one entry, as email is the primary key
+ // for the Author table
+ if (authors.size() != 1)
+ throw new IllegalArgumentException(
+ "We got more than one author with the same email address. This is wrong");
+ else
+ be.setAuthor(authors.get(0));
+ blogEntryList.add(be);
+ }
+ ppsm.close();
+ connection.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return blogEntryList;
+ }
+}
Added: incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java?rev=949534&view=auto
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java (added)
+++ incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java Sun May 30 17:00:06 2010
@@ -0,0 +1,75 @@
+/*
+ * Statements
+ *
+ * Copyright (c) 2010 Sabre Holdings, Inc. All Rights Reserved.
+ */
+package org.apache.aries.samples.blog.persistence.jdbc;
+
+public class Statements {
+
+ private static final String I_THR_TRY_ELEMENT = "I_THR_TRY_ELEMENT";
+
+ private static final String I_THR_TRY_AUTHOR_EMAIL = "I_THR_TRY_AUTHOR_EMAIL";
+
+ public static final String I_BLGNTRY_AUTHOR = "I_BLGNTRY_AUTHOR";
+
+ public static final String AUTHOR_TABLE_NAME = "AUTHOR";
+
+ public static final String AUTHOR_BLOG_ENTRY_TABLE_NAME = "AUTHOR_BLOGENTRY";
+
+ public static final String BLOG_ENTRY_TABLE_NAME = "BLOGENTRY";
+
+ public static final String COMMENT_ENTRY_TABLE_NAME = "COMMENT";
+
+ private String[] dropSchemaStatements;
+
+ private String[] createSchemaStatements;
+
+ public synchronized String[] getCreateSchemaStatements() {
+ if (createSchemaStatements == null) {
+ createSchemaStatements = new String[] {
+ "CREATE TABLE "
+ + AUTHOR_TABLE_NAME
+ + " (email VARCHAR(255) NOT NULL, "
+ + "bio VARCHAR(255), displayName VARCHAR(255), "
+ + "dob TIMESTAMP, name VARCHAR(255), PRIMARY KEY (email))",
+ "CREATE TABLE " + AUTHOR_BLOG_ENTRY_TABLE_NAME
+ + " (AUTHOR_EMAIL VARCHAR(255), POSTS_ID BIGINT)",
+ "CREATE TABLE "
+ + BLOG_ENTRY_TABLE_NAME
+ + " (id BIGINT NOT NULL, blogText VARCHAR(10000), "
+ + "publishDate TIMESTAMP, title VARCHAR(255), updatedDate TIMESTAMP, "
+ + "AUTHOR_EMAIL VARCHAR(255), PRIMARY KEY (id))",
+ "CREATE TABLE "
+ + COMMENT_ENTRY_TABLE_NAME
+ + " (id BIGINT NOT NULL, comment VARCHAR(255), creationDate TIMESTAMP, "
+ + "AUTHOR_EMAIL VARCHAR(255), BLOGENTRY_ID BIGINT)",
+ "CREATE INDEX " + I_THR_TRY_AUTHOR_EMAIL + " ON "
+ + AUTHOR_BLOG_ENTRY_TABLE_NAME + " (AUTHOR_EMAIL)",
+ "CREATE INDEX " + I_THR_TRY_ELEMENT + " ON "
+ + AUTHOR_BLOG_ENTRY_TABLE_NAME + " (POSTS_ID)",
+ "CREATE INDEX " + I_BLGNTRY_AUTHOR + " ON "
+ + BLOG_ENTRY_TABLE_NAME + " (AUTHOR_EMAIL)",
+ "DELETE FROM " + AUTHOR_TABLE_NAME,
+ "DELETE FROM " + AUTHOR_BLOG_ENTRY_TABLE_NAME,
+ "DELETE FROM " + BLOG_ENTRY_TABLE_NAME,
+ "DELETE FROM " + COMMENT_ENTRY_TABLE_NAME };
+ }
+ return createSchemaStatements;
+ }
+
+ public synchronized String[] getDropSchemaStatements() {
+ if (dropSchemaStatements == null) {
+ dropSchemaStatements = new String[] {
+ "DROP INDEX " + I_THR_TRY_ELEMENT,
+ "DROP INDEX " + I_BLGNTRY_AUTHOR,
+ "DROP INDEX " + I_THR_TRY_AUTHOR_EMAIL,
+ "DROP TABLE " + COMMENT_ENTRY_TABLE_NAME,
+ "DROP TABLE " + BLOG_ENTRY_TABLE_NAME,
+ "DROP TABLE " + AUTHOR_BLOG_ENTRY_TABLE_NAME,
+ "DROP TABLE " + AUTHOR_TABLE_NAME };
+ }
+ return dropSchemaStatements;
+ }
+
+}
Modified: incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/resources/OSGI-INF/blueprint/blueprint.xml
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/resources/OSGI-INF/blueprint/blueprint.xml?rev=949534&r1=949533&r2=949534&view=diff
==============================================================================
--- incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/resources/OSGI-INF/blueprint/blueprint.xml (original)
+++ incubator/aries/trunk/samples/blog/blog-persistence-jdbc/src/main/resources/OSGI-INF/blueprint/blueprint.xml Sun May 30 17:00:06 2010
@@ -1,33 +1,34 @@
-<?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.
--->
-
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-
- <bean id="datasource" class="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource">
- <property name="databaseName" value="blogDB"/>
- </bean>
-
- <bean id="persistenceImpl" class="org.apache.aries.samples.blog.persistence.jdbc.BlogPersistenceServiceImpl" activation="lazy">
- <property name="dataSource" ref="datasource" />
- </bean>
-
- <service ref="persistenceImpl" interface="org.apache.aries.samples.blog.api.persistence.BlogPersistenceService"/>
-
-
-</blueprint>
\ No newline at end of file
+<?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.
+-->
+
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+ <bean id="datasource" class="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource">
+ <property name="databaseName" value="memory:blogDB"/>
+ <property name="createDatabase" value="create" />
+ </bean>
+
+ <bean id="persistenceImpl" class="org.apache.aries.samples.blog.persistence.jdbc.BlogPersistenceServiceImpl" activation="lazy" init-method="init" destroy-method="destroy">
+ <property name="dataSource" ref="datasource" />
+ </bean>
+
+ <service ref="persistenceImpl" interface="org.apache.aries.samples.blog.api.persistence.BlogPersistenceService"/>
+
+
+</blueprint>