#1 woat the boolean

오픈
woat woat/YouAreEll:master 에서 master 로 5 commits 를 머지하려 합니다

+ 0
- 18
Client/Client.iml 파일 보기

@@ -1,18 +0,0 @@
1
-<?xml version="1.0" encoding="UTF-8"?>
2
-<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
3
-  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">
4
-    <output url="file://$MODULE_DIR$/target/classes" />
5
-    <output-test url="file://$MODULE_DIR$/target/test-classes" />
6
-    <content url="file://$MODULE_DIR$">
7
-      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
8
-      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
9
-      <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
10
-      <excludeFolder url="file://$MODULE_DIR$/target" />
11
-    </content>
12
-    <orderEntry type="inheritedJdk" />
13
-    <orderEntry type="sourceFolder" forTests="false" />
14
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.6" level="project" />
15
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.8.0" level="project" />
16
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.6" level="project" />
17
-  </component>
18
-</module>

+ 0
- 23
Client/src/main/java/YouAreEll.java 파일 보기

@@ -1,23 +0,0 @@
1
-public class YouAreEll {
2
-
3
-    YouAreEll() {
4
-    }
5
-
6
-    public static void main(String[] args) {
7
-        YouAreEll urlhandler = new YouAreEll();
8
-        System.out.println(urlhandler.MakeURLCall("/ids", "GET", ""));
9
-        System.out.println(urlhandler.MakeURLCall("/messages", "GET", ""));
10
-    }
11
-
12
-    public String get_ids() {
13
-        return MakeURLCall("/ids", "GET", "");
14
-    }
15
-
16
-    public String get_messages() {
17
-        return MakeURLCall("/messages", "GET", "");
18
-    }
19
-
20
-    public String MakeURLCall(String mainurl, String method, String jpayload) {
21
-        return "nada";
22
-    }
23
-}

+ 0
- 15
YouAreEll.iml 파일 보기

@@ -1,15 +0,0 @@
1
-<?xml version="1.0" encoding="UTF-8"?>
2
-<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
3
-  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">
4
-    <output url="file://$MODULE_DIR$/target/classes" />
5
-    <output-test url="file://$MODULE_DIR$/target/test-classes" />
6
-    <content url="file://$MODULE_DIR$">
7
-      <excludeFolder url="file://$MODULE_DIR$/target" />
8
-    </content>
9
-    <orderEntry type="inheritedJdk" />
10
-    <orderEntry type="sourceFolder" forTests="false" />
11
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.6" level="project" />
12
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.8.0" level="project" />
13
-    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.6" level="project" />
14
-  </component>
15
-</module>

+ 155
- 0
go/controllers/controllers.go 파일 보기

@@ -0,0 +1,155 @@
1
+package controllers
2
+
3
+import (
4
+	"bytes"
5
+	"encoding/json"
6
+	"fmt"
7
+	"io/ioutil"
8
+	"log"
9
+	"net/http"
10
+)
11
+
12
+type User struct {
13
+	Userid string `json:"userid"`
14
+	Name   string `json:"name"`
15
+	Github string `json:"github"`
16
+}
17
+
18
+type Msg struct {
19
+	Sequence  string `json:"sequence,omitempty"`
20
+	Timestamp string `json:"timestamp,omitempty"`
21
+	Fromid    string `json:"fromid"`
22
+	Toid      string `json:"toid"`
23
+	Message   string `json:"message"`
24
+}
25
+
26
+// All HTTP methods will take a slug and return a []byte.
27
+// The specific utility handlers will take the []byte and
28
+// marshal them to the proper struct.
29
+
30
+func get(slug string) []byte {
31
+	url := fmt.Sprintf("http://zipcode.rocks:8085/%s", slug)
32
+	res, err := http.Get(url)
33
+	if err != nil {
34
+		log.Fatal(err)
35
+	}
36
+	defer res.Body.Close()
37
+
38
+	resData, err := ioutil.ReadAll(res.Body)
39
+	if err != nil {
40
+		log.Fatal(err)
41
+	}
42
+
43
+	return resData
44
+}
45
+
46
+func post(slug string, data []byte) {
47
+	url := fmt.Sprintf("http://zipcode.rocks:8085/%s", slug)
48
+	res, err := http.Post(url, "application/json", bytes.NewBuffer(data))
49
+	if err != nil {
50
+		log.Fatal(err)
51
+	}
52
+	defer res.Body.Close()
53
+}
54
+
55
+func put(slug string, data []byte) {
56
+	var client = &http.Client{}
57
+	url := fmt.Sprintf("http://zipcode.rocks:8085/%s", slug)
58
+	req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(data))
59
+	if err != nil {
60
+		log.Fatal(err)
61
+	}
62
+	res, err := client.Do(req)
63
+	if err != nil {
64
+		log.Fatal(err)
65
+	}
66
+	defer res.Body.Close()
67
+}
68
+
69
+func doesUserExist(github string) bool {
70
+	resBody := get("ids/" + github)
71
+	s := string(resBody[:])
72
+	// A length of 2 denotes a user not found.
73
+	return len(s) != 2
74
+}
75
+
76
+// ids handlers
77
+func GetIds() []User {
78
+	resData := get("ids")
79
+	var users []User
80
+	json.Unmarshal(resData, &users)
81
+	return users
82
+}
83
+
84
+func PostOrPutIds(name, github string) {
85
+	if doesUserExist(github) {
86
+		PutIds(name, github)
87
+	} else {
88
+		PostIds(name, github)
89
+	}
90
+}
91
+
92
+func PostIds(name, github string) {
93
+	user := User{"", name, github}
94
+	j, err := json.Marshal(&user)
95
+	if err != nil {
96
+		log.Fatal(err)
97
+	}
98
+	post("ids", j)
99
+}
100
+
101
+func PutIds(name, github string) {
102
+	res := get("ids/" + github)
103
+	var id string
104
+	json.Unmarshal(res, &id)
105
+	user := User{id, name, github}
106
+	j, err := json.Marshal(&user)
107
+	if err != nil {
108
+		log.Fatal(err)
109
+	}
110
+	put("ids", j)
111
+}
112
+
113
+// messages handlers
114
+func GetMsg() []Msg {
115
+	resData := get("messages")
116
+	var msgs []Msg
117
+	json.Unmarshal(resData, &msgs)
118
+	return msgs
119
+}
120
+
121
+func ServeMsg(last []byte) ([]Msg, []byte) {
122
+	resData := get("messages")
123
+	if bytes.Equal(resData, last) {
124
+		return nil, nil
125
+	}
126
+	var msgs []Msg
127
+	json.Unmarshal(resData, &msgs)
128
+	return msgs, resData
129
+}
130
+
131
+func GetMsgById(github string) []Msg {
132
+	resData := get("ids/" + github + "/messages")
133
+	var msgs []Msg
134
+	json.Unmarshal(resData, &msgs)
135
+	return msgs
136
+}
137
+
138
+// send handlers
139
+func PostSend(github, message string) {
140
+	m := Msg{Fromid: github, Toid: "", Message: message}
141
+	j, err := json.Marshal(&m)
142
+	if err != nil {
143
+		log.Fatal(err)
144
+	}
145
+	post("ids/"+github+"/messages", j)
146
+}
147
+
148
+func PostSendToGithub(fromGithub, toGithub, message string) {
149
+	m := Msg{Fromid: fromGithub, Toid: toGithub, Message: message}
150
+	j, err := json.Marshal(&m)
151
+	if err != nil {
152
+		log.Fatal(err)
153
+	}
154
+	post("ids/"+fromGithub+"/messages", j)
155
+}

+ 3
- 0
go/controllers/controllers_test.go 파일 보기

@@ -0,0 +1,3 @@
1
+package controllers
2
+
3
+import ()

+ 89
- 0
go/main.go 파일 보기

@@ -0,0 +1,89 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	prompt "github.com/c-bata/go-prompt"
6
+	cont "github.com/woat/youareell/controllers"
7
+	out "github.com/woat/youareell/output"
8
+	srv "github.com/woat/youareell/service"
9
+	"strings"
10
+)
11
+
12
+func completer(d prompt.Document) []prompt.Suggest {
13
+	if len(strings.Split(d.GetWordBeforeCursorUntilSeparator(">"), " ")) > 2 {
14
+		return nil
15
+	}
16
+	s := []prompt.Suggest{
17
+		{Text: "ids", Description: "[<your_name> <github_id]"},
18
+		{Text: "messages", Description: "[<github_id>]"},
19
+		{Text: "send", Description: "{<your_name> <message_body> | <your_name> <message_body> to <your_friend>}"},
20
+	}
21
+	return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
22
+}
23
+
24
+func start(origin chan bool) {
25
+	for {
26
+		x := prompt.Input(">>> ", completer,
27
+			prompt.OptionPrefixTextColor(prompt.Cyan),
28
+			prompt.OptionSuggestionBGColor(prompt.Red),
29
+			prompt.OptionDescriptionBGColor(prompt.Green),
30
+			prompt.OptionSelectedSuggestionBGColor(prompt.DarkRed),
31
+			prompt.OptionSuggestionTextColor(prompt.Black),
32
+			prompt.OptionSelectedDescriptionBGColor(prompt.DarkGreen),
33
+			prompt.OptionPreviewSuggestionTextColor(prompt.Red),
34
+		)
35
+		s := out.ParseArgs(x)
36
+		if len(s) == 0 {
37
+			continue
38
+		}
39
+		if s[0] == "ids" {
40
+			// Post the NAME :: GITHUB
41
+			if len(s) > 1 {
42
+				cont.PostOrPutIds(s[1], s[2])
43
+				continue
44
+			}
45
+			// Get DBs if they didn't pass anything more.
46
+			out.PrintUsers(cont.GetIds())
47
+			continue
48
+		}
49
+		if s[0] == "messages" {
50
+			// Get id messages
51
+			if len(s) == 2 {
52
+				out.PrintMsgs(cont.GetMsgById(s[1]))
53
+				continue
54
+			}
55
+			out.PrintMsgs(cont.GetMsg())
56
+			continue
57
+		}
58
+		if s[0] == "send" {
59
+			// Send to main timeline
60
+			if len(s) == 3 {
61
+				cont.PostSend(s[1], s[2])
62
+				origin <- true
63
+			}
64
+			// Send to another github id
65
+			if len(s) == 5 {
66
+				cont.PostSendToGithub(s[1], s[4], s[2])
67
+				origin <- true
68
+			}
69
+			continue
70
+		}
71
+		if s[0] == "cmd" {
72
+			fmt.Printf("Available commands:\n")
73
+			fmt.Printf("%5s ids [<your_name> <github_id>]\n", "")
74
+			fmt.Printf("%5s messages [<github_id>]\n", "")
75
+			fmt.Printf("%5s send {<your_name> <message_body> | <your_name> <message_body> to <your_friend>}\n", "")
76
+			continue
77
+		}
78
+		if s[0] == "quit" {
79
+			break
80
+		}
81
+		fmt.Printf("Command: %s not recognized. Type \"cmd\" for a list of commands.\n", s)
82
+	}
83
+}
84
+
85
+func main() {
86
+	origin := make(chan bool, 1)
87
+	go srv.NotificationService(origin)
88
+	start(origin)
89
+}

+ 49
- 0
go/output/output.go 파일 보기

@@ -0,0 +1,49 @@
1
+package output
2
+
3
+import (
4
+	"bytes"
5
+	"fmt"
6
+	c "github.com/woat/youareell/controllers"
7
+	"regexp"
8
+)
9
+
10
+func ParseArgs(s string) []string {
11
+	r := regexp.MustCompile("'.+'|\".+\"|\\S+")
12
+	arr := r.FindAllString(s, -1)
13
+	return arr
14
+}
15
+
16
+func ParseMsg(m c.Msg) string {
17
+	var pm string
18
+	if m.Fromid == m.Toid || m.Toid == "" {
19
+		pm = fmt.Sprintf("%v: %v", m.Fromid, m.Message)
20
+	} else {
21
+		pm = fmt.Sprintf("%v: @%v %v", m.Fromid, m.Toid, m.Message)
22
+	}
23
+	return pm
24
+}
25
+
26
+func ParseUser(u c.User) string {
27
+	pu := fmt.Sprintf("Name: %v - Github: %v", u.Name, u.Github)
28
+	return pu
29
+}
30
+
31
+func PrintUsers(u []c.User) string {
32
+	var buffer bytes.Buffer
33
+	for _, e := range u {
34
+		buffer.WriteString(ParseUser(e) + "\n")
35
+	}
36
+
37
+	fmt.Println(buffer.String())
38
+	return buffer.String()
39
+}
40
+
41
+func PrintMsgs(m []c.Msg) string {
42
+	var buffer bytes.Buffer
43
+	for _, e := range m {
44
+		buffer.WriteString(ParseMsg(e) + "\n")
45
+	}
46
+
47
+	fmt.Println(buffer.String())
48
+	return buffer.String()
49
+}

+ 82
- 0
go/output/output_test.go 파일 보기

@@ -0,0 +1,82 @@
1
+package output
2
+
3
+import (
4
+	c "github.com/woat/youareell/controllers"
5
+	"testing"
6
+)
7
+
8
+type Msg struct {
9
+	Sequence  string `json:"sequence"`
10
+	Timestamp string `json:"timestamp"`
11
+	Fromid    string `json:"fromid"`
12
+	Toid      string `json:"toid"`
13
+	Message   string `json:"message"`
14
+}
15
+
16
+func TestParseArgs(t *testing.T) {
17
+	var stdargs = []struct {
18
+		in       string
19
+		expected int
20
+	}{
21
+		{"ids", 1},
22
+		{"messages your_github_id", 2},
23
+		{"ids your_name your_github_id", 3},
24
+		{"send your_github_id 'my string message' to some_friend_githubid", 5},
25
+	}
26
+	for _, arg := range stdargs {
27
+		actual := len(ParseArgs(arg.in))
28
+		if actual != arg.expected {
29
+			t.Errorf("ParseArgs(%s) got: %v, want: %v => arr: %v", arg.in, actual, arg.expected, ParseArgs(arg.in)[3])
30
+		}
31
+	}
32
+}
33
+
34
+func TestParseMsg(t *testing.T) {
35
+	var stdargs = []struct {
36
+		in       c.Msg
37
+		expected string
38
+	}{
39
+		{c.Msg{Fromid: "fromid", Toid: "toid", Message: "msg"}, "fromid: @toid msg"},
40
+		{c.Msg{Fromid: "sameid", Toid: "sameid", Message: "msg"}, "sameid: msg"},
41
+		{c.Msg{Fromid: "sameid", Toid: "", Message: "msg"}, "sameid: msg"},
42
+	}
43
+	for _, arg := range stdargs {
44
+		actual := ParseMsg(arg.in)
45
+		if actual != arg.expected {
46
+			t.Errorf("ParseMsg(%v) got: '%v', want: '%v'", arg.in, actual, arg.expected)
47
+		}
48
+	}
49
+}
50
+
51
+func TestParseUser(t *testing.T) {
52
+	var stdargs = []struct {
53
+		in       c.User
54
+		expected string
55
+	}{
56
+		{c.User{Name: "test", Github: "test"}, "Name: test - Github: test"},
57
+	}
58
+
59
+	for _, arg := range stdargs {
60
+		actual := ParseUser(arg.in)
61
+		if actual != arg.expected {
62
+			t.Errorf("ParseUser(%v) got: '%v', want: '%v'", arg.in, actual, arg.expected)
63
+		}
64
+	}
65
+}
66
+
67
+func TestPrintUser(t *testing.T) {
68
+	var stdargs = []struct {
69
+		in       []c.User
70
+		expected string
71
+	}{
72
+		{[]c.User{{Name: "test", Github: "test"}}, "Name: test - Github: test\n"},
73
+		{[]c.User{{Name: "test", Github: "test"}, {Name: "test1", Github: "test1"}}, "Name: test - Github: test\nName: test1 - Github: test1\n"},
74
+	}
75
+
76
+	for _, arg := range stdargs {
77
+		actual := PrintUsers(arg.in)
78
+		if actual != arg.expected {
79
+			t.Errorf("ParseUser(%v) got: '%v', want: '%v'", arg.in, actual, arg.expected)
80
+		}
81
+	}
82
+}

+ 44
- 0
go/service/service.go 파일 보기

@@ -0,0 +1,44 @@
1
+package service
2
+
3
+import (
4
+	"fmt"
5
+	c "github.com/woat/youareell/controllers"
6
+	"time"
7
+)
8
+
9
+var last []byte
10
+
11
+func SetLastBytes() {
12
+	_, bytes := c.ServeMsg(last)
13
+	last = bytes
14
+}
15
+
16
+func NotificationService(originIp chan bool) {
17
+	SetLastBytes()
18
+	for {
19
+		select {
20
+		case <-originIp:
21
+			_, bytes := c.ServeMsg(last)
22
+			if bytes == nil {
23
+				continue
24
+			}
25
+			fmt.Print("\033[s")
26
+			fmt.Print("Message sent.")
27
+			fmt.Print("\033[u")
28
+			last = bytes
29
+			continue
30
+		default:
31
+		}
32
+
33
+		_, bytes := c.ServeMsg(last)
34
+		if bytes == nil {
35
+			time.Sleep(time.Second * 2)
36
+			continue
37
+		}
38
+		last = bytes
39
+		fmt.Print("\033[s")
40
+		fmt.Print("\033[A\r" + "New unread message!")
41
+		fmt.Print("\033[u")
42
+		time.Sleep(time.Second * 2)
43
+	}
44
+}

BIN
go/youareell 파일 보기


Client/pom.xml → java/Client/pom.xml 파일 보기


+ 64
- 0
java/Client/src/main/java/Message.java 파일 보기

@@ -0,0 +1,64 @@
1
+public class Message implements SimplePrint {
2
+    private String sequence;
3
+    private String timestamp;
4
+    private String fromid;
5
+    private String toid;
6
+    private String message;
7
+
8
+    public Message() {}
9
+
10
+    public Message(String fromid, String message) {
11
+        this.fromid = fromid;
12
+        this.message = message;
13
+    }
14
+
15
+    public Message(String fromid, String toid, String message) {
16
+        this.fromid = fromid;
17
+        this.toid = toid;
18
+        this.message = message;
19
+    }
20
+
21
+    public String getSequence() {
22
+        return sequence;
23
+    }
24
+
25
+    public void setSequence(String sequence) {
26
+        this.sequence = sequence;
27
+    }
28
+
29
+    public String getTimestamp() {
30
+        return timestamp;
31
+    }
32
+
33
+    public void setTimestamp(String timestamp) {
34
+        this.timestamp = timestamp;
35
+    }
36
+
37
+    public String getFromid() {
38
+        return fromid;
39
+    }
40
+
41
+    public void setFromid(String fromid) {
42
+        this.fromid = fromid;
43
+    }
44
+
45
+    public String getToid() {
46
+        return toid;
47
+    }
48
+
49
+    public void setToid(String toid) {
50
+        this.toid = toid;
51
+    }
52
+
53
+    public String getMessage() {
54
+        return message;
55
+    }
56
+
57
+    public void setMessage(String message) {
58
+        this.message = message;
59
+    }
60
+
61
+    public void print() {
62
+        System.out.println("From: " + getFromid() + " To: " + getToid() + " Message: " + getMessage());
63
+    }
64
+}

+ 3
- 0
java/Client/src/main/java/SimplePrint.java 파일 보기

@@ -0,0 +1,3 @@
1
+public interface SimplePrint {
2
+    void print();
3
+}

Client/src/main/java/SimpleShell.java → java/Client/src/main/java/SimpleShell.java 파일 보기

@@ -1,16 +1,35 @@
1
+import com.fasterxml.jackson.core.type.TypeReference;
2
+import com.fasterxml.jackson.databind.ObjectMapper;
3
+import sun.java2d.pipe.SpanShapeRenderer;
4
+
1 5
 import java.io.BufferedReader;
2 6
 import java.io.IOException;
3 7
 import java.io.InputStream;
4 8
 import java.io.InputStreamReader;
9
+import java.lang.reflect.Array;
5 10
 import java.util.ArrayList;
11
+import java.util.Arrays;
6 12
 import java.util.List;
13
+import java.util.regex.Matcher;
14
+import java.util.regex.Pattern;
7 15
 
8 16
 public class SimpleShell {
9 17
 
10 18
 
11
-    public static void prettyPrint(String output) {
12
-        // yep, make an effort to format things nicely, eh?
13
-        System.out.println(output);
19
+    public static <T> void prettyPrint(String output, Class<T> data) throws IOException {
20
+        ObjectMapper mapper = new ObjectMapper();
21
+        if (data.getSimpleName().equals("User")) {
22
+            List<User> myObjects = mapper.readValue(output, new TypeReference<List<User>>(){});
23
+            for (User e : myObjects) {
24
+                e.print();
25
+            }
26
+        }
27
+        if (data.getSimpleName().equals("Message")) {
28
+            List<Message> myObjects = mapper.readValue(output, new TypeReference<List<Message>>(){});
29
+            for (Message e : myObjects) {
30
+                e.print();
31
+            }
32
+        }
14 33
     }
15 34
     public static void main(String[] args) throws java.io.IOException {
16 35
 
@@ -22,17 +41,19 @@ public class SimpleShell {
22 41
         ProcessBuilder pb = new ProcessBuilder();
23 42
         List<String> history = new ArrayList<String>();
24 43
         int index = 0;
25
-        //we break out with <ctrl c>
26 44
         while (true) {
27
-            //read what the user enters
28 45
             System.out.println("cmd? ");
29
-            commandLine = console.readLine();
30 46
 
31
-            //input parsed into array of strings(command and arguments)
32
-            String[] commands = commandLine.split(" ");
47
+            commandLine = console.readLine();
33 48
             List<String> list = new ArrayList<String>();
49
+            Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
50
+            Matcher regexMatcher = regex.matcher(commandLine);
51
+            while (regexMatcher.find()) {
52
+                list.add(regexMatcher.group());
53
+            }
54
+
55
+            history.addAll(list);
34 56
 
35
-            //if the user entered a return, just loop again
36 57
             if (commandLine.equals(""))
37 58
                 continue;
38 59
             if (commandLine.equals("exit")) {
@@ -40,38 +61,43 @@ public class SimpleShell {
40 61
                 break;
41 62
             }
42 63
 
43
-            //loop through to see if parsing worked
44
-            for (int i = 0; i < commands.length; i++) {
45
-                //System.out.println(commands[i]); //***check to see if parsing/split worked***
46
-                list.add(commands[i]);
47
-
48
-            }
49
-            System.out.print(list); //***check to see if list was added correctly***
50
-            history.addAll(list);
51 64
             try {
52
-                //display history of shell with index
53 65
                 if (list.get(list.size() - 1).equals("history")) {
54 66
                     for (String s : history)
55 67
                         System.out.println((index++) + " " + s);
56 68
                     continue;
57 69
                 }
58 70
 
59
-                // Specific Commands.
60
-
61
-                // ids
62
-                if (list.contains("ids")) {
63
-                    String results = webber.get_ids();
64
-                    SimpleShell.prettyPrint(results);
71
+                if (list.get(0).equals("ids")) {
72
+                    if (list.size() > 1) {
73
+                        User u = new User(list.get(1), list.get(2));
74
+                        prettyPrint(webber.postOrPutIds(u), User.class);
75
+                        continue;
76
+                    }
77
+                    prettyPrint(webber.getIds(), User.class);
65 78
                     continue;
66 79
                 }
67 80
 
68
-                // messages
69
-                if (list.contains("messages")) {
70
-                    String results = webber.get_messages();
71
-                    SimpleShell.prettyPrint(results);
81
+                if (list.get(0).equals("messages")) {
82
+                    if (list.size() == 2) {
83
+                        prettyPrint(webber.getMessagesMine(list.get(1)), Message.class);
84
+                        continue;
85
+                    }
86
+                    prettyPrint(webber.getMessages(), Message.class);
72 87
                     continue;
73 88
                 }
74
-                // you need to add a bunch more.
89
+
90
+                if (list.get(0).equals("send")) {
91
+                    if (list.size() == 3) {
92
+                        Message m = new Message(list.get(1), list.get(2));
93
+                        prettyPrint(webber.postMessages(m), Message.class);
94
+                        continue;
95
+                    } else {
96
+                        Message m = new Message(list.get(1), list.get(4), list.get(2));
97
+                        prettyPrint(webber.postMessages(m), Message.class);
98
+                        continue;
99
+                    }
100
+                }
75 101
 
76 102
                 //!! command returns the last command in history
77 103
                 if (list.get(list.size() - 1).equals("!!")) {
@@ -106,6 +132,7 @@ public class SimpleShell {
106 132
             //catch ioexception, output appropriate message, resume waiting for input
107 133
             catch (IOException e) {
108 134
                 System.out.println("Input Error, Please try again!");
135
+                System.out.println(e);
109 136
             }
110 137
             // So what, do you suppose, is the meaning of this comment?
111 138
             /** The steps are:

+ 46
- 0
java/Client/src/main/java/User.java 파일 보기

@@ -0,0 +1,46 @@
1
+public class User implements SimplePrint {
2
+    private String userid;
3
+    private String name;
4
+    private String github;
5
+
6
+    public User() {}
7
+
8
+    public User(String name, String github) {
9
+        this.name = name;
10
+        this.github = github;
11
+    }
12
+
13
+    public User(String userid, String name, String github) {
14
+        this.userid = userid;
15
+        this.name = name;
16
+        this.github = github;
17
+    }
18
+
19
+    public String getUserid() {
20
+        return userid;
21
+    }
22
+
23
+    public void setUserid(String userid) {
24
+        this.userid = userid;
25
+    }
26
+
27
+    public String getName() {
28
+        return name;
29
+    }
30
+
31
+    public void setName(String name) {
32
+        this.name = name;
33
+    }
34
+
35
+    public String getGithub() {
36
+        return github;
37
+    }
38
+
39
+    public void setGithub(String github) {
40
+        this.github = github;
41
+    }
42
+
43
+    public void print() {
44
+        System.out.println("Name : " + getName() + " Github: " + getGithub());
45
+    }
46
+}

+ 92
- 0
java/Client/src/main/java/YouAreEll.java 파일 보기

@@ -0,0 +1,92 @@
1
+import com.fasterxml.jackson.annotation.JsonInclude;
2
+import com.fasterxml.jackson.core.JsonProcessingException;
3
+import com.fasterxml.jackson.databind.ObjectMapper;
4
+import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
5
+import okhttp3.*;
6
+
7
+import java.io.IOException;
8
+
9
+public class YouAreEll {
10
+    private OkHttpClient client = new OkHttpClient();
11
+    private final String BASE_URL = "http://zipcode.rocks:8085/";
12
+    private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
13
+    private ObjectMapper objectMapper = new ObjectMapper();
14
+
15
+    YouAreEll() {
16
+    }
17
+
18
+    public ResponseBody get(String slug) throws IOException {
19
+        Response res = client.newCall(
20
+                new Request
21
+                        .Builder()
22
+                        .url(BASE_URL + slug)
23
+                        .build()
24
+        ).execute();
25
+        return res.body();
26
+    }
27
+
28
+    public ResponseBody post(String slug, String payload) throws IOException {
29
+        Response res = client.newCall(
30
+                new Request
31
+                        .Builder()
32
+                        .url(BASE_URL + slug)
33
+                        .post(RequestBody.create(JSON, payload))
34
+                        .build()
35
+        ).execute();
36
+        return res.body();
37
+    }
38
+
39
+    public ResponseBody put(String slug, String payload) throws IOException {
40
+        Response res = client.newCall(
41
+                new Request
42
+                        .Builder()
43
+                        .url(BASE_URL + slug)
44
+                        .put(RequestBody.create(JSON, payload))
45
+                        .build()
46
+        ).execute();
47
+        return res.body();
48
+    }
49
+
50
+    public String getIds() throws IOException {
51
+        return get("/ids").string();
52
+    }
53
+
54
+    public String postIds(User payload) throws IOException {
55
+        ResponseBody res = post("ids", objectMapper.writeValueAsString(payload));
56
+        return res.string();
57
+    }
58
+
59
+    public String putIds(User payload) throws IOException {
60
+        ResponseBody b = get("ids/" + payload.getGithub());
61
+        String bod = b.string();
62
+        payload.setUserid(bod);
63
+        ResponseBody res = put("ids", objectMapper.writeValueAsString(payload));
64
+        return res.string();
65
+    }
66
+
67
+    public Boolean doesUserExist(String github) throws IOException {
68
+        ResponseBody b = get("ids/" + github);
69
+        return b.string().length() > 2;
70
+    }
71
+
72
+    public String postOrPutIds(User payload) throws IOException {
73
+        if (doesUserExist(payload.getGithub())) return putIds(payload);
74
+        return postIds(payload);
75
+    }
76
+
77
+    public String getMessages() throws IOException {
78
+        return get("messages").string();
79
+    }
80
+
81
+    public String getMessagesMine(String github) throws IOException {
82
+        return get("ids/"+github+"/messages").string();
83
+    }
84
+
85
+    public String getMessagesFromFriend(String from, String to) throws IOException {
86
+        return get("ids/"+from+"/from/"+to).string();
87
+    }
88
+
89
+    public String postMessages(Message payload) throws IOException {
90
+        return post("ids/"+payload.getFromid()+"/messages", objectMapper.writeValueAsString(payload)).string();
91
+    }
92
+}

README.md → java/README.md 파일 보기

@@ -23,7 +23,7 @@
23 23
 	* If you leave the `to id` field empty, the message is `to the world`.
24 24
 	* If you fill out the the JSON template with a valid github_id in the `to id` field of the JSON payload, then that message is addressed to that friend.
25 25
 	* Yes, all messages can be seen by users of the system.
26
-	* There are JSON templates below for both Ids and Messages.
26
+	* There are JSON templates below for both Ids and Message.
27 27
 
28 28
 
29 29
 
@@ -39,7 +39,7 @@ specific command.
39 39
 	* Each one of the command methods will then call a even lower-level method that makes a certain kind of HTTP request (GET, POST, PUT) to specific filled-in URL.
40 40
 
41 41
 * The Under-A-Rock Server can be reached at `http://zipcode.rocks:8085` Everyone uses the same server. 		
42
-	* There are two segments to the API and two kinds of commands in the shell, the ID segment and the Messages segment.
42
+	* There are two segments to the API and two kinds of commands in the shell, the ID segment and the Message segment.
43 43
 
44 44
 
45 45
 * You can explore several ways of doing the HTTP URL calls to the server, using the one of these:
@@ -93,7 +93,7 @@ If I type `cmd? ids Kris xt0fer` into the shell, your command processor creates
93 93
 and send it as the body of a POST request to  `http://zipcode.rocks:8085/ids/`
94 94
 
95 95
  
96
-## Messages
96
+## Message
97 97
 
98 98
 #### Message comands in shell
99 99
 in the shell
@@ -102,7 +102,7 @@ in the shell
102 102
 * `send your_github_id 'Hello World' ` should post a new message in the timeline
103 103
 * `send your_github_id 'my string message' to some_friend_githubid` should post a message to your friend from you on the timeline.
104 104
 
105
-the Messages API is:
105
+the Message API is:
106 106
 
107 107
 #### URL: /messages/
108 108
 * `GET` : Get last 20 msgs - returns an JSON array of message objects

pom.xml → java/pom.xml 파일 보기

@@ -14,6 +14,11 @@
14 14
 
15 15
     <dependencies>
16 16
         <dependency>
17
+            <groupId>com.squareup.okhttp3</groupId>
18
+            <artifactId>okhttp</artifactId>
19
+            <version>3.10.0</version>
20
+        </dependency>
21
+        <dependency>
17 22
             <groupId>com.fasterxml.jackson.core</groupId>
18 23
             <artifactId>jackson-databind</artifactId>
19 24
             <version>2.8.6</version>