-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleHttpServer.java
More file actions
156 lines (139 loc) · 6.49 KB
/
SimpleHttpServer.java
File metadata and controls
156 lines (139 loc) · 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SimpleHttpServer {
private static Logger logger = Logger.getLogger(SimpleHttpServer.class.getName());
public static void main(String[] args) throws IOException {
MotorController.initMotorController();
try {
HttpServer simpleHttpServer = HttpServer.create(new InetSocketAddress(5000), 0);
//log("Started on Port 5000");
HttpContext simpleHtpContext = simpleHttpServer.createContext("/");
//log("Created the HttpContext on \"/\"");
simpleHtpContext.setHandler(SimpleHttpServer::simpleHttpRequestHandler);
log("Starting Coordinate Receiver");
simpleHttpServer.start();
}catch (IOException ex){
logger.log(Level.SEVERE,"Encountered IOException. " + ex.getMessage());
}catch(Exception ex){
logger.log(Level.SEVERE, "Encountered Generic Java Exception. " + ex.getMessage());
}
}
private static void simpleHttpRequestHandler(HttpExchange simpleHttpExchange) throws IOException{
try {
URI simpleRequestURI = simpleHttpExchange.getRequestURI();
String receivedCoordinates = simpleRequestURI.toString();
//log("Recieved Request at " + receivedCoordinates);
String response = processSimpleRequest(simpleHttpExchange);
String simpleHttpResponse = response;
//log("Sending response: " + response + " to caller");
simpleHttpExchange.sendResponseHeaders(200, simpleHttpResponse.getBytes().length);
OutputStream simpleOutputStream = simpleHttpExchange.getResponseBody();
simpleOutputStream.write(simpleHttpResponse.getBytes());
simpleOutputStream.close();
}catch(IOException ex){
logger.log(Level.SEVERE, "Encountered IOException. " + ex.getMessage());
}catch(Exception ex){
logger.log(Level.SEVERE, "Encountered Generic Java Exception. " + ex.getMessage());
}
}
private static String processSimpleRequest(HttpExchange simpleHttpExchange){
String retval = null;
try{
// Get the Request Headers - typically, the browser sends these.
Headers simpleRequestHeaders = simpleHttpExchange.getRequestHeaders();
// Get the principal. When you need to make sure that it is just you that is accessing this URI
HttpPrincipal simpleHttpPrincipal = simpleHttpExchange.getPrincipal();
// How did you send your request - was it a GET, PUT, POST, PATCH, DELETE?
// Usually you use Get when sending parameters in the querystring http://<url>:<port>/?name=mike&command=move&x=300&y=0
String simpleRequestMethod = simpleHttpExchange.getRequestMethod();
// This is the URI that the client used to get to you
URI simpleRequestURI = simpleHttpExchange.getRequestURI();
// This is the querystring in the URI
String query = simpleRequestURI.getQuery();
//Commenting the below logging. Use it if you need it.
//Let us print the headers first to see what can be done with them ... always good to check for nulls first
if(simpleRequestHeaders!=null) {
for (String str : simpleRequestHeaders.keySet()) {
//log("HEADER: " + str);
}
}
//Let us print the Principal being used to access this endpoint, in case we need to authenticate / authorize later.
if(simpleHttpPrincipal!=null) {
//log("PRINCIPAL: " + simpleHttpPrincipal.toString());
}
//What is the method being used?
if(simpleRequestMethod!=null){
//log("METHOD: " + simpleRequestMethod);
}
//What is the URL Accessed?
if (simpleRequestURI != null) {
//log("URI: " + simpleRequestURI.toString());
}
if(query!=null && (query.length()>0)) {
//log("QUERY: " + query);
//Try to get the keys and values that were passed in the request and print them
Map<String, String> params = getQueryMap(query);
if (params != null) {
for (String key : params.keySet()) {
log(key + "=" + params.get(key));
}
}
String xValue, yValue;
Float xFinal, yFinal;
//String sName = params.getOrDefault("name","Unknown");
//String sCommand = params.getOrDefault("command","do nothing");
String xCoordinate = params.getOrDefault("x","0");
String yCoordinate = params.getOrDefault("y","0");
xCoordinate = query.substring((query.indexOf("X") + 2), query.indexOf("&"));
yCoordinate = query.substring((query.indexOf("Y") + 2));
retval = xCoordinate +","+ yCoordinate;
xValue = xCoordinate;
yValue = yCoordinate;
xFinal = Float.parseFloat(xValue);
yFinal = Float.parseFloat(yValue);
//log("motor starting");
try{
MotorController.speedAdapter(xFinal, yFinal);
} catch(Exception ex){
//log(ex.getMessage());
}
//log("motor finished");
}
else
{
retval = "No coordinates";
}
}catch(Exception ex){
logger.log(Level.WARNING, "Encountered Generic Java Exception. " + ex.getMessage());
}
return retval;
}
public static Map<String, String> getQueryMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
/**
* Used for Logging info to console
* You can also use logger.log(Level.NORMAL, <string>); but that will be more verbose so we only use logger for errors
* @param strs
*/
private static void log(String ... strs)
{
for (String str : strs) {
System.out.println(str);
}
}
}