Commits

Vincent Rabeux committed e79bb18

Init

  • Participants

Comments (0)

Files changed (10)

+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.samples.glassfish</groupId>
+    <artifactId>javaee-nosql</artifactId>
+    <version>1.0-SNAPSHOT</version>
+    <packaging>war</packaging>
+
+    <name>javaee-nosql</name>
+
+    <properties>
+        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>javax</groupId>
+            <artifactId>javaee-web-api</artifactId>
+            <version>6.0</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.persistence</groupId>
+            <artifactId>org.eclipse.persistence.jpa</artifactId>
+            <version>2.4.0-SNAPSHOT</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.persistence</groupId>
+            <artifactId>org.eclipse.persistence.nosql</artifactId>
+            <version>2.4.0-SNAPSHOT</version>
+<!--            <scope>provided</scope>-->
+        </dependency>
+        <dependency>
+            <groupId>org.mongodb</groupId>
+            <artifactId>mongo-java-driver</artifactId>
+            <version>2.7.3</version>
+        </dependency>
+        
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>2.3.2</version>
+                <configuration>
+                    <source>1.6</source>
+                    <target>1.6</target>
+                    <compilerArguments>
+                        <endorseddirs>${endorsed.dir}</endorseddirs>
+                    </compilerArguments>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>2.1.1</version>
+                <configuration>
+                    <failOnMissingWebXml>false</failOnMissingWebXml>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-dependency-plugin</artifactId>
+                <version>2.1</version>
+                <executions>
+                    <execution>
+                        <phase>validate</phase>
+                        <goals>
+                            <goal>copy</goal>
+                        </goals>
+                        <configuration>
+                            <outputDirectory>${endorsed.dir}</outputDirectory>
+                            <silent>true</silent>
+                            <artifactItems>
+                                <artifactItem>
+                                    <groupId>javax</groupId>
+                                    <artifactId>javaee-endorsed-api</artifactId>
+                                    <version>6.0</version>
+                                    <type>jar</type>
+                                </artifactItem>
+                            </artifactItems>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+    
+    <repositories>
+        <repository>
+            <id>EclipseLink Repo</id>
+            <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url>
+            <snapshots>
+                <enabled>true</enabled>
+            </snapshots>
+        </repository>  
+    </repositories>
+
+</project>

src/main/java/example/Test.java

+/*******************************************************************************
+ * Copyright (c) 2012 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the 
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
+ * which accompanies this distribution. 
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at 
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *      Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+
+import org.eclipse.persistence.internal.nosql.adapters.mongo.MongoConnection;
+
+import com.mongodb.DB;
+
+import model.*;
+
+/**
+ * Test performs CRUD operations on Orders persisting to a Mongo database.
+ * @author James Sutherland
+ */
+public class Test {
+
+    EntityManagerFactory factory;
+    String oid;
+    
+    public static void main(String[] args) throws Exception {
+        Test test = new Test();
+        test.factory = Persistence.createEntityManagerFactory("mongo");
+        
+        EntityManager em = test.factory.createEntityManager();        
+        // First clear old database.
+        em.getTransaction().begin();
+        DB db = ((MongoConnection)em.unwrap(javax.resource.cci.Connection.class)).getDB();
+        db.dropDatabase();
+        em.getTransaction().commit();
+        em.close();
+        
+        test.testPersist();
+        test.testFind();
+        test.testQuery();
+        test.testUpdate();
+        test.testRemove();
+        test.factory.close();
+    }
+
+    public void testPersist() {
+        System.out.println("\nTesting persist() of orders and customers.\n"); 
+        EntityManager em = factory.createEntityManager();
+        em.getTransaction().begin();
+        Customer customer = new Customer();
+        customer.setName("AMCE");
+        em.persist(customer);        
+        Order order = new Order();
+        order.setCustomer(customer);
+        order.setDescription("Pinball machine");
+        Address address = new Address();
+        address.setStreet("17 Jane St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H7");
+        order.setBillingAddress(address);
+        address = new Address();
+        address.setStreet("17 Jane St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H7");
+        order.setShippingAddress(address);
+        order.addOrderLine(new OrderLine("machine", 2999));
+        order.addOrderLine(new OrderLine("shipping", 129));
+        order.addOrderLine(new OrderLine("installation", 59));
+        em.persist(order);
+        
+        order = new Order();
+        order.setCustomer(customer);
+        order.setDescription("Foosball");
+        address = new Address();
+        address.setStreet("7 Bank St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H8");
+        order.setBillingAddress(address);
+        address = new Address();
+        address.setStreet("17 Jane St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H7");
+        order.setShippingAddress(address);
+        order.addOrderLine(new OrderLine("machine", 500));
+        order.addOrderLine(new OrderLine("balls", 5));
+        order.addOrderLine(new OrderLine("shipping", 60));
+        em.persist(order);
+        
+        customer = new Customer();
+        customer.setName("Smith");
+        em.persist(customer);
+        order = new Order();
+        order.setCustomer(customer);
+        order.setDescription("Pingpong table");
+        address = new Address();
+        address.setStreet("7 Bank St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H8");
+        order.setBillingAddress(address);
+        address = new Address();
+        address.setStreet("17 Jane St.");
+        address.setCity("Ottawa");
+        address.setProvince("ON");
+        address.setCountry("Canada");
+        address.setPostalCode("L5J1H7");
+        order.setShippingAddress(address);
+        order.addOrderLine(new OrderLine("table", 300));
+        order.addOrderLine(new OrderLine("balls", 5));
+        order.addOrderLine(new OrderLine("rackets", 15));
+        order.addOrderLine(new OrderLine("net", 2));
+        order.addOrderLine(new OrderLine("shipping", 80));
+        em.persist(order);
+        
+        em.getTransaction().commit();
+        oid = order.getId();
+        em.close();
+    }
+
+    public void testFind() {
+        System.out.println("\nTesting find() by Id.\n");
+        EntityManager em = factory.createEntityManager();
+        Order order = em.find(Order.class, oid);
+        System.out.println("Found order:" + order + " by its oid: " + oid);
+        em.close();
+    }
+
+    public void testQuery() {
+        System.out.println("\nTesting querying.\n");
+        EntityManager em = factory.createEntityManager();
+        Query query = em.createQuery("Select o from Order o where o.totalCost > 1000");
+        List<Order> orders = query.getResultList();
+        System.out.println("\nFound orders with cost > 1,000: " + orders + "\n");
+        query = em.createQuery("Select o from Order o where o.description like 'Pinball%'");
+        orders = query.getResultList();
+        System.out.println("\nFound orders for pinball: " + orders + "\n");
+        query = em.createQuery("Select o from Order o join o.orderLines l where l.description = :desc");
+        query.setParameter("desc", "shipping");
+        orders = query.getResultList();
+        System.out.println("\nFound orders with shipping charges: " + orders + "\n");
+
+        query = em.createNativeQuery("db.ORDER.findOne({\"_id\":\"" + oid + "\"})", Order.class);
+        Order order = (Order)query.getSingleResult();
+        System.out.println("\nFound order using a native query: " + order + "\n");
+        
+        em.close();
+    }
+
+    public void testUpdate() {
+        System.out.println("\nTesting update of order.\n");
+        EntityManager em = factory.createEntityManager();
+        em.getTransaction().begin();
+        Order order = em.find(Order.class, oid);
+        order.addOrderLine(new OrderLine("handling", 55));
+        order.addOrderLine(new OrderLine("tax", 300));
+        em.getTransaction().commit();
+        em.close();
+    }
+
+    public void testRemove() {
+        System.out.println("\nTesting remove of order.\n");
+        EntityManager em = factory.createEntityManager();
+        em.getTransaction().begin();
+        Order order = em.find(Order.class, oid);
+        em.remove(order);
+        em.getTransaction().commit();
+        em.close();
+    }
+}

src/main/java/example/TestServlet.java

+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package example;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * @author Arun Gupta
+ */
+@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
+public class TestServlet extends HttpServlet {
+
+    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        response.setContentType("text/html;charset=UTF-8");
+        PrintWriter out = response.getWriter();
+        try {
+            out.println("<html>");
+            out.println("<head>");
+            out.println("<title>Servlet TestServlet</title>");            
+            out.println("</head>");
+            out.println("<body>");
+            out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
+            try {
+                Test.main(null);
+            } catch (Exception ex) {
+                ex.printStackTrace();
+            }
+            out.println("</body>");
+            out.println("</html>");
+        } finally {            
+            out.close();
+        }
+    }
+
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        processRequest(request, response);
+    }
+
+    @Override
+    protected void doPost(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        processRequest(request, response);
+    }
+}

src/main/java/model/Address.java

+/*******************************************************************************
+ * Copyright (c) 2012 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the 
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
+ * which accompanies this distribution. 
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at 
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *      Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Serializable;
+
+import javax.persistence.*;
+
+import org.eclipse.persistence.annotations.DataFormatType;
+import org.eclipse.persistence.annotations.NoSql;
+
+/**
+ * Address, stored as part of the Order document.
+ * @author James Sutherland
+ */
+@Embeddable
+@NoSql(dataFormat=DataFormatType.MAPPED)
+public class Address implements Serializable {
+    private String street;
+    private String city;
+    private String province;
+    private String country;
+    private String postalCode;    
+
+    public Address() {
+    }
+
+    public String getStreet() {
+        return street;
+    }
+
+    public void setStreet(String street) {
+        this.street = street;
+    }
+
+    public String getCity() {
+        return city;
+    }
+
+    public void setCity(String city) {
+        this.city = city;
+    }
+
+    public String getProvince() {
+        return province;
+    }
+
+    public void setProvince(String province) {
+        this.province = province;
+    }
+
+    public String getCountry() {
+        return country;
+    }
+
+    public void setCountry(String country) {
+        this.country = country;
+    }
+
+    public String getPostalCode() {
+        return postalCode;
+    }
+
+    public void setPostalCode(String postalCode) {
+        this.postalCode = postalCode;
+    }
+    
+}

src/main/java/model/Customer.java

+/*******************************************************************************
+ * Copyright (c) 2011 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the 
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
+ * which accompanies this distribution. 
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at 
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *      Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Serializable;
+
+import javax.persistence.*;
+
+import org.eclipse.persistence.annotations.DataFormatType;
+import org.eclipse.persistence.annotations.Field;
+import org.eclipse.persistence.annotations.NoSql;
+
+/**
+ * Customer, stored as a root JSON object.
+ * @author James Sutherland
+ */
+@Entity
+@NoSql(dataFormat=DataFormatType.MAPPED)
+public class Customer implements Serializable {
+    /* The id uses the generated OID (UUID) from Mongo. */
+    @Id
+    @GeneratedValue
+    @Field(name="_id")
+    private String id;
+    
+    @Basic
+    private String name;
+
+    public Customer() {
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+}

src/main/java/model/Order.java

+/*******************************************************************************
+ * Copyright (c) 2012 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the 
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
+ * which accompanies this distribution. 
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at 
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *      Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.*;
+
+import org.eclipse.persistence.annotations.DataFormatType;
+import org.eclipse.persistence.annotations.Field;
+import org.eclipse.persistence.annotations.NoSql;
+
+/**
+ * Order, stored as a root JSON object, nesting its order lines in the sane document.
+ * @author James Sutherland
+ */
+@Entity
+@NoSql(dataFormat=DataFormatType.MAPPED)
+public class Order implements Serializable {
+    /* The id uses the generated OID (UUID) from Mongo. */
+    @Id
+    @GeneratedValue
+    @Field(name="_id")
+    private String id;
+    /* Optimistic locking is supported. */
+    @Version
+    private long version;
+    @Basic
+    private String description;
+    @Basic
+    private double totalCost = 0;
+    /* A nested embeddable value is stored as Embedded. */
+    @Embedded
+    private Address billingAddress;
+    @Embedded
+    private Address shippingAddress;
+    /* Nested embeddable values are stored as ElementCollection. */
+    @ElementCollection
+    private List<OrderLine> orderLines = new ArrayList<OrderLine>();
+    /* Relationships are supported, the id is stored as a foreign key, for OneToMany a collection of ids would be stored. */
+    @ManyToOne(fetch=FetchType.LAZY)
+    private Customer customer;
+
+    public Order() {
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+    
+    public long getVersion() {
+        return version;
+    }
+
+    public void setVersion(long version) {
+        this.version = version;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public double getTotalCost() {
+        return totalCost;
+    }
+
+    public void setTotalCost(double totalCost) {
+        this.totalCost = totalCost;
+    }
+
+    public List<OrderLine> getOrderLines() {
+        return orderLines;
+    }
+
+    public void setOrderLines(List<OrderLine> orderLines) {
+        this.orderLines = orderLines;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+    
+    public Address getBillingAddress() {
+        return billingAddress;
+    }
+
+    public void setBillingAddress(Address billingAddress) {
+        this.billingAddress = billingAddress;
+    }
+
+    public Address getShippingAddress() {
+        return shippingAddress;
+    }
+
+    public void setShippingAddress(Address shippingAddress) {
+        this.shippingAddress = shippingAddress;
+    }
+
+    /**
+     * Add the order line to the order, and set the back reference and update the order cost.
+     */
+    public void addOrderLine(OrderLine orderLine) {
+        getOrderLines().add(orderLine);
+        orderLine.setLineNumber(getOrderLines().size());
+        setTotalCost(getTotalCost() + orderLine.getCost());
+    }
+
+    public String toString() {
+        return "Order(" + description + ", " + totalCost + ")";
+    }
+}

src/main/java/model/OrderLine.java

+/*******************************************************************************
+ * Copyright (c) 2012 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the 
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
+ * which accompanies this distribution. 
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at 
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *      Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Serializable;
+
+import javax.persistence.*;
+
+import org.eclipse.persistence.annotations.DataFormatType;
+import org.eclipse.persistence.annotations.NoSql;
+
+/**
+ * OrderLine, stored as part of the Order document.
+ * @author James Sutherland
+ */
+@Embeddable
+@NoSql(dataFormat=DataFormatType.MAPPED)
+public class OrderLine implements Serializable {
+    @Basic
+    private int lineNumber;
+    @Basic
+    private String description;
+    @Basic
+    private double cost = 0;
+
+    public OrderLine() {
+    }
+    
+    public OrderLine(String description, double cost) {
+        this.description = description;
+        this.cost = cost;
+    }
+
+    public int getLineNumber() {
+        return lineNumber;
+    }
+
+    public void setLineNumber(int lineNumber) {
+        this.lineNumber = lineNumber;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public double getCost() {
+        return cost;
+    }
+
+    public void setCost(double cost) {
+        this.cost = cost;
+    }
+    
+}

src/main/resources/META-INF/persistence.xml

+<?xml version="1.0" encoding="UTF-8" ?>
+<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
+        version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
+    <persistence-unit name="mongo" transaction-type="RESOURCE_LOCAL">
+        <class>model.Order</class>
+        <class>model.OrderLine</class>
+        <class>model.Address</class>
+        <class>model.Customer</class>
+        <properties>
+            <property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
+            <property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
+            <!--property name="eclipselink.nosql.property.mongo.port" value="27017"/>
+            <property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
+            <property name="eclipselink.nosql.property.mongo.db" value="mydb"/-->
+            <property name="eclipselink.logging.level" value="FINEST"/>
+        </properties>
+    </persistence-unit>
+</persistence>

src/main/webapp/index.jsp

+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+   "http://www.w3.org/TR/html4/loose.dtd">
+
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+        <title>JSP Page</title>
+    </head>
+    <body>
+        <h1>Hello World!</h1>
+    </body>
+</html>