aboutsummaryrefslogtreecommitdiff
path: root/src/org/traccar/web
diff options
context:
space:
mode:
authorAnton Tananaev <anton.tananaev@gmail.com>2015-12-01 15:20:05 +1300
committerAnton Tananaev <anton.tananaev@gmail.com>2015-12-01 15:20:05 +1300
commitef2ae4103726dae12a0153886219d4ac43d20ae0 (patch)
tree79291f74ce2631a4a9a176b7e510028e534a23d4 /src/org/traccar/web
parentc6692703c8099577cb86c3eace5d8d1bc11f212d (diff)
parent53f70085891cdb0feae56df8990c1245091352a1 (diff)
downloadtraccar-server-ef2ae4103726dae12a0153886219d4ac43d20ae0.tar.gz
traccar-server-ef2ae4103726dae12a0153886219d4ac43d20ae0.tar.bz2
traccar-server-ef2ae4103726dae12a0153886219d4ac43d20ae0.zip
Merge branch 'rest' into master
Diffstat (limited to 'src/org/traccar/web')
-rw-r--r--src/org/traccar/web/BaseServlet.java53
-rw-r--r--src/org/traccar/web/CommandServlet.java9
-rw-r--r--src/org/traccar/web/JsonConverter.java23
-rw-r--r--src/org/traccar/web/MainServlet.java8
-rw-r--r--src/org/traccar/web/WebServer.java23
5 files changed, 65 insertions, 51 deletions
diff --git a/src/org/traccar/web/BaseServlet.java b/src/org/traccar/web/BaseServlet.java
index 283edf1e5..d215c62d0 100644
--- a/src/org/traccar/web/BaseServlet.java
+++ b/src/org/traccar/web/BaseServlet.java
@@ -19,9 +19,10 @@ import org.traccar.helper.Log;
import java.io.IOException;
import java.io.Writer;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
import java.security.AccessControlException;
import java.util.Collection;
-import java.util.Map;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.json.JsonStructure;
@@ -32,20 +33,14 @@ import javax.servlet.http.HttpServletResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.util.CharsetUtil;
import org.traccar.Context;
-import org.traccar.helper.Authorization;
-import org.traccar.model.User;
public abstract class BaseServlet extends HttpServlet {
- public static final String USER_KEY = "user";
+ public static final String USER_ID_KEY = "user";
public static final String ALLOW_ORIGIN_VALUE = "*";
public static final String ALLOW_HEADERS_VALUE = "Origin, X-Requested-With, Content-Type, Accept";
public static final String ALLOW_METHODS_VALUE = "GET, POST, PUT, DELETE";
public static final String APPLICATION_JSON = "application/json";
- public static final String GET = "GET";
- public static final String POST = "POST";
- public static final String PUT = "PUT";
- public static final String DELETE = "DELETE";
@Override
protected final void service(
@@ -61,7 +56,8 @@ public abstract class BaseServlet extends HttpServlet {
if (allowed == null) {
resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ORIGIN_VALUE);
} else if (allowed.contains(origin)) {
- resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
+ String originSafe = URLEncoder.encode(origin, StandardCharsets.UTF_8.displayName());
+ resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, originSafe);
}
if (!handle(getCommand(req), req, resp)) {
@@ -70,7 +66,6 @@ public abstract class BaseServlet extends HttpServlet {
} catch (Exception error) {
if (error instanceof AccessControlException) {
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- resp.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, Authorization.WWW_AUTHENTICATE_VALUE);
} else if (error instanceof SecurityException) {
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
@@ -82,21 +77,11 @@ public abstract class BaseServlet extends HttpServlet {
String command, HttpServletRequest req, HttpServletResponse resp) throws Exception;
public long getUserId(HttpServletRequest req) throws Exception {
- String authorization = req.getHeader(HttpHeaders.Names.AUTHORIZATION);
- if (authorization != null && !authorization.isEmpty()) {
- Map<String, String> authMap = Authorization.parse(authorization);
- String username = authMap.get(Authorization.USERNAME);
- String password = authMap.get(Authorization.PASSWORD);
- User user = Context.getDataManager().login(username, password);
- if (user != null) {
- return user.getId();
- }
- }
- Long userId = (Long) req.getSession().getAttribute(USER_KEY);
- if (userId == null) {
- throw new AccessControlException("User not logged in");
+ Object userId = req.getSession().getAttribute(USER_ID_KEY);
+ if (userId != null) {
+ return (Long) userId;
}
- return userId;
+ throw new AccessControlException("User not logged in");
}
public void sendResponse(Writer writer, boolean success) throws IOException {
@@ -129,26 +114,12 @@ public abstract class BaseServlet extends HttpServlet {
writer.write(result.build().toString());
}
- private String getCommand(HttpServletRequest req) {
+ protected String getCommand(HttpServletRequest req) {
String command = req.getPathInfo();
if (command == null) {
- switch (req.getMethod()) {
- case GET:
- command = "/get";
- break;
- case POST:
- command = "/add";
- break;
- case PUT:
- command = "/update";
- break;
- case DELETE:
- command = "/remove";
- break;
- default:
- command = "";
- }
+ command = "";
}
return command;
}
+
}
diff --git a/src/org/traccar/web/CommandServlet.java b/src/org/traccar/web/CommandServlet.java
index 67bca2d57..d307913df 100644
--- a/src/org/traccar/web/CommandServlet.java
+++ b/src/org/traccar/web/CommandServlet.java
@@ -22,6 +22,7 @@ import javax.servlet.http.HttpServletResponse;
import org.traccar.Context;
import org.traccar.database.ActiveDevice;
import org.traccar.model.Command;
+import org.traccar.model.Device;
public class CommandServlet extends BaseServlet {
@@ -49,19 +50,17 @@ public class CommandServlet extends BaseServlet {
}
private void send(HttpServletRequest req, HttpServletResponse resp) throws Exception {
-
- Command command = JsonConverter.objectFromJson(req.getReader(), new Command());
- Context.getPermissionsManager().checkDevice(getUserId(req), command.getDeviceId());
+ Command command = JsonConverter.objectFromJson(req.getReader(), Command.class);
+ Context.getPermissionsManager().check(Device.class, getUserId(req), command.getDeviceId());
getActiveDevice(command.getDeviceId()).sendCommand(command);
sendResponse(resp.getWriter(), true);
}
private void raw(HttpServletRequest req, HttpServletResponse resp) throws Exception {
-
JsonObject json = Json.createReader(req.getReader()).readObject();
long deviceId = json.getJsonNumber("deviceId").longValue();
String command = json.getString("command");
- Context.getPermissionsManager().checkDevice(getUserId(req), deviceId);
+ Context.getPermissionsManager().check(Device.class, getUserId(req), deviceId);
getActiveDevice(deviceId).write(command);
sendResponse(resp.getWriter(), true);
}
diff --git a/src/org/traccar/web/JsonConverter.java b/src/org/traccar/web/JsonConverter.java
index c01ce8bd6..2ef61fb13 100644
--- a/src/org/traccar/web/JsonConverter.java
+++ b/src/org/traccar/web/JsonConverter.java
@@ -43,6 +43,14 @@ public final class JsonConverter {
private JsonConverter() {
}
+ private static <T> T newClassInstance(Class<T> clazz) {
+ try {
+ return clazz.newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ throw new IllegalArgumentException();
+ }
+ }
+
private static final DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.dateTime();
public static Date parseDate(String value) {
@@ -57,9 +65,23 @@ public final class JsonConverter {
public static <T extends Factory> T objectFromJson(JsonObject json, T prototype) {
T object = (T) prototype.create();
+ Method[] methods = object.getClass().getMethods();
+ return objectFromJson(json, object, methods);
+ }
+ public static <T> T objectFromJson(Reader reader, Class<T> clazz) throws ParseException {
+ try (JsonReader jsonReader = Json.createReader(reader)) {
+ return objectFromJson(jsonReader.readObject(), clazz);
+ }
+ }
+
+ public static <T> T objectFromJson(JsonObject json, Class<T> clazz) {
+ T object = newClassInstance(clazz);
Method[] methods = object.getClass().getMethods();
+ return objectFromJson(json, object, methods);
+ }
+ private static <T> T objectFromJson(JsonObject json, T object, Method[] methods) {
for (final Method method : methods) {
if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) {
@@ -91,7 +113,6 @@ public final class JsonConverter {
}
}
}
-
return object;
}
diff --git a/src/org/traccar/web/MainServlet.java b/src/org/traccar/web/MainServlet.java
index 63ff27813..40bfcddb5 100644
--- a/src/org/traccar/web/MainServlet.java
+++ b/src/org/traccar/web/MainServlet.java
@@ -45,7 +45,7 @@ public class MainServlet extends BaseServlet {
}
private void session(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- Long userId = (Long) req.getSession().getAttribute(USER_KEY);
+ Long userId = (Long) req.getSession().getAttribute(USER_ID_KEY);
if (userId != null) {
sendResponse(resp.getWriter(), JsonConverter.objectToJson(
Context.getDataManager().getUser(userId)));
@@ -58,7 +58,7 @@ public class MainServlet extends BaseServlet {
User user = Context.getDataManager().login(
req.getParameter("email"), req.getParameter("password"));
if (user != null) {
- req.getSession().setAttribute(USER_KEY, user.getId());
+ req.getSession().setAttribute(USER_ID_KEY, user.getId());
sendResponse(resp.getWriter(), JsonConverter.objectToJson(user));
} else {
sendResponse(resp.getWriter(), false);
@@ -66,12 +66,12 @@ public class MainServlet extends BaseServlet {
}
private void logout(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- req.getSession().removeAttribute(USER_KEY);
+ req.getSession().removeAttribute(USER_ID_KEY);
sendResponse(resp.getWriter(), true);
}
private void register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- User user = JsonConverter.objectFromJson(req.getReader(), new User());
+ User user = JsonConverter.objectFromJson(req.getReader(), User.class);
Context.getDataManager().addUser(user);
sendResponse(resp.getWriter(), true);
}
diff --git a/src/org/traccar/web/WebServer.java b/src/org/traccar/web/WebServer.java
index f5a6acdd9..317e4db46 100644
--- a/src/org/traccar/web/WebServer.java
+++ b/src/org/traccar/web/WebServer.java
@@ -24,7 +24,13 @@ import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.servlet.ServletContainer;
import org.traccar.Config;
+import org.traccar.api.CorsResponseFilter;
+import org.traccar.api.SecurityRequestFilter;
+import org.traccar.api.resource.DeviceResource;
+import org.traccar.api.resource.UserResource;
import org.traccar.helper.Log;
/**
@@ -101,6 +107,12 @@ public class WebServer {
}
private void initApi() {
+ initOldApi();
+ initRestApi();
+ }
+
+ @Deprecated
+ private void initOldApi() {
ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletHandler.setContextPath("/api");
servletHandler.addServlet(new ServletHolder(new AsyncServlet()), "/async/*");
@@ -120,6 +132,17 @@ public class WebServer {
handlers.addHandler(servletHandler);
}
+ private void initRestApi() {
+ ResourceConfig resourceConfig = new ResourceConfig();
+ resourceConfig.register(SecurityRequestFilter.class);
+ resourceConfig.register(CorsResponseFilter.class);
+ resourceConfig.registerClasses(DeviceResource.class, UserResource.class);
+ ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
+ ServletHolder servletHolder = new ServletHolder(new ServletContainer(resourceConfig));
+ servletHandler.addServlet(servletHolder, "/rest/*");
+ handlers.addHandler(servletHandler);
+ }
+
public void start() {
try {
server.start();