mirror of
https://github.com/sismics/docs.git
synced 2024-11-14 18:27:58 +01:00
Closes #29: Upgrade to Jersey 2
This commit is contained in:
parent
97694d5d59
commit
0fe51d355c
@ -26,6 +26,11 @@
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Other external dependencies -->
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
|
@ -1,38 +0,0 @@
|
||||
package com.sismics.docs.core.dao.file.theme;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.sismics.docs.core.util.DirectoryUtil;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FilenameFilter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Theme DAO.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class ThemeDao {
|
||||
private final static FilenameFilter CSS_FILTER = new FilenameFilter() {
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
return name.endsWith(".css") || name.endsWith(".less");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the list of all themes.
|
||||
*
|
||||
* @return List of themes
|
||||
*/
|
||||
public List<String> findAll() {
|
||||
final File themeDirectory = DirectoryUtil.getThemeDirectory();
|
||||
if (themeDirectory != null) {
|
||||
return Lists.newArrayList(themeDirectory.list(CSS_FILTER));
|
||||
} else {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,9 +1,10 @@
|
||||
package com.sismics.docs.core.util;
|
||||
|
||||
import com.sismics.util.EnvironmentUtil;
|
||||
import java.io.File;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import com.sismics.util.EnvironmentUtil;
|
||||
|
||||
/**
|
||||
* Utilities to gain access to the storage directories used by the application.
|
||||
@ -18,27 +19,27 @@ public class DirectoryUtil {
|
||||
*/
|
||||
public static File getBaseDataDirectory() {
|
||||
File baseDataDir = null;
|
||||
if (EnvironmentUtil.getWebappRoot() != null) {
|
||||
// We are in a webapp environment
|
||||
if (StringUtils.isNotBlank(EnvironmentUtil.getDocsHome())) {
|
||||
// If the docs.home property is set then use it
|
||||
baseDataDir = new File(EnvironmentUtil.getDocsHome());
|
||||
if (!baseDataDir.isDirectory()) {
|
||||
baseDataDir.mkdirs();
|
||||
}
|
||||
} else {
|
||||
// Use the base of the Webapp directory
|
||||
baseDataDir = new File(EnvironmentUtil.getWebappRoot() + File.separator + "sismicsdocs");
|
||||
if (!baseDataDir.isDirectory()) {
|
||||
baseDataDir.mkdirs();
|
||||
}
|
||||
if (StringUtils.isNotBlank(EnvironmentUtil.getDocsHome())) {
|
||||
// If the docs.home property is set then use it
|
||||
baseDataDir = new File(EnvironmentUtil.getDocsHome());
|
||||
} else if (EnvironmentUtil.isUnitTest()) {
|
||||
// For unit testing, use a temporary directory
|
||||
baseDataDir = new File(System.getProperty("java.io.tmpdir"));
|
||||
} else {
|
||||
// We are in a webapp environment and nothing is specified, use the default directory for this OS
|
||||
if (EnvironmentUtil.isUnix()) {
|
||||
baseDataDir = new File("/var/docs");
|
||||
} if (EnvironmentUtil.isWindows()) {
|
||||
baseDataDir = new File(EnvironmentUtil.getWindowsAppData() + "\\Sismics\\Docs");
|
||||
} else if (EnvironmentUtil.isMacOs()) {
|
||||
baseDataDir = new File(EnvironmentUtil.getMacOsUserHome() + "/Library/Sismics/Docs");
|
||||
}
|
||||
}
|
||||
if (baseDataDir == null) {
|
||||
// Or else (for unit testing), use a temporary directory
|
||||
baseDataDir = new File(System.getProperty("java.io.tmpdir"));
|
||||
|
||||
if (baseDataDir != null && !baseDataDir.isDirectory()) {
|
||||
baseDataDir.mkdirs();
|
||||
}
|
||||
|
||||
|
||||
return baseDataDir;
|
||||
}
|
||||
|
||||
@ -78,25 +79,6 @@ public class DirectoryUtil {
|
||||
return getDataSubDirectory("log");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the themes directory.
|
||||
*
|
||||
* @return Theme directory.
|
||||
*/
|
||||
public static File getThemeDirectory() {
|
||||
String webappRoot = EnvironmentUtil.getWebappRoot();
|
||||
File themeDir = null;
|
||||
if (webappRoot != null) {
|
||||
themeDir = new File(webappRoot + File.separator + "style" + File.separator + "theme");
|
||||
} else {
|
||||
themeDir = new File(DirectoryUtil.class.getResource("/style/theme").getFile());
|
||||
}
|
||||
if (themeDir != null && themeDir.isDirectory()) {
|
||||
return themeDir;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a subdirectory of the base data directory
|
||||
*
|
||||
|
@ -9,7 +9,7 @@ public class EnvironmentUtil {
|
||||
|
||||
private static String OS = System.getProperty("os.name").toLowerCase();
|
||||
|
||||
private static String TEST_ENV = System.getProperty("test");
|
||||
private static String APPLICATION_MODE = System.getProperty("application.mode");
|
||||
|
||||
private static String WINDOWS_APPDATA = System.getenv("APPDATA");
|
||||
|
||||
@ -18,9 +18,9 @@ public class EnvironmentUtil {
|
||||
private static String DOCS_HOME = System.getProperty("docs.home");
|
||||
|
||||
/**
|
||||
* Web application root.
|
||||
* In a web application context.
|
||||
*/
|
||||
private static String webappRoot;
|
||||
private static boolean webappContext;
|
||||
|
||||
/**
|
||||
* Returns true if running under Microsoft Windows.
|
||||
@ -55,10 +55,18 @@ public class EnvironmentUtil {
|
||||
* @return Unit testing environment
|
||||
*/
|
||||
public static boolean isUnitTest() {
|
||||
return webappRoot == null ||
|
||||
TEST_ENV != null && "true".equals(TEST_ENV);
|
||||
return !webappContext || isDevMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if we are in dev mode.
|
||||
*
|
||||
* @return Dev mode
|
||||
*/
|
||||
public static boolean isDevMode() {
|
||||
return "dev".equalsIgnoreCase(APPLICATION_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MS Windows AppData directory of this user.
|
||||
*
|
||||
@ -87,20 +95,20 @@ public class EnvironmentUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter of webappRoot.
|
||||
* Getter of webappContext.
|
||||
*
|
||||
* @return webappRoot
|
||||
* @return webappContext
|
||||
*/
|
||||
public static String getWebappRoot() {
|
||||
return webappRoot;
|
||||
public static boolean isWebappContext() {
|
||||
return webappContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter of webappRoot.
|
||||
* Setter of webappContext.
|
||||
*
|
||||
* @param webappRoot webappRoot
|
||||
* @param webappContext webappContext
|
||||
*/
|
||||
public static void setWebappRoot(String webappRoot) {
|
||||
EnvironmentUtil.webappRoot = webappRoot;
|
||||
public static void setWebappContext(boolean webappContext) {
|
||||
EnvironmentUtil.webappContext = webappContext;
|
||||
}
|
||||
}
|
||||
|
@ -26,7 +26,7 @@
|
||||
<org.slf4j.jcl-over-slf4j.version>1.6.6</org.slf4j.jcl-over-slf4j.version>
|
||||
<junit.junit.version>4.7</junit.junit.version>
|
||||
<com.h2database.h2.version>1.4.188</com.h2database.h2.version>
|
||||
<com.sun.jersey.version>1.17</com.sun.jersey.version>
|
||||
<org.glassfish.jersey.version>2.21</org.glassfish.jersey.version>
|
||||
<org.mindrot.jbcrypt>0.3m</org.mindrot.jbcrypt>
|
||||
<org.apache.lucene.version>4.2.0</org.apache.lucene.version>
|
||||
<org.imgscalr.imgscalr-lib.version>4.2</org.imgscalr.imgscalr-lib.version>
|
||||
@ -34,12 +34,11 @@
|
||||
<org.bouncycastle.bcprov-jdk15on.version>1.49</org.bouncycastle.bcprov-jdk15on.version>
|
||||
<joda-time.joda-time.version>2.8.2</joda-time.joda-time.version>
|
||||
<org.hibernate.hibernate.version>4.1.0.Final</org.hibernate.hibernate.version>
|
||||
<com.sun.grizzly.version>1.9.64</com.sun.grizzly.version>
|
||||
<javax.servlet.javax.servlet-api.version>3.1.0</javax.servlet.javax.servlet-api.version>
|
||||
|
||||
<org.eclipse.jetty.jetty-server.version>9.2.13.v20150730</org.eclipse.jetty.jetty-server.version>
|
||||
<org.eclipse.jetty.jetty-webapp.version>9.2.13.v20150730</org.eclipse.jetty.jetty-webapp.version>
|
||||
<org.eclipse.jetty.jetty-servlet.version>9.2.13.v20150730</org.eclipse.jetty.jetty-servlet.version>
|
||||
<org.mortbay.jetty.servlet-api.version>3.0.20100224</org.mortbay.jetty.servlet-api.version>
|
||||
|
||||
<!-- Plugins version -->
|
||||
<org.apache.maven.plugins.maven-antrun-plugin.version>1.8</org.apache.maven.plugins.maven-antrun-plugin.version>
|
||||
@ -163,9 +162,9 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mortbay.jetty</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<version>${org.mortbay.jetty.servlet-api.version}</version>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet.javax.servlet-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@ -229,47 +228,54 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-server</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-bundle</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-json</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.contribs</groupId>
|
||||
<artifactId>jersey-multipart</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-servlet</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.grizzly</groupId>
|
||||
<artifactId>grizzly-servlet-webserver</artifactId>
|
||||
<version>${com.sun.grizzly.version}</version>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-processing</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.jersey-test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-grizzly2</artifactId>
|
||||
<version>${com.sun.jersey.version}</version>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-multipart</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-bundle</artifactId>
|
||||
<type>pom</type>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-external</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-grizzly2-servlet</artifactId>
|
||||
<version>${org.glassfish.jersey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
@ -288,6 +294,12 @@
|
||||
<version>${org.hibernate.hibernate.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${org.hibernate.hibernate.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-dbcp</groupId>
|
||||
<artifactId>commons-dbcp</artifactId>
|
||||
|
@ -17,10 +17,15 @@
|
||||
<dependencies>
|
||||
<!-- Dependencies to Jersey -->
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-multipart</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Depenedencies to Docs -->
|
||||
<dependency>
|
||||
<groupId>com.sismics.docs</groupId>
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.sismics.docs.stress;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
@ -8,25 +7,30 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.Invocation;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.glassfish.jersey.client.ClientResponse;
|
||||
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
|
||||
import org.glassfish.jersey.media.multipart.MultiPartFeature;
|
||||
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.google.common.io.Resources;
|
||||
import com.sismics.docs.rest.util.ClientUtil;
|
||||
import com.sun.jersey.api.client.Client;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import com.sun.jersey.multipart.FormDataBodyPart;
|
||||
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
/**
|
||||
* Stress app for Sismics Docs.
|
||||
@ -45,7 +49,7 @@ public class Main {
|
||||
private static final int TAG_PER_USER_COUNT = 20;
|
||||
private static final int FILE_PER_DOCUMENT_COUNT = 0;
|
||||
|
||||
private static Client client = Client.create();
|
||||
private static Client client = ClientBuilder.newClient();
|
||||
private static ClientUtil clientUtil;
|
||||
|
||||
private static Set<User> userSet = Sets.newHashSet();
|
||||
@ -54,11 +58,12 @@ public class Main {
|
||||
* Entry point.
|
||||
*
|
||||
* @param args Args
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) throws Exception {
|
||||
log.info("Starting stress test...");
|
||||
|
||||
WebResource resource = client.resource(API_URL);
|
||||
WebTarget resource = client.target(API_URL);
|
||||
clientUtil = new ClientUtil(resource);
|
||||
|
||||
// Create users
|
||||
@ -72,17 +77,16 @@ public class Main {
|
||||
// Create tags for each user
|
||||
int tagCreatedCount = 1;
|
||||
for (User user : userSet) {
|
||||
WebResource tagResource = resource.path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(user.authToken));
|
||||
Invocation.Builder tagResource = resource.path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, user.authToken);
|
||||
|
||||
for (int j = 0; j < TAG_PER_USER_COUNT; j++) {
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
Form form = new Form();
|
||||
String name = generateString();
|
||||
postParams.add("name", name);
|
||||
postParams.add("color", "#ff0000");
|
||||
ClientResponse response = tagResource.put(ClientResponse.class, postParams);
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
user.tagList.add(json.optString("id"));
|
||||
form.param("name", name);
|
||||
form.param("color", "#ff0000");
|
||||
JsonObject json = tagResource.put(Entity.form(form), JsonObject.class);
|
||||
user.tagList.add(json.getString("id"));
|
||||
log.info("Created tag " + (tagCreatedCount++) + "/" + TAG_PER_USER_COUNT * USER_COUNT);
|
||||
}
|
||||
}
|
||||
@ -91,33 +95,32 @@ public class Main {
|
||||
int documentCreatedCount = 1;
|
||||
for (User user : userSet) {
|
||||
for (int i = 0; i < DOCUMENT_PER_USER_COUNT; i++) {
|
||||
WebResource documentResource = resource.path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(user.authToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", generateString());
|
||||
postParams.add("description", generateString());
|
||||
postParams.add("tags", user.tagList.get(ThreadLocalRandom.current().nextInt(user.tagList.size()))); // Random tag
|
||||
postParams.add("language", "eng");
|
||||
long createDate = new Date().getTime();
|
||||
postParams.add("create_date", createDate);
|
||||
ClientResponse response = documentResource.put(ClientResponse.class, postParams);
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String documentId = json.optString("id");
|
||||
Form form = new Form()
|
||||
.param("title", generateString())
|
||||
.param("description", generateString())
|
||||
.param("tags", user.tagList.get(ThreadLocalRandom.current().nextInt(user.tagList.size()))) // Random tag
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(createDate));
|
||||
JsonObject json = resource.path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, user.authToken)
|
||||
.put(Entity.form(form), JsonObject.class);
|
||||
String documentId = json.getString("id");
|
||||
log.info("Created document " + (documentCreatedCount++) + "/" + DOCUMENT_PER_USER_COUNT * USER_COUNT + " for user: " + user.username);
|
||||
|
||||
// Add files for each document
|
||||
for (int j = 0; j < FILE_PER_DOCUMENT_COUNT; j++) {
|
||||
WebResource fileResource = resource.path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(user.authToken));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = Main.class.getResourceAsStream("/empty.png");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", documentId);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
try (InputStream is = Resources.getResource("empty.png").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "empty.png");
|
||||
@SuppressWarnings("resource")
|
||||
ClientResponse response = resource
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, user.authToken)
|
||||
.put(Entity.entity(new FormDataMultiPart().field("id", documentId).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -22,23 +22,13 @@
|
||||
|
||||
<!-- Dependencies to Jersey -->
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-server</artifactId>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-servlet</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-bundle</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-json</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.contribs</groupId>
|
||||
<artifactId>jersey-multipart</artifactId>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-processing</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Other external dependencies -->
|
||||
@ -68,8 +58,8 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mortbay.jetty</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
@ -86,14 +76,20 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.grizzly</groupId>
|
||||
<artifactId>grizzly-servlet-webserver</artifactId>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-external</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.jersey-test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-grizzly2</artifactId>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-grizzly2-servlet</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
@ -1,11 +1,9 @@
|
||||
package com.sismics.rest.exception;
|
||||
|
||||
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
@ -32,9 +30,8 @@ public class ClientException extends WebApplicationException {
|
||||
* @param type Error type (e.g. AlreadyExistingEmail, ValidationError)
|
||||
* @param message Human readable error message
|
||||
* @param e Readable error message
|
||||
* @throws JSONException
|
||||
*/
|
||||
public ClientException(String type, String message, Exception e) throws JSONException {
|
||||
public ClientException(String type, String message, Exception e) {
|
||||
this(type, message);
|
||||
log.error(type + ": " + message, e);
|
||||
}
|
||||
@ -44,11 +41,10 @@ public class ClientException extends WebApplicationException {
|
||||
*
|
||||
* @param type Error type (e.g. AlreadyExistingEmail, ValidationError)
|
||||
* @param message Human readable error message
|
||||
* @throws JSONException
|
||||
*/
|
||||
public ClientException(String type, String message) throws JSONException {
|
||||
super(Response.status(Status.BAD_REQUEST).entity(new JSONObject()
|
||||
.put("type", type)
|
||||
.put("message", message)).build());
|
||||
public ClientException(String type, String message) {
|
||||
super(Response.status(Status.BAD_REQUEST).entity(Json.createObjectBuilder()
|
||||
.add("type", type)
|
||||
.add("message", message).build()).build());
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,6 @@
|
||||
package com.sismics.rest.exception;
|
||||
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
@ -20,12 +18,10 @@ public class ForbiddenClientException extends WebApplicationException {
|
||||
|
||||
/**
|
||||
* Constructor of ForbiddenClientException.
|
||||
*
|
||||
* @throws JSONException
|
||||
*/
|
||||
public ForbiddenClientException() throws JSONException {
|
||||
super(Response.status(Status.FORBIDDEN).entity(new JSONObject()
|
||||
.put("type", "ForbiddenError")
|
||||
.put("message", "You don't have access to this resource")).build());
|
||||
public ForbiddenClientException() {
|
||||
super(Response.status(Status.FORBIDDEN).entity(Json.createObjectBuilder()
|
||||
.add("type", "ForbiddenError")
|
||||
.add("message", "You don't have access to this resource").build()).build());
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,13 @@
|
||||
package com.sismics.rest.exception;
|
||||
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Jersey exception encapsulating an error from the client (INTERNAL_SERVER_ERROR).
|
||||
*
|
||||
@ -31,9 +30,8 @@ public class ServerException extends WebApplicationException {
|
||||
* @param type Error type (e.g. DatabaseError)
|
||||
* @param message Human readable error message
|
||||
* @param e Inner exception
|
||||
* @throws JSONException
|
||||
*/
|
||||
public ServerException(String type, String message, Exception e) throws JSONException {
|
||||
public ServerException(String type, String message, Exception e) {
|
||||
this(type, message);
|
||||
log.error(type + ": " + message, e);
|
||||
}
|
||||
@ -43,11 +41,10 @@ public class ServerException extends WebApplicationException {
|
||||
*
|
||||
* @param type Error type (e.g. DatabaseError)
|
||||
* @param message Human readable error message
|
||||
* @throws JSONException
|
||||
*/
|
||||
public ServerException(String type, String message) throws JSONException {
|
||||
super(Response.status(Status.INTERNAL_SERVER_ERROR).entity(new JSONObject()
|
||||
.put("type", type)
|
||||
.put("message", message)).build());
|
||||
public ServerException(String type, String message) {
|
||||
super(Response.status(Status.INTERNAL_SERVER_ERROR).entity(Json.createObjectBuilder()
|
||||
.add("type", type)
|
||||
.add("message", message).build()).build());
|
||||
}
|
||||
}
|
||||
|
@ -1,45 +0,0 @@
|
||||
package com.sismics.rest.resource;
|
||||
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
|
||||
/**
|
||||
* Generic exception mapper that transforms all unknown exception into ServerError.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
@Provider
|
||||
public class GenericExceptionMapper implements ExceptionMapper<Exception> {
|
||||
/**
|
||||
* Logger.
|
||||
*/
|
||||
private static final Logger log = LoggerFactory.getLogger(GenericExceptionMapper.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(Exception e) {
|
||||
if (e instanceof WebApplicationException) {
|
||||
return ((WebApplicationException) e).getResponse();
|
||||
}
|
||||
|
||||
log.error("Unknown error", e);
|
||||
|
||||
JSONObject entity = new JSONObject();
|
||||
try {
|
||||
entity.put("type", "UnknownError");
|
||||
entity.put("message", "Unknown server error");
|
||||
} catch (JSONException e2) {
|
||||
log.error("Error building response", e2);
|
||||
}
|
||||
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
|
||||
.entity(entity)
|
||||
.build();
|
||||
}
|
||||
}
|
@ -1,40 +1,38 @@
|
||||
package com.sismics.rest.util;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonValue;
|
||||
|
||||
/**
|
||||
* JSON utilities.
|
||||
*
|
||||
* @author jtremeaux
|
||||
* @author bgamard
|
||||
*/
|
||||
public class JsonUtil {
|
||||
|
||||
/**
|
||||
* Returns a JsonValue from a String.
|
||||
*
|
||||
* @param value Value
|
||||
* @return JsonValue
|
||||
*/
|
||||
public static JsonValue nullable(String value) {
|
||||
if (value == null) {
|
||||
return JsonValue.NULL;
|
||||
}
|
||||
return Json.createObjectBuilder().add("_", value).build().get("_");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix of {@see JsonObject.append()}, which seems to create nested arrays.
|
||||
* Returns a JsonValue from an Integer.
|
||||
*
|
||||
* @param o JSON Object
|
||||
* @param key Key containing the array of null
|
||||
* @param value Value to append
|
||||
* @return Updated object
|
||||
* @throws JSONException
|
||||
* @param value Value
|
||||
* @return JsonValue
|
||||
*/
|
||||
public static JSONObject append(JSONObject o, String key, JSONObject value) throws JSONException {
|
||||
Object prevValue = o.opt(key);
|
||||
if (prevValue == null) {
|
||||
o.put(key, new JSONArray().put(value));
|
||||
} else if (!(prevValue instanceof JSONArray)){
|
||||
throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
|
||||
} else {
|
||||
JSONArray newArray = new JSONArray();
|
||||
JSONArray oldArray = ((JSONArray) prevValue);
|
||||
for (int i = 0; i < oldArray.length(); i++) {
|
||||
newArray.put(oldArray.get(i));
|
||||
}
|
||||
newArray.put(value);
|
||||
o.put(key, newArray);
|
||||
public static JsonValue nullable(Integer value) {
|
||||
if (value == null) {
|
||||
return JsonValue.NULL;
|
||||
}
|
||||
return o;
|
||||
return Json.createObjectBuilder().add("_", value).build().get("_");
|
||||
}
|
||||
}
|
||||
|
@ -1,26 +1,22 @@
|
||||
package com.sismics.rest.util;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.sismics.docs.core.dao.file.theme.ThemeDao;
|
||||
import com.sismics.docs.core.dao.jpa.LocaleDao;
|
||||
import com.sismics.docs.core.model.jpa.Locale;
|
||||
import com.sismics.rest.exception.ClientException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.joda.time.DateTime;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.joda.time.DateTime;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.sismics.rest.exception.ClientException;
|
||||
|
||||
/**
|
||||
* Utility class to validate parameters.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class ValidationUtil {
|
||||
private static Pattern EMAIL_PATTERN = Pattern.compile(".+@.+\\..+");
|
||||
private static Pattern EMAIL_PATTERN = Pattern.compile(".+@.+");
|
||||
|
||||
private static Pattern HTTP_URL_PATTERN = Pattern.compile("https?://.+");
|
||||
|
||||
@ -31,9 +27,9 @@ public class ValidationUtil {
|
||||
*
|
||||
* @param s Object tu validate
|
||||
* @param name Name of the parameter
|
||||
* @throws JSONException
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static void validateRequired(Object s, String name) throws JSONException {
|
||||
public static void validateRequired(Object s, String name) throws ClientException {
|
||||
if (s == null) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be set", name));
|
||||
}
|
||||
@ -50,7 +46,7 @@ public class ValidationUtil {
|
||||
* @return String without white spaces
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateLength(String s, String name, Integer lengthMin, Integer lengthMax, boolean nullable) throws JSONException {
|
||||
public static String validateLength(String s, String name, Integer lengthMin, Integer lengthMax, boolean nullable) throws ClientException {
|
||||
s = StringUtils.strip(s);
|
||||
if (nullable && StringUtils.isEmpty(s)) {
|
||||
return s;
|
||||
@ -62,7 +58,7 @@ public class ValidationUtil {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be more than {1} characters", name, lengthMin));
|
||||
}
|
||||
if (lengthMax != null && s.length() > lengthMax) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be less than {1} characters", name, lengthMax));
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be more than {1} characters", name, lengthMax));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
@ -77,7 +73,7 @@ public class ValidationUtil {
|
||||
* @return String without white spaces
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateLength(String s, String name, Integer lengthMin, Integer lengthMax) throws JSONException {
|
||||
public static String validateLength(String s, String name, Integer lengthMin, Integer lengthMax) throws ClientException {
|
||||
return validateLength(s, name, lengthMin, lengthMax, false);
|
||||
}
|
||||
|
||||
@ -87,12 +83,25 @@ public class ValidationUtil {
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @return String without white spaces
|
||||
* @throws JSONException
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateStringNotBlank(String s, String name) throws JSONException {
|
||||
public static String validateStringNotBlank(String s, String name) throws ClientException {
|
||||
return validateLength(s, name, 1, null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the string is an email.
|
||||
*
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static void validateEmail(String s, String name) throws ClientException {
|
||||
if (!EMAIL_PATTERN.matcher(s).matches()) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be an email", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the string is a hexadecimal color.
|
||||
*
|
||||
@ -101,32 +110,19 @@ public class ValidationUtil {
|
||||
* @param nullable True if the string can be empty or null
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static void validateHexColor(String s, String name, boolean nullable) throws JSONException {
|
||||
public static void validateHexColor(String s, String name, boolean nullable) throws ClientException {
|
||||
ValidationUtil.validateLength(s, "name", 7, 7, nullable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the string is an email.
|
||||
*
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static void validateEmail(String s, String name) throws JSONException {
|
||||
if (!EMAIL_PATTERN.matcher(s).matches()) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be an email", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the provided string matches an URL with HTTP or HTTPS scheme.
|
||||
*
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @return Stripped URL
|
||||
* @throws JSONException
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateHttpUrl(String s, String name) throws JSONException {
|
||||
public static String validateHttpUrl(String s, String name) throws ClientException {
|
||||
s = StringUtils.strip(s);
|
||||
if (!HTTP_URL_PATTERN.matcher(s).matches()) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be an HTTP(s) URL", name));
|
||||
@ -139,14 +135,30 @@ public class ValidationUtil {
|
||||
*
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @throws JSONException
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static void validateAlphanumeric(String s, String name) throws JSONException {
|
||||
public static void validateAlphanumeric(String s, String name) throws ClientException {
|
||||
if (!ALPHANUMERIC_PATTERN.matcher(s).matches()) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must have only alphanumeric or underscore characters", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the string is a number.
|
||||
*
|
||||
* @param s String to validate
|
||||
* @param name Name of the parameter
|
||||
* @return Parsed number
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static Integer validateInteger(String s, String name) throws ClientException {
|
||||
try {
|
||||
return Integer.valueOf(s);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new ClientException("Validation Error", MessageFormat.format("{0} is not a number", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and parses a date.
|
||||
*
|
||||
@ -154,9 +166,9 @@ public class ValidationUtil {
|
||||
* @param name Name of the parameter
|
||||
* @param nullable True if the string can be empty or null
|
||||
* @return Parsed date
|
||||
* @throws JSONException
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static Date validateDate(String s, String name, boolean nullable) throws JSONException {
|
||||
public static Date validateDate(String s, String name, boolean nullable) throws ClientException {
|
||||
if (Strings.isNullOrEmpty(s)) {
|
||||
if (!nullable) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be set", name));
|
||||
@ -170,56 +182,4 @@ public class ValidationUtil {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} must be a date", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a locale.
|
||||
*
|
||||
* @param localeId String to validate
|
||||
* @param name Name of the parameter
|
||||
* @return String without white spaces
|
||||
* @param nullable True if the string can be empty or null
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateLocale(String localeId, String name, boolean nullable) throws JSONException {
|
||||
localeId = StringUtils.strip(localeId);
|
||||
if (StringUtils.isEmpty(localeId)) {
|
||||
if (!nullable) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} is required", name));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
LocaleDao localeDao = new LocaleDao();
|
||||
Locale locale = localeDao.getById(localeId);
|
||||
if (locale == null) {
|
||||
throw new ClientException("ValidationError", "Locale not found: " + localeId);
|
||||
}
|
||||
return localeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a theme.
|
||||
*
|
||||
* @param themeId ID of the theme to validate
|
||||
* @param name Name of the parameter
|
||||
* @return String without white spaces
|
||||
* @param nullable True if the string can be empty or null
|
||||
* @throws ClientException
|
||||
*/
|
||||
public static String validateTheme(String themeId, String name, boolean nullable) throws JSONException {
|
||||
themeId = StringUtils.strip(themeId);
|
||||
if (StringUtils.isEmpty(themeId)) {
|
||||
if (!nullable) {
|
||||
throw new ClientException("ValidationError", MessageFormat.format("{0} is required", name));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
ThemeDao themeDao = new ThemeDao();
|
||||
List<String> themeList = themeDao.findAll();
|
||||
if (!themeList.contains(themeId)) {
|
||||
throw new ClientException("ValidationError", "Theme not found: " + themeId);
|
||||
}
|
||||
return themeId;
|
||||
}
|
||||
}
|
||||
|
@ -38,11 +38,10 @@ public class RequestContextFilter implements Filter {
|
||||
// Force the locale in order to not depend on the execution environment
|
||||
Locale.setDefault(new Locale(Constants.DEFAULT_LOCALE_ID));
|
||||
|
||||
// Injects the webapp root
|
||||
String webappRoot = filterConfig.getServletContext().getRealPath("/");
|
||||
EnvironmentUtil.setWebappRoot(webappRoot);
|
||||
|
||||
// Initialize the app directory
|
||||
if (!filterConfig.getServletContext().getServerInfo().startsWith("Grizzly")) {
|
||||
EnvironmentUtil.setWebappContext(true);
|
||||
}
|
||||
File baseDataDirectory = null;
|
||||
try {
|
||||
baseDataDirectory = DirectoryUtil.getBaseDataDirectory();
|
||||
|
@ -1,16 +1,27 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
import javax.ws.rs.core.Application;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
|
||||
import org.glassfish.grizzly.http.server.HttpServer;
|
||||
import org.glassfish.grizzly.http.server.StaticHttpHandler;
|
||||
import org.glassfish.grizzly.servlet.ServletRegistration;
|
||||
import org.glassfish.grizzly.servlet.WebappContext;
|
||||
import org.glassfish.jersey.servlet.ServletContainer;
|
||||
import org.glassfish.jersey.test.JerseyTest;
|
||||
import org.glassfish.jersey.test.TestProperties;
|
||||
import org.glassfish.jersey.test.external.ExternalTestContainerFactory;
|
||||
import org.glassfish.jersey.test.spi.TestContainerException;
|
||||
import org.glassfish.jersey.test.spi.TestContainerFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
|
||||
import com.sismics.docs.rest.descriptor.JerseyTestWebAppDescriptorFactory;
|
||||
import com.sismics.docs.rest.util.ClientUtil;
|
||||
import com.sun.jersey.test.framework.JerseyTest;
|
||||
import com.sismics.util.filter.RequestContextFilter;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
/**
|
||||
* Base class of integration tests with Jersey.
|
||||
@ -28,12 +39,21 @@ public abstract class BaseJerseyTest extends JerseyTest {
|
||||
*/
|
||||
protected ClientUtil clientUtil;
|
||||
|
||||
/**
|
||||
* Constructor of BaseJerseyTest.
|
||||
*/
|
||||
public BaseJerseyTest() {
|
||||
super(JerseyTestWebAppDescriptorFactory.build());
|
||||
this.clientUtil = new ClientUtil(resource());
|
||||
@Override
|
||||
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
|
||||
return new ExternalTestContainerFactory();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Application configure() {
|
||||
enable(TestProperties.LOG_TRAFFIC);
|
||||
enable(TestProperties.DUMP_ENTITY);
|
||||
return new Application();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected URI getBaseUri() {
|
||||
return UriBuilder.fromUri(super.getBaseUri()).path("docs").build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -41,10 +61,23 @@ public abstract class BaseJerseyTest extends JerseyTest {
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
clientUtil = new ClientUtil(target());
|
||||
|
||||
String httpRoot = URLDecoder.decode(new File(getClass().getResource("/").getFile()).getAbsolutePath(), "utf-8");
|
||||
httpServer = HttpServer.createSimpleServer(httpRoot, "localhost", 9997);
|
||||
// Disable file cache to fix https://java.net/jira/browse/GRIZZLY-1350
|
||||
((StaticHttpHandler) httpServer.getServerConfiguration().getHttpHandlers().keySet().iterator().next()).setFileCacheEnabled(false);
|
||||
httpServer = HttpServer.createSimpleServer(httpRoot, "localhost", getPort());
|
||||
WebappContext context = new WebappContext("GrizzlyContext", "/docs");
|
||||
context.addFilter("requestContextFilter", RequestContextFilter.class)
|
||||
.addMappingForUrlPatterns(null, "/*");
|
||||
context.addFilter("tokenBasedSecurityFilter", TokenBasedSecurityFilter.class)
|
||||
.addMappingForUrlPatterns(null, "/*");
|
||||
ServletRegistration reg = context.addServlet("jerseyServlet", ServletContainer.class);
|
||||
reg.setInitParameter("jersey.config.server.provider.packages", "com.sismics.docs.rest.resource");
|
||||
reg.setInitParameter("jersey.config.server.provider.classnames", "org.glassfish.jersey.media.multipart.MultiPartFeature");
|
||||
reg.setInitParameter("jersey.config.server.response.setStatusOverSendError", "true");
|
||||
reg.setLoadOnStartup(1);
|
||||
reg.addMapping("/*");
|
||||
reg.setAsyncSupported(true);
|
||||
context.deploy(httpServer);
|
||||
httpServer.start();
|
||||
}
|
||||
|
||||
@ -52,6 +85,8 @@ public abstract class BaseJerseyTest extends JerseyTest {
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
httpServer.stop();
|
||||
if (httpServer != null) {
|
||||
httpServer.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,36 +0,0 @@
|
||||
package com.sismics.docs.rest.descriptor;
|
||||
|
||||
import com.sismics.util.filter.RequestContextFilter;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
import com.sun.jersey.test.framework.WebAppDescriptor;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Jersey tests Webapp descriptor.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class JerseyTestWebAppDescriptorFactory {
|
||||
private static String basePath = new File("src/main/webapp").getAbsolutePath();
|
||||
|
||||
/**
|
||||
* Constructs a new descriptor.
|
||||
*
|
||||
* @return Descriptor
|
||||
*/
|
||||
public static WebAppDescriptor build() {
|
||||
// Target the base path to the Webapp resources
|
||||
System.setProperty("user.dir", basePath);
|
||||
System.setProperty("test", "true");
|
||||
|
||||
return new WebAppDescriptor.Builder("com.sismics.docs.rest.resource")
|
||||
.contextPath("docs")
|
||||
.addFilter(RequestContextFilter.class, "requestContextFilter")
|
||||
.addFilter(TokenBasedSecurityFilter.class, "tokenBasedSecurityFilter")
|
||||
.initParam("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.LoggingFilter")
|
||||
.initParam("com.sun.jersey.spi.container.ContainerResponseFilters", "com.sun.jersey.api.container.filter.LoggingFilter")
|
||||
.initParam("com.sun.jersey.config.feature.logging.DisableEntitylogging", "true")
|
||||
.build();
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
package com.sismics.docs.rest.filter;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
import com.sun.jersey.api.client.ClientHandlerException;
|
||||
import com.sun.jersey.api.client.ClientRequest;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.filter.ClientFilter;
|
||||
|
||||
import javax.ws.rs.core.Cookie;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Filter to add the authentication token into a cookie.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class CookieAuthenticationFilter extends ClientFilter {
|
||||
private String authToken;
|
||||
|
||||
public CookieAuthenticationFilter(String authToken) {
|
||||
this.authToken = authToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
|
||||
Cookie cookie = new Cookie(TokenBasedSecurityFilter.COOKIE_NAME, authToken);
|
||||
List<Object> cookieList = new ArrayList<Object>();
|
||||
cookieList.add(cookie);
|
||||
if (authToken != null) {
|
||||
request.getHeaders().put("Cookie", cookieList);
|
||||
}
|
||||
ClientResponse response = getNext().handle(request);
|
||||
if (response.getCookies() != null) {
|
||||
cookieList.addAll(response.getCookies());
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
}
|
@ -1,15 +1,13 @@
|
||||
package com.sismics.docs.rest.util;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import junit.framework.Assert;
|
||||
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.NewCookie;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
/**
|
||||
* REST client utilities.
|
||||
@ -17,14 +15,14 @@ import javax.ws.rs.core.NewCookie;
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class ClientUtil {
|
||||
private WebResource resource;
|
||||
private WebTarget resource;
|
||||
|
||||
/**
|
||||
* Constructor of ClientUtil.
|
||||
*
|
||||
* @param webResource Resource corresponding to the base URI of REST resources.
|
||||
* @param resource Resource corresponding to the base URI of REST resources.
|
||||
*/
|
||||
public ClientUtil(WebResource resource) {
|
||||
public ClientUtil(WebTarget resource) {
|
||||
this.resource = resource;
|
||||
}
|
||||
|
||||
@ -38,15 +36,14 @@ public class ClientUtil {
|
||||
String adminAuthenticationToken = login("admin", "admin", false);
|
||||
|
||||
// Create the user
|
||||
WebResource userResource = resource.path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", username);
|
||||
postParams.putSingle("email", username + "@docs.com");
|
||||
postParams.putSingle("password", "12345678");
|
||||
postParams.putSingle("time_zone", "Asia/Tokyo");
|
||||
ClientResponse response = userResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
Form form = new Form();
|
||||
form.param("username", username);
|
||||
form.param("email", username + "@docs.com");
|
||||
form.param("password", "12345678");
|
||||
form.param("time_zone", "Asia/Tokyo");
|
||||
resource.path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(form), JsonObject.class);
|
||||
|
||||
// Logout admin
|
||||
logout(adminAuthenticationToken);
|
||||
@ -61,13 +58,12 @@ public class ClientUtil {
|
||||
* @return Authentication token
|
||||
*/
|
||||
public String login(String username, String password, Boolean remember) {
|
||||
WebResource userResource = resource.path("/user/login");
|
||||
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", username);
|
||||
postParams.putSingle("password", password);
|
||||
postParams.putSingle("remember", remember.toString());
|
||||
ClientResponse response = userResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
Form form = new Form();
|
||||
form.param("username", username);
|
||||
form.param("password", password);
|
||||
form.param("remember", remember.toString());
|
||||
Response response = resource.path("/user/login").request()
|
||||
.post(Entity.form(form));
|
||||
|
||||
return getAuthenticationCookie(response);
|
||||
}
|
||||
@ -88,10 +84,9 @@ public class ClientUtil {
|
||||
* @param authenticationToken Authentication token
|
||||
*/
|
||||
public void logout(String authenticationToken) {
|
||||
WebResource userResource = resource.path("/user/logout");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(authenticationToken));
|
||||
ClientResponse response = userResource.post(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
resource.path("/user/logout").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, authenticationToken)
|
||||
.post(null);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -100,9 +95,9 @@ public class ClientUtil {
|
||||
* @param response Response
|
||||
* @return Authentication token
|
||||
*/
|
||||
public String getAuthenticationCookie(ClientResponse response) {
|
||||
public String getAuthenticationCookie(Response response) {
|
||||
String authToken = null;
|
||||
for (NewCookie cookie : response.getCookies()) {
|
||||
for (NewCookie cookie : response.getCookies().values()) {
|
||||
if (TokenBasedSecurityFilter.COOKIE_NAME.equals(cookie.getName())) {
|
||||
authToken = cookie.getValue();
|
||||
}
|
||||
|
123
docs-web/pom.xml
123
docs-web/pom.xml
@ -28,23 +28,18 @@
|
||||
|
||||
<!-- Dependencies to Jersey -->
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-server</artifactId>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-servlet</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-bundle</artifactId>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-processing</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-json</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.contribs</groupId>
|
||||
<artifactId>jersey-multipart</artifactId>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-multipart</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Other external dependencies -->
|
||||
@ -74,8 +69,8 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mortbay.jetty</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
@ -102,16 +97,23 @@
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.grizzly</groupId>
|
||||
<artifactId>grizzly-servlet-webserver</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.jersey-test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-grizzly2</artifactId>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-bundle</artifactId>
|
||||
<type>pom</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-grizzly2-servlet</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@ -123,29 +125,6 @@
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<systemProperty>
|
||||
<name>webapp.root</name>
|
||||
<value>${basedir}/src/main/webapp</value>
|
||||
</systemProperty>
|
||||
</systemProperties>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
<webAppConfig>
|
||||
<contextPath>/docs-web</contextPath>
|
||||
<extraClasspath>target/classes;../docs-core/target/classes</extraClasspath>
|
||||
<overrideDescriptor>src/dev/main/webapp/web-override.xml</overrideDescriptor>
|
||||
</webAppConfig>
|
||||
<stopKey>STOPKEY</stopKey>
|
||||
<stopPort>1099</stopPort>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
@ -183,14 +162,16 @@
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
<webAppConfig>
|
||||
<systemProperties>
|
||||
<systemProperty>
|
||||
<name>application.mode</name>
|
||||
<value>dev</value>
|
||||
</systemProperty>
|
||||
</systemProperties>
|
||||
<webApp>
|
||||
<contextPath>/docs-web</contextPath>
|
||||
<extraClasspath>target/classes;../docs-core/target/classes</extraClasspath>
|
||||
<overrideDescriptor>src/dev/main/webapp/web-override.xml</overrideDescriptor>
|
||||
</webAppConfig>
|
||||
<stopKey>STOPKEY</stopKey>
|
||||
<stopPort>1099</stopPort>
|
||||
</webApp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
@ -230,14 +211,16 @@
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
<webAppConfig>
|
||||
<systemProperties>
|
||||
<systemProperty>
|
||||
<name>application.mode</name>
|
||||
<value>dev</value>
|
||||
</systemProperty>
|
||||
</systemProperties>
|
||||
<webApp>
|
||||
<contextPath>/docs-web</contextPath>
|
||||
<extraClasspath>target/classes;../docs-core/target/classes</extraClasspath>
|
||||
<overrideDescriptor>src/stress/main/webapp/web-override.xml</overrideDescriptor>
|
||||
</webAppConfig>
|
||||
<stopKey>STOPKEY</stopKey>
|
||||
<stopPort>1099</stopPort>
|
||||
<overrideDescriptor>src/dev/main/webapp/web-override.xml</overrideDescriptor>
|
||||
</webApp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
@ -247,12 +230,6 @@
|
||||
<!-- Production profile -->
|
||||
<profile>
|
||||
<id>prod</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>env</name>
|
||||
<value>prod</value>
|
||||
</property>
|
||||
</activation>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
@ -318,25 +295,5 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- Hosted version profile -->
|
||||
<profile>
|
||||
<id>hosted</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>env</name>
|
||||
<value>hosted</value>
|
||||
</property>
|
||||
</activation>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/hosted/resources</directory>
|
||||
<filtering>false</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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>
|
||||
|
@ -2,18 +2,18 @@ package com.sismics.docs.rest;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Test the ACL resource.
|
||||
@ -27,7 +27,7 @@ public class TestAclResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testAclResource() throws JSONException {
|
||||
public void testAclResource() {
|
||||
// Login acl1
|
||||
clientUtil.createUser("acl1");
|
||||
String acl1Token = clientUtil.login("acl1");
|
||||
@ -37,141 +37,118 @@ public class TestAclResource extends BaseJerseyTest {
|
||||
String acl2Token = clientUtil.login("acl2");
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super title document 1");
|
||||
postParams.add("language", "eng");
|
||||
postParams.add("create_date", new Date().getTime());
|
||||
ClientResponse response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
JsonObject json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super title document 1")
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(new Date().getTime()))), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
|
||||
// Get the document as acl1
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
JSONArray acls = json.getJSONArray("acls");
|
||||
Assert.assertEquals(2, acls.length());
|
||||
JsonArray acls = json.getJsonArray("acls");
|
||||
Assert.assertEquals(2, acls.size());
|
||||
|
||||
// Get the document as acl2
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl2Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Response response = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl2Token)
|
||||
.get();
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Add an ACL READ for acl2 with acl1
|
||||
WebResource aclResource = resource().path("/acl");
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("source", document1Id);
|
||||
postParams.add("perm", "READ");
|
||||
postParams.add("username", "acl2");
|
||||
response = aclResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/acl").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("source", document1Id)
|
||||
.param("perm", "READ")
|
||||
.param("username", "acl2")), JsonObject.class);
|
||||
String acl2Id = json.getString("id");
|
||||
|
||||
// Add an ACL WRITE for acl2 with acl1
|
||||
aclResource = resource().path("/acl");
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("source", document1Id);
|
||||
postParams.add("perm", "WRITE");
|
||||
postParams.add("username", "acl2");
|
||||
response = aclResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/acl").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("source", document1Id)
|
||||
.param("perm", "WRITE")
|
||||
.param("username", "acl2")), JsonObject.class);
|
||||
|
||||
// Add an ACL WRITE for acl2 with acl1 (again)
|
||||
aclResource = resource().path("/acl");
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("source", document1Id);
|
||||
postParams.add("perm", "WRITE");
|
||||
postParams.add("username", "acl2");
|
||||
response = aclResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/acl").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("source", document1Id)
|
||||
.param("perm", "WRITE")
|
||||
.param("username", "acl2")), JsonObject.class);
|
||||
|
||||
// Get the document as acl1
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
acls = json.getJSONArray("acls");
|
||||
Assert.assertEquals(4, acls.length());
|
||||
acls = json.getJsonArray("acls");
|
||||
Assert.assertEquals(4, acls.size());
|
||||
|
||||
// Get the document as acl2
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl2Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl2Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
acls = json.getJSONArray("acls");
|
||||
Assert.assertEquals(4, acls.length());
|
||||
acls = json.getJsonArray("acls");
|
||||
Assert.assertEquals(4, acls.size());
|
||||
|
||||
// Delete the ACL WRITE for acl2 with acl2
|
||||
aclResource = resource().path("/acl/" + document1Id + "/WRITE/" + acl2Id);
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl2Token));
|
||||
response = aclResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
target().path("/acl/" + document1Id + "/WRITE/" + acl2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl2Token)
|
||||
.delete();
|
||||
|
||||
// Delete the ACL READ for acl2 with acl2
|
||||
aclResource = resource().path("/acl/" + document1Id + "/READ/" + acl2Id);
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl2Token));
|
||||
response = aclResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
target().path("/acl/" + document1Id + "/READ/" + acl2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl2Token)
|
||||
.delete();
|
||||
|
||||
// Delete the ACL READ for acl2 with acl1
|
||||
aclResource = resource().path("/acl/" + document1Id + "/READ/" + acl2Id);
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = aclResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
target().path("/acl/" + document1Id + "/READ/" + acl2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.delete();
|
||||
|
||||
// Get the document as acl1
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
acls = json.getJSONArray("acls");
|
||||
Assert.assertEquals(2, acls.length());
|
||||
String acl1Id = acls.getJSONObject(0).getString("id");
|
||||
acls = json.getJsonArray("acls");
|
||||
Assert.assertEquals(2, acls.size());
|
||||
String acl1Id = acls.getJsonObject(0).getString("id");
|
||||
|
||||
// Get the document as acl2
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(acl2Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
response = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl2Token)
|
||||
.get();
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Delete the ACL READ for acl1 with acl1
|
||||
aclResource = resource().path("/acl/" + document1Id + "/READ/" + acl1Id);
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = aclResource.delete(ClientResponse.class);
|
||||
response = target().path("/acl/" + document1Id + "/READ/" + acl1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Delete the ACL WRITE for acl1 with acl1
|
||||
aclResource = resource().path("/acl/" + document1Id + "/WRITE/" + acl1Id);
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = aclResource.delete(ClientResponse.class);
|
||||
response = target().path("/acl/" + document1Id + "/WRITE/" + acl1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Search target list
|
||||
aclResource = resource().path("/acl/target/search");
|
||||
aclResource.addFilter(new CookieAuthenticationFilter(acl1Token));
|
||||
response = aclResource.queryParam("search", "acl").get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray users = json.getJSONArray("users");
|
||||
Assert.assertEquals(2, users.length());
|
||||
json = target().path("/acl/target/search")
|
||||
.queryParam("search", "acl")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, acl1Token)
|
||||
.get(JsonObject.class);
|
||||
JsonArray users = json.getJsonArray("users");
|
||||
Assert.assertEquals(2, users.size());
|
||||
}
|
||||
}
|
@ -1,15 +1,18 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import junit.framework.Assert;
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Test the app resource.
|
||||
*
|
||||
@ -22,36 +25,33 @@ public class TestAppResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testAppResource() throws JSONException {
|
||||
public void testAppResource() {
|
||||
// Login admin
|
||||
String adminAuthenticationToken = clientUtil.login("admin", "admin", false);
|
||||
|
||||
// Check the application info
|
||||
WebResource appResource = resource().path("/app");
|
||||
appResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
ClientResponse response = appResource.get(ClientResponse.class);
|
||||
response = appResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JsonObject json = target().path("/app").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
String currentVersion = json.getString("current_version");
|
||||
Assert.assertNotNull(currentVersion);
|
||||
String minVersion = json.getString("min_version");
|
||||
Assert.assertNotNull(minVersion);
|
||||
Long freeMemory = json.getLong("free_memory");
|
||||
Long freeMemory = json.getJsonNumber("free_memory").longValue();
|
||||
Assert.assertTrue(freeMemory > 0);
|
||||
Long totalMemory = json.getLong("total_memory");
|
||||
Long totalMemory = json.getJsonNumber("total_memory").longValue();
|
||||
Assert.assertTrue(totalMemory > 0 && totalMemory > freeMemory);
|
||||
|
||||
// Rebuild Lucene index
|
||||
appResource = resource().path("/app/batch/reindex");
|
||||
appResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = appResource.post(ClientResponse.class);
|
||||
Response response = target().path("/app/batch/reindex").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.post(Entity.form(new Form()));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Clean storage
|
||||
appResource = resource().path("/app/batch/clean_storage");
|
||||
appResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = appResource.post(ClientResponse.class);
|
||||
response = target().path("/app/batch/clean_storage").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.post(Entity.form(new Form()));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
}
|
||||
|
||||
@ -61,39 +61,33 @@ public class TestAppResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testLogResource() throws JSONException {
|
||||
public void testLogResource() {
|
||||
// Login admin
|
||||
String adminAuthenticationToken = clientUtil.login("admin", "admin", false);
|
||||
|
||||
// Check the logs (page 1)
|
||||
WebResource appResource = resource()
|
||||
.path("/app/log")
|
||||
.queryParam("level", "DEBUG");
|
||||
ClientResponse response = appResource.get(ClientResponse.class);
|
||||
appResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = appResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JSONArray logs = json.getJSONArray("logs");
|
||||
Assert.assertTrue(logs.length() > 0);
|
||||
Long date1 = logs.optJSONObject(0).optLong("date");
|
||||
Long date2 = logs.optJSONObject(9).optLong("date");
|
||||
Assert.assertTrue(date1 > date2);
|
||||
JsonObject json = target().path("/app/log")
|
||||
.queryParam("level", "DEBUG")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
JsonArray logs = json.getJsonArray("logs");
|
||||
Assert.assertTrue(logs.size() > 0);
|
||||
Long date1 = logs.getJsonObject(0).getJsonNumber("date").longValue();
|
||||
Long date2 = logs.getJsonObject(9).getJsonNumber("date").longValue();
|
||||
Assert.assertTrue(date1 >= date2);
|
||||
|
||||
// Check the logs (page 2)
|
||||
appResource = resource()
|
||||
.path("/app/log")
|
||||
json = target().path("/app/log")
|
||||
.queryParam("offset", "10")
|
||||
.queryParam("level", "DEBUG");
|
||||
response = appResource.get(ClientResponse.class);
|
||||
appResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = appResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
logs = json.getJSONArray("logs");
|
||||
Assert.assertTrue(logs.length() > 0);
|
||||
Long date3 = logs.optJSONObject(0).optLong("date");
|
||||
Long date4 = logs.optJSONObject(9).optLong("date");
|
||||
Assert.assertTrue(date3 > date4);
|
||||
.queryParam("level", "DEBUG")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
logs = json.getJsonArray("logs");
|
||||
Assert.assertTrue(logs.size() > 0);
|
||||
Long date3 = logs.getJsonObject(0).getJsonNumber("date").longValue();
|
||||
Long date4 = logs.getJsonObject(9).getJsonNumber("date").longValue();
|
||||
Assert.assertTrue(date3 >= date4);
|
||||
}
|
||||
}
|
@ -2,19 +2,17 @@ package com.sismics.docs.rest;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Test the audit log resource.
|
||||
*
|
||||
@ -27,72 +25,60 @@ public class TestAuditLogResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testAuditLogResource() throws JSONException {
|
||||
public void testAuditLogResource() {
|
||||
// Login auditlog1
|
||||
clientUtil.createUser("auditlog1");
|
||||
String auditlog1Token = clientUtil.login("auditlog1");
|
||||
|
||||
// Create a tag
|
||||
WebResource tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "SuperTag");
|
||||
postParams.add("color", "#ffff00");
|
||||
ClientResponse response = tagResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String tag1Id = json.optString("id");
|
||||
JsonObject json = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("name", "SuperTag")
|
||||
.param("color", "#ffff00")), JsonObject.class);
|
||||
String tag1Id = json.getString("id");
|
||||
Assert.assertNotNull(tag1Id);
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super title document 1");
|
||||
postParams.add("description", "My super description for document 1");
|
||||
postParams.add("tags", tag1Id);
|
||||
postParams.add("language", "eng");
|
||||
long create1Date = new Date().getTime();
|
||||
postParams.add("create_date", create1Date);
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super title document 1")
|
||||
.param("description", "My super description for document 1")
|
||||
.param("tags", tag1Id)
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(create1Date))), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Get all logs for the document
|
||||
WebResource auditLogResource = resource().path("/auditlog");
|
||||
auditLogResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
response = auditLogResource.queryParam("document", document1Id).get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
JSONArray logs = json.getJSONArray("logs");
|
||||
Assert.assertTrue(logs.length() == 3);
|
||||
json = target().path("/auditlog")
|
||||
.queryParam("document", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.get(JsonObject.class);
|
||||
JsonArray logs = json.getJsonArray("logs");
|
||||
Assert.assertTrue(logs.size() == 3);
|
||||
|
||||
// Get all logs for the current user
|
||||
auditLogResource = resource().path("/auditlog");
|
||||
auditLogResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
response = auditLogResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
logs = json.getJSONArray("logs");
|
||||
Assert.assertTrue(logs.length() == 3);
|
||||
json = target().path("/auditlog").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.get(JsonObject.class);
|
||||
logs = json.getJsonArray("logs");
|
||||
Assert.assertTrue(logs.size() == 3);
|
||||
|
||||
// Deletes a tag
|
||||
tagResource = resource().path("/tag/" + tag1Id);
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
response = tagResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/tag/" + tag1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Get all logs for the current user
|
||||
auditLogResource = resource().path("/auditlog");
|
||||
auditLogResource.addFilter(new CookieAuthenticationFilter(auditlog1Token));
|
||||
response = auditLogResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
logs = json.getJSONArray("logs");
|
||||
Assert.assertTrue(logs.length() == 4);
|
||||
json = target().path("/auditlog").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, auditlog1Token)
|
||||
.get(JsonObject.class);
|
||||
logs = json.getJsonArray("logs");
|
||||
Assert.assertTrue(logs.size() == 4);
|
||||
}
|
||||
}
|
@ -1,31 +1,32 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
|
||||
import org.glassfish.jersey.media.multipart.MultiPartFeature;
|
||||
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.Resources;
|
||||
import com.sismics.docs.core.util.DirectoryUtil;
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
import com.sismics.util.mime.MimeType;
|
||||
import com.sismics.util.mime.MimeTypeUtil;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import com.sun.jersey.multipart.FormDataBodyPart;
|
||||
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Exhaustive test of the document resource.
|
||||
@ -35,6 +36,7 @@ import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
public class TestDocumentResource extends BaseJerseyTest {
|
||||
/**
|
||||
* Test the document resource.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
@ -48,131 +50,113 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
String document3Token = clientUtil.login("document3");
|
||||
|
||||
// Create a tag
|
||||
WebResource tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "SuperTag");
|
||||
postParams.add("color", "#ffff00");
|
||||
ClientResponse response = tagResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String tag1Id = json.optString("id");
|
||||
JsonObject json = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("name", "SuperTag")
|
||||
.param("color", "#ffff00")), JsonObject.class);
|
||||
String tag1Id = json.getString("id");
|
||||
Assert.assertNotNull(tag1Id);
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super title document 1");
|
||||
postParams.add("description", "My super description for document 1");
|
||||
postParams.add("tags", tag1Id);
|
||||
postParams.add("language", "eng");
|
||||
long create1Date = new Date().getTime();
|
||||
postParams.add("create_date", create1Date);
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super title document 1")
|
||||
.param("description", "My super description for document 1")
|
||||
.param("tags", tag1Id)
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(create1Date))), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Add a file
|
||||
WebResource fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = this.getClass().getResourceAsStream("/file/Einstein-Roosevelt-letter.png");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document1Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file1Id = json.getString("id");
|
||||
String file1Id = null;
|
||||
try (InputStream is = Resources.getResource("file/Einstein-Roosevelt-letter.png").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "Einstein-Roosevelt-letter.png");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.put(Entity.entity(multiPart.field("id", document1Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file1Id = json.getString("id");
|
||||
Assert.assertNotNull(file1Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Share this document
|
||||
WebResource fileShareResource = resource().path("/share");
|
||||
fileShareResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("id", document1Id);
|
||||
response = fileShareResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/share").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.put(Entity.form(new Form().param("id", document1Id)), JsonObject.class);
|
||||
|
||||
// List all documents
|
||||
documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("sort_column", 3);
|
||||
getParams.putSingle("asc", false);
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray documents = json.getJSONArray("documents");
|
||||
JSONArray tags = documents.getJSONObject(0).getJSONArray("tags");
|
||||
Assert.assertTrue(documents.length() == 1);
|
||||
Assert.assertEquals(document1Id, documents.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals("eng", documents.getJSONObject(0).getString("language"));
|
||||
Assert.assertEquals(1, documents.getJSONObject(0).getInt("file_count"));
|
||||
Assert.assertEquals(1, tags.length());
|
||||
Assert.assertEquals(tag1Id, tags.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals("SuperTag", tags.getJSONObject(0).getString("name"));
|
||||
Assert.assertEquals("#ffff00", tags.getJSONObject(0).getString("color"));
|
||||
json = target().path("/document/list")
|
||||
.queryParam("sort_column", 3)
|
||||
.queryParam("asc", false)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.get(JsonObject.class);
|
||||
JsonArray documents = json.getJsonArray("documents");
|
||||
JsonArray tags = documents.getJsonObject(0).getJsonArray("tags");
|
||||
Assert.assertTrue(documents.size() == 1);
|
||||
Assert.assertEquals(document1Id, documents.getJsonObject(0).getString("id"));
|
||||
Assert.assertEquals("eng", documents.getJsonObject(0).getString("language"));
|
||||
Assert.assertEquals(1, documents.getJsonObject(0).getInt("file_count"));
|
||||
Assert.assertEquals(1, tags.size());
|
||||
Assert.assertEquals(tag1Id, tags.getJsonObject(0).getString("id"));
|
||||
Assert.assertEquals("SuperTag", tags.getJsonObject(0).getString("name"));
|
||||
Assert.assertEquals("#ffff00", tags.getJsonObject(0).getString("color"));
|
||||
|
||||
// List all documents from document3
|
||||
documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document3Token));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("sort_column", 3);
|
||||
getParams.putSingle("asc", false);
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
documents = json.getJSONArray("documents");
|
||||
Assert.assertTrue(documents.length() == 0);
|
||||
json = target().path("/document/list")
|
||||
.queryParam("sort_column", 3)
|
||||
.queryParam("asc", false)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document3Token)
|
||||
.get(JsonObject.class);
|
||||
documents = json.getJsonArray("documents");
|
||||
Assert.assertTrue(documents.size() == 0);
|
||||
|
||||
// Create a document with document3
|
||||
documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document3Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super title document 1");
|
||||
postParams.add("description", "My super description for document 1");
|
||||
postParams.add("language", "eng");
|
||||
long create3Date = new Date().getTime();
|
||||
postParams.add("create_date", create3Date);
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String document3Id = json.optString("id");
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document3Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super title document 1")
|
||||
.param("description", "My super description for document 1")
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(create3Date))), JsonObject.class);
|
||||
String document3Id = json.getString("id");
|
||||
Assert.assertNotNull(document3Id);
|
||||
|
||||
// Add a file
|
||||
fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(document3Token));
|
||||
form = new FormDataMultiPart();
|
||||
file = this.getClass().getResourceAsStream("/file/Einstein-Roosevelt-letter.png");
|
||||
fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document3Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file3Id = json.getString("id");
|
||||
Assert.assertNotNull(file3Id);
|
||||
String file3Id = null;
|
||||
try (InputStream is = Resources.getResource("file/Einstein-Roosevelt-letter.png").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "Einstein-Roosevelt-letter.png");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document3Token)
|
||||
.put(Entity.entity(multiPart.field("id", document3Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file3Id = json.getString("id");
|
||||
Assert.assertNotNull(file3Id);
|
||||
}
|
||||
}
|
||||
|
||||
// List all documents from document3
|
||||
documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document3Token));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("sort_column", 3);
|
||||
getParams.putSingle("asc", false);
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
documents = json.getJSONArray("documents");
|
||||
Assert.assertTrue(documents.length() == 1);
|
||||
json = target().path("/document/list")
|
||||
.queryParam("sort_column", 3)
|
||||
.queryParam("asc", false)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document3Token)
|
||||
.get(JsonObject.class);
|
||||
documents = json.getJsonArray("documents");
|
||||
Assert.assertTrue(documents.size() == 1);
|
||||
|
||||
// Search documents
|
||||
Assert.assertEquals(1, searchDocuments("full:uranium full:einstein", document1Token));
|
||||
@ -200,11 +184,9 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
Assert.assertEquals(0, searchDocuments("lang:fra", document1Token));
|
||||
|
||||
// Get a document
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
Assert.assertEquals("document1", json.getString("creator"));
|
||||
Assert.assertEquals(1, json.getInt("file_count"));
|
||||
@ -212,62 +194,48 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
Assert.assertEquals("My super title document 1", json.getString("title"));
|
||||
Assert.assertEquals("My super description for document 1", json.getString("description"));
|
||||
Assert.assertEquals("eng", json.getString("language"));
|
||||
Assert.assertEquals(create1Date, json.getLong("create_date"));
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertEquals(1, tags.length());
|
||||
Assert.assertEquals(tag1Id, tags.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals(create1Date, json.getJsonNumber("create_date").longValue());
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertEquals(1, tags.size());
|
||||
Assert.assertEquals(tag1Id, tags.getJsonObject(0).getString("id"));
|
||||
|
||||
// Create a tag
|
||||
tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "SuperTag2");
|
||||
postParams.add("color", "#00ffff");
|
||||
response = tagResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String tag2Id = json.optString("id");
|
||||
json = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.put(Entity.form(new Form().param("name", "SuperTag2").param("color", "#00ffff")), JsonObject.class);
|
||||
String tag2Id = json.getString("id");
|
||||
Assert.assertNotNull(tag1Id);
|
||||
|
||||
// Update a document
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My new super document 1");
|
||||
postParams.add("description", "My new super description for document 1");
|
||||
postParams.add("tags", tag2Id);
|
||||
response = documentResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.post(Entity.form(new Form()
|
||||
.param("title", "My new super document 1")
|
||||
.param("description", "My new super description for document 1")
|
||||
.param("tags", tag2Id)), JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
|
||||
// Search documents by query
|
||||
documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("search", "super");
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/list")
|
||||
.queryParam("search", "super")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.get(JsonObject.class);
|
||||
|
||||
// Get a document
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertTrue(json.getString("title").contains("new"));
|
||||
Assert.assertTrue(json.getString("description").contains("new"));
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertEquals(1, tags.length());
|
||||
Assert.assertEquals(tag2Id, tags.getJSONObject(0).getString("id"));
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertEquals(1, tags.size());
|
||||
Assert.assertEquals(tag2Id, tags.getJsonObject(0).getString("id"));
|
||||
|
||||
// Deletes a document
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
response = documentResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Check that the associated files are deleted from FS
|
||||
@ -279,9 +247,9 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
Assert.assertFalse(thumbnailFile.exists());
|
||||
|
||||
// Get a document (KO)
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
Response response = target().path("/document/" + document1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document1Token)
|
||||
.get();
|
||||
Assert.assertEquals(Status.NOT_FOUND, Status.fromStatusCode(response.getStatus()));
|
||||
}
|
||||
|
||||
@ -294,14 +262,12 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
* @throws Exception
|
||||
*/
|
||||
private int searchDocuments(String query, String token) throws Exception {
|
||||
WebResource documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(token));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("search", query);
|
||||
ClientResponse response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
return json.getJSONArray("documents").length();
|
||||
JsonObject json = target().path("/document/list")
|
||||
.queryParam("search", query)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, token)
|
||||
.get(JsonObject.class);
|
||||
return json.getJsonArray("documents").size();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -316,53 +282,48 @@ public class TestDocumentResource extends BaseJerseyTest {
|
||||
String document2Token = clientUtil.login("document2");
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document2Token));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super title document 1");
|
||||
postParams.add("description", "My super description for document 1");
|
||||
postParams.add("language", "eng");
|
||||
long create1Date = new Date().getTime();
|
||||
postParams.add("create_date", create1Date);
|
||||
ClientResponse response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
JsonObject json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document2Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super title document 1")
|
||||
.param("description", "My super description for document 1")
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(create1Date))), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Add a PDF file
|
||||
WebResource fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(document2Token));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = this.getClass().getResourceAsStream("/file/wikipedia.pdf");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document1Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file1Id = json.getString("id");
|
||||
String file1Id = null;
|
||||
try (InputStream is = Resources.getResource("file/wikipedia.pdf").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "wikipedia.pdf");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document2Token)
|
||||
.put(Entity.entity(multiPart.field("id", document1Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file1Id = json.getString("id");
|
||||
Assert.assertNotNull(file1Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Search documents by query in full content
|
||||
documentResource = resource().path("/document/list");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(document2Token));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("search", "full:vrandecic");
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
Assert.assertTrue(json.getJSONArray("documents").length() == 1);
|
||||
json = target().path("/document/list")
|
||||
.queryParam("search", "full:vrandecic")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document2Token)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertTrue(json.getJsonArray("documents").size() == 1);
|
||||
|
||||
// Get the file thumbnail data
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(document2Token));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("size", "thumb");
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
InputStream is = response.getEntityInputStream();
|
||||
Response response = target().path("/file/" + file1Id + "/data")
|
||||
.queryParam("size", "thumb")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, document2Token)
|
||||
.get();
|
||||
InputStream is = (InputStream) response.getEntity();
|
||||
byte[] fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertTrue(fileBytes.length > 0); // Images rendered from PDF differ in size from OS to OS due to font issues
|
||||
Assert.assertEquals(MimeType.IMAGE_JPEG, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
|
@ -4,26 +4,29 @@ import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
|
||||
import org.glassfish.jersey.media.multipart.MultiPartFeature;
|
||||
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.Resources;
|
||||
import com.sismics.docs.core.util.DirectoryUtil;
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
import com.sismics.util.mime.MimeType;
|
||||
import com.sismics.util.mime.MimeTypeUtil;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import com.sun.jersey.multipart.FormDataBodyPart;
|
||||
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
|
||||
|
||||
/**
|
||||
* Exhaustive test of the file resource.
|
||||
@ -43,145 +46,137 @@ public class TestFileResource extends BaseJerseyTest {
|
||||
String file1AuthenticationToken = clientUtil.login("file1");
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "File test document 1");
|
||||
postParams.add("language", "eng");
|
||||
ClientResponse response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
long create1Date = new Date().getTime();
|
||||
JsonObject json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "File test document 1")
|
||||
.param("language", "eng")
|
||||
.param("create_date", Long.toString(create1Date))), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Add a file
|
||||
WebResource fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = this.getClass().getResourceAsStream("/file/PIA00452.jpg");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document1Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file1Id = json.getString("id");
|
||||
String file1Id = null;
|
||||
try (InputStream is = Resources.getResource("file/PIA00452.jpg").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "PIA00452.jpg");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.put(Entity.entity(multiPart.field("id", document1Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file1Id = json.getString("id");
|
||||
Assert.assertNotNull(file1Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Add a file
|
||||
fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
form = new FormDataMultiPart();
|
||||
file = this.getClass().getResourceAsStream("/file/PIA00452.jpg");
|
||||
fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document1Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file2Id = json.getString("id");
|
||||
String file2Id = null;
|
||||
try (InputStream is = Resources.getResource("file/PIA00452.jpg").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "PIA00452.jpg");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.put(Entity.entity(multiPart.field("id", document1Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file2Id = json.getString("id");
|
||||
Assert.assertNotNull(file2Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the file data
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
response = fileResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
InputStream is = response.getEntityInputStream();
|
||||
Response response = target().path("/file/" + file1Id + "/data").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get();
|
||||
InputStream is = (InputStream) response.getEntity();
|
||||
byte[] fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(MimeType.IMAGE_JPEG, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
Assert.assertTrue(fileBytes.length > 0);
|
||||
|
||||
// Get the thumbnail data
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("size", "thumb");
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
response = target().path("/file/" + file1Id + "/data")
|
||||
.queryParam("size", "thumb")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
is = response.getEntityInputStream();
|
||||
is = (InputStream) response.getEntity();
|
||||
fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(MimeType.IMAGE_JPEG, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
Assert.assertTrue(fileBytes.length > 0);
|
||||
|
||||
// Get the web data
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("size", "web");
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
response = target().path("/file/" + file1Id + "/data")
|
||||
.queryParam("size", "web")
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
is = response.getEntityInputStream();
|
||||
is = (InputStream) response.getEntity();
|
||||
fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(MimeType.IMAGE_JPEG, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
Assert.assertTrue(fileBytes.length > 0);
|
||||
|
||||
// Check that the files are not readable directly from FS
|
||||
java.io.File storedFile = Paths.get(DirectoryUtil.getStorageDirectory().getPath(), file1Id).toFile();
|
||||
InputStream storedFileInputStream = new BufferedInputStream(new FileInputStream(storedFile));
|
||||
Assert.assertNull(MimeTypeUtil.guessMimeType(storedFileInputStream));
|
||||
storedFileInputStream.close();
|
||||
try (InputStream storedFileInputStream = new BufferedInputStream(new FileInputStream(storedFile))) {
|
||||
Assert.assertNull(MimeTypeUtil.guessMimeType(storedFileInputStream));
|
||||
}
|
||||
|
||||
// Get all files from a document
|
||||
fileResource = resource().path("/file/list");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray files = json.getJSONArray("files");
|
||||
Assert.assertEquals(2, files.length());
|
||||
Assert.assertEquals(file1Id, files.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals(file2Id, files.getJSONObject(1).getString("id"));
|
||||
json = target().path("/file/list")
|
||||
.queryParam("id", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
JsonArray files = json.getJsonArray("files");
|
||||
Assert.assertEquals(2, files.size());
|
||||
Assert.assertEquals(file1Id, files.getJsonObject(0).getString("id"));
|
||||
Assert.assertEquals(file2Id, files.getJsonObject(1).getString("id"));
|
||||
|
||||
// Reorder files
|
||||
fileResource = resource().path("/file/reorder");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("id", document1Id);
|
||||
postParams.add("order", file2Id);
|
||||
postParams.add("order", file1Id);
|
||||
response = fileResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/file/reorder").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.post(Entity.form(new Form()
|
||||
.param("id", document1Id)
|
||||
.param("order", file2Id)
|
||||
.param("order", file1Id)), JsonObject.class);
|
||||
|
||||
// Get all files from a document
|
||||
fileResource = resource().path("/file/list");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
files = json.getJSONArray("files");
|
||||
Assert.assertEquals(2, files.length());
|
||||
Assert.assertEquals(file2Id, files.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals(file1Id, files.getJSONObject(1).getString("id"));
|
||||
json = target().path("/file/list")
|
||||
.queryParam("id", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
files = json.getJsonArray("files");
|
||||
Assert.assertEquals(2, files.size());
|
||||
Assert.assertEquals(file2Id, files.getJsonObject(0).getString("id"));
|
||||
Assert.assertEquals(file1Id, files.getJsonObject(1).getString("id"));
|
||||
|
||||
// Get a ZIP from all files
|
||||
fileResource = resource().path("/file/zip");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
is = response.getEntityInputStream();
|
||||
response = target().path("/file/zip")
|
||||
.queryParam("id", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get();
|
||||
is = (InputStream) response.getEntity();
|
||||
fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(MimeType.APPLICATION_ZIP, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
|
||||
// Deletes a file
|
||||
fileResource = resource().path("/file/" + file1Id);
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
response = fileResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/file/" + file1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Get the file data (not found)
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
response = fileResource.get(ClientResponse.class);
|
||||
response = target().path("/file/" + file1Id + "/data").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get();
|
||||
Assert.assertEquals(Status.NOT_FOUND, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Check that files are deleted from FS
|
||||
@ -193,15 +188,13 @@ public class TestFileResource extends BaseJerseyTest {
|
||||
Assert.assertFalse(thumbnailFile.exists());
|
||||
|
||||
// Get all files from a document
|
||||
fileResource = resource().path("/file/list");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file1AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
files = json.getJSONArray("files");
|
||||
Assert.assertEquals(1, files.length());
|
||||
json = target().path("/file/list")
|
||||
.queryParam("id", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file1AuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
files = json.getJsonArray("files");
|
||||
Assert.assertEquals(1, files.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -211,91 +204,81 @@ public class TestFileResource extends BaseJerseyTest {
|
||||
String file2AuthenticationToken = clientUtil.login("file2");
|
||||
|
||||
// Add a file
|
||||
WebResource fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = this.getClass().getResourceAsStream("/file/PIA00452.jpg");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
ClientResponse response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String file1Id = json.getString("id");
|
||||
String file1Id = null;
|
||||
try (InputStream is = Resources.getResource("file/PIA00452.jpg").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "PIA00452.jpg");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
JsonObject json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.put(Entity.entity(multiPart.bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file1Id = json.getString("id");
|
||||
Assert.assertNotNull(file1Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Get all orphan files
|
||||
fileResource = resource().path("/file/list");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray files = json.getJSONArray("files");
|
||||
Assert.assertEquals(1, files.length());
|
||||
JsonObject json = target().path("/file/list").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
JsonArray files = json.getJsonArray("files");
|
||||
Assert.assertEquals(1, files.size());
|
||||
|
||||
// Get the file data
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
response = fileResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
InputStream is = response.getEntityInputStream();
|
||||
Response response = target().path("/file/" + file1Id + "/data").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.get();
|
||||
InputStream is = (InputStream) response.getEntity();
|
||||
byte[] fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(MimeType.IMAGE_JPEG, MimeTypeUtil.guessMimeType(fileBytes));
|
||||
Assert.assertEquals(163510, fileBytes.length);
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "File test document 1");
|
||||
postParams.add("language", "eng");
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "File test document 1")
|
||||
.param("language", "eng")), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Attach a file to a document
|
||||
documentResource = resource().path("/file/" + file1Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("id", document1Id);
|
||||
response = documentResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/file/" + file1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.post(Entity.form(new Form()
|
||||
.param("id", document1Id)), JsonObject.class);
|
||||
|
||||
// Get all files from a document
|
||||
fileResource = resource().path("/file/list");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
files = json.getJSONArray("files");
|
||||
Assert.assertEquals(1, files.length());
|
||||
json = target().path("/file/list")
|
||||
.queryParam("id", document1Id)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
files = json.getJsonArray("files");
|
||||
Assert.assertEquals(1, files.size());
|
||||
|
||||
// Add a file
|
||||
fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
form = new FormDataMultiPart();
|
||||
file = this.getClass().getResourceAsStream("/file/PIA00452.jpg");
|
||||
fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file2Id = json.getString("id");
|
||||
String file2Id = null;
|
||||
try (InputStream is0 = Resources.getResource("file/PIA00452.jpg").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is0, "PIA00452.jpg");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.put(Entity.entity(multiPart.bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file2Id = json.getString("id");
|
||||
Assert.assertNotNull(file2Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Deletes a file
|
||||
fileResource = resource().path("/file/" + file2Id);
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(file2AuthenticationToken));
|
||||
response = fileResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/file/" + file2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, file2AuthenticationToken)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
}
|
||||
}
|
@ -1,14 +1,12 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import junit.framework.Assert;
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
/**
|
||||
* Test the locale resource.
|
||||
*
|
||||
@ -21,12 +19,9 @@ public class TestLocaleResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testLocaleResource() throws JSONException {
|
||||
WebResource localeResource = resource().path("/locale");
|
||||
ClientResponse response = localeResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JSONArray locale = json.getJSONArray("locales");
|
||||
Assert.assertTrue(locale.length() > 0);
|
||||
public void testLocaleResource() {
|
||||
JsonObject json = target().path("/locale").request().get(JsonObject.class);
|
||||
JsonArray locale = json.getJsonArray("locales");
|
||||
Assert.assertTrue(locale.size() > 0);
|
||||
}
|
||||
}
|
@ -1,16 +1,18 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
/**
|
||||
* Test of the security layer.
|
||||
*
|
||||
@ -23,50 +25,50 @@ public class TestSecurity extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testSecurity() throws JSONException {
|
||||
public void testSecurity() {
|
||||
// Create a user
|
||||
clientUtil.createUser("testsecurity");
|
||||
|
||||
// Changes a user's email KO : the user is not connected
|
||||
WebResource userResource = resource().path("/user/update");
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("email", "testsecurity2@docs.com");
|
||||
ClientResponse response = userResource.post(ClientResponse.class, postParams);
|
||||
Response response = target().path("/user/update").request()
|
||||
.post(Entity.form(new Form().param("email", "testsecurity2@docs.com")));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JsonObject json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ForbiddenError", json.getString("type"));
|
||||
Assert.assertEquals("You don't have access to this resource", json.getString("message"));
|
||||
|
||||
// User testsecurity logs in
|
||||
String testSecurityAuthenticationToken = clientUtil.login("testsecurity");
|
||||
|
||||
|
||||
// User testsecurity creates a new user KO : no permission
|
||||
response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, testSecurityAuthenticationToken)
|
||||
.put(Entity.form(new Form()));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
Assert.assertEquals("ForbiddenError", json.getString("type"));
|
||||
Assert.assertEquals("You don't have access to this resource", json.getString("message"));
|
||||
|
||||
// User testsecurity changes his email OK
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(testSecurityAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("email", "testsecurity2@docs.com");
|
||||
postParams.add("locale", "en");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, testSecurityAuthenticationToken)
|
||||
.post(Entity.form(
|
||||
new Form()
|
||||
.param("email", "testsecurity2@docs.com")
|
||||
.param("locale", "en")), JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// User testsecurity logs out
|
||||
userResource = resource().path("/user/logout");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(testSecurityAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
response = target().path("/user/logout").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, testSecurityAuthenticationToken)
|
||||
.post(Entity.form(new Form()));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
testSecurityAuthenticationToken = clientUtil.getAuthenticationCookie(response);
|
||||
Assert.assertTrue(StringUtils.isEmpty(testSecurityAuthenticationToken));
|
||||
|
||||
// User testsecurity logs out KO : he is not connected anymore
|
||||
userResource = resource().path("/user/logout");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(testSecurityAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
response = target().path("/user/logout").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, testSecurityAuthenticationToken)
|
||||
.post(Entity.form(new Form()));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// User testsecurity logs in with a long lived session
|
||||
|
@ -1,24 +1,25 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
|
||||
import org.glassfish.jersey.media.multipart.MultiPartFeature;
|
||||
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import com.sun.jersey.multipart.FormDataBodyPart;
|
||||
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
import com.google.common.io.Resources;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Exhaustive test of the share resource.
|
||||
@ -28,6 +29,7 @@ import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
public class TestShareResource extends BaseJerseyTest {
|
||||
/**
|
||||
* Test the share resource.
|
||||
* @throws Exception
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@ -38,99 +40,86 @@ public class TestShareResource extends BaseJerseyTest {
|
||||
String share1AuthenticationToken = clientUtil.login("share1");
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(share1AuthenticationToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "File test document 1");
|
||||
postParams.add("language", "eng");
|
||||
ClientResponse response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String document1Id = json.optString("id");
|
||||
JsonObject json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share1AuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "File test document 1")
|
||||
.param("language", "eng")), JsonObject.class);
|
||||
String document1Id = json.getString("id");
|
||||
Assert.assertNotNull(document1Id);
|
||||
|
||||
// Add a file
|
||||
WebResource fileResource = resource().path("/file");
|
||||
fileResource.addFilter(new CookieAuthenticationFilter(share1AuthenticationToken));
|
||||
FormDataMultiPart form = new FormDataMultiPart();
|
||||
InputStream file = this.getClass().getResourceAsStream("/file/PIA00452.jpg");
|
||||
FormDataBodyPart fdp = new FormDataBodyPart("file",
|
||||
new BufferedInputStream(file),
|
||||
MediaType.APPLICATION_OCTET_STREAM_TYPE);
|
||||
form.bodyPart(fdp);
|
||||
form.field("id", document1Id);
|
||||
response = fileResource.type(MediaType.MULTIPART_FORM_DATA).put(ClientResponse.class, form);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String file1Id = json.getString("id");
|
||||
String file1Id = null;
|
||||
try (InputStream is = Resources.getResource("file/PIA00452.jpg").openStream()) {
|
||||
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", is, "PIA00452.jpg");
|
||||
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
|
||||
json = target()
|
||||
.register(MultiPartFeature.class)
|
||||
.path("/file").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share1AuthenticationToken)
|
||||
.put(Entity.entity(multiPart.field("id", document1Id).bodyPart(streamDataBodyPart),
|
||||
MediaType.MULTIPART_FORM_DATA_TYPE), JsonObject.class);
|
||||
file1Id = json.getString("id");
|
||||
}
|
||||
}
|
||||
|
||||
// Share this document
|
||||
WebResource shareResource = resource().path("/share");
|
||||
shareResource.addFilter(new CookieAuthenticationFilter(share1AuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("id", document1Id);
|
||||
postParams.add("name", "4 All");
|
||||
response = shareResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/share").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share1AuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("id", document1Id)
|
||||
.param("name", "4 All")), JsonObject.class);
|
||||
String share1Id = json.getString("id");
|
||||
|
||||
// Get the document anonymously
|
||||
documentResource = resource().path("/document/" + document1Id);
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("share", share1Id);
|
||||
response = documentResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = target().path("/document/" + document1Id)
|
||||
.queryParam("share", share1Id)
|
||||
.request()
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals(document1Id, json.getString("id"));
|
||||
Assert.assertEquals(3, json.getJSONArray("acls").length()); // 2 for the creator, 1 for the share
|
||||
Assert.assertEquals(3, json.getJsonArray("acls").size()); // 2 for the creator, 1 for the share
|
||||
|
||||
// Get all files from this document anonymously
|
||||
fileResource = resource().path("/file/list");
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("id", document1Id);
|
||||
getParams.putSingle("share", share1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray files = json.getJSONArray("files");
|
||||
Assert.assertEquals(1, files.length());
|
||||
json = target().path("/file/list")
|
||||
.queryParam("id", document1Id)
|
||||
.queryParam("share", share1Id)
|
||||
.request()
|
||||
.get(JsonObject.class);
|
||||
JsonArray files = json.getJsonArray("files");
|
||||
Assert.assertEquals(1, files.size());
|
||||
|
||||
// Get the file data anonymously
|
||||
fileResource = resource().path("/file/" + file1Id + "/data");
|
||||
getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("thumbnail", false);
|
||||
getParams.putSingle("share", share1Id);
|
||||
response = fileResource.queryParams(getParams).get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
InputStream is = response.getEntityInputStream();
|
||||
Response response = target().path("/file/" + file1Id + "/data")
|
||||
.queryParam("thumbnail", false)
|
||||
.queryParam("share", share1Id)
|
||||
.request()
|
||||
.get();
|
||||
InputStream is = (InputStream) response.getEntity();
|
||||
byte[] fileBytes = ByteStreams.toByteArray(is);
|
||||
Assert.assertEquals(163510, fileBytes.length);
|
||||
|
||||
// Deletes the share (not allowed)
|
||||
clientUtil.createUser("share2");
|
||||
String share2AuthenticationToken = clientUtil.login("share2");
|
||||
shareResource = resource().path("/share/" + share1Id);
|
||||
shareResource.addFilter(new CookieAuthenticationFilter(share2AuthenticationToken));
|
||||
response = shareResource.delete(ClientResponse.class);
|
||||
response = target().path("/share/" + share1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share2AuthenticationToken)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("DocumentNotFound", json.getString("type"));
|
||||
|
||||
// Deletes the share
|
||||
shareResource = resource().path("/share/" + share1Id);
|
||||
shareResource.addFilter(new CookieAuthenticationFilter(share1AuthenticationToken));
|
||||
response = shareResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/share/" + share1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share1AuthenticationToken)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Deletes the share again
|
||||
shareResource = resource().path("/share/" + share1Id);
|
||||
shareResource.addFilter(new CookieAuthenticationFilter(share1AuthenticationToken));
|
||||
response = shareResource.delete(ClientResponse.class);
|
||||
response = target().path("/share/" + share1Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, share1AuthenticationToken)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ShareNotFound", json.getString("type"));
|
||||
}
|
||||
}
|
@ -1,16 +1,18 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import junit.framework.Assert;
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Test the tag resource.
|
||||
*
|
||||
@ -23,173 +25,138 @@ public class TestTagResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testTagResource() throws JSONException {
|
||||
public void testTagResource() {
|
||||
// Login tag1
|
||||
clientUtil.createUser("tag1");
|
||||
String tag1Token = clientUtil.login("tag1");
|
||||
|
||||
// Create a tag
|
||||
WebResource tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "Tag3");
|
||||
postParams.add("color", "#ff0000");
|
||||
ClientResponse response = tagResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
String tag3Id = json.optString("id");
|
||||
JsonObject json = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("name", "Tag3")
|
||||
.param("color", "#ff0000")), JsonObject.class);
|
||||
String tag3Id = json.getString("id");
|
||||
Assert.assertNotNull(tag3Id);
|
||||
|
||||
// Create a tag
|
||||
tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "Tag4");
|
||||
postParams.add("color", "#00ff00");
|
||||
response = tagResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
String tag4Id = json.optString("id");
|
||||
json = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("name", "Tag4")
|
||||
.param("color", "#00ff00")), JsonObject.class);
|
||||
String tag4Id = json.getString("id");
|
||||
Assert.assertNotNull(tag4Id);
|
||||
|
||||
// Create a tag with space (not allowed)
|
||||
tagResource = resource().path("/tag");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "Tag 4");
|
||||
response = tagResource.put(ClientResponse.class, postParams);
|
||||
Response response = target().path("/tag").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("name", "Tag 4")));
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Create a document
|
||||
WebResource documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super document 1");
|
||||
postParams.add("tags", tag3Id);
|
||||
postParams.add("language", "eng");
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super document 1")
|
||||
.param("tags", tag3Id)
|
||||
.param("language", "eng")), JsonObject.class);
|
||||
|
||||
// Create a document
|
||||
documentResource = resource().path("/document");
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("title", "My super document 2");
|
||||
postParams.add("tags", tag4Id);
|
||||
postParams.add("language", "eng");
|
||||
response = documentResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/document").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.put(Entity.form(new Form()
|
||||
.param("title", "My super document 2")
|
||||
.param("tags", tag4Id)
|
||||
.param("language", "eng")), JsonObject.class);
|
||||
String document2Id = json.getString("id");
|
||||
|
||||
// Check tags on a document
|
||||
documentResource = resource().path("/document/" + document2Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray tags = json.getJSONArray("tags");
|
||||
Assert.assertEquals(1, tags.length());
|
||||
Assert.assertEquals(tag4Id, tags.getJSONObject(0).getString("id"));
|
||||
json = target().path("/document/" + document2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
JsonArray tags = json.getJsonArray("tags");
|
||||
Assert.assertEquals(1, tags.size());
|
||||
Assert.assertEquals(tag4Id, tags.getJsonObject(0).getString("id"));
|
||||
|
||||
// Update tags on a document
|
||||
documentResource = resource().path("/document/" + document2Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("tags", tag3Id);
|
||||
postParams.add("tags", tag4Id);
|
||||
response = documentResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/document/" + document2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.post(Entity.form(new Form()
|
||||
.param("tags", tag3Id)
|
||||
.param("tags", tag4Id)));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Check tags on a document
|
||||
documentResource = resource().path("/document/" + document2Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertEquals(2, tags.length());
|
||||
Assert.assertEquals(tag3Id, tags.getJSONObject(0).getString("id"));
|
||||
Assert.assertEquals(tag4Id, tags.getJSONObject(1).getString("id"));
|
||||
json = target().path("/document/" + document2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertEquals(2, tags.size());
|
||||
Assert.assertEquals(tag3Id, tags.getJsonObject(0).getString("id"));
|
||||
Assert.assertEquals(tag4Id, tags.getJsonObject(1).getString("id"));
|
||||
|
||||
// Update tags on a document
|
||||
documentResource = resource().path("/document/" + document2Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("tags", tag4Id);
|
||||
response = documentResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/document/" + document2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.post(Entity.form(new Form()
|
||||
.param("tags", tag4Id)));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Check tags on a document
|
||||
documentResource = resource().path("/document/" + document2Id);
|
||||
documentResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = documentResource.get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertEquals(1, tags.length());
|
||||
Assert.assertEquals(tag4Id, tags.getJSONObject(0).getString("id"));
|
||||
json = target().path("/document/" + document2Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertEquals(1, tags.size());
|
||||
Assert.assertEquals(tag4Id, tags.getJsonObject(0).getString("id"));
|
||||
|
||||
// Get tag stats
|
||||
tagResource = resource().path("/tag/stats");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = tagResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
JSONArray stats = json.getJSONArray("stats");
|
||||
Assert.assertTrue(stats.length() == 2);
|
||||
Assert.assertEquals(1, stats.getJSONObject(0).getInt("count"));
|
||||
Assert.assertEquals(1, stats.getJSONObject(1).getInt("count"));
|
||||
json = target().path("/tag/stats").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
JsonArray stats = json.getJsonArray("stats");
|
||||
Assert.assertTrue(stats.size() == 2);
|
||||
Assert.assertEquals(1, stats.getJsonObject(0).getInt("count"));
|
||||
Assert.assertEquals(1, stats.getJsonObject(1).getInt("count"));
|
||||
|
||||
// Get all tags
|
||||
tagResource = resource().path("/tag/list");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = tagResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertTrue(tags.length() > 0);
|
||||
Assert.assertEquals("Tag4", tags.getJSONObject(1).getString("name"));
|
||||
Assert.assertEquals("#00ff00", tags.getJSONObject(1).getString("color"));
|
||||
json = target().path("/tag/list").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertTrue(tags.size() > 0);
|
||||
Assert.assertEquals("Tag4", tags.getJsonObject(1).getString("name"));
|
||||
Assert.assertEquals("#00ff00", tags.getJsonObject(1).getString("color"));
|
||||
|
||||
// Update a tag
|
||||
tagResource = resource().path("/tag/" + tag4Id);
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("name", "UpdatedName");
|
||||
postParams.add("color", "#0000ff");
|
||||
response = tagResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/tag/" + tag4Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.post(Entity.form(new Form()
|
||||
.param("name", "UpdatedName")
|
||||
.param("color", "#0000ff")), JsonObject.class);
|
||||
Assert.assertEquals(tag4Id, json.getString("id"));
|
||||
|
||||
// Get all tags
|
||||
tagResource = resource().path("/tag/list");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = tagResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertTrue(tags.length() > 0);
|
||||
Assert.assertEquals("UpdatedName", tags.getJSONObject(1).getString("name"));
|
||||
Assert.assertEquals("#0000ff", tags.getJSONObject(1).getString("color"));
|
||||
json = target().path("/tag/list").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertTrue(tags.size() > 0);
|
||||
Assert.assertEquals("UpdatedName", tags.getJsonObject(1).getString("name"));
|
||||
Assert.assertEquals("#0000ff", tags.getJsonObject(1).getString("color"));
|
||||
|
||||
// Deletes a tag
|
||||
tagResource = resource().path("/tag/" + tag4Id);
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = tagResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
target().path("/tag/" + tag4Id).request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.delete();
|
||||
|
||||
// Get all tags
|
||||
tagResource = resource().path("/tag/list");
|
||||
tagResource.addFilter(new CookieAuthenticationFilter(tag1Token));
|
||||
response = tagResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
tags = json.getJSONArray("tags");
|
||||
Assert.assertTrue(tags.length() == 1);
|
||||
json = target().path("/tag/list").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, tag1Token)
|
||||
.get(JsonObject.class);
|
||||
tags = json.getJsonArray("tags");
|
||||
Assert.assertTrue(tags.size() == 1);
|
||||
}
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import junit.framework.Assert;
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Test the theme resource.
|
||||
*
|
||||
* @author jtremeaux
|
||||
*/
|
||||
public class TestThemeResource extends BaseJerseyTest {
|
||||
/**
|
||||
* Test the theme resource.
|
||||
*
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testThemeResource() throws JSONException {
|
||||
WebResource themeResource = resource().path("/theme");
|
||||
ClientResponse response = themeResource.get(ClientResponse.class);
|
||||
response = themeResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JSONArray theme = json.getJSONArray("themes");
|
||||
Assert.assertTrue(theme.length() > 0);
|
||||
}
|
||||
}
|
@ -1,18 +1,19 @@
|
||||
package com.sismics.docs.rest;
|
||||
|
||||
import com.sismics.docs.rest.filter.CookieAuthenticationFilter;
|
||||
import com.sun.jersey.api.client.ClientResponse;
|
||||
import com.sun.jersey.api.client.ClientResponse.Status;
|
||||
import com.sun.jersey.api.client.WebResource;
|
||||
import com.sun.jersey.core.util.MultivaluedMapImpl;
|
||||
import junit.framework.Assert;
|
||||
import org.codehaus.jettison.json.JSONArray;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import java.util.Locale;
|
||||
import com.sismics.util.filter.TokenBasedSecurityFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Exhaustive test of the user resource.
|
||||
@ -26,12 +27,11 @@ public class TestUserResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testUserResource() throws JSONException {
|
||||
public void testUserResource() {
|
||||
// Check anonymous user information
|
||||
WebResource userResource = resource().path("/user");
|
||||
ClientResponse response = userResource.acceptLanguage(Locale.US).get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JsonObject json = target().path("/user").request()
|
||||
.acceptLanguage(Locale.US)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertTrue(json.getBoolean("is_default_password"));
|
||||
|
||||
// Create alice user
|
||||
@ -41,95 +41,82 @@ public class TestUserResource extends BaseJerseyTest {
|
||||
String adminAuthenticationToken = clientUtil.login("admin", "admin", false);
|
||||
|
||||
// List all users
|
||||
userResource = resource().path("/user/list");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
MultivaluedMapImpl getParams = new MultivaluedMapImpl();
|
||||
getParams.putSingle("sort_column", 2);
|
||||
getParams.putSingle("asc", false);
|
||||
response = userResource.queryParams(getParams).get(ClientResponse.class);
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONArray users = json.getJSONArray("users");
|
||||
Assert.assertTrue(users.length() > 0);
|
||||
json = target().path("/user/list")
|
||||
.queryParam("sort_column", 2)
|
||||
.queryParam("asc", false)
|
||||
.request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
JsonArray users = json.getJsonArray("users");
|
||||
Assert.assertTrue(users.size() > 0);
|
||||
|
||||
// Create a user KO (login length validation)
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", " bb ");
|
||||
postParams.putSingle("email", "bob@docs.com");
|
||||
postParams.putSingle("password", "12345678");
|
||||
response = userResource.put(ClientResponse.class, postParams);
|
||||
Response response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("username", " bb ")
|
||||
.param("email", "bob@docs.com")
|
||||
.param("password", "12345678")));
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ValidationError", json.getString("type"));
|
||||
Assert.assertTrue(json.getString("message"), json.getString("message").contains("more than 3"));
|
||||
|
||||
// Create a user KO (login format validation)
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", "bob-");
|
||||
postParams.putSingle("email", " bob@docs.com ");
|
||||
postParams.putSingle("password", "12345678");
|
||||
response = userResource.put(ClientResponse.class, postParams);
|
||||
response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("username", "bob-")
|
||||
.param("email", "bob@docs.com")
|
||||
.param("password", "12345678")));
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ValidationError", json.getString("type"));
|
||||
Assert.assertTrue(json.getString("message"), json.getString("message").contains("alphanumeric"));
|
||||
|
||||
// Create a user KO (email format validation)
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", "bob");
|
||||
postParams.putSingle("email", " bobdocs.com ");
|
||||
postParams.putSingle("password", "12345678");
|
||||
response = userResource.put(ClientResponse.class, postParams);
|
||||
response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(new Form()
|
||||
.param("username", "bob")
|
||||
.param("email", "bobdocs.com")
|
||||
.param("password", "12345678")));
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ValidationError", json.getString("type"));
|
||||
Assert.assertTrue(json.getString("message"), json.getString("message").contains("must be an email"));
|
||||
|
||||
// Create a user bob OK
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", " bob ");
|
||||
postParams.putSingle("email", " bob@docs.com ");
|
||||
postParams.putSingle("password", " 12345678 ");
|
||||
postParams.putSingle("locale", "fr");
|
||||
response = userResource.put(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
Form form = new Form()
|
||||
.param("username", " bob ")
|
||||
.param("email", " bob@docs.com ")
|
||||
.param("password", " 12345678 ");
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(form), JsonObject.class);
|
||||
|
||||
// Create a user bob KO : duplicate username
|
||||
response = userResource.put(ClientResponse.class, postParams);
|
||||
response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.put(Entity.form(form));
|
||||
Assert.assertNotSame(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("AlreadyExistingUsername", json.getString("type"));
|
||||
|
||||
// Check if a username is free : OK
|
||||
userResource = resource().path("/user/check_username");
|
||||
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
|
||||
queryParams.add("username", "carol");
|
||||
response = userResource.queryParams(queryParams).get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
target().path("/user/check_username").queryParam("username", "carol").request().get(JsonObject.class);
|
||||
|
||||
// Check if a username is free : KO
|
||||
userResource = resource().path("/user/check_username");
|
||||
queryParams = new MultivaluedMapImpl();
|
||||
queryParams.add("username", "alice");
|
||||
response = userResource.queryParams(queryParams).get(ClientResponse.class);
|
||||
response = target().path("/user/check_username").queryParam("username", "alice").request().get();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ko", json.getString("status"));
|
||||
|
||||
// Login alice with extra whitespaces
|
||||
userResource = resource().path("/user/login");
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.putSingle("username", " alice ");
|
||||
postParams.putSingle("password", " 12345678 ");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/user/login").request()
|
||||
.post(Entity.form(new Form()
|
||||
.param("username", " alice ")
|
||||
.param("password", " 12345678 ")));
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
String aliceAuthToken = clientUtil.getAuthenticationCookie(response);
|
||||
|
||||
@ -138,95 +125,81 @@ public class TestUserResource extends BaseJerseyTest {
|
||||
String bobAuthToken2 = clientUtil.login("bob");
|
||||
|
||||
// List sessions
|
||||
userResource = resource().path("/user/session");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(bobAuthToken));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
response = target().path("/user/session").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, bobAuthToken)
|
||||
.get();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertTrue(json.getJSONArray("sessions").length() > 0);
|
||||
JSONObject session = json.getJSONArray("sessions").getJSONObject(0);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertTrue(json.getJsonArray("sessions").size() > 0);
|
||||
JsonObject session = json.getJsonArray("sessions").getJsonObject(0);
|
||||
Assert.assertEquals("127.0.0.1", session.getString("ip"));
|
||||
Assert.assertTrue(session.getString("user_agent").startsWith("Java"));
|
||||
Assert.assertTrue(session.getString("user_agent").startsWith("Jersey"));
|
||||
|
||||
// Delete all sessions
|
||||
userResource = resource().path("/user/session");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(bobAuthToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
response = target().path("/user/session").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, bobAuthToken)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Check bob user information with token 2 (just deleted)
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(bobAuthToken2));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, bobAuthToken2)
|
||||
.get();
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals(true, json.getBoolean("anonymous"));
|
||||
|
||||
// Check alice user information
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(aliceAuthToken));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, aliceAuthToken)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals("alice@docs.com", json.getString("email"));
|
||||
Assert.assertEquals("default.less", json.getString("theme"));
|
||||
Assert.assertFalse(json.getBoolean("first_connection"));
|
||||
Assert.assertFalse(json.getBoolean("is_default_password"));
|
||||
|
||||
// Check bob user information
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(bobAuthToken));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, bobAuthToken)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals("bob@docs.com", json.getString("email"));
|
||||
Assert.assertEquals("fr", json.getString("locale"));
|
||||
|
||||
// Test login KO (user not found)
|
||||
userResource = resource().path("/user/login");
|
||||
postParams.putSingle("username", "intruder");
|
||||
postParams.putSingle("password", "12345678");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/user/login").request()
|
||||
.post(Entity.form(new Form()
|
||||
.param("username", "intruder")
|
||||
.param("password", "12345678")));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// Test login KO (wrong password)
|
||||
userResource = resource().path("/user/login");
|
||||
postParams.putSingle("username", "alice");
|
||||
postParams.putSingle("password", "error");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/user/login").request()
|
||||
.post(Entity.form(new Form()
|
||||
.param("username", "alice")
|
||||
.param("password", "error")));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
|
||||
// User alice updates her information + changes her email
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(aliceAuthToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("email", " alice2@docs.com ");
|
||||
postParams.add("theme", " default.less ");
|
||||
postParams.add("locale", " en ");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, aliceAuthToken)
|
||||
.post(Entity.form(new Form()
|
||||
.param("email", " alice2@docs.com ")), JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Check the update
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(aliceAuthToken));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, aliceAuthToken)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertEquals("alice2@docs.com", json.getString("email"));
|
||||
|
||||
// Delete user alice
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(aliceAuthToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, aliceAuthToken)
|
||||
.delete();
|
||||
|
||||
// Check the deletion
|
||||
userResource = resource().path("/user/login");
|
||||
postParams.putSingle("username", "alice");
|
||||
postParams.putSingle("password", "12345678");
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
response = target().path("/user/login").request()
|
||||
.post(Entity.form(new Form()
|
||||
.param("username", "alice")
|
||||
.param("password", "12345678")));
|
||||
Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus()));
|
||||
}
|
||||
|
||||
@ -236,86 +209,60 @@ public class TestUserResource extends BaseJerseyTest {
|
||||
* @throws JSONException
|
||||
*/
|
||||
@Test
|
||||
public void testUserResourceAdmin() throws JSONException {
|
||||
// Create admin_user1 user
|
||||
public void testUserResourceAdmin() {
|
||||
// Create admin_user1 user
|
||||
clientUtil.createUser("admin_user1");
|
||||
|
||||
// Login admin
|
||||
String adminAuthenticationToken = clientUtil.login("admin", "admin", false);
|
||||
|
||||
// Check admin information
|
||||
WebResource userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
ClientResponse response = userResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
JSONObject json = response.getEntity(JSONObject.class);
|
||||
JsonObject json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertTrue(json.getBoolean("first_connection"));
|
||||
Assert.assertTrue(json.getBoolean("is_default_password"));
|
||||
|
||||
// User admin updates his information
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
MultivaluedMapImpl postParams = new MultivaluedMapImpl();
|
||||
postParams.add("first_connection", false);
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.post(Entity.form(new Form()
|
||||
.param("first_connection", "false")), JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// Check admin information update
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = userResource.get(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.get(JsonObject.class);
|
||||
Assert.assertFalse(json.getBoolean("first_connection"));
|
||||
|
||||
// User admin update admin_user1 information
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
postParams = new MultivaluedMapImpl();
|
||||
postParams.add("email", " alice2@reader.com ");
|
||||
postParams.add("theme", " default.less");
|
||||
postParams.add("locale", " en ");
|
||||
postParams.add("display_title_web", true);
|
||||
postParams.add("display_title_mobile", false);
|
||||
postParams.add("display_unread_web", false);
|
||||
postParams.add("display_unread_mobile", false);
|
||||
response = userResource.post(ClientResponse.class, postParams);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.post(Entity.form(new Form()
|
||||
.param("email", " alice2@docs.com ")), JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// User admin deletes himself: forbidden
|
||||
userResource = resource().path("/user");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
Response response = target().path("/user").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
Assert.assertEquals("ForbiddenError", json.getString("type"));
|
||||
|
||||
// User admin deletes himself: forbidden
|
||||
userResource = resource().path("/user/admin");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("ForbiddenError", json.getString("type"));
|
||||
|
||||
// User admin deletes user admin_user1
|
||||
userResource = resource().path("/user/admin_user1");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
Assert.assertEquals(Status.OK, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = target().path("/user/admin_user1").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.delete(JsonObject.class);
|
||||
Assert.assertEquals("ok", json.getString("status"));
|
||||
|
||||
// User admin deletes user admin_user1 : KO (user doesn't exist)
|
||||
userResource = resource().path("/user/admin_user1");
|
||||
userResource.addFilter(new CookieAuthenticationFilter(adminAuthenticationToken));
|
||||
response = userResource.delete(ClientResponse.class);
|
||||
response = target().path("/user/admin_user1").request()
|
||||
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
|
||||
.delete();
|
||||
Assert.assertEquals(Status.BAD_REQUEST, Status.fromStatusCode(response.getStatus()));
|
||||
json = response.getEntity(JSONObject.class);
|
||||
json = response.readEntity(JsonObject.class);
|
||||
Assert.assertEquals("UserNotFound", json.getString("type"));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user