Explorar o código

Fixed unit tests to work with new database integration and removed unused files.

Thomas Flucke %!s(int64=9) %!d(string=hai) anos
pai
achega
d274e7452d

+ 0 - 46
server/app/Filters.java

@@ -1,46 +0,0 @@
-import javax.inject.*;
-import play.*;
-import play.mvc.EssentialFilter;
-import play.http.HttpFilters;
-import play.mvc.*;
-
-import filters.ExampleFilter;
-
-/**
- * This class configures filters that run on every request. This
- * class is queried by Play to get a list of filters.
- *
- * Play will automatically use filters from any class called
- * <code>Filters</code> that is placed the root package. You can load filters
- * from a different class by adding a `play.http.filters` setting to
- * the <code>application.conf</code> configuration file.
- */
-@Singleton
-public class Filters implements HttpFilters {
-
-    private final Environment env;
-    private final EssentialFilter exampleFilter;
-
-    /**
-     * @param env Basic environment settings for the current application.
-     * @param exampleFilter A demonstration filter that adds a header to
-     */
-    @Inject
-    public Filters(Environment env, ExampleFilter exampleFilter) {
-        this.env = env;
-        this.exampleFilter = exampleFilter;
-    }
-
-    @Override
-    public EssentialFilter[] filters() {
-      // Use the example filter if we're running development mode. If
-      // we're running in production or test mode then don't use any
-      // filters at all.
-      if (env.mode().equals(Mode.DEV)) {
-          return new EssentialFilter[] { exampleFilter };
-      } else {
-         return new EssentialFilter[] {};
-      }
-    }
-
-}

+ 0 - 31
server/app/Module.java

@@ -1,31 +0,0 @@
-import com.google.inject.AbstractModule;
-import java.time.Clock;
-
-import services.ApplicationTimer;
-import services.AtomicCounter;
-import services.Counter;
-
-/**
- * This class is a Guice module that tells Guice how to bind several
- * different types. This Guice module is created when the Play
- * application starts.
- *
- * Play will automatically use any class called `Module` that is in
- * the root package. You can create modules in other locations by
- * adding `play.modules.enabled` settings to the `application.conf`
- * configuration file.
- */
-public class Module extends AbstractModule {
-
-    @Override
-    public void configure() {
-        // Use the system clock as the default implementation of Clock
-        bind(Clock.class).toInstance(Clock.systemDefaultZone());
-        // Ask Guice to create an instance of ApplicationTimer when the
-        // application starts.
-        bind(ApplicationTimer.class).asEagerSingleton();
-        // Set AtomicCounter as the implementation for Counter.
-        bind(Counter.class).to(AtomicCounter.class);
-    }
-
-}

+ 0 - 65
server/app/controllers/AsyncController.java

@@ -1,65 +0,0 @@
-package controllers;
-
-import akka.actor.ActorSystem;
-import javax.inject.*;
-
-import akka.actor.Scheduler;
-import play.*;
-import play.mvc.*;
-import java.util.concurrent.Executor;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
-import java.util.concurrent.TimeUnit;
-
-import scala.concurrent.ExecutionContext;
-import scala.concurrent.duration.Duration;
-import scala.concurrent.ExecutionContextExecutor;
-
-/**
- * This controller contains an action that demonstrates how to write
- * simple asynchronous code in a controller. It uses a timer to
- * asynchronously delay sending a response for 1 second.
- */
-@Singleton
-public class AsyncController extends Controller {
-
-    private final ActorSystem actorSystem;
-    private final ExecutionContextExecutor exec;
-
-    /**
-     * @param actorSystem We need the {@link ActorSystem}'s
-     * {@link Scheduler} to run code after a delay.
-     * @param exec We need a Java {@link Executor} to apply the result
-     * of the {@link CompletableFuture} and a Scala
-     * {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
-     * An {@link ExecutionContextExecutor} implements both interfaces.
-     */
-    @Inject
-    public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) {
-      this.actorSystem = actorSystem;
-      this.exec = exec;
-    }
-
-    /**
-     * An action that returns a plain text message after a delay
-     * of 1 second.
-     *
-     * The configuration in the <code>routes</code> file means that this method
-     * will be called when the application receives a <code>GET</code> request with
-     * a path of <code>/message</code>.
-     */
-    public CompletionStage<Result> message() {
-        return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec);
-    }
-
-    private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
-        CompletableFuture<String> future = new CompletableFuture<>();
-        actorSystem.scheduler().scheduleOnce(
-            Duration.create(time, timeUnit),
-            () -> future.complete("Hi!"),
-            exec
-        );
-        return future;
-    }
-
-}

+ 0 - 35
server/app/controllers/CountController.java

@@ -1,35 +0,0 @@
-package controllers;
-
-import javax.inject.*;
-import play.*;
-import play.mvc.*;
-
-import services.Counter;
-
-/**
- * This controller demonstrates how to use dependency injection to
- * bind a component into a controller class. The class contains an
- * action that shows an incrementing count to users. The {@link Counter}
- * object is injected by the Guice dependency injection system.
- */
-@Singleton
-public class CountController extends Controller {
-
-    private final Counter counter;
-
-    @Inject
-    public CountController(Counter counter) {
-       this.counter = counter;
-    }
-
-    /**
-     * An action that responds with the {@link Counter}'s current
-     * count. The result is plain text. This action is mapped to
-     * <code>GET</code> requests with a path of <code>/count</code>
-     * requests by an entry in the <code>routes</code> config file.
-     */
-    public Result count() {
-        return ok(Integer.toString(counter.nextCount()));
-    }
-
-}

+ 1 - 1
server/app/controllers/EventsController.java

@@ -23,7 +23,7 @@ public class EventsController extends Controller {
 		List<Event> res = JPA.em().createQuery("SELECT e from Event e", Event.class).getResultList();
 		if (res == null || res.size() == 0)
 		{
-			return notFound();
+			return notFound(Json.toJson("No Events"));
 		}
 		return ok(Json.toJson(res));
     }

+ 0 - 23
server/app/controllers/HomeController.java

@@ -1,23 +0,0 @@
-package controllers;
-
-import play.mvc.*;
-
-import views.html.*;
-
-/**
- * This controller contains an action to handle HTTP requests
- * to the application's home page.
- */
-public class HomeController extends Controller {
-
-    /**
-     * An action that renders an HTML page with a welcome message.
-     * The configuration in the <code>routes</code> file means that
-     * this method will be called when the application receives a
-     * <code>GET</code> request with a path of <code>/</code>.
-     */
-    public Result index() {
-        return ok(index.render("Your new application is ready."));
-    }
-
-}

+ 0 - 45
server/app/filters/ExampleFilter.java

@@ -1,45 +0,0 @@
-package filters;
-
-import akka.stream.Materializer;
-import java.util.concurrent.CompletionStage;
-import java.util.concurrent.Executor;
-import java.util.function.Function;
-import javax.inject.*;
-import play.mvc.*;
-import play.mvc.Http.RequestHeader;
-
-
-/**
- * This is a simple filter that adds a header to all requests. It's
- * added to the application's list of filters by the
- * {@link Filters} class.
- */
-@Singleton
-public class ExampleFilter extends Filter {
-
-    private final Executor exec;
-
-    /**
-     * @param mat This object is needed to handle streaming of requests
-     * and responses.
-     * @param exec This class is needed to execute code asynchronously.
-     * It is used below by the <code>thenAsyncApply</code> method.
-     */
-    @Inject
-    public ExampleFilter(Materializer mat, Executor exec) {
-        super(mat);
-        this.exec = exec;
-    }
-
-    @Override
-    public CompletionStage<Result> apply(
-        Function<RequestHeader, CompletionStage<Result>> next,
-        RequestHeader requestHeader) {
-
-        return next.apply(requestHeader).thenApplyAsync(
-            result -> result.withHeader("X-ExampleFilter", "foo"),
-            exec
-        );
-    }
-
-}

+ 0 - 50
server/app/services/ApplicationTimer.java

@@ -1,50 +0,0 @@
-package services;
-
-import java.time.Clock;
-import java.time.Instant;
-import java.util.concurrent.CompletableFuture;
-import javax.inject.*;
-import play.Logger;
-import play.inject.ApplicationLifecycle;
-
-/**
- * This class demonstrates how to run code when the
- * application starts and stops. It starts a timer when the
- * application starts. When the application stops it prints out how
- * long the application was running for.
- *
- * This class is registered for Guice dependency injection in the
- * {@link Module} class. We want the class to start when the application
- * starts, so it is registered as an "eager singleton". See the code
- * in the {@link Module} class to see how this happens.
- *
- * This class needs to run code when the server stops. It uses the
- * application's {@link ApplicationLifecycle} to register a stop hook.
- */
-@Singleton
-public class ApplicationTimer {
-
-    private final Clock clock;
-    private final ApplicationLifecycle appLifecycle;
-    private final Instant start;
-
-    @Inject
-    public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) {
-        this.clock = clock;
-        this.appLifecycle = appLifecycle;
-        // This code is called when the application starts.
-        start = clock.instant();
-        Logger.info("ApplicationTimer demo: Starting application at " + start);
-
-        // When the application starts, register a stop hook with the
-        // ApplicationLifecycle object. The code inside the stop hook will
-        // be run when the application stops.
-        appLifecycle.addStopHook(() -> {
-            Instant stop = clock.instant();
-            Long runningTime = stop.getEpochSecond() - start.getEpochSecond();
-            Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s.");
-            return CompletableFuture.completedFuture(null);
-        });
-    }
-
-}

+ 0 - 26
server/app/services/AtomicCounter.java

@@ -1,26 +0,0 @@
-package services;
-
-import java.util.concurrent.atomic.AtomicInteger;
-import javax.inject.*;
-
-/**
- * This class is a concrete implementation of the {@link Counter} trait.
- * It is configured for Guice dependency injection in the {@link Module}
- * class.
- *
- * This class has a {@link Singleton} annotation because we need to make
- * sure we only use one counter per application. Without this
- * annotation we would get a new instance every time a {@link Counter} is
- * injected.
- */
-@Singleton
-public class AtomicCounter implements Counter {
-
-    private final AtomicInteger atomicCounter = new AtomicInteger();
-
-    @Override
-    public int nextCount() {
-       return atomicCounter.getAndIncrement();
-    }
-
-}

+ 0 - 13
server/app/services/Counter.java

@@ -1,13 +0,0 @@
-package services;
-
-/**
- * This interface demonstrates how to create a component that is injected
- * into a controller. The interface represents a counter that returns a
- * incremented number each time it is called.
- *
- * The {@link Modules} class binds this interface to the
- * {@link AtomicCounter} implementation.
- */
-public interface Counter {
-    int nextCount();
-}

+ 0 - 20
server/app/views/index.scala.html

@@ -1,20 +0,0 @@
-@*
- * This template takes a single argument, a String containing a
- * message to display.
- *@
-@(message: String)
-
-@*
- * Call the `main` template with two arguments. The first
- * argument is a `String` with the title of the page, the second
- * argument is an `Html` object containing the body of the page.
- *@
-@main("Welcome to Play") {
-
-    @*
-     * Get an `Html` object by calling the built-in Play welcome
-     * template and passing a `String` message.
-     *@
-    @welcome(message, style = "java")
-
-}

+ 0 - 23
server/app/views/main.scala.html

@@ -1,23 +0,0 @@
-@*
- * This template is called from the `index` template. This template
- * handles the rendering of the page header and body tags. It takes
- * two arguments, a `String` for the title of the page and an `Html`
- * object to insert into the body of the page.
- *@
-@(title: String)(content: Html)
-
-<!DOCTYPE html>
-<html lang="en">
-    <head>
-        @* Here's where we render the page title `String`. *@
-        <title>@title</title>
-        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
-        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
-        <script src="@routes.Assets.versioned("javascripts/hello.js")" type="text/javascript"></script>
-    </head>
-    <body>
-        @* And here's where we render the `Html` object containing
-         * the page content. *@
-        @content
-    </body>
-</html>

+ 0 - 173
server/app/views/welcome.scala.html

@@ -1,173 +0,0 @@
-@(message: String, style: String = "java")
-
-@defining(play.core.PlayVersion.current) { version =>
-
-    <link rel="stylesheet" media="screen" href="/@@documentation/resources/style/main.css">
-
-    <section id="top">
-        <div class="wrapper">
-            <h1><a href="https://playframework.com/documentation/@version/Home">@message</a></h1>
-        </div>
-    </section>
-
-    <div id="content" class="wrapper doc">
-        <article>
-
-            <h1>Welcome to Play</h1>
-
-            <p>
-                Congratulations, you’ve just created a new Play application. This page will help you with the next few steps.
-            </p>
-
-            <blockquote>
-                <p>
-                    You’re using Play @version
-                </p>
-            </blockquote>
-
-            <h2>Why do you see this page?</h2>
-
-            <p>
-                The <code>conf/routes</code> file defines a route that tells Play to invoke the <code>HomeController.index</code> action
-                whenever a browser requests the <code>/</code> URI using the GET method:
-            </p>
-
-            <pre><code># Home page
-GET     /               controllers.HomeController.index</code></pre>
-
-
-            <p>
-                Play has invoked the <code>controllers.HomeController.index</code> method:
-            </p>
-
-            <pre><code>public static Result index() {
-    return ok(index.render("Your new application is ready."));
-}</code></pre>
-
-            <p>
-                An action method handles the incoming HTTP request, and returns the HTTP result to send back to the web client.
-                Here we send a <code>200 OK</code> response, using a template to fill its content.
-            </p>
-
-            <p>
-                The template is defined in the <code>app/views/index.scala.html</code> file and compiled as a standard Java class.
-            </p>
-
-            <pre><code>@@(message: String)
-
-  @@main("Welcome to Play") {
-
-  @@play20.welcome(message, style = "Java")
-
-}</code></pre>
-
-            <p>
-                The first line of the template defines the function signature. Here it just takes a single <code>String</code> parameter.
-                Then this template calls another function defined in <code>app/views/main.scala.html</code> which displays the HTML layout, and another
-                function that displays this welcome message. You can freely add any HTML fragment mixed with Scala code in this file.
-            </p>
-
-            <blockquote>
-                <p>
-                    <strong>Note</strong> that Scala is fully compatible with Java, so if you don’t know Scala don’t panic, a Scala statement is very similar to a Java one.
-                </p>
-            </blockquote>
-
-            <p>You can read more about <a href="https://www.playframework.com/documentation/@version/ScalaTemplates">Twirl</a>, the template language used by Play, and how Play handles <a href="https://www.playframework.com/documentation/@version/JavaActions">actions</a>.</p>
-
-            <h2>Async Controller</h2>
-
-            Now that you've seen how Play renders a page, take a look at <code>AsyncController.java</code>, which shows how to do asynchronous programming when handling a request.  The code is almost exactly the same as <code>HomeController.java</code>, but instead of returning <code>Result</code>, the action returns <code>CompletionStage&lt;Result&gt;</code> to Play.  When the execution completes, Play can use a thread to render the result without blocking the thread in the mean time.
-<!--
-            <p>
-                <a href="routes.AsyncController.message">Click here for the AsyncController action!</a>
-            </p>
--->
-            <p>
-                You can read more about <a href="https://www.playframework.com/documentation/@version/JavaAsync">asynchronous actions</a> in the documentation.
-            </p>
-
-            <h2>Count Controller</h2>
-
-            <p>
-                Both the HomeController and AsyncController are very simple, and typically controllers present the results of the interaction of several services.  As an example, see the <code>CountController</code>, which shows how to inject a component into a controller and use the component when handling requests.  The count controller increments every time you click on it, so keep clicking to see the numbers go up.
-            </p>
-<!--
-            <p>
-                <a href="routes.CountController.count">Click here for the CountController action!</a>
-            </p>
--->
-            <p>
-                You can read more about <a href="https://www.playframework.com/documentation/@version/JavaDependencyInjection">dependency injection</a> in the documentation.
-            </p>
-
-            <h2>Need more info on the console?</h2>
-
-            <p>
-                For more information on the various commands you can run on Play, i.e. running tests and packaging applications for production, see <a href="https://playframework.com/documentation/@version/PlayConsole">Using the Play console</a>.
-            </p>
-
-            <h2>Need to set up an IDE?</h2>
-
-            <p>
-                You can start hacking your application right now using any text editor. Any changes will be automatically reloaded at each page refresh,
-                including modifications made to Scala source files.
-            </p>
-
-            <p>
-                If you want to set-up your application in <strong>IntelliJ IDEA</strong> or any other Java IDE, check the
-                <a href="https://www.playframework.com/documentation/@version/IDE">Setting up your preferred IDE</a> page.
-            </p>
-
-            <h2>Need more documentation?</h2>
-
-            <p>
-                Play documentation is available at <a href="https://www.playframework.com/documentation/@version">https://www.playframework.com/documentation</a>.
-            </p>
-
-            <p>
-                Play comes with lots of example templates showcasing various bits of Play functionality at <a href="https://www.playframework.com/download#examples">https://www.playframework.com/download#examples</a>.
-            </p>
-
-            <h2>Need more help?</h2>
-
-            <p>
-                Play questions are asked and answered on Stackoverflow using the "playframework" tag: <a href="https://stackoverflow.com/questions/tagged/playframework">https://stackoverflow.com/questions/tagged/playframework</a>
-            </p>
-
-            <p>
-                The <a href="http://groups.google.com/group/play-framework">Play Google Group</a> is where Play users come to seek help,
-                announce projects, and discuss issues and new features. If you don’t have a Google account, you can still join the mailing
-                list by sending an e-mail to
-                <strong>play-framework+subscribe@@googlegroups.com</strong>.
-            </p>
-
-            <p>
-                Gitter is a real time chat channel, like IRC. The <a href="https://gitter.im/playframework/playframework">playframework/playframework</a>  channel is used by Play users to discuss the ins and outs of writing great Play applications.
-            </p>
-
-        </article>
-
-        <aside>
-            <h3>Browse</h3>
-            <ul>
-                <li><a href="https://playframework.com/documentation/@version">Documentation</a></li>
-                <li><a href="https://playframework.com/documentation/@version/api/@style/index.html">Browse the @{style.capitalize} API</a></li>
-            </ul>
-            <h3>Start here</h3>
-            <ul>
-                <li><a href="https://playframework.com/documentation/@version/PlayConsole">Using the Play console</a></li>
-                <li><a href="https://playframework.com/documentation/@version/IDE">Setting up your preferred IDE</a></li>
-                <li><a href="https://playframework.com/download#examples">Example Projects</a>
-            </ul>
-            <h3>Help here</h3>
-            <ul>
-                <li><a href="https://stackoverflow.com/questions/tagged/playframework">Stack Overflow</a></li>
-                <li><a href="http://groups.google.com/group/play-framework">Mailing List</a></li>
-                <li><a href="https://gitter.im/playframework/playframework">Gitter Channel</a></li>
-            </ul>
-
-        </aside>
-
-    </div>
-}

+ 4 - 1
server/build.sbt

@@ -6,13 +6,16 @@ lazy val root = (project in file(".")).enablePlugins(PlayJava)
 
 scalaVersion := "2.11.11"
 
+val jUnitVersion = "4.11" // replace appropriately
+
 libraryDependencies += javaJdbc
 libraryDependencies += cache
 libraryDependencies += javaWs
 
 libraryDependencies ++= Seq(
   javaJpa,
-  "org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final" // replace by your jpa implementation
+  "org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final", // replace by your jpa implementation
+  "junit" % "junit" % jUnitVersion % Test
 )
 
 PlayKeys.externalizeResources := false

+ 0 - 45
server/test/ApplicationTest.java

@@ -1,45 +0,0 @@
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.*;
-
-import play.mvc.*;
-import play.test.*;
-import play.data.DynamicForm;
-import play.data.validation.ValidationError;
-import play.data.validation.Constraints.RequiredValidator;
-import play.i18n.Lang;
-import play.libs.F;
-import play.libs.F.*;
-import play.twirl.api.Content;
-
-import static play.test.Helpers.*;
-import static org.junit.Assert.*;
-
-
-/**
- *
- * Simple (JUnit) tests that can call all parts of a play app.
- * If you are interested in mocking a whole application, see the wiki for more details.
- *
- */
-public class ApplicationTest {
-
-    @Test
-    public void simpleCheck() {
-        int a = 1 + 1;
-        assertEquals(2, a);
-    }
-
-    @Test
-    public void renderTemplate() {
-        Content html = views.html.index.render("Your new application is ready.");
-        assertEquals("text/html", html.contentType());
-        assertTrue(html.body().contains("Your new application is ready."));
-    }
-
-
-}

+ 0 - 25
server/test/IntegrationTest.java

@@ -1,25 +0,0 @@
-import org.junit.*;
-
-import play.mvc.*;
-import play.test.*;
-
-import static play.test.Helpers.*;
-import static org.junit.Assert.*;
-
-import static org.fluentlenium.core.filter.FilterConstructor.*;
-
-public class IntegrationTest {
-
-    /**
-     * add your integration test here
-     * in this example we just check if the welcome page is being shown
-     */
-    @Test
-    public void test() {
-        running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> {
-            browser.goTo("http://localhost:3333");
-            assertTrue(browser.pageSource().contains("Your new application is ready."));
-        });
-    }
-
-}

+ 22 - 26
server/test/test/EventControllerTester.java

@@ -1,46 +1,42 @@
 package test;
 
 import static org.junit.Assert.assertEquals;
-
-import org.junit.Before;
 import org.junit.Test;
 
-import controllers.EventsController;
 import models.Event;
 import play.libs.Json;
+import play.mvc.Http.RequestBuilder;
+import play.mvc.Result;
 import play.test.Helpers;
+import play.test.WithApplication;
 
-public class EventControllerTester {
-	EventsController controller;
-	
-	@Before
-	public void init()
-	{
-		controller = new EventsController();
-	}
+public class EventControllerTester extends WithApplication {
 	
 	@Test
 	public void testNoEvents()
 	{
-		assertEquals(404, controller.get().status());
+       Helpers.running(Helpers.fakeApplication(Helpers.inMemoryDatabase()), () -> {
+    	   int status = Helpers.route(Helpers.fakeRequest("GET", "/events")).status();
+    	   assertEquals(404, status);
+       });
 	}
 	
 	@Test
 	public void testEventDeserialization()
-	{
-		String name = "Free Pizza Knight", desc = "Board games and free pizza";
-		float lat = 7f, lng = 0.3f;
-		Event e = new Event();
-		e.name = name;
-		e.lat = lat;
-		e.lng = lng;
-		e.description = desc;
-		int status = Helpers.invokeWithContext(
-				Helpers.fakeRequest().bodyText(Json.toJson(e).asText()),
-				controller::create
-			).status();
-		assertEquals(201, status);
-		assertEquals(200, controller.get().status());
+	{ 
+       Helpers.running(Helpers.fakeApplication(Helpers.inMemoryDatabase()), () -> {
+    	    RequestBuilder rb = Helpers.fakeRequest("PUT", "/events");
+			String name = "Free Pizza Knight", desc = "Board games and free pizza";
+			float lat = 7f, lng = 0.3f;
+			Event e = new Event();
+			e.name = name;
+			e.lat = lat;
+			e.lng = lng;
+			e.description = desc;
+    	    rb.bodyJson(Json.toJson(e));
+    	   	Result res = Helpers.route(rb);
+			assertEquals(201, res.status());
+		});
 	}
 
 }