Browse Source

Merge pull request #2188 from knewmanTE/add-missing-java-spark-tests

Upgrade Java spark to v2.3 and add missing tests
A Shawn Bandy 8 years ago
parent
commit
7308038ef5

+ 2 - 0
frameworks/Java/spark/benchmark_config.json

@@ -6,7 +6,9 @@
       "json_url": "/spark/json",
       "json_url": "/spark/json",
       "db_url": "/spark/db",
       "db_url": "/spark/db",
       "query_url": "/spark/db?queries=",
       "query_url": "/spark/db?queries=",
+      "update_url": "/spark/updates?queries=",
       "plaintext_url": "/spark/plaintext",
       "plaintext_url": "/spark/plaintext",
+      "fortune_url": "/spark/fortunes",
       "port": 8080,
       "port": 8080,
       "approach": "Realistic",
       "approach": "Realistic",
       "classification": "Micro",
       "classification": "Micro",

+ 10 - 5
frameworks/Java/spark/pom.xml

@@ -9,8 +9,8 @@
     <version>1.0.0-BUILD-SNAPSHOT</version>
     <version>1.0.0-BUILD-SNAPSHOT</version>
 
 
     <properties>
     <properties>
-        <java-version>1.7</java-version>
-        <spark-version>1.1.1</spark-version>
+        <java-version>1.8</java-version>
+        <spark-version>2.3</spark-version>
         <hibernate-version>4.3.0.Final</hibernate-version>
         <hibernate-version>4.3.0.Final</hibernate-version>
         <gson-version>2.2.4</gson-version>
         <gson-version>2.2.4</gson-version>
         <mysql-connector-version>5.1.38</mysql-connector-version>
         <mysql-connector-version>5.1.38</mysql-connector-version>
@@ -57,8 +57,13 @@
             <groupId>org.slf4j</groupId>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-log4j12</artifactId>
             <artifactId>slf4j-log4j12</artifactId>
         </dependency>
         </dependency>
+        <dependency>
+            <groupId>com.j2html</groupId>
+            <artifactId>j2html</artifactId>
+            <version>0.7</version>
+        </dependency>
     </dependencies>
     </dependencies>
-    
+
     <dependencyManagement>
     <dependencyManagement>
         <dependencies>
         <dependencies>
             <dependency>
             <dependency>
@@ -88,7 +93,7 @@
             </dependency>
             </dependency>
         </dependencies>
         </dependencies>
     </dependencyManagement>
     </dependencyManagement>
-    
+
     <profiles>
     <profiles>
         <profile>
         <profile>
             <id>standalone</id>
             <id>standalone</id>
@@ -103,7 +108,7 @@
             </dependencyManagement>
             </dependencyManagement>
         </profile>
         </profile>
     </profiles>
     </profiles>
-    
+
     <build>
     <build>
         <resources>
         <resources>
             <resource>
             <resource>

+ 16 - 0
frameworks/Java/spark/src/main/java/hello/domain/Fortune.java

@@ -0,0 +1,16 @@
+package hello.domain;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Fortune {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    public int id;
+    public String message;
+
+}

+ 9 - 7
frameworks/Java/spark/src/main/java/hello/web/HibernateUtil.java

@@ -1,6 +1,7 @@
 package hello.web;
 package hello.web;
 
 
 import hello.domain.World;
 import hello.domain.World;
+import hello.domain.Fortune;
 
 
 import org.hibernate.Session;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.SessionFactory;
@@ -14,10 +15,10 @@ import org.slf4j.LoggerFactory;
 public class HibernateUtil {
 public class HibernateUtil {
 
 
     private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
     private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
-    
+
     private static final SessionFactory SESSION_FACTORY = createSessionFactory();
     private static final SessionFactory SESSION_FACTORY = createSessionFactory();
     private static final ThreadLocal<Session> SESSIONS = new ThreadLocal<>();
     private static final ThreadLocal<Session> SESSIONS = new ThreadLocal<>();
-    
+
     public static Session getSession() {
     public static Session getSession() {
         Session session = SESSIONS.get();
         Session session = SESSIONS.get();
         if (session == null) {
         if (session == null) {
@@ -26,7 +27,7 @@ public class HibernateUtil {
         }
         }
         return session;
         return session;
     }
     }
-    
+
     public static void closeSession() {
     public static void closeSession() {
         Session session = SESSIONS.get();
         Session session = SESSIONS.get();
         if (session != null) {
         if (session != null) {
@@ -34,7 +35,7 @@ public class HibernateUtil {
             SESSIONS.remove();
             SESSIONS.remove();
         }
         }
     }
     }
-    
+
     private static SessionFactory createSessionFactory() {
     private static SessionFactory createSessionFactory() {
         try {
         try {
             Configuration configuration = configuration();
             Configuration configuration = configuration();
@@ -45,6 +46,7 @@ public class HibernateUtil {
             configuration.setProperty(AvailableSettings.SHOW_SQL, "false");
             configuration.setProperty(AvailableSettings.SHOW_SQL, "false");
             configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
             configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
             configuration.addAnnotatedClass(World.class);
             configuration.addAnnotatedClass(World.class);
+            configuration.addAnnotatedClass(Fortune.class);
             StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
             StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
             return configuration.buildSessionFactory(serviceRegistryBuilder.build());
             return configuration.buildSessionFactory(serviceRegistryBuilder.build());
         } catch (RuntimeException ex) {
         } catch (RuntimeException ex) {
@@ -52,11 +54,11 @@ public class HibernateUtil {
             throw ex;
             throw ex;
         }
         }
     }
     }
-    
+
     private static Configuration configuration() {
     private static Configuration configuration() {
         boolean jndi = Boolean.parseBoolean(System.getProperty("jndi", "true"));
         boolean jndi = Boolean.parseBoolean(System.getProperty("jndi", "true"));
         Configuration configuration = new Configuration();
         Configuration configuration = new Configuration();
-        // We're always going to use the -local config now since there were previous 
+        // We're always going to use the -local config now since there were previous
         // problems with the jndi config.
         // problems with the jndi config.
         /*
         /*
         if (jndi) {
         if (jndi) {
@@ -68,5 +70,5 @@ public class HibernateUtil {
         configuration.configure("/hibernate-local.cfg.xml");
         configuration.configure("/hibernate-local.cfg.xml");
         return configuration;
         return configuration;
     }
     }
-    
+
 }
 }

+ 0 - 30
frameworks/Java/spark/src/main/java/hello/web/JsonTransformer.java

@@ -1,30 +0,0 @@
-package hello.web;
-
-import spark.Request;
-import spark.Response;
-import spark.ResponseTransformerRoute;
-
-import com.google.gson.Gson;
-
-public abstract class JsonTransformer extends ResponseTransformerRoute {
-
-    private static final Gson   GSON              = new Gson();
-    private static final String CONTENT_TYPE_JSON = "application/json";
-    
-    protected JsonTransformer(final String path) {
-        super(path);
-    }
-
-    @Override
-    public String render(final Object model) {
-        return GSON.toJson(model);
-    }
-
-    @Override
-    public Object handle(final Request request, final Response response) {
-        response.type(CONTENT_TYPE_JSON);
-        return handleInternal(request, response);
-    }
-    
-    protected abstract Object handleInternal(Request request, Response response);
-}

+ 110 - 60
frameworks/Java/spark/src/main/java/hello/web/SparkApplication.java

@@ -4,89 +4,139 @@ import static spark.Spark.after;
 import static spark.Spark.get;
 import static spark.Spark.get;
 import hello.domain.Message;
 import hello.domain.Message;
 import hello.domain.World;
 import hello.domain.World;
+import hello.domain.Fortune;
 
 
 import java.util.Date;
 import java.util.Date;
 import java.util.Random;
 import java.util.Random;
+import java.util.List;
+import java.util.Collections;
 import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.ThreadLocalRandom;
+import java.util.stream.Collectors;
 
 
 import org.hibernate.Session;
 import org.hibernate.Session;
+import org.hibernate.Transaction;
 
 
-import spark.Filter;
 import spark.Request;
 import spark.Request;
 import spark.Response;
 import spark.Response;
-import spark.Route;
+
+import com.google.gson.Gson;
+
+import static j2html.TagCreator.*;
 
 
 public class SparkApplication implements spark.servlet.SparkApplication {
 public class SparkApplication implements spark.servlet.SparkApplication {
 
 
     private static final int DB_ROWS = 10000;
     private static final int DB_ROWS = 10000;
+    private static final int FORTUNE_ROWS = 12;
     private static final String MESSAGE = "Hello, World!";
     private static final String MESSAGE = "Hello, World!";
+    private static final String ADDITIONAL_FORTUNE = "Additional fortune added at request time.";
+    private static final String CONTENT_TYPE_JSON = "application/json";
     private static final String CONTENT_TYPE_TEXT = "text/plain";
     private static final String CONTENT_TYPE_TEXT = "text/plain";
-    
+    private static final Gson GSON = new Gson();
+
+    private int getQueries(final Request request) {
+      try {
+        String param = request.queryParams("queries");
+        if (param == null) {
+          return 1;
+        }
+
+        int queries = Integer.parseInt(param);
+        if (queries < 1) {
+          return 1;
+        }
+        if (queries > 500) {
+          return 500;
+        }
+        return queries;
+      } catch (NumberFormatException ex) {
+        return 1;
+      }
+    }
+
     @Override
     @Override
     public void init() {
     public void init() {
-        get(new JsonTransformer("/json") {
-            @Override
-            protected Object handleInternal(final Request request, final Response response) {
-                return new Message();
-            }
-        });
-        get(new JsonTransformer("/db") {
-            @Override
-            protected Object handleInternal(final Request request, final Response response) {
-                final int queries = getQueries(request);
-                
-                final World[] worlds = new World[queries];
-                final Session session = HibernateUtil.getSession();
-                final Random random = ThreadLocalRandom.current();
-                
-                for (int i = 0; i < queries; i++) {
-                    worlds[i] = (World) session.byId(World.class).load(random.nextInt(DB_ROWS) + 1);
-                }
-                
-                return (request.queryParams("queries") == null ? worlds[0] : worlds);
-            }
-            
-            private int getQueries(final Request request) {
-                try {
-                    String param = request.queryParams("queries");
-                    if (param == null) {
-                        return 1;
-                    }
-                    
-                    int queries = Integer.parseInt(param);
-                    if (queries < 1) {
-                        return 1;
-                    }
-                    if (queries > 500) {
-                        return 500;
-                    }
-                    return queries;
-                } catch (NumberFormatException ex) {
-                    return 1;
-                }
+
+        get("/json", (request, response) -> {
+          response.type(CONTENT_TYPE_JSON);
+          return new Message(); }
+        , GSON::toJson);
+        get("/db", (request, response) -> {
+            response.type(CONTENT_TYPE_JSON);
+
+            final int queries = getQueries(request);
+
+            final World[] worlds = new World[queries];
+            final Session session = HibernateUtil.getSession();
+            final Random random = ThreadLocalRandom.current();
+
+            for (int i = 0; i < queries; i++) {
+                worlds[i] = (World) session.byId(World.class).load(random.nextInt(DB_ROWS) + 1);
             }
             }
-        });
-        get(new Route("/plaintext") {
-            @Override
-            public Object handle(final Request request, final Response response) {
-                response.type(CONTENT_TYPE_TEXT);
-                return MESSAGE;
+
+            return (request.queryParams("queries") == null ? worlds[0] : worlds);
+        }, GSON::toJson);
+        get("/updates", (request, response) -> {
+            response.type(CONTENT_TYPE_JSON);
+
+            final int queries = getQueries(request);
+
+            final World[] worlds = new World[queries];
+            final Session session = HibernateUtil.getSession();
+            final Random random = ThreadLocalRandom.current();
+
+            for (int i = 0; i < queries; i++) {
+                int id = random.nextInt(DB_ROWS) + 1;
+                int randomNumber = random.nextInt(DB_ROWS) + 1;
+                World world = (World) session.byId(World.class).load(id);
+                world.randomNumber = randomNumber;
+                Transaction transaction = session.beginTransaction();
+                session.update(world);
+                transaction.commit();
+                worlds[i] = world;
             }
             }
+
+            return worlds;
+        }, GSON::toJson);
+        get("/plaintext", (request, response) -> {
+            response.type(CONTENT_TYPE_TEXT);
+            return MESSAGE;
         });
         });
-        after(new Filter("/db") {
-            @Override
-            public void handle(final Request request, final Response response) {
-                HibernateUtil.closeSession();
-            }
+        get("/fortunes", (request, response) -> {
+          final Session session = HibernateUtil.getSession();
+          Fortune newFortune = new Fortune();
+          newFortune.id = 0;
+          newFortune.message = ADDITIONAL_FORTUNE;
+          List<Fortune> fortunes = session.createCriteria(Fortune.class).list();
+          fortunes.add(newFortune);
+          Collections.sort(fortunes, (f1, f2) -> f1.message.compareTo(f2.message));
+          return document().render() +
+            html().with(
+                head().with(
+                    title("Fortunes")
+                ),
+                body().with(
+                    table().with(
+                        tr().with(
+                            th("id"),
+                            th("message")
+                        )).with(
+                        fortunes.stream().map((fortune) ->
+                            tr().with(
+                                td(Integer.toString(fortune.id)),
+                                td(fortune.message)
+                            )
+                        ).collect(Collectors.toList())
+                    )
+                )
+          ).render();
+
         });
         });
-        after(new Filter() {
-            @Override
-            public void handle(final Request request, final Response response) {
-                response.raw().addDateHeader("Date", new Date().getTime());
-            }
+        after((request, response) -> {
+            HibernateUtil.closeSession();
+            response.raw().addDateHeader("Date", new Date().getTime());
         });
         });
     }
     }
-    
+
     public static void main(final String[] args) {
     public static void main(final String[] args) {
         System.setProperty("jndi", "false");
         System.setProperty("jndi", "false");
         new SparkApplication().init();
         new SparkApplication().init();