aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAnton Tananaev <anton.tananaev@gmail.com>2015-11-30 13:55:05 +1300
committerAnton Tananaev <anton.tananaev@gmail.com>2015-11-30 13:55:05 +1300
commitcefc12afe98f610aa0f266bcac4361f9ec414ee5 (patch)
tree48d47a0eec0c2d8a3ee7f448f8d535d7d826d546 /src
parentc6692703c8099577cb86c3eace5d8d1bc11f212d (diff)
parent1a25796d62bdf88f2cba0387a09e2eb71599e588 (diff)
downloadtraccar-server-cefc12afe98f610aa0f266bcac4361f9ec414ee5.tar.gz
traccar-server-cefc12afe98f610aa0f266bcac4361f9ec414ee5.tar.bz2
traccar-server-cefc12afe98f610aa0f266bcac4361f9ec414ee5.zip
Merge master of guterresrafael/traccar into rest
Diffstat (limited to 'src')
-rw-r--r--src/org/traccar/api/ApplicationRole.java25
-rw-r--r--src/org/traccar/api/AuthorizationBasic.java98
-rw-r--r--src/org/traccar/api/BaseResource.java99
-rw-r--r--src/org/traccar/api/CORSResponseFilter.java54
-rw-r--r--src/org/traccar/api/ResponseBuilder.java129
-rw-r--r--src/org/traccar/api/SecurityContextApi.java55
-rw-r--r--src/org/traccar/api/SecurityRequestFilter.java82
-rw-r--r--src/org/traccar/api/UserPrincipal.java74
-rw-r--r--src/org/traccar/api/resource/DeviceResource.java77
-rw-r--r--src/org/traccar/api/resource/UserResource.java77
-rw-r--r--src/org/traccar/database/DataManager.java58
-rw-r--r--src/org/traccar/database/PermissionsManager.java8
-rw-r--r--src/org/traccar/helper/Authorization.java49
-rw-r--r--src/org/traccar/helper/Clazz.java108
-rw-r--r--src/org/traccar/helper/CommandCall.java51
-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.java16
-rw-r--r--src/org/traccar/web/MainServlet.java8
-rw-r--r--src/org/traccar/web/WebServer.java17
20 files changed, 1047 insertions, 100 deletions
diff --git a/src/org/traccar/api/ApplicationRole.java b/src/org/traccar/api/ApplicationRole.java
new file mode 100644
index 000000000..4da5f6708
--- /dev/null
+++ b/src/org/traccar/api/ApplicationRole.java
@@ -0,0 +1,25 @@
+/*
+ * 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.api;
+
+public final class ApplicationRole {
+
+ public static final String USER = "USER";
+ public static final String ADMIN = "ADMIN";
+
+ private ApplicationRole() {
+ }
+}
diff --git a/src/org/traccar/api/AuthorizationBasic.java b/src/org/traccar/api/AuthorizationBasic.java
new file mode 100644
index 000000000..807320940
--- /dev/null
+++ b/src/org/traccar/api/AuthorizationBasic.java
@@ -0,0 +1,98 @@
+/*
+ * 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.api;
+
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.MultivaluedMap;
+import org.jboss.netty.buffer.ChannelBuffer;
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.jboss.netty.handler.codec.base64.Base64;
+import org.jboss.netty.util.CharsetUtil;
+import org.traccar.Context;
+import org.traccar.model.User;
+
+public final class AuthorizationBasic {
+
+ private AuthorizationBasic() {
+ }
+
+ public static final String AUTHORIZATION_HEADER = "Authorization";
+ public static final String AUTHORIZATION_SCHEME_VALUE = "Basic";
+ public static final String REGEX = AUTHORIZATION_SCHEME_VALUE + " ";
+ public static final String REPLACEMENT = "";
+ public static final String TOKENIZER = ":";
+ public static final String USERNAME = "username";
+ public static final String PASSWORD = "password";
+ public static final String WWW_AUTHENTICATE_VALUE = "Basic realm=\"api\"";
+
+ public static UserPrincipal getUserPrincipal(ContainerRequestContext requestContext) {
+ final MultivaluedMap<String, String> headers = requestContext.getHeaders();
+ final List<String> authorization = headers.get(AUTHORIZATION_HEADER);
+ if (authorization == null || authorization.isEmpty()) {
+ return null;
+ }
+ final String encodedUsernameAndPassword = authorization.get(0).replaceFirst(REGEX, REPLACEMENT);
+ ChannelBuffer buffer = ChannelBuffers.copiedBuffer(encodedUsernameAndPassword, CharsetUtil.UTF_8);
+ String usernameAndPassword = Base64.decode(buffer).toString(CharsetUtil.UTF_8);
+ final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, TOKENIZER);
+ String username = tokenizer.nextToken();
+ String password = tokenizer.nextToken();
+ Set<String> roles = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ UserPrincipal userPrincipal = new UserPrincipal(username, password, roles);
+ return userPrincipal;
+ }
+
+ public static boolean isAuthenticatedUser(UserPrincipal userPrincipal) {
+ if (userPrincipal.getName() != null && userPrincipal.getPassword() != null) {
+ User user;
+ try {
+ user = Context.getDataManager().login(userPrincipal.getName(), userPrincipal.getPassword());
+ } catch (SQLException e) {
+ return false;
+ }
+ if (user != null) {
+ userPrincipal.setId(user.getId());
+ /*
+ for (Role role : user.getRoles()) {
+ userPrincipal.getRoles().add(role.getName());
+ }
+ */
+
+ //Temporary solution
+ userPrincipal.getRoles().add(ApplicationRole.USER);
+ if (user.getAdmin()) {
+ userPrincipal.getRoles().add(ApplicationRole.ADMIN);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static boolean isAuthorizedUser(UserPrincipal userPrincipal, Set<String> roles) {
+ for (String role : roles) {
+ if (userPrincipal.getRoles().contains(role)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java
new file mode 100644
index 000000000..54d606ab6
--- /dev/null
+++ b/src/org/traccar/api/BaseResource.java
@@ -0,0 +1,99 @@
+/*
+ * 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.api;
+
+import java.sql.SQLException;
+import java.util.Collection;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.SecurityContext;
+import org.traccar.Context;
+import org.traccar.helper.Clazz;
+
+public class BaseResource<T, I> {
+
+ private final Class<T> clazz = Clazz.getGenericArgumentType(getClass());
+
+ @javax.ws.rs.core.Context
+ private SecurityContext securityContext;
+
+ public Collection<T> getEntities() {
+ Collection<T> collection;
+ try {
+ collection = Context.getDataManager().get(clazz);
+ } catch (SQLException e) {
+ throw new WebApplicationException(ResponseBuilder.badRequest(e));
+ }
+ if (collection == null || collection.isEmpty()) {
+ throw new WebApplicationException(ResponseBuilder.notFound());
+ } else {
+ return collection;
+ }
+ }
+
+ public T getEntity(I id) {
+ validateSecurityContext(ApplicationRole.USER, id);
+ T entity = Clazz.newInstance(clazz);
+ try {
+ Clazz.setId(entity, id);
+ entity = Context.getDataManager().get(entity);
+ } catch (Exception e) {
+ throw new WebApplicationException(ResponseBuilder.badRequest(e));
+ }
+ if (entity == null) {
+ throw new WebApplicationException(ResponseBuilder.notFound());
+ } else {
+ return entity;
+ }
+ }
+
+ public Response postEntity(T entity) {
+ try {
+ Context.getDataManager().add(entity);
+ return ResponseBuilder.ok(entity);
+ } catch (Exception e) {
+ return ResponseBuilder.badRequest(e);
+ }
+ }
+
+ public Response putEntity(I id, T entity) {
+ try {
+ Clazz.setId(entity, id);
+ Context.getDataManager().update(entity);
+ return ResponseBuilder.ok(entity);
+ } catch (Exception e) {
+ return ResponseBuilder.badRequest(e);
+ }
+ }
+
+ public Response deleteEntity(I id) {
+ try {
+ T entity = Clazz.newInstance(clazz);
+ Clazz.setId(entity, id);
+ Context.getDataManager().remove(entity);
+ return ResponseBuilder.deleted();
+ } catch (Exception e) {
+ return ResponseBuilder.badRequest(e);
+ }
+ }
+
+ private void validateSecurityContext(String role, I id) {
+ UserPrincipal userPrincipal = (UserPrincipal) securityContext.getUserPrincipal();
+ if (!securityContext.isUserInRole(role) && !userPrincipal.getId().equals(id)) {
+ throw new WebApplicationException(ResponseBuilder.forbidden());
+ }
+ }
+}
diff --git a/src/org/traccar/api/CORSResponseFilter.java b/src/org/traccar/api/CORSResponseFilter.java
new file mode 100644
index 000000000..039a749c4
--- /dev/null
+++ b/src/org/traccar/api/CORSResponseFilter.java
@@ -0,0 +1,54 @@
+/*
+ * 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.api;
+
+import java.io.IOException;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+import javax.ws.rs.ext.Provider;
+
+@Provider
+public class CORSResponseFilter implements ContainerResponseFilter {
+
+ public static final String ACCESS_CONTROL_ALLOW_ORIGIN_KEY = "Access-Control-Allow-Origin";
+ public static final String ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";
+
+ public static final String ACCESS_CONTROL_ALLOW_HEADERS_KEY = "Access-Control-Allow-Headers";
+ public static final String ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "origin, content-type, accept, authorization";
+
+ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_KEY = "Access-Control-Allow-Credentials";
+ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE = "true";
+
+ public static final String ACCESS_CONTROL_ALLOW_METHODS_KEY = "Access-Control-Allow-Methods";
+ public static final String ACCESS_CONTROL_ALLOW_METHODS_VALUE = "GET, POST, PUT, DELETE";
+
+ @Override
+ public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
+ if (!response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN_KEY)) {
+ response.getHeaders().add(ACCESS_CONTROL_ALLOW_ORIGIN_KEY, ACCESS_CONTROL_ALLOW_ORIGIN_VALUE);
+ }
+ if (!response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS_KEY)) {
+ response.getHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS_KEY, ACCESS_CONTROL_ALLOW_HEADERS_VALUE);
+ }
+ if (!response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_CREDENTIALS_KEY)) {
+ response.getHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS_KEY, ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
+ }
+ if (!response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_METHODS_KEY)) {
+ response.getHeaders().add(ACCESS_CONTROL_ALLOW_METHODS_KEY, ACCESS_CONTROL_ALLOW_METHODS_VALUE);
+ }
+ }
+}
diff --git a/src/org/traccar/api/ResponseBuilder.java b/src/org/traccar/api/ResponseBuilder.java
new file mode 100644
index 000000000..195cb1923
--- /dev/null
+++ b/src/org/traccar/api/ResponseBuilder.java
@@ -0,0 +1,129 @@
+/*
+ * 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.api;
+
+import java.io.Serializable;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+import javax.ws.rs.core.Response;
+
+public final class ResponseBuilder implements Serializable {
+
+ private static final long serialVersionUID = -2348334499023022836L;
+
+ private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
+ private static final String BASIC_REALM = "Basic realm=\"api\"";
+ private static final String ERROR = "error";
+
+ private ResponseBuilder() {
+ }
+
+ public static Response ok() {
+ return Response.status(Response.Status.OK).build();
+ }
+
+ public static <T> Response ok(T entity) {
+ return Response.status(Response.Status.OK).entity(entity).build();
+ }
+
+ public static <T> Response ok(Collection<T> entities) {
+ return Response.ok(entities).build();
+ }
+
+ public static Response created() {
+ return Response.status(Response.Status.CREATED).build();
+ }
+
+ public static <T> Response created(T entity) {
+ return Response.status(Response.Status.CREATED).entity(entity).build();
+ }
+
+ public static Response accepted() {
+ return Response.status(Response.Status.ACCEPTED).build();
+ }
+
+ public static <T> Response accepted(T entity) {
+ return Response.status(Response.Status.ACCEPTED).entity(entity).build();
+ }
+
+ public static Response deleted() {
+ return Response.status(Response.Status.NO_CONTENT).build();
+ }
+
+ public static Response notModified() {
+ return Response.status(Response.Status.NOT_MODIFIED).build();
+ }
+
+ public static Response badRequest() {
+ return Response.status(Response.Status.BAD_REQUEST).build();
+ }
+
+ public static Response badRequest(Exception e) {
+ return Response.status(Response.Status.BAD_REQUEST).entity(getError(e)).build();
+ }
+
+ public static Response unauthorized() {
+ return Response.status(Response.Status.UNAUTHORIZED).header(WWW_AUTHENTICATE, BASIC_REALM).build();
+ }
+
+ public static Response forbidden() {
+ return Response.status(Response.Status.FORBIDDEN).entity(getError(Response.Status.FORBIDDEN.name())).build();
+ }
+
+ public static Response notFound() {
+ return Response.status(Response.Status.NOT_FOUND).build();
+ }
+
+ public static Response timeout() {
+ return Response.status(Response.Status.REQUEST_TIMEOUT).build();
+ }
+
+ public static Response conflict() {
+ return Response.status(Response.Status.CONFLICT).build();
+ }
+
+ public static Response conflict(Exception e) {
+ return Response.status(Response.Status.CONFLICT).entity(getError(e)).build();
+ }
+
+ public static Response notImplemented() {
+ return Response.status(Response.Status.NOT_IMPLEMENTED).build();
+ }
+
+ public static Response redirect(String uri) {
+ try {
+ return Response.seeOther(new URI(uri)).build();
+ } catch (URISyntaxException e) {
+ Logger.getAnonymousLogger().warning(e.getMessage());
+ return null;
+ }
+ }
+
+ private static Map<String, String> getError(Exception e) {
+ return getError(e.getMessage());
+ }
+
+ private static Map<String, String> getError(String message) {
+ Map<String, String> error = new HashMap<>();
+ error.put(ERROR, message);
+ return error;
+ }
+
+}
diff --git a/src/org/traccar/api/SecurityContextApi.java b/src/org/traccar/api/SecurityContextApi.java
new file mode 100644
index 000000000..df10340c5
--- /dev/null
+++ b/src/org/traccar/api/SecurityContextApi.java
@@ -0,0 +1,55 @@
+/*
+ * 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.api;
+
+import java.security.Principal;
+import javax.ws.rs.core.SecurityContext;
+
+public class SecurityContextApi implements SecurityContext {
+
+ private static final String AUTHENTICATION_SCHEME = "BASIC";
+ private static final boolean IS_SECURE = true;
+
+ private Principal userPrincipal;
+
+ public SecurityContextApi(Principal userPrincipal) {
+ this.userPrincipal = userPrincipal;
+ }
+
+ public SecurityContextApi() {
+ }
+
+ @Override
+ public Principal getUserPrincipal() {
+ return userPrincipal;
+ }
+
+ @Override
+ public boolean isUserInRole(String role) {
+ UserPrincipal user = (UserPrincipal) userPrincipal;
+ return user.getRoles().contains(role);
+ }
+
+ @Override
+ public boolean isSecure() {
+ return IS_SECURE;
+ }
+
+ @Override
+ public String getAuthenticationScheme() {
+ return AUTHENTICATION_SCHEME;
+ }
+}
diff --git a/src/org/traccar/api/SecurityRequestFilter.java b/src/org/traccar/api/SecurityRequestFilter.java
new file mode 100644
index 000000000..9d59cdc01
--- /dev/null
+++ b/src/org/traccar/api/SecurityRequestFilter.java
@@ -0,0 +1,82 @@
+/*
+ * 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.api;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import javax.annotation.security.DenyAll;
+import javax.annotation.security.PermitAll;
+import javax.annotation.security.RolesAllowed;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.ResourceInfo;
+import javax.ws.rs.ext.Provider;
+
+@Provider
+public class SecurityRequestFilter implements ContainerRequestFilter {
+
+ @javax.ws.rs.core.Context
+ private ResourceInfo resourceInfo;
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) {
+ Method method = resourceInfo.getResourceMethod();
+
+ //@PermitAll
+ if (method.isAnnotationPresent(PermitAll.class)) {
+ return;
+ }
+
+ //@DenyAll
+ if (method.isAnnotationPresent(DenyAll.class)) {
+ requestContext.abortWith(ResponseBuilder.forbidden());
+ return;
+ }
+
+ //AuthorizationBasic
+ UserPrincipal userPrincipal = AuthorizationBasic.getUserPrincipal(requestContext);
+ if (userPrincipal == null
+ || userPrincipal.getName() == null
+ || userPrincipal.getPassword() == null
+ || !isAuthenticatedUser(userPrincipal)) {
+ requestContext.abortWith(ResponseBuilder.unauthorized());
+ return;
+ }
+
+ //@RolesAllowed
+ if (method.isAnnotationPresent(RolesAllowed.class)) {
+ RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
+ Set<String> roles = new HashSet<>(Arrays.asList(rolesAnnotation.value()));
+ if (!isAuthorizedUser(userPrincipal, roles)) {
+ requestContext.abortWith(ResponseBuilder.forbidden());
+ return;
+ }
+ }
+
+ //SecurityContext
+ requestContext.setSecurityContext(new SecurityContextApi(userPrincipal));
+ }
+
+ private boolean isAuthenticatedUser(UserPrincipal principal) {
+ return AuthorizationBasic.isAuthenticatedUser(principal);
+ }
+
+ private boolean isAuthorizedUser(UserPrincipal userPrincipal, Set<String> roles) {
+ return AuthorizationBasic.isAuthorizedUser(userPrincipal, roles);
+ }
+}
diff --git a/src/org/traccar/api/UserPrincipal.java b/src/org/traccar/api/UserPrincipal.java
new file mode 100644
index 000000000..387b7627c
--- /dev/null
+++ b/src/org/traccar/api/UserPrincipal.java
@@ -0,0 +1,74 @@
+/*
+ * 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.api;
+
+import java.security.Principal;
+import java.util.Set;
+
+public class UserPrincipal implements Principal {
+
+ private Long id;
+ private String username;
+ private String password;
+ private Set<String> roles;
+
+ public UserPrincipal(String username, String password, Set<String> roles) {
+ this.username = username;
+ this.password = password;
+ this.roles = roles;
+ }
+
+ public UserPrincipal(String username, Set<String> roles) {
+ this.username = username;
+ this.roles = roles;
+ }
+
+ public UserPrincipal(String username) {
+ this.username = username;
+ }
+
+ public UserPrincipal() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @Override
+ public String getName() {
+ return username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public Set<String> getRoles() {
+ return roles;
+ }
+
+ public void setRoles(Set<String> roles) {
+ this.roles = roles;
+ }
+}
diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java
new file mode 100644
index 000000000..4152bcf81
--- /dev/null
+++ b/src/org/traccar/api/resource/DeviceResource.java
@@ -0,0 +1,77 @@
+/*
+ * 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.api.resource;
+
+import org.traccar.api.BaseResource;
+import java.util.Collection;
+import javax.annotation.security.RolesAllowed;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.traccar.api.ApplicationRole;
+import org.traccar.model.Device;
+
+@Path("devices")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class DeviceResource extends BaseResource<Device, Long> {
+
+ @GET
+ @RolesAllowed(ApplicationRole.ADMIN)
+ @Override
+ public Collection<Device> getEntities() {
+ return super.getEntities();
+ }
+
+ @GET
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Device getEntity(@PathParam("id") Long id) {
+ return super.getEntity(id);
+ }
+
+ @POST
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response postEntity(Device entity) {
+ return super.postEntity(entity);
+ }
+
+ @PUT
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response putEntity(@PathParam("id") Long id, Device entity) {
+ return super.putEntity(id, entity);
+ }
+
+ @DELETE
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response deleteEntity(@PathParam("id") Long id) {
+ return super.deleteEntity(id);
+ }
+
+}
diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java
new file mode 100644
index 000000000..da615e052
--- /dev/null
+++ b/src/org/traccar/api/resource/UserResource.java
@@ -0,0 +1,77 @@
+/*
+ * 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.api.resource;
+
+import java.util.Collection;
+import javax.annotation.security.RolesAllowed;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.traccar.api.ApplicationRole;
+import org.traccar.api.BaseResource;
+import org.traccar.model.User;
+
+@Path("users")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class UserResource extends BaseResource<User, Long> {
+
+ @GET
+ @RolesAllowed(ApplicationRole.ADMIN)
+ @Override
+ public Collection<User> getEntities() {
+ return super.getEntities();
+ }
+
+ @GET
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public User getEntity(@PathParam("id") Long id) {
+ return super.getEntity(id);
+ }
+
+ @POST
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response postEntity(User entity) {
+ return super.postEntity(entity);
+ }
+
+ @PUT
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response putEntity(@PathParam("id") Long id, User entity) {
+ return super.putEntity(id, entity);
+ }
+
+ @DELETE
+ @Path("{id}")
+ @RolesAllowed({ApplicationRole.ADMIN, ApplicationRole.USER})
+ @Override
+ public Response deleteEntity(@PathParam("id") Long id) {
+ return super.deleteEntity(id);
+ }
+
+}
diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java
index da87c6c27..31d7155d3 100644
--- a/src/org/traccar/database/DataManager.java
+++ b/src/org/traccar/database/DataManager.java
@@ -31,6 +31,7 @@ import java.util.Map;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.traccar.Config;
+import org.traccar.helper.Clazz;
import org.traccar.helper.DriverDelegate;
import org.traccar.helper.Log;
import org.traccar.model.Device;
@@ -386,4 +387,61 @@ public class DataManager implements IdentityManager {
.executeUpdate();
}
+ public <T> Collection<T> get(Class<T> clazz) throws SQLException {
+ if (clazz.equals(User.class)) {
+ return (Collection<T>) getUsers();
+ } else if (clazz.equals(Device.class)) {
+ return (Collection<T>) getAllDevices();
+ }
+ return null;
+ }
+
+ public <T> T get(T entity) throws Exception {
+ if (entity instanceof User) {
+ return (T) getUser(Clazz.getId(entity));
+ } else if (entity instanceof Device) {
+ return (T) getDeviceById(Clazz.getId(entity));
+ }
+ return null;
+ }
+
+ public void add(Object entity) throws SQLException {
+ if (entity instanceof User) {
+ addUser((User) entity);
+ } else if (entity instanceof Device) {
+ addDevice((Device) entity);
+ } else if (entity instanceof Position) {
+ addPosition((Position) entity);
+ }
+ }
+
+ public void update(Object entity) throws SQLException {
+ if (entity instanceof User) {
+ updateUser((User) entity);
+ } else if (entity instanceof Device) {
+ updateDevice((Device) entity);
+ } else if (entity instanceof Server) {
+ updateServer((Server) entity);
+ }
+ }
+
+ public void remove(Object entity) throws SQLException {
+ if (entity instanceof User) {
+ removeUser((User) entity);
+ } else if (entity instanceof Device) {
+ removeDevice((Device) entity);
+ }
+ }
+
+ public void link(Class clazz, long userId, long entityId) throws SQLException {
+ if (clazz.equals(Device.class)) {
+ linkDevice(userId, entityId);
+ }
+ }
+
+ public void unlink(Class clazz, long userId, long entityId) throws SQLException {
+ if (clazz.equals(Device.class)) {
+ unlinkDevice(userId, entityId);
+ }
+ }
}
diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java
index a38a29c32..0a43f4ff4 100644
--- a/src/org/traccar/database/PermissionsManager.java
+++ b/src/org/traccar/database/PermissionsManager.java
@@ -22,6 +22,7 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.traccar.helper.Log;
+import org.traccar.model.Device;
import org.traccar.model.Permission;
import org.traccar.model.User;
@@ -82,4 +83,11 @@ public class PermissionsManager {
}
}
+ public <T> void check(Class<T> clazz, long userId, long entityId) throws SecurityException {
+ if (clazz.equals(User.class)) {
+ checkUser(userId, entityId);
+ } else if (clazz.equals(Device.class)) {
+ checkDevice(userId, entityId);
+ }
+ }
}
diff --git a/src/org/traccar/helper/Authorization.java b/src/org/traccar/helper/Authorization.java
deleted file mode 100644
index d0877630d..000000000
--- a/src/org/traccar/helper/Authorization.java
+++ /dev/null
@@ -1,49 +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.helper;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-import org.jboss.netty.buffer.ChannelBuffer;
-import org.jboss.netty.buffer.ChannelBuffers;
-import org.jboss.netty.handler.codec.base64.Base64;
-import org.jboss.netty.util.CharsetUtil;
-
-public final class Authorization {
-
- private Authorization() {
- }
-
- public static final String AUTHORIAZTION_SCHEME_VALUE = "Basic";
- public static final String REGEX = AUTHORIAZTION_SCHEME_VALUE + " ";
- public static final String REPLACEMENT = "";
- public static final String TOKENIZER = ":";
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
- public static final String WWW_AUTHENTICATE_VALUE = "Basic realm=\"api\"";
-
- public static Map<String, String> parse(String authorization) {
- Map<String, String> authMap = new HashMap<>();
- final String encodedUsernameAndPassword = authorization.replaceFirst(REGEX, REPLACEMENT);
- ChannelBuffer buffer = ChannelBuffers.copiedBuffer(encodedUsernameAndPassword, CharsetUtil.UTF_8);
- String usernameAndPassword = Base64.decode(buffer).toString(CharsetUtil.UTF_8);
- final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, TOKENIZER);
- authMap.put(USERNAME, tokenizer.nextToken());
- authMap.put(PASSWORD, tokenizer.nextToken());
- return authMap;
- }
-}
diff --git a/src/org/traccar/helper/Clazz.java b/src/org/traccar/helper/Clazz.java
new file mode 100644
index 000000000..ba4c4fded
--- /dev/null
+++ b/src/org/traccar/helper/Clazz.java
@@ -0,0 +1,108 @@
+/*
+ * 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.helper;
+
+import java.beans.Introspector;
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+public final class Clazz implements Serializable {
+
+ private static final long serialVersionUID = 4983299355055144885L;
+
+ private Clazz() {
+ }
+
+ public static Class getGenericArgumentType(Class currentClass, Class genericSuperClass) {
+ return getGenericArgumentType(currentClass, genericSuperClass, 0);
+ }
+
+ public static Class getGenericArgumentType(Class currentClass, int argumentIndex) {
+ return getGenericArgumentType(currentClass, null, argumentIndex);
+ }
+
+ public static Class getGenericArgumentType(Class currentClass) {
+ return getGenericArgumentType(currentClass, null, 0);
+ }
+
+ public static Class getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex) {
+ Type superType = currentClass.getGenericSuperclass();
+ if (superType == null) {
+ throw new IllegalArgumentException();
+ }
+ if (!(superType instanceof ParameterizedType)
+ || genericSuperClass != null
+ && ((ParameterizedType) superType).getRawType() != genericSuperClass) {
+ return getGenericArgumentType(currentClass.getSuperclass(), genericSuperClass, argumentIndex);
+ }
+ Object[] args = ((ParameterizedType) superType).getActualTypeArguments();
+ if (argumentIndex >= args.length) {
+ throw new IllegalArgumentException();
+ }
+ return cast(Class.class, args[argumentIndex]);
+ }
+
+ public static <T> T newInstance(Class<T> clazz) {
+ try {
+ return clazz.newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public static <T> T cast(Class<T> classe, Object objeto) {
+ if (classe.isAssignableFrom(objeto.getClass())) {
+ return classe.cast(objeto);
+ }
+ throw new ClassCastException();
+ }
+
+ public static Class forName(String className) {
+ try {
+ return Class.forName(className, false, Thread.currentThread().getContextClassLoader());
+ } catch (ClassNotFoundException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ public static <T> long getId(T entity) throws Exception {
+ Method[] methods = entity.getClass().getMethods();
+ for (final Method method : methods) {
+ if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
+ final String name = Introspector.decapitalize(method.getName().substring(3));
+ if (name.equals("id")) {
+ return Long.parseLong(method.invoke(entity).toString());
+ }
+ }
+ }
+ throw new IllegalArgumentException();
+ }
+
+ public static <T, I> void setId(T entity, I id) throws Exception {
+ Method[] methods = entity.getClass().getMethods();
+ for (final Method method : methods) {
+ if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) {
+ final String name = Introspector.decapitalize(method.getName().substring(3));
+ if (name.equals("id")) {
+ method.invoke(entity, id);
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/org/traccar/helper/CommandCall.java b/src/org/traccar/helper/CommandCall.java
new file mode 100644
index 000000000..d5da79348
--- /dev/null
+++ b/src/org/traccar/helper/CommandCall.java
@@ -0,0 +1,51 @@
+/*
+ * 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.helper;
+
+public abstract class CommandCall<T> {
+
+ private long userId;
+ private T entity;
+
+ public void before() throws Exception {
+ //Do nothing.
+ }
+
+ public void check() throws Exception {
+ //Do nothing.
+ }
+
+ public void after() throws Exception {
+ //Do nothing.
+ }
+
+ public long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(long userId) {
+ this.userId = userId;
+ }
+
+ public T getEntity() {
+ return entity;
+ }
+
+ public void setEntity(T entity) {
+ this.entity = entity;
+ }
+
+}
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..38721db61 100644
--- a/src/org/traccar/web/JsonConverter.java
+++ b/src/org/traccar/web/JsonConverter.java
@@ -34,6 +34,7 @@ import javax.json.JsonValue;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
+import org.traccar.helper.Clazz;
import org.traccar.helper.Log;
import org.traccar.model.Factory;
import org.traccar.model.MiscFormatter;
@@ -57,9 +58,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 = Clazz.newInstance(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 +106,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..2318c4151 100644
--- a/src/org/traccar/web/WebServer.java
+++ b/src/org/traccar/web/WebServer.java
@@ -24,6 +24,8 @@ 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.helper.Log;
@@ -101,6 +103,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 +128,15 @@ public class WebServer {
handlers.addHandler(servletHandler);
}
+ private void initRestApi() {
+ ResourceConfig resourceConfig = new ResourceConfig();
+ resourceConfig.packages("org.traccar.api");
+ 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();