Browse Source

spark update

tobby48 5 years ago
parent
commit
818395b809

+ 6
- 0
pom.xml View File

@@ -213,6 +213,12 @@
213 213
 			<artifactId>icu4j</artifactId>
214 214
 			<version>63.1</version>
215 215
 		</dependency>
216
+
217
+		<dependency>
218
+			<groupId>com.sparkjava</groupId>
219
+			<artifactId>spark-core</artifactId>
220
+			<version>2.9.0</version>
221
+		</dependency>
216 222
 		
217 223
 	</dependencies>
218 224
 	

+ 117
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/Books.java View File

@@ -0,0 +1,117 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+import java.util.HashMap;
6
+import java.util.Map;
7
+import java.util.Random;
8
+
9
+/**
10
+ * A simple CRUD example showing how to create, get, update and delete book resources.
11
+ */
12
+public class Books {
13
+
14
+	/**
15
+	 * Map holding the books
16
+	 */
17
+	private static Map<String, Book> books = new HashMap<String, Book>();
18
+
19
+	public static void main(String[] args) {
20
+		final Random random = new Random();
21
+
22
+		// Creates a new book resource, will return the ID to the created resource
23
+		// author and title are sent in the post body as x-www-urlencoded values e.g. author=Foo&title=Bar
24
+		// you get them by using request.queryParams("valuename")
25
+		post("/books", (request, response) -> {
26
+			String author = request.queryParams("author");
27
+			String title = request.queryParams("title");
28
+			Book book = new Book(author, title);
29
+
30
+			int id = random.nextInt(Integer.MAX_VALUE);
31
+			books.put(String.valueOf(id), book);
32
+
33
+			response.status(201); // 201 Created
34
+			return id;
35
+		});
36
+
37
+		// Gets the book resource for the provided id
38
+		get("/books/:id", (request, response) -> {
39
+			Book book = books.get(request.params(":id"));
40
+			if (book != null) {
41
+				return "Title: " + book.getTitle() + ", Author: " + book.getAuthor();
42
+			} else {
43
+				response.status(404); // 404 Not found
44
+				return "Book not found";
45
+			}
46
+		});
47
+
48
+		// Updates the book resource for the provided id with new information
49
+		// author and title are sent in the request body as x-www-urlencoded values e.g. author=Foo&title=Bar
50
+		// you get them by using request.queryParams("valuename")
51
+		put("/books/:id", (request, response) -> {
52
+			String id = request.params(":id");
53
+			Book book = books.get(id);
54
+			if (book != null) {
55
+				String newAuthor = request.queryParams("author");
56
+				String newTitle = request.queryParams("title");
57
+				if (newAuthor != null) {
58
+					book.setAuthor(newAuthor);
59
+				}
60
+				if (newTitle != null) {
61
+					book.setTitle(newTitle);
62
+				}
63
+				return "Book with id '" + id + "' updated";
64
+			} else {
65
+				response.status(404); // 404 Not found
66
+				return "Book not found";
67
+			}
68
+		});
69
+
70
+		// Deletes the book resource for the provided id
71
+		delete("/books/:id", (request, response) -> {
72
+			String id = request.params(":id");
73
+			Book book = books.remove(id);
74
+			if (book != null) {
75
+				return "Book with id '" + id + "' deleted";
76
+			} else {
77
+				response.status(404); // 404 Not found
78
+				return "Book not found";
79
+			}
80
+		});
81
+
82
+		// Gets all available book resources (ids)
83
+		get("/books", (request, response) -> {
84
+			String ids = "";
85
+			for (String id : books.keySet()) {
86
+				ids += id + " ";
87
+			}
88
+			return ids;
89
+		});
90
+	}
91
+
92
+	public static class Book {
93
+
94
+		public String author, title;
95
+
96
+		public Book(String author, String title) {
97
+			this.author = author;
98
+			this.title = title;
99
+		}
100
+
101
+		public String getAuthor() {
102
+			return author;
103
+		}
104
+
105
+		public void setAuthor(String author) {
106
+			this.author = author;
107
+		}
108
+
109
+		public String getTitle() {
110
+			return title;
111
+		}
112
+
113
+		public void setTitle(String title) {
114
+			this.title = title;
115
+		}
116
+	}
117
+}

+ 52
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/FilterExample.java View File

@@ -0,0 +1,52 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+import java.util.HashMap;
6
+import java.util.Map;
7
+
8
+/**
9
+ * Example showing a very simple (and stupid) authentication filter that is
10
+ * executed before all other resources.
11
+ *
12
+ * When requesting the resource with e.g.
13
+ *     http://localhost:4567/hello?user=some&password=guy
14
+ * the filter will stop the execution and the client will get a 401 UNAUTHORIZED with the content 'You are not welcome here'
15
+ *
16
+ * When requesting the resource with e.g.
17
+ *     http://localhost:4567/hello?user=foo&password=bar
18
+ * the filter will accept the request and the request will continue to the /hello route.
19
+ *
20
+ * Note: There is a second "before filter" that adds a header to the response
21
+ * Note: There is also an "after filter" that adds a header to the response
22
+ */
23
+public class FilterExample {
24
+
25
+    private static Map<String, String> usernamePasswords = new HashMap<String, String>();
26
+
27
+    public static void main(String[] args) {
28
+
29
+        usernamePasswords.put("foo", "bar");
30
+        usernamePasswords.put("admin", "admin");
31
+
32
+        before((request, response) -> {
33
+            String user = request.queryParams("user");
34
+            String password = request.queryParams("password");
35
+
36
+            String dbPassword = usernamePasswords.get(user);
37
+            if (!(password != null && password.equals(dbPassword))) {
38
+                halt(401, "You are not welcome here!!!");
39
+            }
40
+        });
41
+
42
+        before("/hello", (request, response) -> response.header("Foo", "Set by second before filter"));
43
+
44
+        get("/hello", (request, response) -> "Hello World!");
45
+
46
+        after("/hello", (request, response) -> response.header("spark", "added by after-filter"));
47
+
48
+        afterAfter("/hello", (request, response) -> response.header("finally", "executed even if exception is throw"));
49
+
50
+        afterAfter((request, response) -> response.header("finally", "executed after any route even if exception is throw"));
51
+    }
52
+}

+ 32
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/FilterExampleAttributes.java View File

@@ -0,0 +1,32 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.after;
4
+import static spark.Spark.get;
5
+
6
+/**
7
+ * Example showing the use of attributes
8
+ */
9
+public class FilterExampleAttributes {
10
+
11
+    public static void main(String[] args) {
12
+        get("/hi", (request, response) -> {
13
+            request.attribute("foo", "bar");
14
+            return null;
15
+        });
16
+
17
+        after("/hi", (request, response) -> {
18
+            for (String attr : request.attributes()) {
19
+                System.out.println("attr: " + attr);
20
+            }
21
+        });
22
+
23
+        after("/hi", (request, response) -> {
24
+            Object foo = request.attribute("foo");
25
+            response.body(asXml("foo", foo));
26
+        });
27
+    }
28
+
29
+    private static String asXml(String name, Object value) {
30
+        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><" + name +">" + value + "</"+ name + ">";
31
+    }
32
+}

+ 21
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/FreeMarkerExample.java View File

@@ -0,0 +1,21 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.get;
4
+import static spark.Spark.modelAndView;
5
+import java.util.HashMap;
6
+import java.util.Map;
7
+
8
+public class FreeMarkerExample {
9
+
10
+    public static void main(String args[]) {
11
+
12
+        get("/hello", (request, response) -> {
13
+            Map<String, Object> attributes = new HashMap<>();
14
+            attributes.put("message", "Hello FreeMarker World");
15
+
16
+            // The hello.ftl file is located in directory:
17
+            // src/test/resources/spark/examples/templateview/freemarker
18
+            return modelAndView(attributes, "hello.ftl");
19
+        }, new FreeMarkerTemplateEngine());
20
+    }
21
+}

+ 36
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/FreeMarkerTemplateEngine.java View File

@@ -0,0 +1,36 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+import spark.TemplateEngine;
6
+
7
+public class FreeMarkerTemplateEngine extends TemplateEngine {
8
+
9
+    private Configuration configuration;
10
+
11
+    protected FreeMarkerTemplateEngine() {
12
+        this.configuration = createFreemarkerConfiguration();
13
+    }
14
+
15
+    @Override
16
+    public String render(ModelAndView modelAndView) {
17
+        try {
18
+            StringWriter stringWriter = new StringWriter();
19
+
20
+            Template template = configuration.getTemplate(modelAndView.getViewName());
21
+            template.process(modelAndView.getModel(), stringWriter);
22
+
23
+            return stringWriter.toString();
24
+        } catch (IOException e) {
25
+            throw new IllegalArgumentException(e);
26
+        } catch (TemplateException e) {
27
+            throw new IllegalArgumentException(e);
28
+        }
29
+    }
30
+
31
+    private Configuration createFreemarkerConfiguration() {
32
+        Configuration retVal = new Configuration();
33
+        retVal.setClassForTemplateLoading(FreeMarkerTemplateEngine.class, "freemarker");
34
+        return retVal;
35
+    }
36
+}

+ 24
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/HelloWorld.java View File

@@ -0,0 +1,24 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+/**
6
+ * <pre>
7
+ * kr.co.swh.lecture.opensource.sparkjava 
8
+ * HelloWorld.java
9
+ *
10
+ * 설명 :	HelloWorld - spark tiny framework
11
+ * https://github.com/perwendel/spark
12
+ * 
13
+ * </pre>
14
+ * 
15
+ * @since : 2019. 11. 17
16
+ * @author : tobby48
17
+ * @version : v1.0
18
+ */
19
+public class HelloWorld {
20
+
21
+	public static void main(String[] arg){
22
+		get("/hello", (request, response) -> "Hello World!");
23
+	}
24
+}

+ 13
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/JsonAcceptTypeExample.java View File

@@ -0,0 +1,13 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+public class JsonAcceptTypeExample {
6
+
7
+    public static void main(String args[]) {
8
+
9
+        //Running curl -i -H "Accept: application/json" http://localhost:4567/hello json message is read.
10
+        //Running curl -i -H "Accept: text/html" http://localhost:4567/hello HTTP 404 error is thrown.
11
+        get("/hello", "application/json", (request, response) -> "{\"message\": \"Hello World\"}");
12
+    }
13
+} 

+ 14
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/JsonTransformer.java View File

@@ -0,0 +1,14 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import com.google.gson.Gson;
4
+import spark.ResponseTransformer;
5
+
6
+public class JsonTransformer implements ResponseTransformer {
7
+
8
+	private Gson gson = new Gson();
9
+
10
+	@Override
11
+	public String render(Object model) {
12
+		return gson.toJson(model);
13
+	}
14
+}

+ 46
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/SimpleExample.java View File

@@ -0,0 +1,46 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+/**
6
+ * A simple example just showing some basic functionality
7
+ */
8
+public class SimpleExample {
9
+
10
+    public static void main(String[] args) {
11
+
12
+        //  port(5678); <- Uncomment this if you want spark to listen to port 5678 instead of the default 4567
13
+
14
+    	port(5678);
15
+    	
16
+        get("/hello", (request, response) -> "Hello World!");
17
+
18
+        post("/hello", (request, response) ->
19
+            "Hello World: " + request.body()
20
+        );
21
+
22
+        get("/private", (request, response) -> {
23
+            response.status(401);
24
+            return "Go Away!!!";
25
+        });
26
+
27
+        get("/users/:name", (request, response) -> "Selected user: " + request.params(":name"));
28
+
29
+        get("/news/:section", (request, response) -> {
30
+            response.type("text/xml");
31
+            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><news>" + request.params("section") + "</news>";
32
+        });
33
+
34
+        get("/protected", (request, response) -> {
35
+            halt(403, "I don't think so!!!");
36
+            return null;
37
+        });
38
+
39
+        get("/redirect", (request, response) -> {
40
+            response.redirect("/news/world");
41
+            return null;
42
+        });
43
+
44
+        get("/", (request, response) -> "root");
45
+    }
46
+}

+ 15
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/StaticResources.java View File

@@ -0,0 +1,15 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+public class StaticResources {
6
+
7
+    public static void main(String[] args) {
8
+
9
+        // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes.
10
+        // When using Maven, the "/public" folder is assumed to be in "/main/resources"
11
+        staticFileLocation("/public");
12
+
13
+        get("/hello", (request, response) -> "Hello World!");
14
+    }
15
+}

+ 12
- 0
src/main/java/kr/co/swh/lecture/opensource/sparkjava/TransformerExample.java View File

@@ -0,0 +1,12 @@
1
+package kr.co.swh.lecture.opensource.sparkjava;
2
+
3
+import static spark.Spark.*;
4
+
5
+public class TransformerExample {
6
+
7
+    public static void main(String args[]) {
8
+        get("/hello", "application/json", (request, response) -> {
9
+            return new MyMessage("Hello World");
10
+        }, new JsonTransformer());
11
+    }
12
+}