From 30f10f12d32915d74e36b4bf336e4e2d7ac3aada Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sat, 16 Apr 2016 11:24:54 +1200 Subject: Remove old web API service --- src/org/traccar/web/AsyncServlet.java | 237 ------------------------------- src/org/traccar/web/BaseServlet.java | 125 ---------------- src/org/traccar/web/CommandServlet.java | 66 --------- src/org/traccar/web/DeviceServlet.java | 114 --------------- src/org/traccar/web/JsonConverter.java | 3 - src/org/traccar/web/JsonIgnore.java | 12 -- src/org/traccar/web/MainServlet.java | 79 ----------- src/org/traccar/web/PositionServlet.java | 69 --------- src/org/traccar/web/ServerServlet.java | 53 ------- src/org/traccar/web/UserServlet.java | 81 ----------- src/org/traccar/web/WebServer.java | 29 +--- 11 files changed, 5 insertions(+), 863 deletions(-) delete mode 100644 src/org/traccar/web/AsyncServlet.java delete mode 100644 src/org/traccar/web/BaseServlet.java delete mode 100644 src/org/traccar/web/CommandServlet.java delete mode 100644 src/org/traccar/web/DeviceServlet.java delete mode 100644 src/org/traccar/web/JsonIgnore.java delete mode 100644 src/org/traccar/web/MainServlet.java delete mode 100644 src/org/traccar/web/PositionServlet.java delete mode 100644 src/org/traccar/web/ServerServlet.java delete mode 100644 src/org/traccar/web/UserServlet.java (limited to 'src/org/traccar/web') diff --git a/src/org/traccar/web/AsyncServlet.java b/src/org/traccar/web/AsyncServlet.java deleted file mode 100644 index e4cb64c57..000000000 --- a/src/org/traccar/web/AsyncServlet.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import javax.json.Json; -import javax.json.JsonObjectBuilder; -import javax.servlet.AsyncContext; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.jboss.netty.util.Timeout; -import org.jboss.netty.util.TimerTask; -import org.traccar.Context; -import org.traccar.GlobalTimer; -import org.traccar.database.ConnectionManager; -import org.traccar.helper.Log; -import org.traccar.model.Device; -import org.traccar.model.Position; - -public class AsyncServlet extends BaseServlet { - - private static final long ASYNC_TIMEOUT = 120000; - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - async(req.startAsync(), getUserId(req)); - return true; - } - - public static class AsyncSession { - - public static final boolean DEBUG_ASYNC = false; - - private static final long SESSION_TIMEOUT = 30; - private static final long REQUEST_TIMEOUT = 20; - - private boolean destroyed; - private final long userId; - private final Set devices = new HashSet<>(); - private Timeout sessionTimeout; - private Timeout requestTimeout; - private final Set deviceUpdates = new HashSet<>(); - private final Set positionUpdates = new HashSet<>(); - private AsyncContext activeContext; - - private void logEvent(String message) { - if (DEBUG_ASYNC) { - Log.debug("AsyncSession: " + this.hashCode() + " destroyed: " + destroyed + " " + message); - } - } - - public AsyncSession(long userId, Collection devices) { - logEvent("create userId: " + userId + " devices: " + devices.size()); - this.userId = userId; - this.devices.addAll(devices); - - Collection initialPositions = Context.getConnectionManager().getInitialState(devices); - for (Position position : initialPositions) { - positionUpdates.add(position); - } - - Context.getConnectionManager().addListener(devices, dataListener); - } - - public boolean hasDevice(long deviceId) { - return devices.contains(deviceId); - } - - private final ConnectionManager.UpdateListener dataListener = new ConnectionManager.UpdateListener() { - @Override - public void onUpdateDevice(Device device) { - synchronized (AsyncSession.this) { - logEvent("onUpdateDevice deviceId: " + device.getId()); - if (!destroyed) { - if (requestTimeout != null) { - requestTimeout.cancel(); - requestTimeout = null; - } - deviceUpdates.add(device); - if (activeContext != null) { - response(); - } - } - } - } - - @Override - public void onUpdatePosition(Position position) { - synchronized (AsyncSession.this) { - logEvent("onUpdatePosition deviceId: " + position.getDeviceId()); - if (!destroyed) { - if (requestTimeout != null) { - requestTimeout.cancel(); - requestTimeout = null; - } - positionUpdates.add(position); - if (activeContext != null) { - response(); - } - } - } - } - }; - - private final TimerTask sessionTimer = new TimerTask() { - @Override - public void run(Timeout tmt) throws Exception { - synchronized (AsyncSession.this) { - logEvent("sessionTimeout"); - destroyed = true; - } - Context.getConnectionManager().removeListener(devices, dataListener); - synchronized (ASYNC_SESSIONS) { - if (ASYNC_SESSIONS.get(userId) == AsyncSession.this) { - ASYNC_SESSIONS.remove(userId); - } - } - } - }; - - private final TimerTask requestTimer = new TimerTask() { - @Override - public void run(Timeout tmt) throws Exception { - synchronized (AsyncSession.this) { - logEvent("requestTimeout"); - if (!destroyed && activeContext != null) { - response(); - } - } - } - }; - - public synchronized void request(AsyncContext context) { - logEvent("request context: " + context.hashCode()); - if (!destroyed) { - activeContext = context; - if (sessionTimeout != null) { - sessionTimeout.cancel(); - sessionTimeout = null; - } - - if (!deviceUpdates.isEmpty() || !positionUpdates.isEmpty()) { - response(); - } else { - requestTimeout = GlobalTimer.getTimer().newTimeout( - requestTimer, REQUEST_TIMEOUT, TimeUnit.SECONDS); - } - } - } - - private synchronized void response() { - logEvent("response context: " + activeContext.hashCode()); - if (!destroyed) { - ServletResponse response = activeContext.getResponse(); - - JsonObjectBuilder result = Json.createObjectBuilder(); - result.add("success", true); - - result.add("data", JsonConverter.arrayToJson(positionUpdates)); - - deviceUpdates.clear(); - positionUpdates.clear(); - - try { - response.getWriter().println(result.build().toString()); - } catch (IOException error) { - Log.warning(error); - } - - activeContext.complete(); - activeContext = null; - - sessionTimeout = GlobalTimer.getTimer().newTimeout( - sessionTimer, SESSION_TIMEOUT, TimeUnit.SECONDS); - } - } - - } - - private static final Map ASYNC_SESSIONS = new HashMap<>(); - - public static void sessionRefreshUser(long userId) { - synchronized (ASYNC_SESSIONS) { - ASYNC_SESSIONS.remove(userId); - } - } - - public static void sessionRefreshDevice(long deviceId) { - synchronized (ASYNC_SESSIONS) { - Iterator> iterator = ASYNC_SESSIONS.entrySet().iterator(); - while (iterator.hasNext()) { - if (iterator.next().getValue().hasDevice(deviceId)) { - iterator.remove(); - } - } - } - } - - private void async(final AsyncContext context, long userId) { - - context.setTimeout(ASYNC_TIMEOUT); - HttpServletRequest req = (HttpServletRequest) context.getRequest(); - - synchronized (ASYNC_SESSIONS) { - - if (Boolean.parseBoolean(req.getParameter("first")) || !ASYNC_SESSIONS.containsKey(userId)) { - Collection devices = Context.getPermissionsManager().getDevicePermissions(userId); - ASYNC_SESSIONS.put(userId, new AsyncSession(userId, devices)); - } - - ASYNC_SESSIONS.get(userId).request(context); - } - } - -} diff --git a/src/org/traccar/web/BaseServlet.java b/src/org/traccar/web/BaseServlet.java deleted file mode 100644 index 17f4f19cd..000000000 --- a/src/org/traccar/web/BaseServlet.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -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 javax.json.Json; -import javax.json.JsonObjectBuilder; -import javax.json.JsonStructure; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.util.CharsetUtil; -import org.traccar.Context; - -public abstract class BaseServlet extends HttpServlet { - - public static final String USER_ID_KEY = "userId"; - 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"; - - @Override - protected final void service( - HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - resp.setContentType(APPLICATION_JSON); - resp.setCharacterEncoding(CharsetUtil.UTF_8.name()); - resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, ALLOW_HEADERS_VALUE); - resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_METHODS, ALLOW_METHODS_VALUE); - - String origin = req.getHeader(HttpHeaders.Names.ORIGIN); - String allowed = Context.getConfig().getString("web.origin"); - if (allowed == null || origin == null) { - resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ORIGIN_VALUE); - } else if (allowed.contains(origin)) { - String originSafe = URLEncoder.encode(origin, StandardCharsets.UTF_8.name()); - resp.setHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, originSafe); - } - - if (!handle(getCommand(req), req, resp)) { - resp.sendError(HttpServletResponse.SC_BAD_REQUEST); - } - } catch (Exception error) { - if (error instanceof AccessControlException) { - resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } else if (error instanceof SecurityException) { - resp.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - sendResponse(resp.getWriter(), error); - } - } - - protected abstract boolean handle( - String command, HttpServletRequest req, HttpServletResponse resp) throws Exception; - - public long getUserId(HttpServletRequest req) throws Exception { - Object userId = req.getSession().getAttribute(USER_ID_KEY); - if (userId != null) { - return (Long) userId; - } - throw new AccessControlException("User not logged in"); - } - - public void sendResponse(Writer writer, boolean success) throws IOException { - JsonObjectBuilder result = Json.createObjectBuilder(); - result.add("success", success); - writer.write(result.build().toString()); - } - - public void sendResponse(Writer writer, JsonStructure json) throws IOException { - JsonObjectBuilder result = Json.createObjectBuilder(); - result.add("success", true); - result.add("data", json); - writer.write(result.build().toString()); - } - - public void sendResponse(HttpServletResponse resp, Collection collection) throws IOException { - if (collection.isEmpty()) { - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - } - JsonObjectBuilder result = Json.createObjectBuilder(); - result.add("success", true); - result.add("data", JsonConverter.arrayToJson(collection)); - resp.getWriter().write(result.build().toString()); - } - - public void sendResponse(Writer writer, Exception error) throws IOException { - JsonObjectBuilder result = Json.createObjectBuilder(); - result.add("success", false); - result.add("error", Log.exceptionStack(error)); - writer.write(result.build().toString()); - } - - protected String getCommand(HttpServletRequest req) { - String command = req.getPathInfo(); - if (command == null) { - command = ""; - } - return command; - } - -} diff --git a/src/org/traccar/web/CommandServlet.java b/src/org/traccar/web/CommandServlet.java deleted file mode 100644 index ff8c85542..000000000 --- a/src/org/traccar/web/CommandServlet.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.json.Json; -import javax.json.JsonObject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.database.ActiveDevice; -import org.traccar.model.Command; - -public class CommandServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/send": - send(req, resp); - return true; - case "/raw": - raw(req, resp); - return true; - default: - return false; - } - } - - public ActiveDevice getActiveDevice(long deviceId) { - ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); - if (activeDevice == null) { - throw new RuntimeException("The device is not registered on the server"); - } - return activeDevice; - } - - private void send(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Command command = JsonConverter.objectFromJson(req.getReader(), Command.class); - Context.getPermissionsManager().checkDevice(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); - getActiveDevice(deviceId).write(command); - sendResponse(resp.getWriter(), true); - } -} diff --git a/src/org/traccar/web/DeviceServlet.java b/src/org/traccar/web/DeviceServlet.java deleted file mode 100644 index a501bd8f6..000000000 --- a/src/org/traccar/web/DeviceServlet.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.model.Device; - -public class DeviceServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/get": - get(req, resp); - break; - case "/add": - add(req, resp); - break; - case "/update": - update(req, resp); - break; - case "/remove": - remove(req, resp); - break; - case "/link": - link(req, resp); - break; - case "/unlink": - unlink(req, resp); - break; - default: - return false; - } - return true; - } - - private void get(HttpServletRequest req, HttpServletResponse resp) throws Exception { - if (Boolean.parseBoolean(req.getParameter("all"))) { - Context.getPermissionsManager().checkAdmin(getUserId(req)); - sendResponse(resp.getWriter(), JsonConverter.arrayToJson( - Context.getDataManager().getAllDevices())); - } else { - long userId; - String userIdParam = req.getParameter("userId"); - if (userIdParam != null) { - userId = Long.parseLong(userIdParam); - } else { - userId = getUserId(req); - } - Context.getPermissionsManager().checkUser(getUserId(req), userId); - sendResponse(resp.getWriter(), JsonConverter.arrayToJson( - Context.getDataManager().getDevices(userId))); - } - } - - private void add(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Device device = JsonConverter.objectFromJson(req.getReader(), Device.class); - long userId = getUserId(req); - Context.getDataManager().addDevice(device); - Context.getDataManager().linkDevice(userId, device.getId()); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), JsonConverter.objectToJson(device)); - } - - private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Device device = JsonConverter.objectFromJson(req.getReader(), Device.class); - Context.getPermissionsManager().checkDevice(getUserId(req), device.getId()); - Context.getDataManager().updateDevice(device); - sendResponse(resp.getWriter(), true); - } - - private void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Device device = JsonConverter.objectFromJson(req.getReader(), Device.class); - Context.getPermissionsManager().checkDevice(getUserId(req), device.getId()); - Context.getDataManager().removeDevice(device); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), true); - } - - private void link(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Context.getPermissionsManager().checkAdmin(getUserId(req)); - Context.getDataManager().linkDevice( - Long.parseLong(req.getParameter("userId")), - Long.parseLong(req.getParameter("deviceId"))); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), true); - } - - private void unlink(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Context.getPermissionsManager().checkAdmin(getUserId(req)); - Context.getDataManager().unlinkDevice( - Long.parseLong(req.getParameter("userId")), - Long.parseLong(req.getParameter("deviceId"))); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), true); - } - -} diff --git a/src/org/traccar/web/JsonConverter.java b/src/org/traccar/web/JsonConverter.java index 8bf5607fb..d018de101 100644 --- a/src/org/traccar/web/JsonConverter.java +++ b/src/org/traccar/web/JsonConverter.java @@ -106,9 +106,6 @@ public final class JsonConverter { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { - if (method.isAnnotationPresent(JsonIgnore.class)) { - continue; - } if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { String name = Introspector.decapitalize(method.getName().substring(3)); try { diff --git a/src/org/traccar/web/JsonIgnore.java b/src/org/traccar/web/JsonIgnore.java deleted file mode 100644 index 208cdc627..000000000 --- a/src/org/traccar/web/JsonIgnore.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.traccar.web; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; - -@Retention(RetentionPolicy.RUNTIME) -@Target(value = {METHOD}) -public @interface JsonIgnore { -} diff --git a/src/org/traccar/web/MainServlet.java b/src/org/traccar/web/MainServlet.java deleted file mode 100644 index 40bfcddb5..000000000 --- a/src/org/traccar/web/MainServlet.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.model.User; - -public class MainServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/session": - session(req, resp); - break; - case "/login": - login(req, resp); - break; - case "/logout": - logout(req, resp); - break; - case "/register": - register(req, resp); - break; - default: - return false; - } - return true; - } - - private void session(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Long userId = (Long) req.getSession().getAttribute(USER_ID_KEY); - if (userId != null) { - sendResponse(resp.getWriter(), JsonConverter.objectToJson( - Context.getDataManager().getUser(userId))); - } else { - sendResponse(resp.getWriter(), false); - } - } - - private void login(HttpServletRequest req, HttpServletResponse resp) throws Exception { - User user = Context.getDataManager().login( - req.getParameter("email"), req.getParameter("password")); - if (user != null) { - req.getSession().setAttribute(USER_ID_KEY, user.getId()); - sendResponse(resp.getWriter(), JsonConverter.objectToJson(user)); - } else { - sendResponse(resp.getWriter(), false); - } - } - - private void logout(HttpServletRequest req, HttpServletResponse resp) throws Exception { - 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(), User.class); - Context.getDataManager().addUser(user); - sendResponse(resp.getWriter(), true); - } - -} diff --git a/src/org/traccar/web/PositionServlet.java b/src/org/traccar/web/PositionServlet.java deleted file mode 100644 index 150b1a27c..000000000 --- a/src/org/traccar/web/PositionServlet.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.model.MiscFormatter; -import org.traccar.model.Position; - -import java.util.HashMap; -import java.util.Map; - -public class PositionServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/get": - get(req, resp); - break; - case "/devices": - devices(req, resp); - break; - default: - return false; - } - return true; - } - - private void get(HttpServletRequest req, HttpServletResponse resp) throws Exception { - long deviceId = Long.parseLong(req.getParameter("deviceId")); - Context.getPermissionsManager().checkDevice(getUserId(req), deviceId); - sendResponse(resp.getWriter(), JsonConverter.arrayToJson( - Context.getDataManager().getPositions(deviceId, - JsonConverter.parseDate(req.getParameter("from")), - JsonConverter.parseDate(req.getParameter("to"))))); - } - - private void devices(HttpServletRequest req, HttpServletResponse resp) throws Exception { - long userId = getUserId(req); - Map positions = new HashMap<>(); - - for (String deviceIdString : req.getParameterValues("devicesId")) { - Long deviceId = Long.parseLong(deviceIdString); - - Context.getPermissionsManager().checkDevice(userId, deviceId); - - Position position = Context.getConnectionManager().getLastPosition(deviceId); - positions.put(deviceId.toString(), position); - } - - sendResponse(resp.getWriter(), MiscFormatter.toJson(positions)); - } -} diff --git a/src/org/traccar/web/ServerServlet.java b/src/org/traccar/web/ServerServlet.java deleted file mode 100644 index b0ee181da..000000000 --- a/src/org/traccar/web/ServerServlet.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.model.Server; - -public class ServerServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/get": - get(resp); - break; - case "/update": - update(req, resp); - break; - default: - return false; - } - return true; - } - - private void get(HttpServletResponse resp) throws Exception { - sendResponse(resp.getWriter(), JsonConverter.objectToJson( - Context.getDataManager().getServer())); - } - - private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Server server = JsonConverter.objectFromJson(req.getReader(), Server.class); - Context.getPermissionsManager().checkAdmin(getUserId(req)); - Context.getDataManager().updateServer(server); - sendResponse(resp.getWriter(), true); - } - -} diff --git a/src/org/traccar/web/UserServlet.java b/src/org/traccar/web/UserServlet.java deleted file mode 100644 index ef1888667..000000000 --- a/src/org/traccar/web/UserServlet.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.traccar.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.traccar.Context; -import org.traccar.model.User; - -public class UserServlet extends BaseServlet { - - @Override - protected boolean handle(String command, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - switch (command) { - case "/get": - get(req, resp); - break; - case "/add": - add(req, resp); - break; - case "/update": - update(req, resp); - break; - case "/remove": - remove(req, resp); - break; - default: - return false; - } - return true; - } - - private void get(HttpServletRequest req, HttpServletResponse resp) throws Exception { - Context.getPermissionsManager().checkAdmin(getUserId(req)); - sendResponse(resp.getWriter(), JsonConverter.arrayToJson( - Context.getDataManager().getUsers())); - } - - private void add(HttpServletRequest req, HttpServletResponse resp) throws Exception { - User user = JsonConverter.objectFromJson(req.getReader(), User.class); - Context.getPermissionsManager().checkUser(getUserId(req), user.getId()); - Context.getDataManager().addUser(user); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), JsonConverter.objectToJson(user)); - } - - private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception { - User user = JsonConverter.objectFromJson(req.getReader(), User.class); - if (user.getAdmin()) { - Context.getPermissionsManager().checkAdmin(getUserId(req)); - } else { - Context.getPermissionsManager().checkUser(getUserId(req), user.getId()); - } - Context.getDataManager().updateUser(user); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), true); - } - - private void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception { - User user = JsonConverter.objectFromJson(req.getReader(), User.class); - Context.getPermissionsManager().checkUser(getUserId(req), user.getId()); - Context.getDataManager().removeUser(user); - Context.getPermissionsManager().refresh(); - sendResponse(resp.getWriter(), true); - } - -} diff --git a/src/org/traccar/web/WebServer.java b/src/org/traccar/web/WebServer.java index 973f6a0a5..f1a282567 100644 --- a/src/org/traccar/web/WebServer.java +++ b/src/org/traccar/web/WebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2015 Anton Tananaev (anton.tananaev@gmail.com) + * Copyright 2012 - 2016 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,19 +76,15 @@ public class WebServer { this.dataSource = dataSource; initServer(); + initApi(); + if (config.getBoolean("web.console")) { + initConsole(); + } switch (config.getString("web.type", "new")) { - case "api": - initOldApi(); - break; case "old": - initOldApi(); initOldWebApp(); break; default: - initApi(); - if (config.getBoolean("web.console")) { - initConsole(); - } initWebApp(); break; } @@ -151,21 +147,6 @@ public class WebServer { handlers.addHandler(servletHandler); } - private void initOldApi() { - ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); - servletHandler.setContextPath("/api"); - servletHandler.getSessionHandler().setSessionManager(sessionManager); - - servletHandler.addServlet(new ServletHolder(new AsyncServlet()), "/async/*"); - servletHandler.addServlet(new ServletHolder(new ServerServlet()), "/server/*"); - servletHandler.addServlet(new ServletHolder(new UserServlet()), "/user/*"); - servletHandler.addServlet(new ServletHolder(new DeviceServlet()), "/device/*"); - servletHandler.addServlet(new ServletHolder(new PositionServlet()), "/position/*"); - servletHandler.addServlet(new ServletHolder(new CommandServlet()), "/command/*"); - servletHandler.addServlet(new ServletHolder(new MainServlet()), "/*"); - handlers.addHandler(servletHandler); - } - private void initConsole() { ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); servletHandler.setContextPath("/console"); -- cgit v1.2.3