empire-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From franci...@apache.org
Subject svn commit: r907508 - in /incubator/empire-db/trunk/empire-db-examples: ./ empire-db-example-spring/ empire-db-example-spring/src/ empire-db-example-spring/src/main/ empire-db-example-spring/src/main/java/ empire-db-example-spring/src/main/java/org/ em...
Date Sun, 07 Feb 2010 22:49:10 GMT
Author: francisdb
Date: Sun Feb  7 22:49:09 2010
New Revision: 907508

URL: http://svn.apache.org/viewvc?rev=907508&view=rev
Log:
EMPIREDB-73
Added spring example code submitted through jira by Eike Kettner
Also added missing Apache License headers

Added:
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/pom.xml
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireApp.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireAppImpl.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/SampleSpringApp.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDBException.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDaoSupport.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDriverFactory.java
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/applicationContext.xml
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/log4j.properties
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/settings.properties
    incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/test/
Modified:
    incubator/empire-db/trunk/empire-db-examples/pom.xml

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/pom.xml
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/pom.xml?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/pom.xml (added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/pom.xml Sun Feb
 7 22:49:09 2010
@@ -0,0 +1,81 @@
+<?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.
+	-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+         xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <artifactId>empire-db-examples</artifactId>
+        <groupId>org.apache.empire-db</groupId>
+        <version>2.0.5-incubating-SNAPSHOT</version>
+    </parent>
+    <groupId>org.apache.empire-db</groupId>
+    <artifactId>empire-db-example-basic-spring</artifactId>
+    <name>Apache Empire-db Spring Example</name>
+
+    <properties>
+        <spring.version>3.0.0.M3</spring.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.empire-db</groupId>
+            <artifactId>empire-db-example-basic</artifactId>
+            <version>2.0.6-incubating-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.empire-db</groupId>
+            <artifactId>empire-db</artifactId>
+            <version>2.0.6-incubating-SNAPSHOT</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-context</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-orm</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-aop</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-jdbc</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-dbcp</groupId>
+            <artifactId>commons-dbcp</artifactId>
+            <version>1.2.2</version>
+        </dependency>
+    </dependencies>
+    
+    <!-- better would be to add this repository in your settings.xml -->
+    <repositories>
+    	<repository>
+		    <id>spring-milestone</id>
+		    <name>Spring Portfolio Milestone Repository</name>
+		    <url>http://s3.amazonaws.com/maven.springframework.org/milestone</url>
+		</repository>
+    </repositories>
+</project>

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireApp.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireApp.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireApp.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireApp.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,47 @@
+/*
+ * 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.empire.samples.spring;
+
+
+/**
+ * This is the interface to the application. It is usually some high level interface; for
this basic
+ * example this is the dao object.
+ *
+ */
+public interface EmpireApp {
+
+    void clearDatabase();
+
+    void setupDatabase();
+    
+    Integer insertDepartment(String departmentName, String businessUnit);
+
+    Integer insertEmployee(String firstName, String lastName, String gender, int departmentId);
+
+    void updateEmployee(int idPers, String phoneNumber);
+
+    void doQuery(QueryType type);
+
+    public enum QueryType
+    {
+	    Reader,
+        BeanList,
+	    XmlDocument
+	}
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireAppImpl.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireAppImpl.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireAppImpl.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/EmpireAppImpl.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,231 @@
+/*
+ * 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.empire.samples.spring;
+
+import java.sql.Connection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBColumnExpr;
+import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBReader;
+import org.apache.empire.db.DBRecord;
+import org.apache.empire.db.DBTable;
+import org.apache.empire.db.derby.DBDatabaseDriverDerby;
+import org.apache.empire.db.h2.DBDatabaseDriverH2;
+import org.apache.empire.db.hsql.DBDatabaseDriverHSql;
+import org.apache.empire.db.postgresql.DBDatabaseDriverPostgreSQL;
+import org.apache.empire.samples.db.SampleBean;
+import org.apache.empire.samples.db.SampleDB;
+import org.apache.empire.samples.spring.support.EmpireDaoSupport;
+import org.apache.empire.xml.XMLWriter;
+import org.springframework.transaction.annotation.Transactional;
+import org.w3c.dom.Document;
+
+/**
+ *
+ */
+public class EmpireAppImpl extends EmpireDaoSupport implements EmpireApp {
+
+
+    @Transactional
+    public void clearDatabase() {
+        SampleDB db = getDB();
+        Connection conn = getConnection();
+
+        DBCommand cmd = db.createCommand();
+        // Delete all Employees (no constraints)
+        db.executeSQL(cmd.getDelete(db.EMPLOYEES), conn);
+        // Delete all Departments (no constraints)
+        db.executeSQL(cmd.getDelete(db.DEPARTMENTS), conn);
+    }
+
+    @Transactional
+    public Integer insertDepartment(String departmentName, String businessUnit) {
+        SampleDB db = getDB();
+        Connection conn = getConnection();
+
+        DBRecord rec = new DBRecord();
+        rec.create(db.DEPARTMENTS);
+        rec.setValue(db.DEPARTMENTS.NAME, departmentName);
+        rec.setValue(db.DEPARTMENTS.BUSINESS_UNIT, businessUnit);
+        rec.update(conn);
+        // Return Department ID
+        return rec.getInt(db.DEPARTMENTS.DEPARTMENT_ID);
+    }
+
+    @Transactional
+    public Integer insertEmployee(String firstName, String lastName, String gender, int departmentId)
{
+        SampleDB db = getDB();
+        Connection conn = getConnection();
+
+        DBRecord rec = new DBRecord();
+        rec.create(db.EMPLOYEES);
+        rec.setValue(db.EMPLOYEES.FIRSTNAME, firstName);
+        rec.setValue(db.EMPLOYEES.LASTNAME, lastName);
+        rec.setValue(db.EMPLOYEES.GENDER, gender);
+        rec.setValue(db.EMPLOYEES.DEPARTMENT_ID, departmentId);
+        rec.update(conn);
+        // Return Employee ID
+        return rec.getInt(db.EMPLOYEES.EMPLOYEE_ID);
+    }
+
+    @Transactional
+    public void updateEmployee(int idPers, String phoneNumber) {
+        if (getEmployee(idPers) == null) {
+            //if you like more verbose exceptions for the app
+            throw new IllegalArgumentException("The specified employee does not exist.");
+        }
+
+        SampleDB db = getDB();
+        Connection conn = getConnection();
+
+        DBRecord rec = new DBRecord();
+		rec.read(db.EMPLOYEES, idPers, conn);
+		// Set
+		rec.setValue(db.EMPLOYEES.PHONE_NUMBER, phoneNumber);
+		rec.update(conn);
+    }
+
+    @Transactional
+    public void setupDatabase() {
+        initializeDatabase();
+    }
+
+    @Transactional(readOnly = true)
+    public void doQuery(QueryType type) {
+        SampleDB db = getDB();
+        Connection conn = getConnection();
+
+	    // Define the query
+	    DBCommand cmd = db.createCommand();
+	    // Define shortcuts for tables used - not necessary but convenient
+	    SampleDB.Employees   EMP = db.EMPLOYEES;
+	    SampleDB.Departments DEP = db.DEPARTMENTS;
+
+	    // The following expression concats lastname + ', ' + firstname
+        DBColumnExpr EMPLOYEE_FULLNAME = EMP.LASTNAME.append(", ").append(EMP.FIRSTNAME).as("FULL_NAME");
+
+        // The following expression extracts the extension number from the phone field
+        // e.g. substr(PHONE_NUMBER, length(PHONE_NUMBER)-instr(reverse(PHONE_NUMBER), '-')+2)
AS PHONE_EXTENSION
+        // Hint: Since the reverse() function is not supported by HSQLDB there is special
treatment for HSQL
+        DBColumnExpr PHONE_LAST_DASH;
+        if ( db.getDriver() instanceof DBDatabaseDriverHSql
+        		|| db.getDriver() instanceof DBDatabaseDriverDerby
+        		|| db.getDriver() instanceof DBDatabaseDriverH2)
+             PHONE_LAST_DASH = EMP.PHONE_NUMBER.indexOf("-", EMP.PHONE_NUMBER.indexOf("-").plus(1)).plus(1);
// HSQLDB only
+        else PHONE_LAST_DASH = EMP.PHONE_NUMBER.length().minus(EMP.PHONE_NUMBER.reverse().indexOf("-")).plus(2);
+        DBColumnExpr PHONE_EXT_NUMBER = EMP.PHONE_NUMBER.substring(PHONE_LAST_DASH).as("PHONE_EXTENSION");
+
+        // DBColumnExpr genderExpr = cmd.select(EMP.GENDER.decode(EMP.GENDER.getOptions()).as(EMP.GENDER.getName()));
+		// Select required columns
+		cmd.select(EMP.EMPLOYEE_ID, EMPLOYEE_FULLNAME);
+		if(db.getDriver() instanceof DBDatabaseDriverPostgreSQL)
+		{
+			// postgres does not support the substring expression
+			cmd.select(EMP.GENDER, EMP.PHONE_NUMBER);
+		}else{
+			cmd.select(EMP.GENDER, EMP.PHONE_NUMBER, PHONE_EXT_NUMBER);
+
+		}
+		cmd.select(DEP.NAME.as("DEPARTMENT"));
+		cmd.select(DEP.BUSINESS_UNIT);
+		cmd.join(EMP.DEPARTMENT_ID, DEP.DEPARTMENT_ID);
+        // Set constraints and order
+        cmd.where(EMP.LASTNAME.length().isGreaterThan(0));
+        cmd.orderBy(EMP.LASTNAME, EMP.FIRSTNAME);
+
+		// Query Records and print output
+		DBReader reader = new DBReader();
+		try
+        {
+			// Open Reader
+			System.out.println("Running Query:");
+			System.out.println(cmd.getSelect());
+			reader.open(cmd, conn);
+			// Print output
+			System.out.println("---------------------------------");
+			switch(type)
+			{
+			    case BeanList:
+			        // Text-Output by iterating through all records.
+	                while (reader.moveNext())
+                    {
+	                    System.out.println(reader.getString(EMP.EMPLOYEE_ID)
+	                            + "\t" + reader.getString(EMPLOYEE_FULLNAME)
+	                            + "\t" + EMP.GENDER.getOptions().get(reader.getString(EMP.GENDER))
+                                + "\t" + reader.getString(PHONE_EXT_NUMBER)
+	                            + "\t" + reader.getString(DEP.NAME));
+	                }
+			        break;
+                case Reader:
+                    // Text-Output using a list of Java Beans supplied by the DBReader
+                    List<SampleBean> beanList = reader.getBeanList(SampleBean.class);
+                    System.out.println(String.valueOf(beanList.size()) + " SampleBeans returned
from Query.");
+                    for (SampleBean b : beanList)
+                    {
+                        System.out.println(b.toString());
+                    }
+                    break;
+                case XmlDocument:
+                    // XML Output
+                    Document doc = reader.getXmlDocument();
+                    // Print XML Document to System.out
+                    XMLWriter.debug(doc);
+                    break;
+			}
+
+		} finally
+        {
+			// always close Reader
+			reader.close();
+		}
+    }
+
+
+    public Map<Object, Object> getDepartment(int id) {
+        SampleDB db = getDB();
+        return get(db.DEPARTMENTS, id);
+    }
+
+    public Map<Object, Object> getEmployee(int id) {
+        SampleDB db = getDB();
+        return get(db.EMPLOYEES, id);
+    }
+
+    private Map<Object, Object> get(DBTable table, int pk) {
+        Connection conn = getConnection();
+
+        DBCommand cmd = db.createCommand();
+        cmd.select(table.getColumns());
+        cmd.where(table.getPrimaryKey().getColumns()[0].is(pk)); //i know there is just one
pk-column ;-)
+        DBReader reader = openReader(cmd, conn);
+        Map<Object, Object> dep = null;
+        if (reader.moveNext()) {
+            dep = new HashMap<Object, Object>();
+            for (DBColumn col : table.getColumns()) {
+                dep.put(col.getName(), reader.getValue(col));
+            }
+        }
+        reader.close();
+        return dep;
+    }
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/SampleSpringApp.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/SampleSpringApp.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/SampleSpringApp.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/SampleSpringApp.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,87 @@
+/*
+ * 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.empire.samples.spring;
+
+import java.util.logging.Logger;
+
+import org.apache.empire.commons.ErrorObject;
+import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.core.io.ClassPathResource;
+
+/**
+ * 
+ */
+public class SampleSpringApp {
+    private static final Logger log = Logger.getLogger(SampleSpringApp.class.getName());
+    static {
+        ErrorObject.setExceptionsEnabled(true);
+    }
+    //creates the application context
+    //this is usually in some bootstrapping code; so your application will
+    //just have one at runtime.
+    static ApplicationContext ctx = getContext();
+
+    //get the service that is the entry point into the application
+    //normally this is injected by spring into classes that need it
+    static EmpireApp appBean = ctx.getBean("empireApp", EmpireApp.class);
+
+    public static void main(String[] args) throws Exception {
+
+        System.out.println("Running Spring Example...");
+
+        appBean.setupDatabase();
+        appBean.clearDatabase();
+        
+        System.out.println("*** Step 6: insertDepartment() & insertEmployee() ***");
+        int idDevDep = appBean.insertDepartment("Development", "ITTK");
+		int idSalDep = appBean.insertDepartment("Sales", "ITTK");
+
+        int idPers1 = appBean.insertEmployee("Peter", "Sharp", "M", idDevDep);
+		int idPers2 = appBean.insertEmployee("Fred", "Bloggs", "M", idDevDep);
+		int idPers3 = appBean.insertEmployee("Emma", "White", "F", idSalDep);
+
+        System.out.println("*** Step 7: updateEmployee() ***");
+        appBean.updateEmployee(idPers1, "+49-7531-457160");
+        appBean.updateEmployee(idPers2, "+49-5555-505050");
+        appBean.updateEmployee(idPers3, "+49-040-125486");
+
+        System.out.println("*** Step 8 Option 1: queryRecords() / Tab-Output ***");
+        appBean.doQuery(EmpireApp.QueryType.Reader);
+
+        System.out.println("*** Step 8 Option 2: queryRecords() / Bean-List-Output ***");
+        appBean.doQuery(EmpireApp.QueryType.BeanList);
+
+        System.out.println("*** Step 8 Option 3: queryRecords() / XML-Output ***");
+        appBean.doQuery(EmpireApp.QueryType.XmlDocument);
+    }
+
+
+
+    static GenericApplicationContext getContext() {
+        log.info("Creating Spring Application Context ...");
+        GenericApplicationContext ctx = new GenericApplicationContext();
+        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
+        reader.loadBeanDefinitions(new ClassPathResource("/applicationContext.xml"));
+
+        ctx.refresh();
+        return ctx;
+    }
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDBException.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDBException.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDBException.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDBException.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,38 @@
+/*
+ * 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.empire.samples.spring.support;
+
+import org.apache.empire.EmpireException;
+import org.springframework.dao.UncategorizedDataAccessException;
+
+/**
+ * Exception inside springs exception hierarchy. This may be good for client
+ * code that catches any {@link org.springframework.dao.DataAccessException}
+ * and doesn't want to look for implementation specific {@link org.apache.empire.EmpireException}.
+ */
+public class EmpireDBException extends UncategorizedDataAccessException {
+
+    public EmpireDBException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    public EmpireDBException(EmpireException e) {
+        super(e.getMessage(), e);
+    }
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDaoSupport.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDaoSupport.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDaoSupport.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDaoSupport.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,135 @@
+/*
+ * 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.empire.samples.spring.support;
+
+import java.sql.Connection;
+
+import org.apache.empire.EmpireException;
+import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.DBReader;
+import org.apache.empire.db.DBSQLScript;
+import org.apache.empire.db.DBTable;
+import org.springframework.jdbc.core.support.JdbcDaoSupport;
+
+/**
+ * Extent JdbcDaoSupport from spring to provide a helper class to implement DAO objects using
the Empire-DB framework.
+ *
+ */
+public class EmpireDaoSupport extends JdbcDaoSupport {
+
+    protected DBDatabase db;
+    protected DBDatabaseDriver driver;
+
+    public EmpireDaoSupport() {
+    }
+
+    public void setDatabase(DBDatabase db) {
+        this.db = db;
+    }
+
+    public void setDatabaseDriver(DBDatabaseDriver dbdriver) {
+        this.driver = dbdriver;
+    }
+
+    @Override
+    protected void checkDaoConfig() {
+        super.checkDaoConfig();
+        if (db == null)
+            throw new IllegalArgumentException("'database' must be given!");
+
+        if (driver == null)
+            throw new IllegalArgumentException("'databaseDriver' must be given!");
+    }
+
+    public DBDatabase getDatabase() {
+        try {
+            if (!db.isOpen())
+                db.open(driver, getConnection());
+            return db;
+        } catch (EmpireException e) {
+            throw translateEmpireException(e);
+        }
+    }
+
+    public boolean databaseExists() {
+        Connection conn = getConnection();
+        try {
+            DBDatabase db = getDatabase();
+            if (db.getTables() == null || db.getTables().isEmpty()) {
+                throw new AssertionError("There are no tables in this database!");
+            }
+            DBCommand cmd = db.createCommand();
+            if (cmd == null) {
+                throw new AssertionError("The DBCommand object is null.");
+            }
+            DBTable t = db.getTables().get(0);
+            cmd.select(t.count());
+            return (db.querySingleInt(cmd.getSelect(), -1, conn) >= 0);
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    public void createDatabase() {
+        Connection conn = getConnection();
+
+        // create DLL for Database Definition
+        DBSQLScript script = new DBSQLScript();
+        db.getCreateDDLScript(driver, script);
+        // Show DLL Statement
+        System.out.println(script.toString());
+        // Execute Script
+        script.run(driver, conn, false);
+    }
+
+    public void initializeDatabase() {
+        try {
+            if (!databaseExists()) {
+                createDatabase();
+            }
+        } catch (EmpireException e) {
+            throw translateEmpireException(e);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public <T extends DBDatabase> T getDB() {
+        if (getDatabase() == null) {
+            throw new IllegalStateException("The database is null?!");
+        }
+        return (T) getDatabase();
+    }
+
+    public DBDatabaseDriver getDatabasedriver() {
+        return driver;
+    }
+
+    public RuntimeException translateEmpireException(EmpireException e) {
+        return new EmpireDBException(e);
+    }
+
+    protected DBReader openReader(DBCommand cmd, Connection conn) {
+        DBReader r = new DBReader();
+        r.open(cmd, conn);
+        return r;
+    }
+
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDriverFactory.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDriverFactory.java?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDriverFactory.java
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/support/EmpireDriverFactory.java
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,101 @@
+/*
+ * 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.empire.samples.spring.support;
+
+import java.sql.Connection;
+
+import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.derby.DBDatabaseDriverDerby;
+import org.apache.empire.db.h2.DBDatabaseDriverH2;
+import org.apache.empire.db.hsql.DBDatabaseDriverHSql;
+import org.apache.empire.db.mysql.DBDatabaseDriverMySQL;
+import org.apache.empire.db.oracle.DBDatabaseDriverOracle;
+import org.apache.empire.db.postgresql.DBDatabaseDriverPostgreSQL;
+import org.apache.empire.db.sqlserver.DBDatabaseDriverMSSQL;
+import org.springframework.jdbc.core.support.JdbcDaoSupport;
+
+/**
+ * Creates the Empire-DB Drivers. Extends JdbcDaoSupport because it needs a Connection
+ */
+public class EmpireDriverFactory extends JdbcDaoSupport {
+
+    // copy&paste from the SampleApp
+
+    public DBDatabaseDriver createDriver(String driverclass, String schema) {
+        if (isClass(DBDatabaseDriverMySQL.class, driverclass))
+        {
+            DBDatabaseDriverMySQL driver = new DBDatabaseDriverMySQL();
+            // Set Driver specific properties (if any)
+            driver.setDatabaseName(schema);
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverOracle.class, driverclass))
+        {
+            DBDatabaseDriverOracle driver = new DBDatabaseDriverOracle();
+            // Set Driver specific properties (if any)
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverMSSQL.class, driverclass))
+        {
+            DBDatabaseDriverMSSQL driver = new DBDatabaseDriverMSSQL();
+            // Set Driver specific properties (if any)
+            driver.setDatabaseName(schema);
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverHSql.class, driverclass))
+        {
+            DBDatabaseDriverHSql driver = new DBDatabaseDriverHSql();
+            // Set Driver specific properties (if any)
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverPostgreSQL.class, driverclass))
+        {
+            DBDatabaseDriverPostgreSQL driver = new DBDatabaseDriverPostgreSQL();
+            // Set Driver specific properties (if any)
+            driver.setDatabaseName(schema);
+            // Create the reverse function that is needed by this sample
+            Connection conn = getConnection();
+            driver.createReverseFunction(conn);
+            releaseConnection(conn);
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverH2.class, driverclass))
+        {
+            DBDatabaseDriverH2 driver = new DBDatabaseDriverH2();
+            // Set Driver specific properties (if any)
+            driver.setDatabaseName(schema);
+            return driver;
+        }
+        else if (isClass(DBDatabaseDriverDerby.class, driverclass))
+        {
+            DBDatabaseDriverDerby driver = new DBDatabaseDriverDerby();
+            // Set Driver specific properties (if any)
+            driver.setDatabaseName(schema);
+            return driver;
+        }
+        else
+        {   // Unknown Provider
+            throw new RuntimeException("Unknown Database Driver " + driverclass);
+        }
+    }
+
+    private boolean isClass(Class<? extends DBDatabaseDriver> clazz, String name) {
+        return name.equals(clazz.getName());
+    }
+}

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/applicationContext.xml
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/applicationContext.xml?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/applicationContext.xml
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/applicationContext.xml
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,72 @@
+<?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.
+	-->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:tx="http://www.springframework.org/schema/tx"
+       xmlns:aop="http://www.springframework.org/schema/aop"
+       xsi:schemaLocation="
+       	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+       	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
+		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
+
+
+    <!-- one option is to use a class from spring that will read the properties file
+         and replaces the ${...} placeholders with the appropriate values -->
+    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
+        <property name="locations">
+            <value>classpath:/settings.properties</value>
+        </property>
+    </bean>
+
+    <!-- Data Source / DB Settings -->
+    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
+        <property name="driverClassName" value="${jdbc.driverClass}"/>
+        <property name="url" value="${jdbc.url}"/>
+        <property name="username" value="${jdbc.username}"/>
+        <property name="password" value="${jdbc.password}"/>
+    </bean>
+
+    <!-- Transaction manager for a single JDBC DataSource (alternative to JTA) -->
+    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
+        <property name="transactionManager" ref="transactionManager"/>
+    </bean>
+
+    <!-- @Transactional -->
+    <tx:annotation-driven transaction-manager="transactionManager"/>
+
+    <!-- Empire-DB classes -->
+    <bean id="driverFactory" class="org.apache.empire.samples.spring.support.EmpireDriverFactory">
+        <property name="dataSource" ref="dataSource" />
+    </bean>
+    <bean id="databaseDriver" factory-bean="driverFactory" factory-method="createDriver">
+        <constructor-arg value="${empire.driver}"/>
+        <constructor-arg value="${empire.schemaname}"/>
+    </bean>
+    <bean id="sampleDatabase" class="org.apache.empire.samples.db.SampleDB">
+    </bean>
+
+    <!-- application dao/services -->
+    <bean id="empireApp" class="org.apache.empire.samples.spring.EmpireAppImpl">
+        <property name="dataSource" ref="dataSource"/>
+        <property name="database" ref="sampleDatabase"/>
+        <property name="databaseDriver" ref="databaseDriver"/> 
+    </bean>
+</beans>
\ No newline at end of file

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/log4j.properties
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/log4j.properties?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/log4j.properties
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/log4j.properties
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,21 @@
+# 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.
+
+log4j.rootCategory=FATAL, console
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.conversionPattern = %d{ISO8601} %-5p [%c] - %m%n

Added: incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/settings.properties
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/settings.properties?rev=907508&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/settings.properties
(added)
+++ incubator/empire-db/trunk/empire-db-examples/empire-db-example-spring/src/main/resources/settings.properties
Sun Feb  7 22:49:09 2010
@@ -0,0 +1,44 @@
+# 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.
+
+## HSQLDB settings (tested)
+jdbc.url=jdbc:hsqldb:file:target/hsqldb/sample;shutdown=true
+jdbc.driverClass=org.hsqldb.jdbcDriver
+jdbc.username=sa
+jdbc.password=
+
+empire.driver= org.apache.empire.db.hsql.DBDatabaseDriverHSql
+empire.schemaname=DBSAMPLE1
+
+
+## Derby settings (tested)
+#jdbc.url=jdbc:derby:target/dbsample1;create=true
+#jdbc.driverClass=org.apache.derby.jdbc.EmbeddedDriver
+#jdbc.username=
+#jdbc.password=
+#
+#empire.driver=org.apache.empire.db.derby.DBDatabaseDriverDerby
+#empire.schemaname=DBSAMPLE1
+
+## MySQL settings (tested)
+#jdbc.url=jdbc:mysql://localhost
+#jdbc.driverClass=com.mysql.jdbc.Driver
+#jdbc.username=test
+#jdbc.password=test
+#
+#empire.driver=org.apache.empire.db.mysql.DBDatabaseDriverMySQL
+#empire.schemaname=dbsample1

Modified: incubator/empire-db/trunk/empire-db-examples/pom.xml
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-examples/pom.xml?rev=907508&r1=907507&r2=907508&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-examples/pom.xml (original)
+++ incubator/empire-db/trunk/empire-db-examples/pom.xml Sun Feb  7 22:49:09 2010
@@ -29,8 +29,9 @@
 	<modules>
 		<module>empire-db-example-basic</module>
 		<module>empire-db-example-advanced</module>
-		<module>empire-db-example-struts2</module>
 		<module>empire-db-example-cxf</module>
+		<module>empire-db-example-spring</module>
+		<module>empire-db-example-struts2</module>
 		<module>empire-db-example-struts2-cxf</module>
 		<!-- <module>empire-db-example-codegen</module> -->
 	</modules>



Mime
View raw message