refactoring
diff --git a/src/main/java/de/ids_mannheim/korap/config/BeanInjectable.java b/src/main/java/de/ids_mannheim/korap/config/BeanInjectable.java
new file mode 100644
index 0000000..54f432e
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/config/BeanInjectable.java
@@ -0,0 +1,10 @@
+package de.ids_mannheim.korap.config;
+
+/**
+ * @author hanl
+ * @date 26/02/2016
+ */
+public interface BeanInjectable {
+
+ <T extends ContextHolder> void insertBeans (T beans);
+}
diff --git a/src/main/java/de/ids_mannheim/korap/config/ExceptionBuilder.java b/src/main/java/de/ids_mannheim/korap/config/ExceptionBuilder.java
new file mode 100644
index 0000000..4eb2725
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/config/ExceptionBuilder.java
@@ -0,0 +1,11 @@
+package de.ids_mannheim.korap.config;
+
+/**
+ * @author hanl
+ * @date 10/02/2016
+ */
+// run simple queries to determine the exception cause (e.g. policy could not be created because resource doesnt exist, etc.)
+public class ExceptionBuilder {
+ // use sqlbuilder to build the respective query (one instance per dao interface)
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/config/KustvaktContext.java b/src/main/java/de/ids_mannheim/korap/config/KustvaktContext.java
new file mode 100644
index 0000000..ed3b5dc
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/config/KustvaktContext.java
@@ -0,0 +1,14 @@
+package de.ids_mannheim.korap.config;
+
+/**
+ * @author hanl
+ * @date 14/03/2016
+ */
+public class KustvaktContext {
+
+
+ private KustvaktContext context;
+
+
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/config/UserClientInfo.java b/src/main/java/de/ids_mannheim/korap/config/UserClientInfo.java
new file mode 100644
index 0000000..c76d6b3
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/config/UserClientInfo.java
@@ -0,0 +1,30 @@
+package de.ids_mannheim.korap.config;
+
+import lombok.Data;
+
+/**
+ * @author hanl
+ * @date 22/01/2014
+ */
+@Data
+public class UserClientInfo {
+
+
+ private String OSName;
+ private String userAgent;
+ private String clientIP;
+
+
+ public UserClientInfo () {
+ this.clientIP = "";
+ this.userAgent = "";
+ this.OSName = "";
+ }
+
+
+ public UserClientInfo (String os, String ua, String ip) {
+ this.OSName = os;
+ this.userAgent = ua;
+ this.clientIP = ip;
+ }
+}
diff --git a/src/main/java/de/ids_mannheim/korap/managers/ManagerInterface.java b/src/main/java/de/ids_mannheim/korap/managers/ManagerInterface.java
new file mode 100644
index 0000000..946dfc2
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/managers/ManagerInterface.java
@@ -0,0 +1,61 @@
+package de.ids_mannheim.korap.managers;
+
+import java.util.Set;
+
+/**
+ * @author hanl
+ * @date 17/02/2016
+ */
+public interface ManagerInterface {
+
+ String name ();
+
+
+ Set<Function> getFunctions ();
+
+
+ Result process ();
+
+ class Result {
+
+ }
+
+ class Function {
+
+ private String name;
+ private String[] args;
+
+
+ @Override
+ public boolean equals (Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ Function function = (Function) o;
+
+ return name != null ? name.equals(function.name)
+ : function.name == null;
+
+ }
+
+
+ @Override
+ public int hashCode () {
+ return name != null ? name.hashCode() : 0;
+ }
+
+
+ public void setName (String name) {
+ this.name = name;
+ }
+
+
+ public void setArgs (String ... args) {
+ this.args = args;
+ }
+
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionCleanupFilter.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionCleanupFilter.java
index 46c39f9..3f9ce89 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionCleanupFilter.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionCleanupFilter.java
@@ -19,7 +19,7 @@
@Override
public JsonNode preProcess (KoralNode node, KustvaktConfiguration config,
User user) {
- return process(node.rawNode());
+ return node.rawNode();
}
@@ -59,7 +59,7 @@
@Override
public JsonNode postProcess (KoralNode node) {
- return null;
+ return process(node.rawNode());
}
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java
index 13e6196..05b6168 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java
@@ -2,8 +2,6 @@
import com.fasterxml.jackson.databind.JsonNode;
import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.config.BeanInjectable;
-import de.ids_mannheim.korap.config.ContextHolder;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.resources.Corpus;
@@ -15,16 +13,18 @@
* @author hanl
* @date 03/07/2015
*/
-public class CollectionConstraint implements RewriteTask.IterableRewriteAt {
+public class CollectionConstraint implements RewriteTask.IterableRewritePath {
+
+
+
@Override
public JsonNode preProcess (KoralNode node, KustvaktConfiguration config,
User user) {
if (node.get("@type").equals("koral:doc")) {
- if (node.get("key").equals(Attributes.CORPUS_SIGLE) && !check(node, user)) {
+ if (node.get("key").equals(Attributes.CORPUS_SIGLE)
+ && !check(node, user))
node.removeNode();
- // todo: add message that node was removed!
- }
}
return node.rawNode();
}
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/DocMatchRewrite.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/DocMatchRewrite.java
index fb4ba86..796592a 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/DocMatchRewrite.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/DocMatchRewrite.java
@@ -18,7 +18,7 @@
* @date 12/11/2015
*/
//todo : test
-public class DocMatchRewrite implements RewriteTask.IterableRewriteAt,
+public class DocMatchRewrite implements RewriteTask.IterableRewritePath,
BeanInjectable {
private DocumentDao docDao;
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/FoundryInject.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/FoundryInject.java
index 19d4145..486ae25 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/FoundryInject.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/FoundryInject.java
@@ -8,7 +8,6 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.interfaces.db.UserDataDbIface;
import de.ids_mannheim.korap.resource.LayerMapper;
-import de.ids_mannheim.korap.resources.Foundry;
import de.ids_mannheim.korap.user.User;
import de.ids_mannheim.korap.user.UserSettings;
import edu.emory.mathcs.backport.java.util.Collections;
@@ -19,7 +18,7 @@
* @author hanl
* @date 30/06/2015
*/
-public class FoundryInject implements RewriteTask.IterableRewriteAt,
+public class FoundryInject implements RewriteTask.IterableRewritePath,
BeanInjectable {
private Collection userdaos;
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/KoralNode.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/KoralNode.java
index 16debc8..8df544e 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/KoralNode.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/KoralNode.java
@@ -5,10 +5,7 @@
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.ids_mannheim.korap.utils.JsonUtils;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
/**
* @author hanl
@@ -16,13 +13,13 @@
*/
public abstract class KoralNode {
private JsonNode node;
- private KoralRewriteBuilder builder;
+ private KoralRewriteBuilder rewrites;
private boolean remove;
private KoralNode (JsonNode node) {
this.node = node;
- this.builder = new KoralRewriteBuilder();
+ this.rewrites = new KoralRewriteBuilder();
this.remove = false;
}
@@ -32,6 +29,12 @@
}
+ public void buildRewrites() {
+ System.out.println("LIST REWRITES "+ this.rewrites.rewrites);
+ this.rewrites.build(this.node);
+
+ }
+
@Override
public String toString () {
return this.node.toString();
@@ -39,7 +42,6 @@
public void put (String name, Object value) {
-
if (this.node.isObject() && this.node.path(name).isMissingNode()) {
ObjectNode node = (ObjectNode) this.node;
if (value instanceof String)
@@ -48,8 +50,7 @@
node.put(name, (Integer) value);
else if (value instanceof JsonNode)
node.put(name, (JsonNode) value);
- builder.setOperation("injection");
- builder.build(this.node);
+ this.rewrites.add("injection", name);
}
else
throw new UnsupportedOperationException(
@@ -70,8 +71,7 @@
set = true;
}
if (set) {
- builder.setOperation("deletion");
- builder.build(this.node);
+ this.rewrites.add("deletion", identifier);
}
}
@@ -85,12 +85,11 @@
n.put(name, (Integer) value);
else if (value instanceof JsonNode)
n.put(name, (JsonNode) value);
- builder.setOperation("override");
- builder.build(this.node);
+ this.rewrites.add("override", name);
}
}
- public void set (String name, Object value) {
+ public void set (String name, Object value, String attrIdent) {
if (this.node.isObject()) {
ObjectNode n = (ObjectNode) this.node;
if (value instanceof String)
@@ -99,12 +98,10 @@
n.put(name, (Integer) value);
else if (value instanceof JsonNode)
n.put(name, (JsonNode) value);
- builder.setOperation("insertion");
- builder.build(this.node);
+ this.rewrites.add("insertion", attrIdent);
}
}
-
public String get (String name) {
if (this.node.isObject())
return this.node.path(name).asText();
@@ -113,7 +110,8 @@
public KoralNode at (String name) {
- return KoralNode.wrapNode(this.node.at(name));
+ this.node = this.node.at(name);
+ return this;
}
@@ -132,6 +130,7 @@
public void removeNode () {
+ this.rewrites.add("deletion", this.node);
this.remove = true;
}
@@ -141,20 +140,61 @@
}
- //todo: 21.10.15 -- redo with better return policies!
public static class KoralRewriteBuilder {
+ private List<KoralRewrite> rewrites;
+
+ public KoralRewriteBuilder() {
+ this.rewrites = new ArrayList<>();
+ }
+
+
+ public KoralRewriteBuilder add(String op, Object scope) {
+ KoralRewrite rewrite = new KoralRewrite();
+ rewrite.setOperation(op);
+ rewrite.setScope(scope.toString());
+ this.rewrites.add(rewrite);
+ return this;
+ }
+
+
+ public JsonNode build (JsonNode node) {
+ for (KoralRewrite rewrite : this.rewrites) {
+ if (rewrite.map.get("operation") == null)
+ throw new UnsupportedOperationException(
+ "operation not set properly");
+
+ if (node.has("rewrites")) {
+ ArrayNode n = (ArrayNode) node.path("rewrites");
+ n.add(JsonUtils.valueToTree(rewrite.map));
+ } else {
+ ObjectNode n = (ObjectNode) node;
+ List l = new LinkedList<>();
+ l.add(JsonUtils.valueToTree(rewrite.map));
+ n.put("rewrites", JsonUtils.valueToTree(l));
+ }
+ }
+ this.rewrites.clear();
+ return node;
+ }
+
+ }
+
+
+
+
+ private static class KoralRewrite {
+
private Map<String, String> map;
-
- public KoralRewriteBuilder () {
+ private KoralRewrite () {
this.map = new LinkedHashMap<>();
this.map.put("@type", "koral:rewrite");
this.map.put("src", "Kustvakt");
}
- public KoralRewriteBuilder setOperation (String op) {
+ public KoralRewrite setOperation (String op) {
if (!op.startsWith("operation:"))
op = "operation:" + op;
this.map.put("operation", op);
@@ -162,29 +202,10 @@
}
- public KoralRewriteBuilder setScope (String scope) {
+ public KoralRewrite setScope (String scope) {
this.map.put("scope", scope);
return this;
}
-
- public JsonNode build (JsonNode node) {
- if (this.map.get("operation") == null)
- throw new UnsupportedOperationException(
- "operation not set properly");
-
- if (node.has("rewrites")) {
- ArrayNode n = (ArrayNode) node.path("rewrites");
- n.add(JsonUtils.valueToTree(this.map));
- }
- else {
- ObjectNode n = (ObjectNode) node;
- List l = new LinkedList<>();
- l.add(JsonUtils.valueToTree(this.map));
- n.put("rewrites", JsonUtils.valueToTree(l));
- }
- return node;
- }
-
}
}
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java
index a8efce3..114c35a 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java
@@ -11,8 +11,10 @@
import de.ids_mannheim.korap.user.User;
import de.ids_mannheim.korap.utils.KoralCollectionQueryBuilder;
import de.ids_mannheim.korap.utils.JsonUtils;
+import org.w3c.dom.Attr;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Set;
/**
@@ -43,7 +45,7 @@
ArrayList<KustvaktResource> list = new ArrayList(resources);
if (list.isEmpty())
- throw new KustvaktException(StatusCodes.REQUEST_INVALID,
+ throw new KustvaktException(StatusCodes.PERMISSION_DENIED,
"No resources found for user", user.getUsername());
for (int i = 0; i < list.size(); i++) {
@@ -52,7 +54,8 @@
b.with(Attributes.CORPUS_SIGLE+"=" + list.get(i).getPersistentID());
}
JsonNode rewritten = JsonUtils.readTree(b.toJSON());
- node.set("collection", rewritten.at("/collection"));
+ node.set("collection", rewritten.at("/collection"), Attributes.CORPUS_SIGLE);
+ node.at("/collection");
}
catch (KustvaktException e) {
e.printStackTrace();
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
index 746c3a0..fb98864 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
@@ -7,7 +7,6 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.user.User;
import de.ids_mannheim.korap.utils.JsonUtils;
-import org.apache.xpath.SourceTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -24,7 +23,7 @@
public class RewriteHandler implements BeanInjectable {
private static Logger jlog = LoggerFactory.getLogger(RewriteHandler.class);
- private Collection<RewriteTask.IterableRewriteAt> node_processors;
+ private Collection<RewriteTask.IterableRewritePath> node_processors;
private Collection<RewriteTask.RewriteKoralToken> token_node_processors;
private Collection<RewriteTask> query_processors;
@@ -66,9 +65,9 @@
if (rewriter instanceof RewriteTask.RewriteKoralToken)
return this.token_node_processors
.add((RewriteTask.RewriteKoralToken) rewriter);
- else if (rewriter instanceof RewriteTask.IterableRewriteAt)
+ else if (rewriter instanceof RewriteTask.IterableRewritePath)
return this.node_processors
- .add((RewriteTask.IterableRewriteAt) rewriter);
+ .add((RewriteTask.IterableRewritePath) rewriter);
else if (rewriter instanceof RewriteTask.RewriteBefore
| rewriter instanceof RewriteTask.RewriteAfter)
return this.query_processors.add(rewriter);
@@ -122,25 +121,25 @@
}
- private boolean process (String name, JsonNode root, User user, boolean post) {
+ private boolean processNode (String name, JsonNode root, User user, boolean post) {
if (root.isObject()) {
if (root.has("operands")) {
JsonNode ops = root.at("/operands");
Iterator<JsonNode> it = ops.elements();
while (it.hasNext()) {
JsonNode next = it.next();
- if (process(name, next, user, post))
+ if (processNode(name, next, user, post))
it.remove();
}
}
else if (root.path("@type").asText().equals("koral:token")) {
// todo: koral:token nodes cannot be flagged for deletion --> creates the possibility for empty koral:token nodes
- processNode(name, KoralNode.wrapNode(root), user,
+ rewrite(name, KoralNode.wrapNode(root), user,
this.token_node_processors, post);
- return process(name, root.path("wrap"), user, post);
+ return processNode(name, root.path("wrap"), user, post);
}
else {
- return processNode(name, KoralNode.wrapNode(root), user,
+ return rewrite(name, KoralNode.wrapNode(root), user,
this.node_processors, post);
}
}
@@ -148,7 +147,7 @@
Iterator<JsonNode> it = root.elements();
while (it.hasNext()) {
JsonNode next = it.next();
- if (process(name, next, user, post))
+ if (processNode(name, next, user, post))
it.remove();
}
}
@@ -156,13 +155,13 @@
}
- private JsonNode process (JsonNode root, User user, boolean post) {
+ private JsonNode iterate (JsonNode root, User user, boolean post) {
jlog.debug("Running rewrite process on query {}", root);
if (root != null) {
Iterator<Map.Entry<String, JsonNode>> it = root.fields();
while (it.hasNext()) {
Map.Entry<String, JsonNode> next = it.next();
- process(next.getKey(), next.getValue(), user, post);
+ processNode(next.getKey(), next.getValue(), user, post);
}
processFixedNode(root, user, this.query_processors, post);
}
@@ -170,24 +169,14 @@
}
- public JsonNode preProcess (JsonNode root, User user) {
- return process(root, user, false);
+ public JsonNode process(JsonNode root, User user) {
+ JsonNode pre = iterate(root, user, false);
+ return iterate(pre, user, true);
}
- // fixme: redo with first, second iteration and push clean up filters into second run
- public String preProcess (String json, User user) {
- return JsonUtils.toJSON(preProcess(JsonUtils.readTree(json), user));
- }
-
-
- public JsonNode postProcess (JsonNode root, User user) {
- return process(root, user, true);
- }
-
-
- public String postProcess (String json, User user) {
- return JsonUtils.toJSON(postProcess(JsonUtils.readTree(json), user));
+ public String process(String json, User user) {
+ return JsonUtils.toJSON(process(JsonUtils.readTree(json), user));
}
@@ -198,8 +187,7 @@
* @return boolean true if node is to be removed from parent! Only
* applies if parent is an array node
*/
- // todo: integrate notifications into system!
- private boolean processNode (String rootNode, KoralNode node, User user,
+ private boolean rewrite (String rootNode, KoralNode node, User user,
Collection<? extends RewriteTask> tasks, boolean post) {
if (this.config == null)
throw new RuntimeException("KustvaktConfiguration must be set!");
@@ -211,8 +199,8 @@
if (this.beans != null && task instanceof BeanInjectable)
((BeanInjectable) task).insertBeans(this.beans);
- if (task instanceof RewriteTask.IterableRewriteAt) {
- RewriteTask.IterableRewriteAt rw = (RewriteTask.IterableRewriteAt) task;
+ if (task instanceof RewriteTask.IterableRewritePath) {
+ RewriteTask.IterableRewritePath rw = (RewriteTask.IterableRewritePath) task;
if (rw.path() != null && !rw.path().equals(rootNode)) {
jlog.debug("skipping node: " + node);
continue;
@@ -226,6 +214,7 @@
else if (task instanceof RewriteTask.RewriteAfter) {
((RewriteTask.RewriteAfter) task).postProcess(node);
}
+ node.buildRewrites();
}
catch (KustvaktException e) {
jlog.error("Error in rewrite processor {} for node {}", task
@@ -242,20 +231,20 @@
private void processFixedNode (JsonNode node, User user,
Collection<RewriteTask> tasks, boolean post) {
for (RewriteTask task : tasks) {
- JsonNode next = node;
+ KoralNode next = KoralNode.wrapNode(node);
if (task instanceof RewriteTask.RewriteNodeAt) {
RewriteTask.RewriteNodeAt rwa = (RewriteTask.RewriteNodeAt) task;
if ((rwa.at() != null && !node.at(rwa.at()).isMissingNode()))
- next = node.at(rwa.at());
+ next = next.at(rwa.at());
}
try {
if (!post & task instanceof RewriteTask.RewriteBefore)
- ((RewriteTask.RewriteBefore) task).preProcess(
- KoralNode.wrapNode(next), this.config, user);
+ ((RewriteTask.RewriteBefore) task).preProcess(next,
+ this.config, user);
else if (task instanceof RewriteTask.RewriteAfter)
- ((RewriteTask.RewriteAfter) task).postProcess(KoralNode
- .wrapNode(next));
+ ((RewriteTask.RewriteAfter) task).postProcess(next);
+ next.buildRewrites();
}
catch (KustvaktException e) {
jlog.error("Error in rewrite processor {} for node {}", task
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteTask.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteTask.java
index 2c7fa06..fcc43aa 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteTask.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteTask.java
@@ -38,7 +38,7 @@
* {@link de.ids_mannheim.korap.resource.rewrite.RewriteTask.RewriteAfter}
* queries will run
* after
- * {@link de.ids_mannheim.korap.resource.rewrite.RewriteTask.IterableRewriteAt}
+ * {@link IterableRewritePath}
* have been processed
*/
interface RewriteAfter extends RewriteTask {
@@ -61,7 +61,7 @@
* iteration
* (both object and array node iteration supported)
*/
- interface IterableRewriteAt extends RewriteBefore, RewriteAfter {
+ interface IterableRewritePath extends RewriteBefore, RewriteAfter {
String path ();
}
diff --git a/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java b/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java
new file mode 100644
index 0000000..ba984d6
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java
@@ -0,0 +1,111 @@
+package de.ids_mannheim.korap.security.ac;
+
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.exceptions.EmptyResultException;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
+import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
+import de.ids_mannheim.korap.resources.KustvaktResource;
+import de.ids_mannheim.korap.resources.Permissions;
+import de.ids_mannheim.korap.security.PolicyCondition;
+import de.ids_mannheim.korap.user.User;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+
+/**
+ * @author hanl
+ * @date 04/03/2014
+ */
+public class ConditionManager {
+
+ private static final Logger jlog = LoggerFactory
+ .getLogger(ConditionManager.class);
+ private User user;
+ private PolicyHandlerIface policydao;
+
+
+ public ConditionManager (User user) {
+ this.user = user;
+ this.policydao = BeansFactory.getKustvaktContext()
+ .getPolicyDbProvider();
+ }
+
+
+ /**
+ * adds a user to an existing group
+ *
+ * @param usernames
+ * @param condition
+ * @param admin
+ */
+ // todo: conflict resolution
+ // fixme: not applicable to korap system roles
+ // only works if there is a policy with that condition and permission set, if not, create one!
+ public void addUser (List<String> usernames, PolicyCondition condition,
+ boolean admin) throws NotAuthorizedException, KustvaktException {
+ if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
+ policydao.addToCondition(usernames, condition, admin);
+ }
+ else
+ jlog.error("Users '{}' could not be added to condition '{}'",
+ usernames, condition.getSpecifier());
+ }
+
+
+ public void addUser (String username, PolicyCondition condition,
+ boolean admin) throws NotAuthorizedException, KustvaktException {
+ addUser(Arrays.asList(username), condition, admin);
+ }
+
+
+ public void removeUser (List<String> users, PolicyCondition condition)
+ throws KustvaktException {
+ if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
+ policydao.removeFromCondition(users, condition);
+ }
+ }
+
+
+ public Set<String> getMembers (PolicyCondition condition) {
+ try {
+ if (policydao.matchCondition(this.user, condition.getSpecifier(),
+ true) == 1) {
+ return new HashSet<>(policydao.getUsersFromCondition(condition));
+ }
+ }
+ catch (KustvaktException e) {
+ return Collections.emptySet();
+ }
+ return Collections.emptySet();
+ }
+
+
+ @Deprecated
+ public void addUser (KustvaktResource resource, String user,
+ Permissions.Permission ... pps) throws NotAuthorizedException,
+ KustvaktException, EmptyResultException {
+ addUser(resource, Arrays.asList(user), pps);
+ }
+
+
+ @Deprecated
+ public void addUser (KustvaktResource resource, List<String> users,
+ Permissions.Permission ... pps) throws NotAuthorizedException,
+ KustvaktException, EmptyResultException {
+ SecurityManager policies = SecurityManager.findbyId(resource.getId(),
+ this.user);
+ PolicyCondition c = policies.getExtensional(pps);
+ if (c != null)
+ this.addUser(users, c, false);
+ else {
+ PolicyCondition ex = new PolicyCondition();
+ new PolicyBuilder(this.user).setResources(resource)
+ .addCondition(ex.getSpecifier()).setPermissions(pps)
+ .create();
+ this.addUser(users, ex, false);
+ }
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java b/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java
new file mode 100644
index 0000000..b129373
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java
@@ -0,0 +1,15 @@
+package de.ids_mannheim.korap.security.ac;
+
+/**
+ * @author hanl
+ * @date 22/11/2015
+ */
+public class SecurityManagerFactory {
+
+ // make security manager and policydao transferable and exchangable
+ // resource finder
+ // resource handler
+
+
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManager.java b/src/main/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManager.java
index 97e67af..00a6e17 100644
--- a/src/main/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManager.java
+++ b/src/main/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManager.java
@@ -756,12 +756,12 @@
data = dao.get(user);
if (data == null)
- throw new WrappedException(user.getId(),
- StatusCodes.EMPTY_RESULTS, clazz.getSimpleName());
+ throw new KustvaktException(user.getId(),
+ StatusCodes.EMPTY_RESULTS, "No data found!", clazz.getSimpleName());
return data;
}
catch (KustvaktException e) {
- jlog.error("Error ", e);
+ jlog.error("Error during user data retrieval!", e.getEntity());
throw new WrappedException(e, StatusCodes.GET_ACCOUNT_FAILED);
}
}
@@ -780,32 +780,11 @@
dao.update(data);
}
catch (KustvaktException e) {
- jlog.error("Error ", e);
+ jlog.error("Error during update of user data!", e.getEntity());
throw new WrappedException(e, StatusCodes.UPDATE_ACCOUNT_FAILED);
}
}
-
- // public UserDetails getUserDetails(User user) throws KustvaktException {
- // try {
- // if (user.getDetails() == null)
- // user.setDetails(entHandler.getUserDetails(user.getId()));
- // }catch (KustvaktException e) {
- // throw new WrappedException(e, StatusCodes.GET_ACCOUNT_FAILED);
- // }
- // return user.getDetails();
- // }
- //
- // public UserSettings getUserSettings(User user) throws KustvaktException {
- // try {
- // if (user.getSettings() == null)
- // user.setSettings(entHandler.getUserSettings(user.getId()));
- // }catch (KustvaktException e) {
- // throw new WrappedException(e, StatusCodes.GET_ACCOUNT_FAILED);
- // }
- // return user.getSettings();
- // }
-
private String cache_key (String input) throws KustvaktException {
try {
return crypto.hash(KEY + "@" + input);
diff --git a/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java b/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java
new file mode 100644
index 0000000..52f8663
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java
@@ -0,0 +1,71 @@
+package de.ids_mannheim.korap.utils;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * Created by hanl on 14.05.16.
+ */
+public class NamingUtils {
+
+ private static final String SLASH = "/";
+
+
+ private NamingUtils () {}
+
+
+ public static Collection<String> joinStringSet (Collection<String> source,
+ String other) {
+ Set<String> set = new HashSet<>(source);
+ set.add(other);
+ return set;
+ }
+
+
+ public static Collection<UUID> joinUUIDSet (Collection<UUID> source,
+ UUID other) {
+ Set<UUID> set = new HashSet<>(source);
+ set.add(other);
+ return set;
+ }
+
+
+ public static String joinResources (String first, String second) {
+ String res;
+ if (first != null && !first.isEmpty())
+ res = first + SLASH + second;
+ else
+ res = second;
+ return res.replaceAll("\\s", "");
+ }
+
+
+ public static String[] splitAnnotations (String joined) {
+ String[] spl = joined.split(SLASH);
+ if (spl.length == 2)
+ return spl;
+ else
+ return null;
+ }
+
+
+ public static String stripTokenType (String token) {
+ int idx = token.lastIndexOf(" ");
+ if (idx == -1)
+ return token;
+ return token.substring(idx).replaceAll("\\s", "");
+ }
+
+
+ public static String getTokenType (String token) {
+ if (token.contains(" "))
+ return token.substring(0, token.lastIndexOf(" "))
+ .replaceAll("\\s", "").toLowerCase();
+ else
+ return null;
+ }
+
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java b/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java
new file mode 100644
index 0000000..a30c8be
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java
@@ -0,0 +1,59 @@
+package de.ids_mannheim.korap.utils;
+
+import lombok.Getter;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * @author hanl
+ * @date 23/01/2014
+ */
+public class ServiceInfo {
+
+ private static final ServiceInfo info = new ServiceInfo();
+
+ private static String UNKNOWN = "UNKNOWN";
+
+ @Getter
+ private String name;
+ @Getter
+ private String version;
+
+
+ private ServiceInfo () {
+ load();
+ }
+
+
+ private void load () {
+ Properties props = new Properties();
+ try {
+ InputStream stream = getStream();
+ props.load(stream);
+ stream.close();
+ this.version = (String) props.get("kustvakt.version");
+ this.name = (String) props.get("kustvakt.name");
+ }
+ catch (IOException e) {
+ this.version = UNKNOWN;
+ this.name = UNKNOWN;
+ }
+ }
+
+
+ private static InputStream getStream () throws IOException {
+ String path = "/kustvakt.info";
+ InputStream stream = ServiceInfo.class.getResourceAsStream(path);
+ if (stream == null)
+ throw new IOException("stream for resource " + path
+ + " could not be found...");
+ return stream;
+ }
+
+
+ public static ServiceInfo getInfo () {
+ return info;
+ }
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/Arg.java b/src/main/java/de/ids_mannheim/korap/web/Arg.java
new file mode 100644
index 0000000..1fe8bf3
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/Arg.java
@@ -0,0 +1,124 @@
+package de.ids_mannheim.korap.web;
+
+import de.ids_mannheim.korap.config.KustvaktClassLoader;
+import lombok.Getter;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author hanl
+ * @date 11/02/2016
+ */
+public abstract class Arg<T> {
+
+ @Getter
+ protected T value;
+
+
+ protected Arg () {}
+
+
+ public abstract void setValue (String value);
+
+
+ public String toString () {
+ return "--" + getName();
+ }
+
+
+ public abstract String getName ();
+
+
+ public abstract void run ();
+
+
+ public static Set<Arg> loadArgs (String[] args) {
+ Set<Arg> argSet = new HashSet<>();
+ Set<Class<? extends Arg>> set = KustvaktClassLoader
+ .loadSubTypes(Arg.class);
+
+ for (int idx = 0; idx < args.length; idx++) {
+ for (Class aClass : new HashSet<>(set)) {
+ if (!argSet.contains(aClass)) {
+ Arg arg;
+ try {
+ arg = (Arg) aClass.newInstance();
+ }
+ catch (InstantiationException | IllegalAccessException e) {
+ continue;
+ }
+ if (arg.toString().equals(args[idx])) {
+ int i = args.length - 1;
+ if (i > idx + 1)
+ i = idx + 1;
+ arg.setValue(args[i]);
+ arg.run();
+ argSet.add(arg);
+ set.remove(aClass);
+ }
+ }
+ }
+ }
+ return argSet;
+ }
+
+ public static class ConfigArg extends Arg<String> {
+
+ @Override
+ public void setValue (String value) {
+ this.value = value;
+ }
+
+
+ @Override
+ public String getName () {
+ return "config";
+ }
+
+
+ @Override
+ public void run () {
+
+ }
+ }
+
+ public static class InitArg extends Arg<Boolean> {
+
+ @Override
+ public void setValue (String value) {
+ this.value = true;
+ }
+
+
+ @Override
+ public String getName () {
+ return "init";
+ }
+
+
+ @Override
+ public void run () {
+
+ }
+ }
+
+ public static class PortArg extends Arg<Integer> {
+
+ @Override
+ public void setValue (String value) {
+ this.value = Integer.valueOf(value);
+ }
+
+
+ @Override
+ public String getName () {
+ return "port";
+ }
+
+
+ @Override
+ public void run () {}
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java b/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java
new file mode 100644
index 0000000..29763fa
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java
@@ -0,0 +1,60 @@
+package de.ids_mannheim.korap.web.filter;
+
+import com.sun.jersey.spi.container.ContainerRequest;
+import com.sun.jersey.spi.container.ContainerRequestFilter;
+import com.sun.jersey.spi.container.ContainerResponseFilter;
+import com.sun.jersey.spi.container.ResourceFilter;
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.user.TokenContext;
+import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.utils.NamingUtils;
+import de.ids_mannheim.korap.utils.StringUtils;
+import de.ids_mannheim.korap.web.utils.KorAPContext;
+import de.ids_mannheim.korap.web.utils.KustvaktResponseHandler;
+
+import javax.ws.rs.ext.Provider;
+
+/**
+ * @author hanl
+ * @date 17/06/2014
+ */
+@Provider
+public class AdminFilter implements ContainerRequestFilter, ResourceFilter {
+
+ // check over ssl!
+ @Override
+ public ContainerRequest filter (ContainerRequest cr) {
+ // todo:
+ String host = cr.getHeaderValue(ContainerRequest.HOST);
+ String ua = cr.getHeaderValue(ContainerRequest.USER_AGENT);
+
+ String authentication = cr
+ .getHeaderValue(ContainerRequest.AUTHORIZATION);
+
+ if (authentication != null
+ && authentication.endsWith(BeansFactory.getKustvaktContext()
+ .getConfiguration().getAdminToken())) {
+ TokenContext c = new TokenContext();
+ c.setUsername(User.ADMINISTRATOR_NAME);
+ c.setTokenType(NamingUtils.getTokenType(authentication));
+ c.setToken(NamingUtils.stripTokenType(authentication));
+ cr.setSecurityContext(new KorAPContext(c));
+ }
+ else
+ throw KustvaktResponseHandler.throwAuthenticationException();
+
+ return cr;
+ }
+
+
+ @Override
+ public ContainerRequestFilter getRequestFilter () {
+ return this;
+ }
+
+
+ @Override
+ public ContainerResponseFilter getResponseFilter () {
+ return null;
+ }
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java b/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java
new file mode 100644
index 0000000..ff77428
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java
@@ -0,0 +1,58 @@
+package de.ids_mannheim.korap.web.filter;
+
+import com.sun.jersey.spi.container.ContainerRequest;
+import com.sun.jersey.spi.container.ContainerRequestFilter;
+import com.sun.jersey.spi.container.ContainerResponseFilter;
+import com.sun.jersey.spi.container.ResourceFilter;
+import de.ids_mannheim.korap.security.auth.BasicHttpAuth;
+import de.ids_mannheim.korap.config.Attributes;
+import de.ids_mannheim.korap.user.TokenContext;
+import de.ids_mannheim.korap.web.utils.KorAPContext;
+
+import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.Provider;
+
+/**
+ * @author hanl
+ * @date 08/02/2016
+ */
+@Provider
+public class DemoFilter implements ContainerRequestFilter, ResourceFilter {
+
+ @Override
+ public ContainerRequest filter (ContainerRequest request) {
+ String authentication = request
+ .getHeaderValue(ContainerRequest.AUTHORIZATION);
+ if (authentication == null || authentication.isEmpty()) {
+ try {
+ request.getUserPrincipal();
+ }
+ catch (UnsupportedOperationException e) {
+ request.setSecurityContext(createContext());
+ }
+ }
+ return request;
+ }
+
+
+ private SecurityContext createContext () {
+ TokenContext context = new TokenContext();
+ String token = BasicHttpAuth.encode("demo", "demo2015");
+ context.setToken(token);
+ context.setTokenType(Attributes.BASIC_AUTHENTICATION);
+ context.setUsername("demo");
+ return new KorAPContext(context);
+ }
+
+
+ @Override
+ public ContainerRequestFilter getRequestFilter () {
+ return this;
+ }
+
+
+ @Override
+ public ContainerResponseFilter getResponseFilter () {
+ return null;
+ }
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/BootableBeanInterface.java b/src/main/java/de/ids_mannheim/korap/web/service/BootableBeanInterface.java
new file mode 100644
index 0000000..c600aaa
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/service/BootableBeanInterface.java
@@ -0,0 +1,17 @@
+package de.ids_mannheim.korap.web.service;
+
+import de.ids_mannheim.korap.config.ContextHolder;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+
+/**
+ * @author hanl
+ * @date 12/01/2016
+ */
+public interface BootableBeanInterface {
+
+ void load (ContextHolder beans) throws KustvaktException;
+
+
+ Class<? extends BootableBeanInterface>[] getDependencies ();
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/AdminService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/AdminService.java
new file mode 100644
index 0000000..08fd322
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/AdminService.java
@@ -0,0 +1,153 @@
+package de.ids_mannheim.korap.web.service.full;
+
+import com.sun.jersey.spi.container.ResourceFilters;
+import de.ids_mannheim.korap.auditing.AuditRecord;
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.exceptions.StatusCodes;
+import de.ids_mannheim.korap.handlers.DocumentDao;
+import de.ids_mannheim.korap.interfaces.db.AuditingIface;
+import de.ids_mannheim.korap.interfaces.AuthenticationManagerIface;
+import de.ids_mannheim.korap.resources.Document;
+import de.ids_mannheim.korap.resources.KustvaktResource;
+import de.ids_mannheim.korap.resources.Permissions;
+import de.ids_mannheim.korap.resources.ResourceFactory;
+import de.ids_mannheim.korap.security.PolicyCondition;
+import de.ids_mannheim.korap.security.ac.PolicyBuilder;
+import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.utils.JsonUtils;
+import de.ids_mannheim.korap.utils.KustvaktLogger;
+import de.ids_mannheim.korap.utils.TimeUtils;
+import de.ids_mannheim.korap.web.KustvaktServer;
+import de.ids_mannheim.korap.web.filter.AdminFilter;
+import de.ids_mannheim.korap.web.filter.PiwikFilter;
+import de.ids_mannheim.korap.web.utils.KustvaktResponseHandler;
+import org.joda.time.DateTime;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+import org.slf4j.Logger;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Created by hanl on 6/11/14.
+ */
+@Path(KustvaktServer.API_VERSION + "/admin")
+@ResourceFilters({ AdminFilter.class, PiwikFilter.class })
+@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+public class AdminService {
+
+ private static Logger jlog = KustvaktLogger.getLogger(AdminService.class);
+ // todo: map in timeutils
+ private static DateTimeFormatter dtf = DateTimeFormat
+ .forPattern("dd/MM/yyyy");
+ // private AdminQueryController adminController;
+ private AuthenticationManagerIface controller;
+ private AuditingIface auditingController;
+ private DocumentDao documentDao;
+
+
+ public AdminService () {
+ this.auditingController = BeansFactory.getKustvaktContext()
+ .getAuditingProvider();
+ this.controller = BeansFactory.getKustvaktContext()
+ .getAuthenticationManager();
+ this.documentDao = new DocumentDao(BeansFactory.getKustvaktContext()
+ .getPersistenceClient());
+ }
+
+
+ @GET
+ @Path("audit/{type}")
+ public Response getAudits (@PathParam("type") String type,
+ @QueryParam("from") String from, @QueryParam("until") String until,
+ @QueryParam("day") Boolean day, @QueryParam("limit") String limit,
+ @Context Locale locale) {
+ DateTime from_date, until_date;
+
+ if (from == null)
+ from_date = new DateTime();
+ else
+ from_date = DateTime.parse(from, dtf);
+ if (until == null)
+ until_date = new DateTime();
+ else
+ until_date = DateTime.parse(until, dtf);
+
+ int integer_limit;
+ boolean dayOnly = Boolean.valueOf(day);
+ try {
+ integer_limit = Integer.valueOf(limit);
+ }
+ catch (NumberFormatException | NullPointerException e) {
+ throw KustvaktResponseHandler.throwit(StatusCodes.ILLEGAL_ARGUMENT);
+ }
+ String result = JsonUtils.toJSON(auditingController.retrieveRecords(
+ AuditRecord.CATEGORY.valueOf(type.toUpperCase()), from_date,
+ until_date, dayOnly, integer_limit));
+ // limit number of records to return
+ return Response.ok(result).build();
+ }
+
+
+ @POST
+ @Path("createPolicies/{id}")
+ public Response addResourcePolicy (@PathParam("id") String persistentid,
+ @QueryParam("type") String type, @QueryParam("name") String name,
+ @QueryParam("description") String description,
+ @QueryParam("group") String group,
+ @QueryParam("perm") List<String> permissions,
+ @QueryParam("loc") String loc, @QueryParam("expire") String duration) {
+
+ KustvaktResource resource = ResourceFactory.getResource(type);
+ resource.setPersistentID(persistentid);
+ resource.setDescription(description);
+ resource.setName(name);
+
+ Permissions.Permission[] p = new Permissions.Permission[permissions
+ .size()];
+ for (int idx = 0; idx < permissions.size(); idx++)
+ p[idx] = Permissions.Permission.valueOf(permissions.get(idx)
+ .toUpperCase());
+
+ try {
+ PolicyBuilder cr = new PolicyBuilder(User.UserFactory.getAdmin())
+ .setConditions(new PolicyCondition(group)).setResources(
+ resource);
+ if (loc != null && !loc.isEmpty())
+ cr.setLocation(loc);
+
+ if (duration != null && duration.isEmpty())
+ cr.setContext(TimeUtils.getNow().getMillis(),
+ TimeUtils.convertTimeToSeconds(duration));
+
+ cr.setPermissions(p).create();
+ }
+ catch (KustvaktException e) {
+ throw KustvaktResponseHandler.throwit(e);
+ }
+
+ return Response.ok().build();
+ }
+
+
+ //fixme: documentservice?!
+ @POST
+ @Path("doc/{id}/add")
+ public Response addDocument (@PathParam("id") String id) {
+ Document document = new Document(id);
+ try {
+ this.documentDao.storeResource(document, null);
+ }
+ catch (KustvaktException e) {
+ throw KustvaktResponseHandler.throwit(e);
+ }
+ return Response.ok().build();
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/DocumentService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/DocumentService.java
new file mode 100644
index 0000000..e1648d2
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/DocumentService.java
@@ -0,0 +1,78 @@
+package de.ids_mannheim.korap.web.service.full;
+
+import com.sun.jersey.spi.container.ResourceFilters;
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.handlers.DocumentDao;
+import de.ids_mannheim.korap.resources.Document;
+import de.ids_mannheim.korap.utils.JsonUtils;
+import de.ids_mannheim.korap.utils.KustvaktLogger;
+import de.ids_mannheim.korap.web.KustvaktServer;
+import de.ids_mannheim.korap.web.filter.AdminFilter;
+import de.ids_mannheim.korap.web.utils.KustvaktResponseHandler;
+import org.slf4j.Logger;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
+
+/**
+ * @author hanl
+ * @date 19/11/2014
+ */
+@Path(KustvaktServer.API_VERSION + "/doc")
+@ResourceFilters({ AdminFilter.class })
+@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+public class DocumentService {
+
+ private static Logger jlog = KustvaktLogger
+ .getLogger(DocumentService.class);
+ private DocumentDao documentDao;
+
+
+ // todo: error handling
+ public DocumentService () {
+ this.documentDao = new DocumentDao(BeansFactory.getKustvaktContext()
+ .getPersistenceClient());
+ }
+
+
+ @POST
+ @Path("{doc}")
+ public Response store (@PathParam("doc") String docid,
+ @QueryParam("disabled") Boolean disabled) {
+ Document doc = new Document(docid);
+ doc.setDisabled(disabled);
+ try {
+ this.documentDao.storeResource(doc, null);
+ }
+ catch (KustvaktException e) {
+ throw KustvaktResponseHandler.throwit(e);
+ }
+ return Response.ok().build();
+ }
+
+
+ //todo: pipe add document to index endpoint
+
+ @GET
+ @Path("{corpus}")
+ public Response get (@PathParam("corpus") String corpus,
+ @QueryParam("index") Integer index,
+ @QueryParam("offset") Integer length) {
+ if (index == null)
+ index = 1;
+ if (length == null)
+ length = 25;
+ try {
+ List docs = this.documentDao.findbyCorpus(corpus, length, index);
+ //todo: serialize to document json
+ return Response.ok(JsonUtils.toJSON(docs)).build();
+ }
+ catch (KustvaktException e) {
+ throw KustvaktResponseHandler.throwit(e);
+ }
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/KustvaktService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/KustvaktService.java
new file mode 100644
index 0000000..c4db1b8
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/KustvaktService.java
@@ -0,0 +1,35 @@
+package de.ids_mannheim.korap.web.service.full;
+
+import de.ids_mannheim.korap.utils.JsonUtils;
+import de.ids_mannheim.korap.utils.ServiceInfo;
+import de.ids_mannheim.korap.web.KustvaktServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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.HashMap;
+import java.util.Map;
+
+/**
+ * Created by hanl on 29.04.16.
+ */
+@Path("kustvakt")
+@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+public class KustvaktService {
+
+ private static Logger jlog = LoggerFactory.getLogger(UserService.class);
+
+
+ @Path("info")
+ public Response getInfo () {
+ Map m = new HashMap();
+ m.put("version", ServiceInfo.getInfo().getVersion());
+ m.put("recent_api_version", KustvaktServer.API_VERSION);
+ m.put("service_name", ServiceInfo.getInfo().getName());
+ return Response.ok(JsonUtils.toJSON(m)).build();
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
index 0bfab1e..17f8595 100644
--- a/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
@@ -312,7 +312,7 @@
ss.setMeta(meta);
- String query = this.processor.preProcess(ss.toJSON(), user);
+ String query = this.processor.process(ss.toJSON(), user);
return Response.ok(query).build();
}
@@ -408,7 +408,7 @@
// todo: should be possible to add the meta part to the query serialization
try {
User user = controller.getUser(ctx.getUsername());
- jsonld = this.processor.preProcess(jsonld, user);
+ jsonld = this.processor.process(jsonld, user);
}
catch (KustvaktException e) {
throw KustvaktResponseHandler.throwit(e);
@@ -467,7 +467,7 @@
serializer.setMeta(meta.raw());
//fixme: policy rewrite!
- String query = this.processor.preProcess(serializer.toJSON(), user);
+ String query = this.processor.process(serializer.toJSON(), user);
jlog.info("the serialized query {}", query);
@@ -576,7 +576,7 @@
try {
// rewrite process
- query = this.processor.preProcess(query, user);
+ query = this.processor.process(query, user);
if (eng.equals(KustvaktConfiguration.BACKENDS.NEO4J)) {
if (raw)
@@ -668,14 +668,10 @@
query.setBaseQuery(resource.getData());
}
else if (resource instanceof Corpus) {
- query.with("corpusID=" + resource.getName());
+ query.with(Attributes.CORPUS_SIGLE+"=" + resource.getName());
}
-
String res = query.toJSON();
- jlog.info("BEFORE REWRITE " + res);
- // rewrite process
- String qstr = processor.preProcess(res, user);
- jlog.info("AFTER REWRITE " + qstr);
+ String qstr = processor.process(res, user);
return Response.ok(searchKrill.getStatistics(qstr)).build();
}
catch (KustvaktException e) {
@@ -710,7 +706,7 @@
if (tmp == null) {
KoralCollectionQueryBuilder cquery = new KoralCollectionQueryBuilder()
.setBaseQuery((String) cache.getData());
- String query = this.processor.preProcess((String) cache.getData(),
+ String query = this.processor.process((String) cache.getData(),
user);
String stats = searchKrill.getStatistics(query);
cache.setStats(JsonUtils.readSimple(stats, Map.class));
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java b/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
index 9c5a74a..d07b912 100644
--- a/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
+++ b/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
@@ -102,14 +102,14 @@
ss.setMeta(meta);
if (cq != null)
ss.setCollection(cq);
- return Response.ok(processor.preProcess(ss.toJSON(), null)).build();
+ return Response.ok(processor.process(ss.toJSON(), null)).build();
}
@POST
@Path("search")
public Response queryRaw (@QueryParam("engine") String engine, String jsonld) {
- jsonld = processor.preProcess(jsonld, null);
+ jsonld = processor.process(jsonld, null);
// todo: should be possible to add the meta part to the query serialization
jlog.info("Serialized search: {}", jsonld);
@@ -143,7 +143,7 @@
if (cq != null)
serializer.setCollection(cq);
- String query = processor.preProcess(serializer.toJSON(), null);
+ String query = processor.process(serializer.toJSON(), null);
jlog.info("the serialized query {}", query);
// This may not work with the the KoralQuery
@@ -214,7 +214,7 @@
// meta.addEntry("itemsPerResource", 1);
QuerySerializer s = new QuerySerializer().setQuery(query, ql, v)
.setMeta(meta);
- query = processor.preProcess(s.toJSON(), null);
+ query = processor.process(s.toJSON(), null);
}
String result;
try {
diff --git a/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java b/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java
new file mode 100644
index 0000000..b43adf8
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java
@@ -0,0 +1,33 @@
+package de.ids_mannheim.korap.web.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author hanl
+ * @date 20/01/2016
+ */
+public class KustvaktResponseBuilder {
+ Map<String, Object> _values;
+
+
+ public KustvaktResponseBuilder () {
+ this._values = new HashMap<>();
+ }
+
+
+ public KustvaktResponseBuilder addEntity (Object o) {
+ if (o instanceof Map && !((Map) o).isEmpty())
+ this._values.putAll((Map<? extends String, ?>) o);
+
+
+ return this;
+ }
+
+
+ @Override
+ public String toString () {
+ return "";
+ }
+
+}
diff --git a/src/main/java/de/ids_mannheim/korap/web/utils/ShutdownHook.java b/src/main/java/de/ids_mannheim/korap/web/utils/ShutdownHook.java
new file mode 100644
index 0000000..de34e38
--- /dev/null
+++ b/src/main/java/de/ids_mannheim/korap/web/utils/ShutdownHook.java
@@ -0,0 +1,29 @@
+package de.ids_mannheim.korap.web.utils;
+
+/**
+ * @author hanl
+ * @date 18/02/2014
+ */
+public class ShutdownHook extends Thread {
+
+ @Override
+ public void run () {
+ // Properties config = ExtensionBeans.getInstance().getConfiguration()
+ // .getMailProperties();
+
+ // Email e = new SimpleEmail();
+ // try {
+ // e.setHostName(config.getProperty("mail.host"));
+ // e.setSmtpPort(587);
+ // e.setSubject("KorAP Rest service shutdown Notification");
+ // e.setFrom(config.getProperty("mail.from"));
+ // e.addTo("hanl@ids-mannheim.de");
+ // e.setMsg("The KorAP - REST application shut down unexpectedly!!");
+ // e.send();
+ // } catch (EmailException e1) {
+ // e1.printStackTrace();
+ // }
+
+ }
+
+}
diff --git a/src/main/resources/db/mysql/V1.3__triggers.sql b/src/main/resources/db/mysql/V1.3__triggers.sql
new file mode 100644
index 0000000..687a10a
--- /dev/null
+++ b/src/main/resources/db/mysql/V1.3__triggers.sql
@@ -0,0 +1,15 @@
+-- indices
+DELIMITER $$
+create trigger delete_policy after delete on resource_store
+for each row begin
+ delete from policy_store where target_id=OLD.id;
+end; $$
+
+CREATE TRIGGER tree_entry_insert AFTER INSERT ON resource_store FOR EACH ROW BEGIN
+ INSERT INTO resource_tree (parent_id, child_id, depth, name_path)
+ VALUES (NEW.id, NEW.id, 0, NEW.name);
+ INSERT INTO resource_tree (parent_id, child_id, depth, name_path)
+ SELECT parent_id, NEW.id, depth + 1, concat(name_path,"/",NEW.name) FROM resource_tree WHERE child_id = NEW.parent_id;
+END; $$
+
+DELIMITER ;
\ No newline at end of file
diff --git a/src/main/resources/db/mysql/V1.4__indices.sql b/src/main/resources/db/mysql/V1.4__indices.sql
new file mode 100644
index 0000000..32a0211
--- /dev/null
+++ b/src/main/resources/db/mysql/V1.4__indices.sql
@@ -0,0 +1,5 @@
+-- todo: are this automatically adapted when refactoring?
+CREATE INDEX group_index ON group_users(user_id, group_id);
+CREATE INDEX policy_index ON group_ref(policy_id);
+CREATE UNIQUE INDEX resource_tree_index ON resource_tree (parent_id, depth, child_id);
+CREATE UNIQUE INDEX param_unique ON param_store (p_key, p_value);
diff --git a/src/main/resources/index-goe-lucene5/_0.cfe b/src/main/resources/index-goe-lucene5/_0.cfe
new file mode 100644
index 0000000..72246bc
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_0.cfe
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_0.cfs b/src/main/resources/index-goe-lucene5/_0.cfs
new file mode 100644
index 0000000..d15185a
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_0.cfs
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_0.si b/src/main/resources/index-goe-lucene5/_0.si
new file mode 100644
index 0000000..d66ea34
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_0.si
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_1.cfe b/src/main/resources/index-goe-lucene5/_1.cfe
new file mode 100644
index 0000000..221e372
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_1.cfe
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_1.cfs b/src/main/resources/index-goe-lucene5/_1.cfs
new file mode 100644
index 0000000..6b998a4
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_1.cfs
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_1.si b/src/main/resources/index-goe-lucene5/_1.si
new file mode 100644
index 0000000..18b647a
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_1.si
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_2.cfe b/src/main/resources/index-goe-lucene5/_2.cfe
new file mode 100644
index 0000000..0b8386b
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_2.cfe
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_2.cfs b/src/main/resources/index-goe-lucene5/_2.cfs
new file mode 100644
index 0000000..f9828fd
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_2.cfs
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_2.si b/src/main/resources/index-goe-lucene5/_2.si
new file mode 100644
index 0000000..ddcd167
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_2.si
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_3.cfe b/src/main/resources/index-goe-lucene5/_3.cfe
new file mode 100644
index 0000000..2eaa97b
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_3.cfe
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_3.cfs b/src/main/resources/index-goe-lucene5/_3.cfs
new file mode 100644
index 0000000..f2ec38e
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_3.cfs
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_3.si b/src/main/resources/index-goe-lucene5/_3.si
new file mode 100644
index 0000000..c1fbcdf
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_3.si
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_4.cfe b/src/main/resources/index-goe-lucene5/_4.cfe
new file mode 100644
index 0000000..34cda7d
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_4.cfe
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_4.cfs b/src/main/resources/index-goe-lucene5/_4.cfs
new file mode 100644
index 0000000..224beae
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_4.cfs
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/_4.si b/src/main/resources/index-goe-lucene5/_4.si
new file mode 100644
index 0000000..84a3366
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/_4.si
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/segments_1 b/src/main/resources/index-goe-lucene5/segments_1
new file mode 100644
index 0000000..1cb809a
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/segments_1
Binary files differ
diff --git a/src/main/resources/index-goe-lucene5/write.lock b/src/main/resources/index-goe-lucene5/write.lock
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/main/resources/index-goe-lucene5/write.lock
diff --git a/src/main/resources/index-kustvakt-example.zip b/src/main/resources/index-kustvakt-example.zip
new file mode 100644
index 0000000..33c4b5c
--- /dev/null
+++ b/src/main/resources/index-kustvakt-example.zip
Binary files differ
diff --git a/src/main/resources/kustvakt.info b/src/main/resources/kustvakt.info
new file mode 100644
index 0000000..32b65d1
--- /dev/null
+++ b/src/main/resources/kustvakt.info
@@ -0,0 +1,2 @@
+kustvakt.version=${project.version}
+kustvakt.name=${project.name}
diff --git a/src/test/java/DemoUserTest.java b/src/test/java/DemoUserTest.java
new file mode 100644
index 0000000..1387ead
--- /dev/null
+++ b/src/test/java/DemoUserTest.java
@@ -0,0 +1,65 @@
+import com.sun.jersey.api.client.ClientResponse;
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.web.service.FastJerseyTest;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 04/02/2016
+ */
+public class DemoUserTest extends FastJerseyTest {
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().setupAccount();
+ BeansFactory.setKustvaktContext(helper().getContext());
+ }
+
+
+ @BeforeClass
+ public static void setup () throws Exception {
+ FastJerseyTest.setPackages("de.ids_mannheim.korap.web.service.full",
+ "de.ids_mannheim.korap.web.filter",
+ "de.ids_mannheim.korap.web.utils");
+ }
+
+
+ @Test
+ public void testDemoCollectionGet () {
+ // ClientResponse response = resource().path(getVersion())
+ // .path("collection").path("i");
+ }
+
+
+ @Test
+ public void testDemoUserInfoGet () {
+
+ }
+
+
+ @Test
+ public void testDemoUserDetailsGet () {
+
+ }
+
+
+ @Test
+ public void testDemoUserSettingsGet () {
+
+ }
+
+
+ @Test
+ public void testSearch () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[base=Wort]")
+ .queryParam("ql", "poliqarp").get(ClientResponse.class);
+
+ System.out.println("_____________________________");
+ System.out.println(response);
+ System.out.println("entity " + response.getEntity(String.class));
+ }
+
+}
diff --git a/src/test/java/JerseyTest1.java b/src/test/java/JerseyTest1.java
new file mode 100644
index 0000000..dc0ca87
--- /dev/null
+++ b/src/test/java/JerseyTest1.java
@@ -0,0 +1,48 @@
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.test.framework.JerseyTest;
+import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
+import com.sun.jersey.test.framework.spi.container.grizzly.web.GrizzlyWebTestContainerFactory;
+import de.ids_mannheim.korap.config.BeansFactory;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 29/07/2015
+ */
+@Deprecated
+public class JerseyTest1 extends JerseyTest {
+
+ public JerseyTest1 () {
+ super("de.ids_mannheim.korap.web.service",
+ "de.ids_mannheim.korap.web.utils");
+ }
+
+
+ @BeforeClass
+ public static void setup () {
+ BeansFactory.loadClasspathContext();
+ }
+
+
+ @AfterClass
+ public static void close () {
+ BeansFactory.closeApplication();
+ }
+
+
+ @Override
+ protected TestContainerFactory getTestContainerFactory () {
+ return new GrizzlyWebTestContainerFactory();
+ }
+
+
+ @Test
+ public void testFieldsInSearch () {
+ ClientResponse response = resource().path("v0.1/search")
+ .queryParam("q", "[base=Wort]").queryParam("ql", "poliqarp")
+ .get(ClientResponse.class);
+ System.out.println("response " + response);
+ }
+}
diff --git a/src/test/java/KoralNodeTest.java b/src/test/java/KoralNodeTest.java
new file mode 100644
index 0000000..d8f5ab1
--- /dev/null
+++ b/src/test/java/KoralNodeTest.java
@@ -0,0 +1,48 @@
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import de.ids_mannheim.korap.resource.rewrite.KoralNode;
+import de.ids_mannheim.korap.utils.JsonUtils;
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 21/10/2015
+ */
+public class KoralNodeTest {
+
+ // todo: 21.10.15 --> e.g. injection does not tell you if an entire node was injected, or just a value!
+ @Test
+ public void addToNode () {
+ ObjectNode node = JsonUtils.createObjectNode();
+ KoralNode knode = KoralNode.wrapNode(node);
+ knode.put("value_1", "setting_1");
+
+ System.out.println(knode.rawNode().toString());
+ }
+
+
+ @Test
+ public void removeFromNode () {
+ ObjectNode node = JsonUtils.createObjectNode();
+ node.put("value_1", "setting_1");
+ KoralNode knode = KoralNode.wrapNode(node);
+ knode.remove("value_1");
+ System.out.println(knode.rawNode().toString());
+ }
+
+
+ @Test
+ public void replaceObject () {
+ ObjectNode node = JsonUtils.createObjectNode();
+ node.put("value_1", "setting_1");
+ KoralNode knode = KoralNode.wrapNode(node);
+ knode.replace("value_1", "settings_2");
+ System.out.println(knode.rawNode().toString());
+ }
+
+
+ // todo: 21.10.15 --> if a node is injected, that node must contain a "rewrites" reference?!
+ @Test
+ public void addNodeToKoral () {
+
+ }
+}
diff --git a/src/test/java/LocalQueryTest.java b/src/test/java/LocalQueryTest.java
new file mode 100644
index 0000000..0f9d007
--- /dev/null
+++ b/src/test/java/LocalQueryTest.java
@@ -0,0 +1,79 @@
+import de.ids_mannheim.korap.KrillCollection;
+import de.ids_mannheim.korap.config.BeanConfigTest;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.query.serialize.CollectionQueryProcessor;
+import de.ids_mannheim.korap.utils.KoralCollectionQueryBuilder;
+import de.ids_mannheim.korap.utils.JsonUtils;
+import de.ids_mannheim.korap.web.SearchKrill;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.IOException;
+
+/**
+ * @author hanl
+ * @date 14/01/2016
+ */
+public class LocalQueryTest extends BeanConfigTest {
+
+ private static String index;
+ private static String qstring;
+
+
+ @BeforeClass
+ public static void setup () throws Exception {
+ qstring = "creationDate since 1786 & creationDate until 1788";
+ // qstring = "creationDate since 1765 & creationDate until 1768";
+ // qstring = "textType = Aphorismus";
+ // qstring = "title ~ \"Werther\"";
+ }
+
+
+ @AfterClass
+ public static void drop () {}
+
+
+ @Test
+ public void testQuery () {
+ SearchKrill krill = new SearchKrill(index);
+ KoralCollectionQueryBuilder coll = new KoralCollectionQueryBuilder();
+ coll.with(qstring);
+ String stats = krill.getStatistics(coll.toJSON());
+ assert stats != null && !stats.isEmpty() && !stats.equals("null");
+ }
+
+
+ @Test
+ public void testCollQuery () throws IOException {
+ CollectionQueryProcessor processor = new CollectionQueryProcessor();
+ processor.process(qstring);
+
+ String s = JsonUtils.toJSON(processor.getRequestMap());
+ KrillCollection c = new KrillCollection(s);
+ c.setIndex(new SearchKrill(index).getIndex());
+ long docs = c.numberOf("documents");
+ assert docs > 0 && docs < 15;
+ }
+
+
+ @Test
+ public void testCollQuery2 () throws IOException {
+ String query = "{\"@context\":\"http://korap.ids-mannheim.de/ns/koral/0.3/context.jsonld\",\"errors\":[],\"warnings\":[],\"messages\":[],\"collection\":{\"@type\":\"koral:docGroup\",\"operation\":\"operation:and\",\"operands\":[{\"@type\":\"koral:doc\",\"key\":\"creationDate\",\"type\":\"type:date\",\"value\":\"1786\",\"match\":\"match:geq\"},{\"@type\":\"koral:doc\",\"key\":\"creationDate\",\"type\":\"type:date\",\"value\":\"1788\",\"match\":\"match:leq\"}]},\"query\":{},\"meta\":{}}";
+ KrillCollection c = new KrillCollection(query);
+ c.setIndex(new SearchKrill(index).getIndex());
+ long sent = c.numberOf("base/sentences");
+ long docs = c.numberOf("documents");
+ }
+
+
+ @Test
+ public void testQueryHash () {}
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().runBootInterfaces();
+ index = helper().getContext().getConfiguration().getIndexDir();
+ }
+}
diff --git a/src/test/java/MetaQueryBuilderTest.java b/src/test/java/MetaQueryBuilderTest.java
new file mode 100644
index 0000000..4bdbedc
--- /dev/null
+++ b/src/test/java/MetaQueryBuilderTest.java
@@ -0,0 +1,30 @@
+import de.ids_mannheim.korap.config.QueryBuilderUtil;
+import de.ids_mannheim.korap.query.serialize.MetaQueryBuilder;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Created by hanl on 17.04.16.
+ */
+public class MetaQueryBuilderTest {
+
+
+
+ @Test
+ public void testSpanContext () {
+ System.out.println("____________________-");
+ MetaQueryBuilder m = QueryBuilderUtil.defaultMetaBuilder(0, 1, 5,
+ "sentence", false);
+ Map map = m.raw();
+
+ assertEquals("sentence", map.get("context"));
+ assertEquals(1, map.get("startPage"));
+ assertEquals(0, map.get("startIndex"));
+ assertEquals(false, map.get("cufOff"));
+
+ }
+}
diff --git a/src/test/java/PublicAPITest.java b/src/test/java/PublicAPITest.java
new file mode 100644
index 0000000..1bc282b
--- /dev/null
+++ b/src/test/java/PublicAPITest.java
@@ -0,0 +1,42 @@
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.web.service.FastJerseyTest;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Created by hanl on 17.04.16.
+ */
+public class PublicAPITest extends FastJerseyTest {
+
+
+ @BeforeClass
+ public static void setup () {
+ FastJerseyTest.setPackages("de.ids_mannheim.korap.web.service.light",
+ "de.ids_mannheim.korap.web.filter",
+ "de.ids_mannheim.korap.web.utils");
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {}
+
+
+ @Test
+ public void testContextSpanSent () {
+
+ }
+
+
+ @Test
+ public void testContextSpanPara () {
+
+ }
+
+
+ @Test
+ public void testSimpleSearch () {
+
+ }
+
+
+}
diff --git a/src/test/java/ScopesTest.java b/src/test/java/ScopesTest.java
new file mode 100644
index 0000000..af84402
--- /dev/null
+++ b/src/test/java/ScopesTest.java
@@ -0,0 +1,19 @@
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 20/01/2016
+ */
+public class ScopesTest {
+
+ @Test
+ public void testScopes () {
+
+ }
+
+
+ @Test
+ public void testOpenIDScopes () {
+
+ }
+}
diff --git a/src/test/java/SerializationTest.java b/src/test/java/SerializationTest.java
new file mode 100644
index 0000000..334982a
--- /dev/null
+++ b/src/test/java/SerializationTest.java
@@ -0,0 +1,21 @@
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 21/01/2016
+ */
+public class SerializationTest {
+
+ @Test
+ public void testSettingsObject () {
+ String t = "poliqarp_test";
+
+ // UserSettings s = new UserSettings();
+ // Map map = s.toObjectMap();
+ // map.put(Attributes.QUERY_LANGUAGE, t);
+ // s.updateObjectSettings(map);
+ //
+ // assert s.getQueryLanguage().equals(t);
+
+ }
+}
diff --git a/src/test/java/ServiceSuite.java b/src/test/java/ServiceSuite.java
new file mode 100644
index 0000000..f13b776
--- /dev/null
+++ b/src/test/java/ServiceSuite.java
@@ -0,0 +1,11 @@
+import de.ids_mannheim.korap.config.ConfigTest;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * @author hanl
+ * @date 29/02/2016
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({ ConfigTest.class })
+public class ServiceSuite {}
diff --git a/src/test/java/TestNullableSqls.java b/src/test/java/TestNullableSqls.java
new file mode 100644
index 0000000..a220233
--- /dev/null
+++ b/src/test/java/TestNullableSqls.java
@@ -0,0 +1,5 @@
+/**
+ * @author hanl
+ * @date 30/01/2016
+ */
+public class TestNullableSqls {}
diff --git a/src/test/java/TestUtil.java b/src/test/java/TestUtil.java
new file mode 100644
index 0000000..1fb3ce7
--- /dev/null
+++ b/src/test/java/TestUtil.java
@@ -0,0 +1,62 @@
+import de.ids_mannheim.korap.config.Attributes;
+import de.ids_mannheim.korap.utils.SqlBuilder;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 26/11/2015
+ */
+public class TestUtil {
+
+ @Test
+ public void testSqlBuilderSELECT () {
+ SqlBuilder b = new SqlBuilder("users");
+ b.select(Attributes.USERNAME, Attributes.PASSWORD).where(
+ Attributes.USERNAME + "=?");
+ Assert.assertEquals("query does not match",
+ "SELECT username, password FROM users WHERE username=?;",
+ b.toString());
+ }
+
+
+ @Test
+ public void testSqlBuilderINSERT () {
+ SqlBuilder b = new SqlBuilder("users");
+ b.insert(Attributes.USERNAME, Attributes.PASSWORD).params("user",
+ "pass");
+ Assert.assertEquals("query does not match",
+ "INSERT INTO users (username, password) VALUES (user, pass);",
+ b.toString());
+ }
+
+
+ @Test
+ public void testSqlBuilderINSERTExcludeWhere () {
+ SqlBuilder b = new SqlBuilder("users");
+ b.insert(Attributes.USERNAME, Attributes.PASSWORD)
+ .params("user", "pass").where("some=?");
+ Assert.assertEquals("query does not match",
+ "INSERT INTO users (username, password) VALUES (user, pass);",
+ b.toString());
+ }
+
+
+ @Test
+ public void testSqlBuilderDELETE () {
+ SqlBuilder b = new SqlBuilder("users");
+ b.delete().where(Attributes.PERSISTENT_ID + "=?");
+ Assert.assertEquals("query does not match",
+ "DELETE FROM users WHERE persistent_id=?;", b.toString());
+ }
+
+
+ @Test
+ public void testSqlBuilderUPDATE () {
+ SqlBuilder b = new SqlBuilder("users");
+ b.update(Attributes.USERNAME, Attributes.PASSWORD).params("user",
+ "pass");
+ Assert.assertEquals("query does not match",
+ "UPDATE users SET username=user, password=pass;", b.toString());
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java b/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java
new file mode 100644
index 0000000..266b784
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java
@@ -0,0 +1,96 @@
+package de.ids_mannheim.korap.config;
+
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import net.jcip.annotations.NotThreadSafe;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.model.InitializationError;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.PostConstruct;
+
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * @author hanl
+ * @date 09/03/2016
+ */
+@NotThreadSafe
+@RunWith(BeanConfigTest.SpringExtendedSetupListener.class)
+@ContextConfiguration(classes = TestHelper.AppTestConfig.class)
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
+public abstract class BeanConfigTest {
+
+ @Autowired
+ private ApplicationContext context;
+
+
+ public void init () throws Exception {
+ assertNotNull("Application context must not be null!", this.context);
+ System.out.println("running one-time before init for class "
+ + this.getClass().getSimpleName() + " ...");
+ initMethod();
+ BeansFactory.setKustvaktContext(helper().getContext());
+ }
+
+
+ public void close () {
+ BeansFactory.closeApplication();
+ }
+
+
+ public abstract void initMethod () throws KustvaktException;
+
+
+ protected TestHelper helper () {
+ try {
+ return TestHelper.newInstance(this.context);
+ }
+ catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ public static class SpringExtendedSetupListener extends
+ SpringJUnit4ClassRunner {
+
+ private BeanConfigTest instanceSetupListener;
+
+
+ public SpringExtendedSetupListener (Class<?> clazz)
+ throws InitializationError {
+ super(clazz);
+ }
+
+
+ @Override
+ protected Object createTest () throws Exception {
+ Object test = super.createTest();
+ // Note that JUnit4 will call this createTest() multiple times for each
+ // test method, so we need to ensure to call "beforeClassSetup" only once.
+ if (test instanceof BeanConfigTest && instanceSetupListener == null) {
+ instanceSetupListener = (BeanConfigTest) test;
+ instanceSetupListener.init();
+ }
+ return test;
+ }
+
+
+ @Override
+ public void run (RunNotifier notifier) {
+ super.run(notifier);
+ if (instanceSetupListener != null)
+ instanceSetupListener.close();
+ }
+
+
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/config/EsapiTest.java b/src/test/java/de/ids_mannheim/korap/config/EsapiTest.java
new file mode 100644
index 0000000..5d26cd7
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/config/EsapiTest.java
@@ -0,0 +1,54 @@
+package de.ids_mannheim.korap.config;
+
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.interfaces.EncryptionIface;
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author hanl
+ * @date 08/01/2016
+ */
+public class EsapiTest extends BeanConfigTest {
+
+ @Test
+ public void testInputPassword () throws KustvaktException {
+ String pass = TestHelper.getUserCredentials()[1];
+ EncryptionIface cr = helper().getContext().getEncryption();
+ String spass = cr.validateEntry(pass, Attributes.PASSWORD);
+ assertNotNull(spass);
+ assertFalse(spass.isEmpty());
+ }
+
+
+ @Test
+ public void testMapValidation () throws KustvaktException {
+ int exp_size = KustvaktConfiguration.KUSTVAKT_USER.size();
+ Map map = helper().getContext().getEncryption()
+ .validateMap(KustvaktConfiguration.KUSTVAKT_USER);
+ assertEquals(exp_size, map.size());
+ }
+
+
+ @Test
+ public void testUsernameValidation () throws KustvaktException {
+ String sus = helper()
+ .getContext()
+ .getEncryption()
+ .validateEntry(
+ (String) KustvaktConfiguration.KUSTVAKT_USER
+ .get(Attributes.USERNAME),
+ Attributes.USERNAME);
+ assertNotNull(sus);
+ assertFalse(sus.isEmpty());
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/config/KustvaktResourceTest.java b/src/test/java/de/ids_mannheim/korap/config/KustvaktResourceTest.java
new file mode 100644
index 0000000..4222f88
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/config/KustvaktResourceTest.java
@@ -0,0 +1,31 @@
+package de.ids_mannheim.korap.config;
+
+import de.ids_mannheim.korap.resources.KustvaktResource;
+import de.ids_mannheim.korap.resources.VirtualCollection;
+
+/**
+ * @author hanl
+ * @date 11/02/2016
+ */
+public class KustvaktResourceTest {
+
+
+ public void testIDCreation () {
+ KustvaktResource resource = new VirtualCollection(1);
+ resource.addField("field_1", "data");
+
+ }
+
+
+ public void testNullableData () {
+
+ }
+
+
+ public void testWrongDataType () {
+
+ }
+
+
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/config/LoaderTest.java b/src/test/java/de/ids_mannheim/korap/config/LoaderTest.java
new file mode 100644
index 0000000..ce4de02
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/config/LoaderTest.java
@@ -0,0 +1,89 @@
+package de.ids_mannheim.korap.config;
+
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.web.service.BootableBeanInterface;
+import de.ids_mannheim.korap.web.service.CollectionLoader;
+import de.ids_mannheim.korap.web.service.PolicyLoader;
+import de.ids_mannheim.korap.web.service.UserLoader;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+/**
+ * @author hanl
+ * @date 12/02/2016
+ */
+public class LoaderTest extends BeanConfigTest {
+
+ @Test
+ @Ignore
+ public void testConfigOrder () {
+ System.out.println("done ...");
+
+ List s = new ArrayList<>();
+ s.add("new");
+ s.add("new2");
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {}
+
+
+ @Test
+ public void runBootInterfaces () {
+ Set<Class<? extends BootableBeanInterface>> set = new HashSet<>();
+ set.add(CollectionLoader.class);
+ set.add(PolicyLoader.class);
+ set.add(UserLoader.class);
+
+ List<BootableBeanInterface> list = new ArrayList<>(set.size());
+ for (Class cl : set) {
+ BootableBeanInterface iface;
+ try {
+ iface = (BootableBeanInterface) cl.newInstance();
+ list.add(iface);
+ }
+ catch (InstantiationException | IllegalAccessException e) {
+ // do nothing
+ }
+ }
+ assertEquals(set.size(), list.size());
+ List tracer = new ArrayList();
+ System.out.println("Found boot loading interfaces: " + list);
+ while (!set.isEmpty()) {
+ out_loop: for (BootableBeanInterface iface : new ArrayList<>(list)) {
+ try {
+ System.out.println("Running boot instructions from class "
+ + iface.getClass().getSimpleName());
+ for (Class cl : iface.getDependencies()) {
+ if (set.contains(cl))
+ continue out_loop;
+ }
+ set.remove(iface.getClass());
+ list.remove(iface);
+ iface.load(helper().getContext());
+ tracer.add(iface.getClass());
+ }
+ catch (KustvaktException e) {
+ // don't do anything!
+ System.out.println("An error occurred in class "
+ + iface.getClass().getSimpleName() + "!\n" + e);
+ throw new RuntimeException(
+ "Boot loading interface failed ...");
+ }
+ }
+ }
+ assertEquals(0, tracer.indexOf(UserLoader.class));
+ assertNotEquals(0, tracer.indexOf(CollectionLoader.class));
+ assertNotEquals(0, tracer.indexOf(PolicyLoader.class));
+ }
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java b/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
index 4e4aa3f..fbf88c0 100644
--- a/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
+++ b/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
@@ -6,11 +6,9 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.query.serialize.QuerySerializer;
import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.KustvaktResource;
import de.ids_mannheim.korap.security.ac.ResourceFinder;
import de.ids_mannheim.korap.user.User;
import de.ids_mannheim.korap.utils.JsonUtils;
-import org.junit.Assert;
import org.junit.Test;
import java.util.Set;
@@ -58,14 +56,19 @@
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("textClass=politik & corpusID=WPD");
+ s.setCollection("textClass=politik & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(1, node.at("/collection/operands").size());
}
+ @Test
+ public void testCollectionNodeDeletionNotification() {
+
+ }
+
@Test
public void testCollectionNodeRemoveAllCorpusIdNoErrors () {
@@ -74,9 +77,9 @@
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("corpusID=BRZ13 & corpusID=WPD");
+ s.setCollection("corpusSigle=BRZ13 & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
// System.out.println("RESULTING REWR NODE " + node);
assertNotNull(node);
@@ -91,9 +94,9 @@
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("(corpusID=BRZ13 & textClass=Wissenschaft) & corpusID=WPD");
+ s.setCollection("(corpusSigle=BRZ13 & textClass=Wissenschaft) & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
@@ -113,11 +116,13 @@
handler.add(CollectionCleanupFilter.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("(corpusID=BRZ13 & corpusID=WPD) & textClass=Wissenschaft & textClass=Sport");
+ s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft & textClass=Sport");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
+
assertNotNull(node);
assertEquals("koral:docGroup", node.at("/collection/@type").asText());
assertEquals(2, node.at("/collection/operands").size());
@@ -137,9 +142,9 @@
handler.add(CollectionCleanupFilter.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("(corpusID=BRZ13 & textClass=Wissenschaft)");
+ s.setCollection("(corpusSigle=BRZ13 & textClass=Wissenschaft)");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals("koral:doc", node.at("/collection/@type").asText());
@@ -154,9 +159,9 @@
handler.add(CollectionCleanupFilter.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("(corpusID=BRZ13 & corpusID=WPD) & textClass=Wissenschaft");
+ s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(result,
+ JsonNode node = JsonUtils.readTree(handler.process(result,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
@@ -173,11 +178,11 @@
handler.add(CollectionCleanupFilter.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
- s.setCollection("(docID=random & textClass=Wissenschaft) & corpusID=WPD");
+ s.setCollection("(docID=random & textClass=Wissenschaft) & corpusSigle=WPD");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(org,
+ JsonNode node = JsonUtils.readTree(handler.process(org,
User.UserFactory.getUser("test_user")));
-
+ System.out.println(node);
assertNotNull(node);
assertEquals("koral:docGroup", node.at("/collection/@type").asText());
assertEquals(2, node.at("/collection/operands").size());
@@ -195,10 +200,12 @@
QuerySerializer s = new QuerySerializer();
s.setQuery(simple_add_query, "poliqarp");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(org,
+ JsonNode node = JsonUtils.readTree(handler.process(org,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
- System.out.println("EMPTY " + node);
+ assertEquals("corpusSigle", node.at("/collection/operands/0/key").asText());
+ assertEquals("corpusSigle", node.at("/collection/operands/1/key").asText());
+ assertEquals("koral:rewrite", node.at("/collection/rewrites/@type").asText());
}
@@ -214,11 +221,14 @@
s.setQuery(simple_add_query, "poliqarp");
s.setCollection("(docSigle=WPD_AAA & textClass=wissenschaft)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.preProcess(org,
+ JsonNode node = JsonUtils.readTree(handler.process(org,
User.UserFactory.getUser("test_user")));
assertNotNull(node);
- System.out.println("NON EMPTY " + node);
- Set<Corpus> resourceSet = ResourceFinder.searchPublic(Corpus.class);
+ assertEquals(2, node.at("/collection/operands").size());
+ assertEquals("corpusSigle", node.at("/collection/operands/1/operands/0/key").asText());
+ assertEquals("corpusSigle", node.at("/collection/operands/1/operands/1/key").asText());
+ assertEquals("koral:rewrite", node.at("/collection/rewrites/@type").asText());
+
}
catch (Exception e) {
e.printStackTrace();
diff --git a/src/test/java/de/ids_mannheim/korap/resource/rewrite/FoundryRewriteTest.java b/src/test/java/de/ids_mannheim/korap/resource/rewrite/FoundryRewriteTest.java
index 032b9f7..92ef92c 100644
--- a/src/test/java/de/ids_mannheim/korap/resource/rewrite/FoundryRewriteTest.java
+++ b/src/test/java/de/ids_mannheim/korap/resource/rewrite/FoundryRewriteTest.java
@@ -21,7 +21,7 @@
* @author hanl
* @date 18/06/2015
*/
-//todo: refactor and structure tests
+//todo: check position and information of rewrites!
public class FoundryRewriteTest extends BeanConfigTest {
private static String simple_add_query = "[pos=ADJA]";
@@ -63,9 +63,10 @@
processor.add(FoundryInject.class);
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
- String result = processor.preProcess(s.toJSON(), null);
+ String result = processor.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(result);
+ System.out.println("REWRITTEN "+ node);
assertNotNull(node);
assertFalse(node.at("/query/wrap/foundry").isMissingNode());
assertEquals(c.getDefault_lemma(), node.at("/query/wrap/foundry")
@@ -88,7 +89,7 @@
handler.insertBeans(helper().getContext());
s.setQuery("[pos=ADJA]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String result = handler.preProcess(s.toJSON(), null);
+ String result = handler.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
@@ -113,7 +114,7 @@
handler.add(FoundryInject.class);
QuerySerializer s = new QuerySerializer();
s.setQuery("[pos=ADJA]", "poliqarp");
- String result = handler.preProcess(s.toJSON(), user);
+ String result = handler.process(s.toJSON(), user);
JsonNode node = JsonUtils.readTree(result);
UserDataDbIface dao = BeansFactory.getTypeFactory().getTypedBean(
@@ -143,7 +144,7 @@
handler.add(FoundryInject.class);
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
- String result = handler.preProcess(s.toJSON(), user);
+ String result = handler.process(s.toJSON(), user);
JsonNode node = JsonUtils.readTree(result);
UserDataDbIface dao = BeansFactory.getTypeFactory().getTypedBean(
@@ -171,7 +172,7 @@
handler.insertBeans(helper().getContext());
s.setQuery("[orth=laufe/i & base!=Lauf]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String result = handler.preProcess(s.toJSON(), null);
+ String result = handler.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
@@ -190,7 +191,7 @@
handler.insertBeans(helper().getContext());
s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String result = handler.preProcess(s.toJSON(), null);
+ String result = handler.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
diff --git a/src/test/java/de/ids_mannheim/korap/resource/rewrite/IdRewriteTest.java b/src/test/java/de/ids_mannheim/korap/resource/rewrite/IdRewriteTest.java
index 2f069f1..909f9c9 100644
--- a/src/test/java/de/ids_mannheim/korap/resource/rewrite/IdRewriteTest.java
+++ b/src/test/java/de/ids_mannheim/korap/resource/rewrite/IdRewriteTest.java
@@ -25,7 +25,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery(query, "poliqarp");
- String value = handler.preProcess(s.toJSON(), null);
+ String value = handler.process(s.toJSON(), null);
JsonNode result = JsonUtils.readTree(value);
assertNotNull(result);
@@ -41,7 +41,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
- String result = handler.preProcess(s.toJSON(), null);
+ String result = handler.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
assertFalse(node.at("/query/wrap").isMissingNode());
diff --git a/src/test/java/de/ids_mannheim/korap/resource/rewrite/PostRewriteTest.java b/src/test/java/de/ids_mannheim/korap/resource/rewrite/PostRewriteTest.java
index 78db747..ef0c10a 100644
--- a/src/test/java/de/ids_mannheim/korap/resource/rewrite/PostRewriteTest.java
+++ b/src/test/java/de/ids_mannheim/korap/resource/rewrite/PostRewriteTest.java
@@ -47,7 +47,7 @@
try {
Document d = dao.findbyId("BRZ13_APR.00014", null);
assertNull(d);
- String v = ha.postProcess(RESULT, null);
+ String v = ha.process(RESULT, null);
assertEquals("results do not match", JsonUtils.readTree(RESULT),
JsonUtils.readTree(v));
}
@@ -76,7 +76,7 @@
assertEquals("Handler could not be added to rewriter instance!", true,
ha.add(DocMatchRewrite.class));
- String v = ha.postProcess(RESULT, null);
+ String v = ha.process(RESULT, null);
JsonNode node = JsonUtils.readTree(v);
diff --git a/src/test/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandlerTest.java b/src/test/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandlerTest.java
index 070e0bb..15df2a9 100644
--- a/src/test/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandlerTest.java
+++ b/src/test/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandlerTest.java
@@ -51,7 +51,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- handler.preProcess(s.toJSON(), null);
+ handler.process(s.toJSON(), null);
}
@@ -62,7 +62,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String res = handler.preProcess(s.toJSON(), null);
+ String res = handler.process(s.toJSON(), null);
assertNotNull(res);
}
@@ -74,7 +74,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String res = handler.preProcess(s.toJSON(), null);
+ String res = handler.process(s.toJSON(), null);
JsonNode node = JsonUtils.readTree(res);
assertNotNull(node);
@@ -93,7 +93,7 @@
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
assertTrue(handler.add(FoundryInject.class));
- String res = handler.preProcess(s.toJSON(), helper().getUser());
+ String res = handler.process(s.toJSON(), helper().getUser());
JsonNode node = JsonUtils.readTree(res);
assertNotNull(node);
assertEquals("tt_test",
diff --git a/src/test/java/de/ids_mannheim/korap/security/PermissionBufferTest.java b/src/test/java/de/ids_mannheim/korap/security/PermissionBufferTest.java
new file mode 100644
index 0000000..68e874a
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/PermissionBufferTest.java
@@ -0,0 +1,209 @@
+package de.ids_mannheim.korap.security;
+
+import de.ids_mannheim.korap.resources.Permissions;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author hanl
+ * @date 15/02/2016
+ */
+public class PermissionBufferTest {
+
+ @Test
+ public void testDuplicatePermission () {
+ PermissionsBuffer buffer = new PermissionsBuffer();
+ assertEquals(0, buffer.addPermission(4));
+ assertEquals(-1, buffer.addPermission(4));
+
+ // 0 means permission was successfully added, -1 means it wasn't because it's already present
+ assertEquals(0, buffer.addPermission(1));
+ assertEquals(-1, buffer.addPermission(1));
+
+ assertEquals(0, buffer.addPermission(8));
+ assertEquals(-1, buffer.addPermission(4));
+ }
+
+
+ @Test
+ public void testPermissionsAdd () {
+ PermissionsBuffer buffer = new PermissionsBuffer();
+ buffer.addPermissions(Permissions.Permission.READ);
+ assertEquals(1, buffer.getPermissions().size());
+
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer
+ .containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.ALL.toByte()));
+
+ buffer = new PermissionsBuffer();
+ buffer.addPermissions(Permissions.Permission.WRITE);
+ buffer.addPermissions(Permissions.Permission.DELETE_POLICY);
+ assertEquals(2, buffer.getPermissions().size());
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer
+ .containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.ALL.toByte()));
+ }
+
+
+ @Test
+ public void testPermissionsAddAll2 () {
+ PermissionsBuffer buffer = new PermissionsBuffer();
+ buffer.addPermissions(Permissions.Permission.ALL);
+
+ assertEquals(Permissions.Permission.values().length, buffer
+ .getPermissions().size());
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.ALL.toByte()));
+ }
+
+
+ @Test
+ public void testPermissionsAddAll () {
+ PermissionsBuffer buffer = new PermissionsBuffer();
+ buffer.addPermissions(Permissions.Permission.DELETE_POLICY);
+ buffer.addPermissions(Permissions.Permission.CREATE_POLICY);
+ buffer.addPermissions(Permissions.Permission.READ);
+ buffer.addPermissions(Permissions.Permission.MODIFY_POLICY);
+ buffer.addPermissions(Permissions.Permission.DELETE);
+ buffer.addPermissions(Permissions.Permission.READ_POLICY);
+ buffer.addPermissions(Permissions.Permission.WRITE);
+
+ assertEquals(Permissions.Permission.values().length, buffer
+ .getPermissions().size());
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.ALL.toByte()));
+
+ }
+
+
+ @Test
+ public void testPermissionsInit () {
+ PermissionsBuffer buffer = new PermissionsBuffer((short) 1);
+ assertEquals(1, buffer.getPermissions().size());
+
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertFalse(buffer
+ .containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+
+ }
+
+
+ @Test
+ public void testPermissionsStringConversion () {
+ PermissionsBuffer buffer = new PermissionsBuffer(Short.valueOf("1"));
+ assertEquals(1, buffer.getPermissions().size());
+
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertFalse(buffer
+ .containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+
+ buffer = new PermissionsBuffer(Short.valueOf("5"));
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+
+ buffer = new PermissionsBuffer(Short.valueOf("69"));
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.READ_POLICY
+ .toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.CREATE_POLICY
+ .toByte()));
+ }
+
+
+ @Test
+ public void testPermissionRemovalOne () {
+ PermissionsBuffer buffer = new PermissionsBuffer();
+ buffer.addPermissions(Permissions.Permission.READ,
+ Permissions.Permission.DELETE,
+ Permissions.Permission.MODIFY_POLICY);
+
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+
+ buffer.removePermission(Permissions.Permission.MODIFY_POLICY);
+
+ assertTrue(buffer.containsPByte(Permissions.Permission.READ.toByte()));
+ assertTrue(buffer.containsPByte(Permissions.Permission.DELETE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.WRITE.toByte()));
+ assertFalse(buffer.containsPByte(Permissions.Permission.MODIFY_POLICY
+ .toByte()));
+ }
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/PolicyBenchmarkTest.java b/src/test/java/de/ids_mannheim/korap/security/PolicyBenchmarkTest.java
new file mode 100644
index 0000000..6804770
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/PolicyBenchmarkTest.java
@@ -0,0 +1,10 @@
+package de.ids_mannheim.korap.security;
+
+/**
+ * @author hanl
+ * @date 09/02/2016
+ */
+public class PolicyBenchmarkTest {
+
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/PolicyBuilderTest.java b/src/test/java/de/ids_mannheim/korap/security/PolicyBuilderTest.java
new file mode 100644
index 0000000..eb0c3d8
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/PolicyBuilderTest.java
@@ -0,0 +1,31 @@
+package de.ids_mannheim.korap.security;
+
+import de.ids_mannheim.korap.config.BeanConfigTest;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.security.ac.PolicyBuilder;
+import org.junit.Test;
+
+/**
+ * @author hanl
+ * @date 20/11/2015
+ */
+public class PolicyBuilderTest extends BeanConfigTest {
+
+ @Test
+ public void testBuild () {
+ PolicyBuilder b = new PolicyBuilder(helper().getUser());
+
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().setupAccount();
+ }
+
+
+ @Test
+ public void testCreateForMultipleResources () {
+ //todo:
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java b/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java
new file mode 100644
index 0000000..24922e6
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java
@@ -0,0 +1,44 @@
+package de.ids_mannheim.korap.security;
+
+import de.ids_mannheim.korap.config.BeanConfigTest;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.resources.Corpus;
+import de.ids_mannheim.korap.resources.VirtualCollection;
+import de.ids_mannheim.korap.security.ac.ResourceFinder;
+import org.junit.Test;
+
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+
+/**
+ * @author hanl
+ * @date 06/02/2016
+ */
+public class ResourceFinderTest extends BeanConfigTest {
+
+ @Test
+ public void searchResources () throws KustvaktException {
+ Set<VirtualCollection> resources = ResourceFinder
+ .searchPublic(VirtualCollection.class);
+ assertFalse(resources.isEmpty());
+ assertEquals(3, resources.size());
+ }
+
+
+ @Test
+ public void searchResourcesDemo () throws KustvaktException {
+ Set<Corpus> resources = ResourceFinder.searchPublic(Corpus.class);
+ assertFalse(resources.isEmpty());
+ assertNotEquals(0, resources.size());
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().setupAccount();
+ helper().runBootInterfaces();
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java b/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java
new file mode 100644
index 0000000..99fd537
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java
@@ -0,0 +1,124 @@
+package de.ids_mannheim.korap.security;
+
+import de.ids_mannheim.korap.config.BeanConfigTest;
+import de.ids_mannheim.korap.config.ContextHolder;
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
+import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface;
+import de.ids_mannheim.korap.resources.*;
+import de.ids_mannheim.korap.security.ac.ResourceFinder;
+import de.ids_mannheim.korap.security.ac.ResourceHandler;
+import de.ids_mannheim.korap.security.ac.SecurityManager;
+import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.utils.TimeUtils;
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * @author hanl
+ * @date 20/11/2015
+ */
+// todo: run functions without data to check for nullpointers!
+public class ResourcesTest extends BeanConfigTest {
+
+ private static Corpus c1;
+
+
+ @Test
+ public void testCreate () throws KustvaktException {
+ ResourceHandler h = new ResourceHandler();
+ Corpus ncorps = new Corpus("new_wiki");
+ h.storeResources(helper().getUser(), ncorps);
+ }
+
+
+ @Test
+ public void testGet () throws KustvaktException {
+ DateTime beg = new DateTime();
+ ResourceHandler h = new ResourceHandler();
+ Corpus c = h.findbyStrId(c1.getPersistentID(), helper().getUser(),
+ Corpus.class);
+ float end = TimeUtils.floating(beg, new DateTime());
+ System.out.println("END ----------------- : " + end);
+ assertNotNull(c);
+ }
+
+
+ @Test(expected = KustvaktException.class)
+ public void testGetthrowsUnauthorizedException () throws KustvaktException {
+ DateTime beg = new DateTime();
+ ResourceHandler h = new ResourceHandler();
+ Corpus c = h.findbyStrId(c1.getPersistentID(),
+ User.UserFactory.getDemoUser(), Corpus.class);
+ float end = TimeUtils.floating(beg, new DateTime());
+ System.out.println("END ----------------- : " + end);
+ assertNotNull(c);
+ }
+
+
+ // in case of null, should not return nullpointer!
+ @Test(expected = KustvaktException.class)
+ @Ignore
+ public void testCollectionGet () throws KustvaktException {
+ //todo: do use test user!
+ User user = User.UserFactory
+ .toUser(KustvaktConfiguration.KUSTVAKT_USER);
+ EntityHandlerIface ice = helper()
+ .getBean(ContextHolder.KUSTVAKT_USERDB);
+ User test = ice.getAccount(user.getUsername());
+ assertNotNull(test);
+ Set<KustvaktResource> resources = ResourceFinder.search(user,
+ ResourceFactory.getResourceClass("collection"));
+
+ assertFalse(resources.isEmpty());
+ KustvaktResource r = (KustvaktResource) resources.toArray()[0];
+
+ assertNotNull(r);
+ ResourceHandler h = new ResourceHandler();
+ h.findbyStrId(r.getPersistentID(), user, VirtualCollection.class);
+ }
+
+
+ // securitymanager does not allow for anonymous retrieval, only resourcefinder!
+ @Test(expected = NotAuthorizedException.class)
+ public void getResource () throws KustvaktException {
+ User user = User.UserFactory.getDemoUser();
+ SecurityManager m = SecurityManager.findbyId(2, user,
+ Permissions.Permission.READ);
+ m.getResource();
+ }
+
+
+ @Test
+ public void getDemoResources () throws KustvaktException {
+ Set s = ResourceFinder.searchPublic(Corpus.class);
+ assertEquals(2, s.size());
+ s = ResourceFinder.searchPublic(Foundry.class);
+ assertEquals(1, s.size());
+ }
+
+
+ @Test
+ public void getDemoResourceFiltered () throws KustvaktException {
+ Set s = ResourceFinder.searchPublicFiltered(Corpus.class, "WPD");
+ assertEquals(1, s.size());
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().setupAccount();
+ c1 = new Corpus("WPD_test");
+ helper().runBootInterfaces();
+ helper().setupResource(c1);
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/SecurityPolicyTest.java b/src/test/java/de/ids_mannheim/korap/security/SecurityPolicyTest.java
new file mode 100644
index 0000000..0235e81
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/security/SecurityPolicyTest.java
@@ -0,0 +1,148 @@
+package de.ids_mannheim.korap.security;
+
+import de.ids_mannheim.korap.config.BeanConfigTest;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
+import de.ids_mannheim.korap.resources.Corpus;
+import de.ids_mannheim.korap.resources.Permissions;
+import org.junit.Test;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author hanl
+ * @date 12/02/2016
+ */
+public class SecurityPolicyTest extends BeanConfigTest {
+
+ @Test
+ public void testConditionUpdate () {
+ SecurityPolicy policy = new SecurityPolicy();
+ policy.addNewCondition(new PolicyCondition("test_1"));
+ policy.addNewCondition(new PolicyCondition("test_2"));
+ policy.setCreator(1);
+ policy.setTarget(new Corpus("WPD"));
+ policy.addPermission(Permissions.Permission.READ);
+
+ assertEquals(2, policy.getAdded().size());
+ policy.removeCondition(new PolicyCondition("test_1"));
+ assertEquals(1, policy.getAdded().size());
+ }
+
+
+ @Test
+ public void testConditionMapping () throws KustvaktException {
+ helper().setupResource(new Corpus("WPD_2"));
+ SecurityPolicy policy = new SecurityPolicy();
+ policy.addNewCondition(new PolicyCondition("test_1"));
+ policy.addNewCondition(new PolicyCondition("test_2"));
+ policy.setCreator(1);
+ policy.setTarget(new Corpus("WPD_2"));
+ policy.addPermission(Permissions.Permission.READ);
+
+ PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
+ dao.createPolicy(policy, helper().getUser());
+
+ List<SecurityPolicy>[] list = dao.getPolicies("WPD_2", helper()
+ .getUser(), Permissions.Permission.READ.toByte());
+ assertNotNull(list);
+ List<SecurityPolicy> policies = list[0];
+ assertNotNull(policies);
+ assertFalse(policies.isEmpty());
+ assertEquals(2, policies.size());
+ assertTrue(policies.get(0) instanceof SecurityPolicy.OwnerPolicy);
+ policy = policies.get(1);
+ assertEquals(2, policy.getConditions().size());
+ policy.removeCondition(new PolicyCondition("test_1"));
+ assertEquals(1, policy.getRemoved().size());
+ assertTrue(policy.getAdded().isEmpty());
+ }
+
+
+ @Test
+ public void testPersistingPermissionMapping () throws KustvaktException {
+ helper().setupResource(new Corpus("WPD_3"));
+ SecurityPolicy policy = new SecurityPolicy();
+ policy.addNewCondition(new PolicyCondition("test_1"));
+ policy.addNewCondition(new PolicyCondition("test_2"));
+ policy.setCreator(1);
+ policy.setTarget(new Corpus("WPD_3"));
+ policy.addPermission(Permissions.Permission.READ);
+ policy.addPermission(Permissions.Permission.WRITE);
+
+ PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
+ dao.createPolicy(policy, helper().getUser());
+
+ List<SecurityPolicy>[] list = dao.getPolicies("WPD_3", helper()
+ .getUser(), Permissions.Permission.READ.toByte());
+
+ assertNotNull(list);
+ List<SecurityPolicy> policies = list[0];
+ assertNotNull(policies);
+ assertFalse(policies.isEmpty());
+ assertEquals(2, policies.size());
+ assertTrue(policies.get(0) instanceof SecurityPolicy.OwnerPolicy);
+ policy = policies.get(1);
+
+ Set<Permissions.Permission> check = new HashSet<>();
+ check.add(Permissions.Permission.READ);
+ check.add(Permissions.Permission.WRITE);
+ assertEquals(check, policy.getPermissions());
+ }
+
+
+ @Test
+ public void testConditionRemoval () throws KustvaktException {
+ helper().setupResource(new Corpus("WPD_1"));
+ SecurityPolicy policy = new SecurityPolicy();
+ policy.addNewCondition(new PolicyCondition("test_1"));
+ policy.addNewCondition(new PolicyCondition("test_2"));
+ policy.setCreator(1);
+ policy.setTarget(new Corpus("WPD_1"));
+ policy.addPermission(Permissions.Permission.READ);
+
+ PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
+ dao.createPolicy(policy, helper().getUser());
+
+ Object[] list = dao.getPolicies("WPD_1", helper().getUser(),
+ Permissions.Permission.READ.toByte());
+ assertNotNull(list);
+ List<SecurityPolicy> policies = (List<SecurityPolicy>) list[0];
+ assertNotNull(policies);
+ assertFalse(policies.isEmpty());
+ policy = policies.get(1);
+
+ assertEquals(2, policy.getConditions().size());
+ policy.removeCondition(new PolicyCondition("test_1"));
+ assertEquals(1, policy.getRemoved().size());
+ assertTrue(policy.getAdded().isEmpty());
+
+ dao.updatePolicy(policy, helper().getUser());
+ policies = dao.getPolicies("WPD_1", helper().getUser(),
+ Permissions.Permission.READ.toByte())[0];
+ policy = policies.get(1);
+ assertEquals(1, policy.getConditions().size());
+ }
+
+
+ @Test
+ public void testPermissionConversion () {
+ SecurityPolicy policy = new SecurityPolicy();
+ policy.setPOSIX("3");
+ Set<Permissions.Permission> perms = new HashSet<>();
+ perms.add(Permissions.Permission.READ);
+ perms.add(Permissions.Permission.WRITE);
+ assertEquals(perms, policy.getPermissions());
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {
+ helper().runBootInterfaces();
+ helper().setupAccount();
+ }
+}
diff --git a/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java b/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
index 2c0d83e..35d06af 100644
--- a/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
+++ b/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
@@ -96,9 +96,7 @@
.getAuthenticationManager();
User user = new KorAPUser(10, "random");
-
- Userdata data = manager.getUserData(user, UserDetails.class);
- assertNotNull(data);
+ manager.getUserData(user, UserDetails.class);
}
@@ -109,9 +107,7 @@
.getAuthenticationManager();
User user = new KorAPUser(10, "random");
-
- Userdata data = manager.getUserData(user, UserSettings.class);
- assertNotNull(data);
+ manager.getUserData(user, UserSettings.class);
}
diff --git a/src/test/java/de/ids_mannheim/korap/suites/LoaderTestSuite.java b/src/test/java/de/ids_mannheim/korap/suites/LoaderTestSuite.java
new file mode 100644
index 0000000..9f3a05e
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/suites/LoaderTestSuite.java
@@ -0,0 +1,15 @@
+package de.ids_mannheim.korap.suites;
+
+/**
+ * @author hanl
+ * @date 09/03/2016
+ */
+
+import de.ids_mannheim.korap.config.CollectionLoaderTest;
+import de.ids_mannheim.korap.config.PolicyLoaderTest;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+@RunWith(Suite.class)
+@Suite.SuiteClasses({ PolicyLoaderTest.class, CollectionLoaderTest.class })
+public class LoaderTestSuite {}
diff --git a/src/test/java/de/ids_mannheim/korap/suites/SecurityEntityTestSuite.java b/src/test/java/de/ids_mannheim/korap/suites/SecurityEntityTestSuite.java
new file mode 100644
index 0000000..c3cceda
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/suites/SecurityEntityTestSuite.java
@@ -0,0 +1,17 @@
+package de.ids_mannheim.korap.suites;
+
+import de.ids_mannheim.korap.security.PermissionBufferTest;
+import de.ids_mannheim.korap.security.PolicyBuilderTest;
+import de.ids_mannheim.korap.security.SecurityPolicyTest;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * @author hanl
+ * @date 09/03/2016
+ */
+// test object serialization and I/O buffers
+@RunWith(Suite.class)
+@Suite.SuiteClasses({ PermissionBufferTest.class, PolicyBuilderTest.class,
+ SecurityPolicyTest.class })
+public class SecurityEntityTestSuite {}
diff --git a/src/test/java/de/ids_mannheim/korap/suites/SecurityTestSuite.java b/src/test/java/de/ids_mannheim/korap/suites/SecurityTestSuite.java
new file mode 100644
index 0000000..45116b5
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/suites/SecurityTestSuite.java
@@ -0,0 +1,12 @@
+package de.ids_mannheim.korap.suites;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * @author hanl
+ * @date 09/03/2016
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({})
+public class SecurityTestSuite {}
diff --git a/src/test/java/de/ids_mannheim/korap/suites/ServiceTestSuite.java b/src/test/java/de/ids_mannheim/korap/suites/ServiceTestSuite.java
new file mode 100644
index 0000000..e83e232
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/suites/ServiceTestSuite.java
@@ -0,0 +1,15 @@
+package de.ids_mannheim.korap.suites;
+
+/**
+ * @author hanl
+ * @date 09/03/2016
+ */
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+@RunWith(Suite.class)
+@Suite.SuiteClasses({})
+public class ServiceTestSuite {
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/user/UserFactoryTest.java b/src/test/java/de/ids_mannheim/korap/user/UserFactoryTest.java
new file mode 100644
index 0000000..51d03cb
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/user/UserFactoryTest.java
@@ -0,0 +1,7 @@
+package de.ids_mannheim.korap.user;
+
+/**
+ * @author hanl
+ * @date 04/02/2016
+ */
+public class UserFactoryTest {}
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/KustvaktCoreRestTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/KustvaktCoreRestTest.java
index ec25c17..72a4a01 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/KustvaktCoreRestTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/KustvaktCoreRestTest.java
@@ -72,7 +72,7 @@
// @Test
public void testGetStatsThrowsNoException () {
CollectionQueryProcessor pr = new CollectionQueryProcessor();
- pr.process("corpusID=WPD & textClass=Sport");
+ pr.process("corpusSigle=WPD & textClass=Sport");
Map map = new LinkedHashMap();
map.put("collection", pr.getRequestMap());
ClientResponse response = resource().path(getAPIVersion())
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/LightServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/LightServiceTest.java
new file mode 100644
index 0000000..5a604e2
--- /dev/null
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/LightServiceTest.java
@@ -0,0 +1,184 @@
+package de.ids_mannheim.korap.web.service.full;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.sun.jersey.api.client.ClientResponse;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.query.serialize.QuerySerializer;
+import de.ids_mannheim.korap.utils.JsonUtils;
+import de.ids_mannheim.korap.web.service.FastJerseyTest;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Created by hanl on 29.04.16.
+ */
+public class LightServiceTest extends FastJerseyTest {
+
+ @BeforeClass
+ public static void configure () throws Exception {
+ FastJerseyTest.setPackages("de.ids_mannheim.korap.web.service.light");
+ }
+
+
+ @Override
+ public void initMethod () throws KustvaktException {}
+
+
+ @Test
+ public void testQueryTrace () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp").queryParam("context", "sentence")
+ .queryParam("count", "13")
+ .method("TRACE", ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
+ assertEquals("sentence", node.at("/meta/context").asText());
+ assertEquals("13", node.at("/meta/count").asText());
+ }
+
+ @Test
+ public void testbuildAndPostQuery() {
+ ClientResponse response = resource()
+ .path(getAPIVersion())
+ .path("search")
+ .queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp")
+ .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
+ .method("TRACE", ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+
+ response = resource()
+ .path(getAPIVersion())
+ .path("search").post(ClientResponse.class, query);
+
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String matches = response.getEntity(String.class);
+ JsonNode match_node = JsonUtils.readTree(matches);
+ assertNotEquals(0, match_node.path("matches").size());
+ }
+
+
+ @Test
+ public void testQueryGet () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp").queryParam("context", "sentence")
+ .queryParam("count", "13").get(ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals("base/s:s", node.at("/meta/context").asText());
+ assertEquals("13", node.at("/meta/count").asText());
+ assertNotEquals(0, node.at("/matches").size());
+ }
+
+
+ @Test
+ public void testFoundryRewrite () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp").queryParam("context", "sentence")
+ .queryParam("count", "13").get(ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
+ }
+
+
+ @Test
+ public void testQueryPost () {
+ QuerySerializer s = new QuerySerializer();
+ s.setQuery("[orth=das]", "poliqarp");
+
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").post(ClientResponse.class, s.toJSON());
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertNotEquals(0, node.at("/matches").size());
+ }
+
+
+ @Test
+ public void testParameterField () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp")
+ .queryParam("fields", "author, docSigle")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .get(ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertNotEquals(0, node.at("/matches").size());
+ assertEquals("[\"author, docSigle\"]", node.at("/meta/fields")
+ .toString());
+ }
+
+
+ @Test
+ public void testCQParameter () {
+ ClientResponse response = resource().path(getAPIVersion())
+ .path("search").queryParam("q", "[orth=das]")
+ .queryParam("ql", "poliqarp")
+ .queryParam("fields", "author, docSigle")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .queryParam("cq", "textClass=Politik & corpus=WPD")
+ .method("TRACE", ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ String query = response.getEntity(String.class);
+ JsonNode node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals("Politik", node.at("/collection/operands/0/value")
+ .asText());
+ assertEquals("WPD", node.at("/collection/operands/1/value").asText());
+
+ response = resource().path(getAPIVersion()).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author, docSigle")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .queryParam("cq", "textClass=Politik & corpus=WPD")
+ .get(ClientResponse.class);
+ assertEquals(ClientResponse.Status.OK.getStatusCode(),
+ response.getStatus());
+ query = response.getEntity(String.class);
+ node = JsonUtils.readTree(query);
+ assertNotNull(node);
+ assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals("Politik", node.at("/collection/operands/0/value")
+ .asText());
+ assertEquals("WPD", node.at("/collection/operands/1/value").asText());
+ }
+
+}
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceServiceTest.java
index 6cb7700..d0a5b96 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceServiceTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceServiceTest.java
@@ -135,8 +135,10 @@
ClientResponse.Status.OK.getStatusCode());
String ent = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- System.out.println("PUBLIC COLLECTION");
- System.out.println(node);
+ assertNotNull(node);
+ assertEquals("koral:docGroup", node.at("/collection/@type").asText());
+ assertEquals("operation:or", node.at("/collection/operation").asText());
+ assertNotEquals(0, node.at("/collection/operands").size());
}