1
0
mirror of https://github.com/sismics/docs.git synced 2026-01-03 03:49:32 +00:00

Closes #29: Upgrade to Jersey 2

This commit is contained in:
jendib
2015-09-07 21:51:13 +02:00
parent 97694d5d59
commit 0fe51d355c
44 changed files with 1643 additions and 2292 deletions

View File

@@ -1,23 +1,19 @@
package com.sismics.docs.rest.resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.sismics.docs.core.constant.AclTargetType;
import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao;
@@ -46,13 +42,11 @@ public class AclResource extends BaseResource {
* Add an ACL.
*
* @return Response
* @throws JSONException
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response add(@FormParam("source") String sourceId,
@FormParam("perm") String permStr,
@FormParam("username") String username) throws JSONException {
@FormParam("username") String username) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -86,15 +80,15 @@ public class AclResource extends BaseResource {
aclDao.create(acl);
// Returns the ACL
JSONObject response = new JSONObject();
response.put("perm", acl.getPerm().name());
response.put("id", acl.getTargetId());
response.put("name", user.getUsername());
response.put("type", AclTargetType.USER.name());
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("perm", acl.getPerm().name())
.add("id", acl.getTargetId())
.add("name", user.getUsername())
.add("type", AclTargetType.USER.name());
return Response.ok().entity(response.build()).build();
}
return Response.ok().entity(new JSONObject()).build();
return Response.ok().entity(Json.createObjectBuilder().build()).build();
}
/**
@@ -102,15 +96,13 @@ public class AclResource extends BaseResource {
*
* @param id ACL ID
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{sourceId: [a-z0-9\\-]+}/{perm: [A-Z]+}/{targetId: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@PathParam("sourceId") String sourceId,
@PathParam("perm") String permStr,
@PathParam("targetId") String targetId) throws JSONException {
@PathParam("targetId") String targetId) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -136,16 +128,21 @@ public class AclResource extends BaseResource {
// Delete the ACL
aclDao.delete(sourceId, perm, targetId);
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
* Search possible ACL target.
*
* @param search Search query
* @return Response
*/
@GET
@Path("target/search")
@Produces(MediaType.APPLICATION_JSON)
public Response targetList(@QueryParam("search") String search) throws JSONException {
public Response targetList(@QueryParam("search") String search) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -155,20 +152,19 @@ public class AclResource extends BaseResource {
// Search users
UserDao userDao = new UserDao();
JSONObject response = new JSONObject();
List<JSONObject> users = new ArrayList<>();
JsonArrayBuilder users = Json.createArrayBuilder();
PaginatedList<UserDto> paginatedList = PaginatedLists.create();
SortCriteria sortCriteria = new SortCriteria(1, true);
userDao.findByCriteria(paginatedList, new UserCriteria().setSearch(search), sortCriteria);
for (UserDto userDto : paginatedList.getResultList()) {
JSONObject user = new JSONObject();
user.put("username", userDto.getUsername());
users.add(user);
users.add(Json.createObjectBuilder()
.add("username", userDto.getUsername()));
}
response.put("users", users);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("users", users);
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -1,24 +1,22 @@
package com.sismics.docs.rest.resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.sismics.docs.core.dao.jpa.FileDao;
import com.sismics.docs.core.model.context.AppContext;
@@ -45,11 +43,9 @@ public class AppResource extends BaseResource {
* Return the information about the application.
*
* @return Response
* @throws JSONException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response info() throws JSONException {
public Response info() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -58,14 +54,13 @@ public class AppResource extends BaseResource {
String currentVersion = configBundle.getString("api.current_version");
String minVersion = configBundle.getString("api.min_version");
JSONObject response = new JSONObject();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("current_version", currentVersion.replace("-SNAPSHOT", ""))
.add("min_version", minVersion)
.add("total_memory", Runtime.getRuntime().totalMemory())
.add("free_memory", Runtime.getRuntime().freeMemory());
response.put("current_version", currentVersion.replace("-SNAPSHOT", ""));
response.put("min_version", minVersion);
response.put("total_memory", Runtime.getRuntime().totalMemory());
response.put("free_memory", Runtime.getRuntime().freeMemory());
return Response.ok().entity(response).build();
return Response.ok().entity(response.build()).build();
}
/**
@@ -77,17 +72,15 @@ public class AppResource extends BaseResource {
* @param limit Page limit
* @param offset Page offset
* @return Response
* @throws JSONException
*/
@GET
@Path("log")
@Produces(MediaType.APPLICATION_JSON)
public Response log(
@QueryParam("level") String level,
@QueryParam("tag") String tag,
@QueryParam("message") String message,
@QueryParam("limit") Integer limit,
@QueryParam("offset") Integer offset) throws JSONException {
@QueryParam("offset") Integer offset) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -109,32 +102,30 @@ public class AppResource extends BaseResource {
PaginatedList<LogEntry> paginatedList = PaginatedLists.create(limit, offset);
memoryAppender.find(logCriteria, paginatedList);
JSONObject response = new JSONObject();
List<JSONObject> logs = new ArrayList<>();
JsonArrayBuilder logs = Json.createArrayBuilder();
for (LogEntry logEntry : paginatedList.getResultList()) {
JSONObject log = new JSONObject();
log.put("date", logEntry.getTimestamp());
log.put("level", logEntry.getLevel());
log.put("tag", logEntry.getTag());
log.put("message", logEntry.getMessage());
logs.add(log);
logs.add(Json.createObjectBuilder()
.add("date", logEntry.getTimestamp())
.add("level", logEntry.getLevel())
.add("tag", logEntry.getTag())
.add("message", logEntry.getMessage()));
}
response.put("total", paginatedList.getResultCount());
response.put("logs", logs);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("total", paginatedList.getResultCount())
.add("logs", logs);
return Response.ok().entity(response.build()).build();
}
/**
* Destroy and rebuild Lucene index.
*
* @return Response
* @throws JSONException
*/
@POST
@Path("batch/reindex")
@Produces(MediaType.APPLICATION_JSON)
public Response batchReindex() throws JSONException {
public Response batchReindex() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -146,21 +137,20 @@ public class AppResource extends BaseResource {
throw new ServerException("IndexingError", "Error rebuilding index", e);
}
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
* Clean storage.
*
* @return Response
* @throws JSONException
*/
@POST
@Path("batch/clean_storage")
@Produces(MediaType.APPLICATION_JSON)
public Response batchCleanStorage() throws JSONException {
public Response batchCleanStorage() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -184,8 +174,9 @@ public class AppResource extends BaseResource {
}
}
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -1,19 +1,14 @@
package com.sismics.docs.rest.resource;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao;
import com.sismics.docs.core.dao.jpa.AuditLogDao;
@@ -36,11 +31,9 @@ public class AuditLogResource extends BaseResource {
* Returns the list of all logs for a document or user.
*
* @return Response
* @throws JSONException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list(@QueryParam("document") String documentId) throws JSONException {
public Response list(@QueryParam("document") String documentId) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -70,22 +63,21 @@ public class AuditLogResource extends BaseResource {
}
// Assemble the results
List<JSONObject> logs = new ArrayList<>();
JSONObject response = new JSONObject();
JsonArrayBuilder logs = Json.createArrayBuilder();
for (AuditLogDto auditLogDto : paginatedList.getResultList()) {
JSONObject log = new JSONObject();
log.put("id", auditLogDto.getId());
log.put("target", auditLogDto.getEntityId());
log.put("class", auditLogDto.getEntityClass());
log.put("type", auditLogDto.getType().name());
log.put("message", auditLogDto.getMessage());
log.put("create_date", auditLogDto.getCreateTimestamp());
logs.add(log);
logs.add(Json.createObjectBuilder()
.add("id", auditLogDto.getId())
.add("target", auditLogDto.getEntityId())
.add("class", auditLogDto.getEntityClass())
.add("type", auditLogDto.getType().name())
.add("message", auditLogDto.getMessage())
.add("create_date", auditLogDto.getCreateTimestamp()));
}
// Send the response
response.put("logs", logs);
response.put("total", paginatedList.getResultCount());
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("logs", logs)
.add("total", paginatedList.getResultCount());
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -1,17 +1,17 @@
package com.sismics.docs.rest.resource;
import java.security.Principal;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import com.sismics.docs.rest.constant.BaseFunction;
import com.sismics.rest.exception.ForbiddenClientException;
import com.sismics.security.IPrincipal;
import com.sismics.security.UserPrincipal;
import com.sismics.util.filter.TokenBasedSecurityFilter;
import org.codehaus.jettison.json.JSONException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import java.security.Principal;
import java.util.Set;
/**
* Base class of REST resources.
@@ -57,7 +57,7 @@ public abstract class BaseResource {
* @param baseFunction Base function to check
* @throws JSONException
*/
protected void checkBaseFunction(BaseFunction baseFunction) throws JSONException {
protected void checkBaseFunction(BaseFunction baseFunction) {
if (!hasBaseFunction(baseFunction)) {
throw new ForbiddenClientException();
}
@@ -70,7 +70,7 @@ public abstract class BaseResource {
* @return True if the user has the base function
* @throws JSONException
*/
protected boolean hasBaseFunction(BaseFunction baseFunction) throws JSONException {
protected boolean hasBaseFunction(BaseFunction baseFunction) {
if (principal == null || !(principal instanceof UserPrincipal)) {
return false;
}

View File

@@ -8,6 +8,9 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.persistence.NoResultException;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
@@ -16,15 +19,11 @@ 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.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
@@ -58,6 +57,7 @@ import com.sismics.docs.core.util.jpa.SortCriteria;
import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException;
import com.sismics.rest.exception.ServerException;
import com.sismics.rest.util.JsonUtil;
import com.sismics.rest.util.ValidationUtil;
/**
@@ -72,14 +72,12 @@ public class DocumentResource extends BaseResource {
*
* @param documentId Document ID
* @return Response
* @throws JSONException
*/
@GET
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(
@PathParam("id") String documentId,
@QueryParam("share") String shareId) throws JSONException {
@QueryParam("share") String shareId) {
authenticate();
DocumentDao documentDao = new DocumentDao();
@@ -96,48 +94,46 @@ public class DocumentResource extends BaseResource {
return Response.status(Status.NOT_FOUND).build();
}
JSONObject document = new JSONObject();
document.put("id", documentDto.getId());
document.put("title", documentDto.getTitle());
document.put("description", documentDto.getDescription());
document.put("create_date", documentDto.getCreateTimestamp());
document.put("language", documentDto.getLanguage());
document.put("shared", documentDto.getShared());
document.put("file_count", documentDto.getFileCount());
JsonObjectBuilder document = Json.createObjectBuilder()
.add("id", documentDto.getId())
.add("title", documentDto.getTitle())
.add("description", JsonUtil.nullable(documentDto.getDescription()))
.add("create_date", documentDto.getCreateTimestamp())
.add("language", documentDto.getLanguage())
.add("shared", documentDto.getShared())
.add("file_count", documentDto.getFileCount());
if (principal.isAnonymous()) {
// No tags in anonymous mode (sharing)
document.put("tags", new ArrayList<JSONObject>());
document.add("tags", Json.createArrayBuilder());
} else {
// Add tags added by the current user on this document
TagDao tagDao = new TagDao();
List<TagDto> tagDtoList = tagDao.getByDocumentId(documentId, principal.getId());
List<JSONObject> tags = new ArrayList<>();
JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) {
JSONObject tag = new JSONObject();
tag.put("id", tagDto.getId());
tag.put("name", tagDto.getName());
tag.put("color", tagDto.getColor());
tags.add(tag);
tags.add(Json.createObjectBuilder()
.add("id", tagDto.getId())
.add("name", tagDto.getName())
.add("color", tagDto.getColor()));
}
document.put("tags", tags);
document.add("tags", tags);
}
// Below is specific to GET /document/id
document.put("creator", documentDto.getCreator());
document.add("creator", documentDto.getCreator());
// Add ACL
List<AclDto> aclDtoList = aclDao.getBySourceId(documentId);
List<JSONObject> aclList = new ArrayList<>();
JsonArrayBuilder aclList = Json.createArrayBuilder();
boolean writable = false;
for (AclDto aclDto : aclDtoList) {
JSONObject acl = new JSONObject();
acl.put("perm", aclDto.getPerm().name());
acl.put("id", aclDto.getTargetId());
acl.put("name", aclDto.getTargetName());
acl.put("type", aclDto.getTargetType());
aclList.add(acl);
aclList.add(Json.createObjectBuilder()
.add("perm", aclDto.getPerm().name())
.add("id", aclDto.getTargetId())
.add("name", JsonUtil.nullable(aclDto.getTargetName()))
.add("type", aclDto.getTargetType()));
if (!principal.isAnonymous()
&& aclDto.getTargetId().equals(principal.getId())
@@ -146,10 +142,10 @@ public class DocumentResource extends BaseResource {
writable = true;
}
}
document.put("acls", aclList);
document.put("writable", writable);
document.add("acls", aclList)
.add("writable", writable);
return Response.ok().entity(document).build();
return Response.ok().entity(document.build()).build();
}
/**
@@ -158,23 +154,21 @@ public class DocumentResource extends BaseResource {
* @param limit Page limit
* @param offset Page offset
* @return Response
* @throws JSONException
*/
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public Response list(
@QueryParam("limit") Integer limit,
@QueryParam("offset") Integer offset,
@QueryParam("sort_column") Integer sortColumn,
@QueryParam("asc") Boolean asc,
@QueryParam("search") String search) throws JSONException {
@QueryParam("search") String search) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
JSONObject response = new JSONObject();
List<JSONObject> documents = new ArrayList<>();
JsonObjectBuilder response = Json.createObjectBuilder();
JsonArrayBuilder documents = Json.createArrayBuilder();
DocumentDao documentDao = new DocumentDao();
TagDao tagDao = new TagDao();
@@ -189,33 +183,30 @@ public class DocumentResource extends BaseResource {
}
for (DocumentDto documentDto : paginatedList.getResultList()) {
JSONObject document = new JSONObject();
document.put("id", documentDto.getId());
document.put("title", documentDto.getTitle());
document.put("description", documentDto.getDescription());
document.put("create_date", documentDto.getCreateTimestamp());
document.put("language", documentDto.getLanguage());
document.put("shared", documentDto.getShared());
document.put("file_count", documentDto.getFileCount());
// Get tags added by the current user on this document
List<TagDto> tagDtoList = tagDao.getByDocumentId(documentDto.getId(), principal.getId());
List<JSONObject> tags = new ArrayList<>();
JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) {
JSONObject tag = new JSONObject();
tag.put("id", tagDto.getId());
tag.put("name", tagDto.getName());
tag.put("color", tagDto.getColor());
tags.add(tag);
tags.add(Json.createObjectBuilder()
.add("id", tagDto.getId())
.add("name", tagDto.getName())
.add("color", tagDto.getColor()));
}
document.put("tags", tags);
documents.add(document);
documents.add(Json.createObjectBuilder()
.add("id", documentDto.getId())
.add("title", documentDto.getTitle())
.add("description", JsonUtil.nullable(documentDto.getDescription()))
.add("create_date", documentDto.getCreateTimestamp())
.add("language", documentDto.getLanguage())
.add("shared", documentDto.getShared())
.add("file_count", documentDto.getFileCount())
.add("tags", tags));
}
response.put("total", paginatedList.getResultCount());
response.put("documents", documents);
response.add("total", paginatedList.getResultCount())
.add("documents", documents);
return Response.ok().entity(response).build();
return Response.ok().entity(response.build()).build();
}
/**
@@ -329,16 +320,14 @@ public class DocumentResource extends BaseResource {
* @param language Language
* @param createDateStr Creation date
* @return Response
* @throws JSONException
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response add(
@FormParam("title") String title,
@FormParam("description") String description,
@FormParam("tags") List<String> tagList,
@FormParam("language") String language,
@FormParam("create_date") String createDateStr) throws JSONException {
@FormParam("create_date") String createDateStr) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -389,9 +378,9 @@ public class DocumentResource extends BaseResource {
documentCreatedAsyncEvent.setDocument(document);
AppContext.getInstance().getAsyncEventBus().post(documentCreatedAsyncEvent);
JSONObject response = new JSONObject();
response.put("id", documentId);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("id", documentId);
return Response.ok().entity(response.build()).build();
}
/**
@@ -400,18 +389,16 @@ public class DocumentResource extends BaseResource {
* @param title Title
* @param description Description
* @return Response
* @throws JSONException
*/
@POST
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response update(
@PathParam("id") String id,
@FormParam("title") String title,
@FormParam("description") String description,
@FormParam("tags") List<String> tagList,
@FormParam("language") String language,
@FormParam("create_date") String createDateStr) throws JSONException {
@FormParam("create_date") String createDateStr) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -458,10 +445,9 @@ public class DocumentResource extends BaseResource {
documentUpdatedAsyncEvent.setDocument(document);
AppContext.getInstance().getAsyncEventBus().post(documentUpdatedAsyncEvent);
// Always return ok
JSONObject response = new JSONObject();
response.put("id", id);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("id", id);
return Response.ok().entity(response.build()).build();
}
/**
@@ -469,9 +455,8 @@ public class DocumentResource extends BaseResource {
*
* @param documentId Document ID
* @param tagList Tag ID list
* @throws JSONException
*/
private void updateTagList(String documentId, List<String> tagList) throws JSONException {
private void updateTagList(String documentId, List<String> tagList) {
if (tagList != null) {
TagDao tagDao = new TagDao();
Set<String> tagSet = new HashSet<>();
@@ -495,13 +480,11 @@ public class DocumentResource extends BaseResource {
*
* @param id Document ID
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@PathParam("id") String id) throws JSONException {
@PathParam("id") String id) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -533,9 +516,9 @@ public class DocumentResource extends BaseResource {
documentDeletedAsyncEvent.setDocument(document);
AppContext.getInstance().getAsyncEventBus().post(documentDeletedAsyncEvent);
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -8,12 +8,14 @@ import java.io.OutputStream;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.persistence.NoResultException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -28,10 +30,11 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.StreamingOutput;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataParam;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
@@ -54,12 +57,10 @@ import com.sismics.docs.core.util.FileUtil;
import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException;
import com.sismics.rest.exception.ServerException;
import com.sismics.rest.util.JsonUtil;
import com.sismics.rest.util.ValidationUtil;
import com.sismics.util.mime.MimeType;
import com.sismics.util.mime.MimeTypeUtil;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataParam;
/**
* File REST resources.
@@ -74,14 +75,12 @@ public class FileResource extends BaseResource {
* @param documentId Document ID
* @param fileBodyPart File to add
* @return Response
* @throws JSONException
*/
@PUT
@Consumes("multipart/form-data")
@Produces(MediaType.APPLICATION_JSON)
public Response add(
@FormDataParam("id") String documentId,
@FormDataParam("file") FormDataBodyPart fileBodyPart) throws JSONException {
@FormDataParam("file") FormDataBodyPart fileBodyPart) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -156,11 +155,11 @@ public class FileResource extends BaseResource {
AppContext.getInstance().getAsyncEventBus().post(fileCreatedAsyncEvent);
}
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
response.put("id", fileId);
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok")
.add("id", fileId);
return Response.ok().entity(response.build()).build();
} catch (Exception e) {
throw new ServerException("FileError", "Error adding a file", e);
}
@@ -171,14 +170,12 @@ public class FileResource extends BaseResource {
*
* @param id File ID
* @return Response
* @throws JSONException
*/
@POST
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response attach(
@PathParam("id") String id,
@FormParam("id") String documentId) throws JSONException {
@FormParam("id") String documentId) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -226,10 +223,10 @@ public class FileResource extends BaseResource {
throw new ClientException("AttachError", "Error attaching file to document", e);
}
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -238,14 +235,12 @@ public class FileResource extends BaseResource {
* @param documentId Document ID
* @param idList List of files ID in the new order
* @return Response
* @throws JSONException
*/
@POST
@Path("reorder")
@Produces(MediaType.APPLICATION_JSON)
public Response reorder(
@FormParam("id") String documentId,
@FormParam("order") List<String> idList) throws JSONException {
@FormParam("order") List<String> idList) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -271,10 +266,10 @@ public class FileResource extends BaseResource {
}
}
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -283,14 +278,12 @@ public class FileResource extends BaseResource {
* @param documentId Document ID
* @param shareId Sharing ID
* @return Response
* @throws JSONException
*/
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public Response list(
@QueryParam("id") String documentId,
@QueryParam("share") String shareId) throws JSONException {
@QueryParam("share") String shareId) {
boolean authenticated = authenticate();
// Check document visibility
@@ -306,20 +299,18 @@ public class FileResource extends BaseResource {
FileDao fileDao = new FileDao();
List<File> fileList = fileDao.getByDocumentId(principal.getId(), documentId);
JSONObject response = new JSONObject();
List<JSONObject> files = new ArrayList<>();
JsonArrayBuilder files = Json.createArrayBuilder();
for (File fileDb : fileList) {
JSONObject file = new JSONObject();
file.put("id", fileDb.getId());
file.put("mimetype", fileDb.getMimeType());
file.put("document_id", fileDb.getDocumentId());
file.put("create_date", fileDb.getCreateDate().getTime());
files.add(file);
files.add(Json.createObjectBuilder()
.add("id", fileDb.getId())
.add("mimetype", fileDb.getMimeType())
.add("document_id", JsonUtil.nullable(fileDb.getDocumentId()))
.add("create_date", fileDb.getCreateDate().getTime()));
}
response.put("files", files);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("files", files);
return Response.ok().entity(response.build()).build();
}
/**
@@ -327,13 +318,11 @@ public class FileResource extends BaseResource {
*
* @param id File ID
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@PathParam("id") String id) throws JSONException {
@PathParam("id") String id) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -365,10 +354,10 @@ public class FileResource extends BaseResource {
fileDeletedAsyncEvent.setFile(file);
AppContext.getInstance().getAsyncEventBus().post(fileDeletedAsyncEvent);
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -376,15 +365,13 @@ public class FileResource extends BaseResource {
*
* @param fileId File ID
* @return Response
* @throws JSONException
*/
@GET
@Path("{id: [a-z0-9\\-]+}/data")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response data(
@PathParam("id") final String fileId,
@QueryParam("share") String shareId,
@QueryParam("size") String size) throws JSONException {
@QueryParam("size") String size) {
authenticate();
if (size != null) {
@@ -472,14 +459,13 @@ public class FileResource extends BaseResource {
*
* @param documentId Document ID
* @return Response
* @throws JSONException
*/
@GET
@Path("zip")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response zip(
@QueryParam("id") String documentId,
@QueryParam("share") String shareId) throws JSONException {
@QueryParam("share") String shareId) {
authenticate();
// Get the document

View File

@@ -1,17 +1,16 @@
package com.sismics.docs.rest.resource;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import com.sismics.docs.core.dao.jpa.LocaleDao;
import com.sismics.docs.core.model.jpa.Locale;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* Locale REST resources.
@@ -24,21 +23,19 @@ public class LocaleResource extends BaseResource {
* Returns the list of all locales.
*
* @return Response
* @throws JSONException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list() throws JSONException {
public Response list() {
LocaleDao localeDao = new LocaleDao();
List<Locale> localeList = localeDao.findAll();
JSONObject response = new JSONObject();
List<JSONObject> items = new ArrayList<>();
JsonArrayBuilder items = Json.createArrayBuilder();
for (Locale locale : localeList) {
JSONObject item = new JSONObject();
item.put("id", locale.getId());
items.add(item);
items.add(Json.createObjectBuilder()
.add("id", locale.getId()));
}
response.put("locales", items);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("locales", items);
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -4,19 +4,16 @@ package com.sismics.docs.rest.resource;
import java.text.MessageFormat;
import java.util.List;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.persistence.NoResultException;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
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.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.sismics.docs.core.constant.AclTargetType;
import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao;
@@ -26,6 +23,7 @@ import com.sismics.docs.core.model.jpa.Acl;
import com.sismics.docs.core.model.jpa.Share;
import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException;
import com.sismics.rest.util.JsonUtil;
import com.sismics.rest.util.ValidationUtil;
/**
@@ -40,13 +38,11 @@ public class ShareResource extends BaseResource {
*
* @param documentId Document ID
* @return Response
* @throws JSONException
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response add(
@FormParam("id") String documentId,
@FormParam("name") String name) throws JSONException {
@FormParam("name") String name) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -78,12 +74,12 @@ public class ShareResource extends BaseResource {
aclDao.create(acl);
// Returns the created ACL
JSONObject response = new JSONObject();
response.put("perm", acl.getPerm().name());
response.put("id", acl.getTargetId());
response.put("name", name);
response.put("type", AclTargetType.SHARE);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("perm", acl.getPerm().name())
.add("id", acl.getTargetId())
.add("name", JsonUtil.nullable(name))
.add("type", AclTargetType.SHARE.toString());
return Response.ok().entity(response.build()).build();
}
/**
@@ -91,13 +87,11 @@ public class ShareResource extends BaseResource {
*
* @param id Share ID
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@PathParam("id") String id) throws JSONException {
@PathParam("id") String id) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -118,9 +112,9 @@ public class ShareResource extends BaseResource {
ShareDao shareDao = new ShareDao();
shareDao.delete(id);
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -1,21 +1,28 @@
package com.sismics.docs.rest.resource;
import java.text.MessageFormat;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
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.core.Response;
import org.apache.commons.lang.StringUtils;
import com.sismics.docs.core.dao.jpa.TagDao;
import com.sismics.docs.core.dao.jpa.dto.TagStatDto;
import com.sismics.docs.core.model.jpa.Tag;
import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException;
import com.sismics.rest.util.ValidationUtil;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Tag REST resources.
@@ -28,29 +35,27 @@ public class TagResource extends BaseResource {
* Returns the list of all tags.
*
* @return Response
* @throws JSONException
*/
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public Response list() throws JSONException {
public Response list() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
TagDao tagDao = new TagDao();
List<Tag> tagList = tagDao.getByUserId(principal.getId());
JSONObject response = new JSONObject();
List<JSONObject> items = new ArrayList<>();
JsonArrayBuilder items = Json.createArrayBuilder();
for (Tag tag : tagList) {
JSONObject item = new JSONObject();
item.put("id", tag.getId());
item.put("name", tag.getName());
item.put("color", tag.getColor());
items.add(item);
items.add(Json.createObjectBuilder()
.add("id", tag.getId())
.add("name", tag.getName())
.add("color", tag.getColor()));
}
response.put("tags", items);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("tags", items);
return Response.ok().entity(response.build()).build();
}
/**
@@ -61,26 +66,25 @@ public class TagResource extends BaseResource {
*/
@GET
@Path("/stats")
@Produces(MediaType.APPLICATION_JSON)
public Response stats() throws JSONException {
public Response stats() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
TagDao tagDao = new TagDao();
List<TagStatDto> tagStatDtoList = tagDao.getStats(principal.getId());
JSONObject response = new JSONObject();
List<JSONObject> items = new ArrayList<>();
JsonArrayBuilder items = Json.createArrayBuilder();
for (TagStatDto tagStatDto : tagStatDtoList) {
JSONObject item = new JSONObject();
item.put("id", tagStatDto.getId());
item.put("name", tagStatDto.getName());
item.put("color", tagStatDto.getColor());
item.put("count", tagStatDto.getCount());
items.add(item);
items.add(Json.createObjectBuilder()
.add("id", tagStatDto.getId())
.add("name", tagStatDto.getName())
.add("color", tagStatDto.getColor())
.add("count", tagStatDto.getCount()));
}
response.put("stats", items);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("stats", items);
return Response.ok().entity(response.build()).build();
}
/**
@@ -88,13 +92,11 @@ public class TagResource extends BaseResource {
*
* @param name Name
* @return Response
* @throws JSONException
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response add(
@FormParam("name") String name,
@FormParam("color") String color) throws JSONException {
@FormParam("color") String color) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -120,11 +122,11 @@ public class TagResource extends BaseResource {
tag.setName(name);
tag.setColor(color);
tag.setUserId(principal.getId());
String tagId = tagDao.create(tag);
String id = tagDao.create(tag);
JSONObject response = new JSONObject();
response.put("id", tagId);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("id", id);
return Response.ok().entity(response.build()).build();
}
/**
@@ -132,15 +134,13 @@ public class TagResource extends BaseResource {
*
* @param name Name
* @return Response
* @throws JSONException
*/
@POST
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response update(
@PathParam("id") String id,
@FormParam("name") String name,
@FormParam("color") String color) throws JSONException {
@FormParam("color") String color) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -177,9 +177,9 @@ public class TagResource extends BaseResource {
tagDao.update(tag);
JSONObject response = new JSONObject();
response.put("id", id);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("id", id);
return Response.ok().entity(response.build()).build();
}
/**
@@ -187,13 +187,11 @@ public class TagResource extends BaseResource {
*
* @param tagId Tag ID
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{id: [a-z0-9\\-]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@PathParam("id") String tagId) throws JSONException {
@PathParam("id") String tagId) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -208,8 +206,9 @@ public class TagResource extends BaseResource {
// Delete the tag
tagDao.delete(tagId);
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -1,55 +0,0 @@
package com.sismics.docs.rest.resource;
import com.sun.jersey.core.util.ReaderWriter;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* MessageBodyWriter personalized to write JSON despite the text/plain MIME type.
* Used in particuler in return of a posted form, since IE doesn't knw how to read the application/json MIME type.
*
* @author bgamard
*/
@Provider
@Produces(MediaType.TEXT_PLAIN)
public class TextPlainMessageBodyWriter implements
MessageBodyWriter<JSONObject> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public long getSize(JSONObject array, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(JSONObject jsonObject, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
try {
OutputStreamWriter writer = new OutputStreamWriter(entityStream, ReaderWriter.getCharset(mediaType));
jsonObject.write(writer);
writer.flush();
} catch (JSONException e) {
throw new WebApplicationException(e);
}
}
}

View File

@@ -1,43 +0,0 @@
package com.sismics.docs.rest.resource;
import com.sismics.docs.core.dao.file.theme.ThemeDao;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* Theme REST resources.
*
* @author jtremeaux
*/
@Path("/theme")
public class ThemeResource extends BaseResource {
/**
* Returns the list of all themes.
*
* @return Response
* @throws JSONException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list() throws JSONException {
ThemeDao themeDao = new ThemeDao();
List<String> themeList = themeDao.findAll();
JSONObject response = new JSONObject();
List<JSONObject> items = new ArrayList<>();
for (String theme : themeList) {
JSONObject item = new JSONObject();
item.put("id", theme);
items.add(item);
}
response.put("themes", items);
return Response.ok().entity(response).build();
}
}

View File

@@ -1,5 +1,28 @@
package com.sismics.docs.rest.resource;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.servlet.http.Cookie;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
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.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Strings;
import com.sismics.docs.core.constant.Constants;
import com.sismics.docs.core.dao.jpa.AuthenticationTokenDao;
@@ -22,23 +45,6 @@ import com.sismics.security.UserPrincipal;
import com.sismics.util.LocaleUtil;
import com.sismics.util.filter.TokenBasedSecurityFilter;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.servlet.http.Cookie;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* User REST resources.
*
@@ -52,17 +58,13 @@ public class UserResource extends BaseResource {
* @param username User's username
* @param password Password
* @param email E-Mail
* @param localeId Locale ID
* @return Response
* @throws JSONException
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response register(
@FormParam("username") String username,
@FormParam("password") String password,
@FormParam("locale") String localeId,
@FormParam("email") String email) throws JSONException {
@FormParam("email") String email) {
if (!authenticate()) {
throw new ForbiddenClientException();
@@ -89,11 +91,7 @@ public class UserResource extends BaseResource {
}
user.setCreateDate(new Date());
if (localeId == null) {
// Set the locale from the HTTP headers
localeId = LocaleUtil.getLocaleIdFromAcceptLanguage(request.getHeader("Accept-Language"));
}
user.setLocaleId(localeId);
user.setLocaleId(LocaleUtil.getLocaleIdFromAcceptLanguage(request.getHeader("Accept-Language")));
// Create the user
UserDao userDao = new UserDao();
@@ -108,9 +106,9 @@ public class UserResource extends BaseResource {
}
// Always return OK
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -118,20 +116,14 @@ public class UserResource extends BaseResource {
*
* @param password Password
* @param email E-Mail
* @param themeId Theme
* @param localeId Locale ID
* @param firstConnection True if the user hasn't acknowledged the first connection wizard yet.
* @return Response
* @throws JSONException
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response update(
@FormParam("password") String password,
@FormParam("email") String email,
@FormParam("theme") String themeId,
@FormParam("locale") String localeId,
@FormParam("first_connection") Boolean firstConnection) throws JSONException {
@FormParam("first_connection") Boolean firstConnection) {
if (!authenticate()) {
throw new ForbiddenClientException();
@@ -140,8 +132,6 @@ public class UserResource extends BaseResource {
// Validate the input data
password = ValidationUtil.validateLength(password, "password", 8, 50, true);
email = ValidationUtil.validateLength(email, "email", null, 100, true);
localeId = ValidationUtil.validateLocale(localeId, "locale", true);
themeId = ValidationUtil.validateTheme(themeId, "theme", true);
// Update the user
UserDao userDao = new UserDao();
@@ -149,12 +139,6 @@ public class UserResource extends BaseResource {
if (email != null) {
user.setEmail(email);
}
if (themeId != null) {
user.setTheme(themeId);
}
if (localeId != null) {
user.setLocaleId(localeId);
}
if (firstConnection != null && hasBaseFunction(BaseFunction.ADMIN)) {
user.setFirstConnection(firstConnection);
}
@@ -166,10 +150,10 @@ public class UserResource extends BaseResource {
userDao.updatePassword(user);
}
// Always return "ok"
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -178,20 +162,14 @@ public class UserResource extends BaseResource {
* @param username Username
* @param password Password
* @param email E-Mail
* @param themeId Theme
* @param localeId Locale ID
* @return Response
* @throws JSONException
*/
@POST
@Path("{username: [a-zA-Z0-9_]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response update(
@PathParam("username") String username,
@FormParam("password") String password,
@FormParam("email") String email,
@FormParam("theme") String themeId,
@FormParam("locale") String localeId) throws JSONException {
@FormParam("email") String email) {
if (!authenticate()) {
throw new ForbiddenClientException();
@@ -201,8 +179,6 @@ public class UserResource extends BaseResource {
// Validate the input data
password = ValidationUtil.validateLength(password, "password", 8, 50, true);
email = ValidationUtil.validateLength(email, "email", null, 100, true);
localeId = ValidationUtil.validateLocale(localeId, "locale", true);
themeId = ValidationUtil.validateTheme(themeId, "theme", true);
// Check if the user exists
UserDao userDao = new UserDao();
@@ -215,12 +191,6 @@ public class UserResource extends BaseResource {
if (email != null) {
user.setEmail(email);
}
if (themeId != null) {
user.setTheme(themeId);
}
if (localeId != null) {
user.setLocaleId(localeId);
}
user = userDao.update(user);
@@ -230,10 +200,10 @@ public class UserResource extends BaseResource {
userDao.updatePassword(user);
}
// Always return "ok"
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -244,22 +214,21 @@ public class UserResource extends BaseResource {
*/
@GET
@Path("check_username")
@Produces(MediaType.APPLICATION_JSON)
public Response checkUsername(
@QueryParam("username") String username) throws JSONException {
@QueryParam("username") String username) {
UserDao userDao = new UserDao();
User user = userDao.getActiveByUsername(username);
JSONObject response = new JSONObject();
JsonObjectBuilder response = Json.createObjectBuilder();
if (user != null) {
response.put("status", "ko");
response.put("message", "Username already registered");
response.add("status", "ko")
.add("message", "Username already registered");
} else {
response.put("status", "ok");
response.add("status", "ok");
}
return Response.ok().entity(response).build();
return Response.ok().entity(response.build()).build();
}
/**
@@ -273,11 +242,10 @@ public class UserResource extends BaseResource {
*/
@POST
@Path("login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(
@FormParam("username") String username,
@FormParam("password") String password,
@FormParam("remember") boolean longLasted) throws JSONException {
@FormParam("remember") boolean longLasted) {
// Validate the input data
username = StringUtils.strip(username);
@@ -308,10 +276,10 @@ public class UserResource extends BaseResource {
// Cleanup old session tokens
authenticationTokenDao.deleteOldSessionToken(userId);
JSONObject response = new JSONObject();
JsonObjectBuilder response = Json.createObjectBuilder();
int maxAge = longLasted ? TokenBasedSecurityFilter.TOKEN_LONG_LIFETIME : -1;
NewCookie cookie = new NewCookie(TokenBasedSecurityFilter.COOKIE_NAME, token, "/", null, null, maxAge, false);
return Response.ok().entity(response).cookie(cookie).build();
return Response.ok().entity(response.build()).cookie(cookie).build();
}
/**
@@ -321,8 +289,7 @@ public class UserResource extends BaseResource {
*/
@POST
@Path("logout")
@Produces(MediaType.APPLICATION_JSON)
public Response logout() throws JSONException {
public Response logout() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -356,9 +323,9 @@ public class UserResource extends BaseResource {
}
// Deletes the client token in the HTTP response
JSONObject response = new JSONObject();
JsonObjectBuilder response = Json.createObjectBuilder();
NewCookie cookie = new NewCookie(TokenBasedSecurityFilter.COOKIE_NAME, null);
return Response.ok().entity(response).cookie(cookie).build();
return Response.ok().entity(response.build()).cookie(cookie).build();
}
/**
@@ -367,8 +334,7 @@ public class UserResource extends BaseResource {
* @return Response
*/
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response delete() throws JSONException {
public Response delete() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -382,10 +348,10 @@ public class UserResource extends BaseResource {
UserDao userDao = new UserDao();
userDao.delete(principal.getName());
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
@@ -393,12 +359,10 @@ public class UserResource extends BaseResource {
*
* @param username Username
* @return Response
* @throws JSONException
*/
@DELETE
@Path("{username: [a-zA-Z0-9_]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("username") String username) throws JSONException {
public Response delete(@PathParam("username") String username) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -421,49 +385,49 @@ public class UserResource extends BaseResource {
// Delete the user
userDao.delete(user.getUsername());
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
/**
* Returns the information about the connected user.
*
* @return Response
* @throws JSONException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response info() throws JSONException {
JSONObject response = new JSONObject();
public Response info() {
JsonObjectBuilder response = Json.createObjectBuilder();
if (!authenticate()) {
response.put("anonymous", true);
response.add("anonymous", true);
String localeId = LocaleUtil.getLocaleIdFromAcceptLanguage(request.getHeader("Accept-Language"));
response.put("locale", localeId);
response.add("locale", localeId);
// Check if admin has the default password
UserDao userDao = new UserDao();
User adminUser = userDao.getById("admin");
if (adminUser != null && adminUser.getDeleteDate() == null) {
response.put("is_default_password", Constants.DEFAULT_ADMIN_PASSWORD.equals(adminUser.getPassword()));
response.add("is_default_password", Constants.DEFAULT_ADMIN_PASSWORD.equals(adminUser.getPassword()));
}
} else {
response.put("anonymous", false);
response.add("anonymous", false);
UserDao userDao = new UserDao();
User user = userDao.getById(principal.getId());
response.put("username", user.getUsername());
response.put("email", user.getEmail());
response.put("theme", user.getTheme());
response.put("locale", user.getLocaleId());
response.put("first_connection", user.isFirstConnection());
JSONArray baseFunctions = new JSONArray(((UserPrincipal) principal).getBaseFunctionSet());
response.put("base_functions", baseFunctions);
response.put("is_default_password", hasBaseFunction(BaseFunction.ADMIN) && Constants.DEFAULT_ADMIN_PASSWORD.equals(user.getPassword()));
response.add("username", user.getUsername())
.add("email", user.getEmail())
.add("locale", user.getLocaleId())
.add("first_connection", user.isFirstConnection());
JsonArrayBuilder baseFunctions = Json.createArrayBuilder();
for (String baseFunction : ((UserPrincipal) principal).getBaseFunctionSet()) {
baseFunctions.add(baseFunction);
}
response.add("base_functions", baseFunctions)
.add("is_default_password", hasBaseFunction(BaseFunction.ADMIN) && Constants.DEFAULT_ADMIN_PASSWORD.equals(user.getPassword()));
}
return Response.ok().entity(response).build();
return Response.ok().entity(response.build()).build();
}
/**
@@ -471,31 +435,27 @@ public class UserResource extends BaseResource {
*
* @param username Username
* @return Response
* @throws JSONException
*/
@GET
@Path("{username: [a-zA-Z0-9_]+}")
@Produces(MediaType.APPLICATION_JSON)
public Response view(@PathParam("username") String username) throws JSONException {
public Response view(@PathParam("username") String username) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
checkBaseFunction(BaseFunction.ADMIN);
JSONObject response = new JSONObject();
UserDao userDao = new UserDao();
User user = userDao.getActiveByUsername(username);
if (user == null) {
throw new ClientException("UserNotFound", "The user doesn't exist");
}
response.put("username", user.getUsername());
response.put("email", user.getEmail());
response.put("theme", user.getTheme());
response.put("locale", user.getLocaleId());
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("username", user.getUsername())
.add("email", user.getEmail())
.add("locale", user.getLocaleId());
return Response.ok().entity(response.build()).build();
}
/**
@@ -506,53 +466,47 @@ public class UserResource extends BaseResource {
* @param sortColumn Sort index
* @param asc If true, ascending sorting, else descending
* @return Response
* @throws JSONException
*/
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public Response list(
@QueryParam("limit") Integer limit,
@QueryParam("offset") Integer offset,
@QueryParam("sort_column") Integer sortColumn,
@QueryParam("asc") Boolean asc) throws JSONException {
@QueryParam("asc") Boolean asc) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
checkBaseFunction(BaseFunction.ADMIN);
JSONObject response = new JSONObject();
List<JSONObject> users = new ArrayList<>();
JsonArrayBuilder users = Json.createArrayBuilder();
PaginatedList<UserDto> paginatedList = PaginatedLists.create(limit, offset);
SortCriteria sortCriteria = new SortCriteria(sortColumn, asc);
UserDao userDao = new UserDao();
userDao.findByCriteria(paginatedList, new UserCriteria(), sortCriteria);
for (UserDto userDto : paginatedList.getResultList()) {
JSONObject user = new JSONObject();
user.put("id", userDto.getId());
user.put("username", userDto.getUsername());
user.put("email", userDto.getEmail());
user.put("create_date", userDto.getCreateTimestamp());
users.add(user);
users.add(Json.createObjectBuilder()
.add("id", userDto.getId())
.add("username", userDto.getUsername())
.add("email", userDto.getEmail())
.add("create_date", userDto.getCreateTimestamp()));
}
response.put("total", paginatedList.getResultCount());
response.put("users", users);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("total", paginatedList.getResultCount())
.add("users", users);
return Response.ok().entity(response.build()).build();
}
/**
* Returns all active sessions.
*
* @return Response
* @throws JSONException
*/
@GET
@Path("session")
@Produces(MediaType.APPLICATION_JSON)
public Response session() throws JSONException {
public Response session() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -567,37 +521,34 @@ public class UserResource extends BaseResource {
}
}
JSONObject response = new JSONObject();
List<JSONObject> sessions = new ArrayList<>();
JsonArrayBuilder sessions = Json.createArrayBuilder();
AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao();
for (AuthenticationToken authenticationToken : authenticationTokenDao.getByUserId(principal.getId())) {
JSONObject session = new JSONObject();
session.put("create_date", authenticationToken.getCreationDate().getTime());
session.put("ip", authenticationToken.getIp());
session.put("user_agent", authenticationToken.getUserAgent());
JsonObjectBuilder session = Json.createObjectBuilder()
.add("create_date", authenticationToken.getCreationDate().getTime())
.add("ip", authenticationToken.getIp())
.add("user_agent", authenticationToken.getUserAgent());
if (authenticationToken.getLastConnectionDate() != null) {
session.put("last_connection_date", authenticationToken.getLastConnectionDate().getTime());
session.add("last_connection_date", authenticationToken.getLastConnectionDate().getTime());
}
session.put("current", authenticationToken.getId().equals(authToken));
session.add("current", authenticationToken.getId().equals(authToken));
sessions.add(session);
}
response.put("sessions", sessions);
return Response.ok().entity(response).build();
JsonObjectBuilder response = Json.createObjectBuilder()
.add("sessions", sessions);
return Response.ok().entity(response.build()).build();
}
/**
* Deletes all active sessions except the one used for this request.
*
* @return Response
* @throws JSONException
*/
@DELETE
@Path("session")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteSession() throws JSONException {
public Response deleteSession() {
if (!authenticate()) {
throw new ForbiddenClientException();
}
@@ -616,9 +567,9 @@ public class UserResource extends BaseResource {
AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao();
authenticationTokenDao.deleteByUserId(principal.getId(), authToken);
// Always return ok
JSONObject response = new JSONObject();
response.put("status", "ok");
return Response.ok().entity(response).build();
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()
.add("status", "ok");
return Response.ok().entity(response.build()).build();
}
}

View File

@@ -6,10 +6,11 @@
version="3.0">
<display-name>Docs</display-name>
<!-- This filter is used to secure URLs -->
<!-- This filter is used to process a couple things in the request context -->
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>com.sismics.util.filter.RequestContextFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
@@ -22,6 +23,7 @@
<filter>
<filter-name>tokenBasedSecurityFilter</filter-name>
<filter-class>com.sismics.util.filter.TokenBasedSecurityFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
@@ -29,23 +31,28 @@
<url-pattern>/api/*</url-pattern>
</filter-mapping>
<!-- Welcome files -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Jersey -->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<servlet-name>JerseyServlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.sismics.docs.rest.resource</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.response.setStatusOverSendError</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-name>JerseyServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>