Formatted project
Change-Id: I6993ddfab02e06541b4138040280a4777c719562
diff --git a/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java b/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java
index ccb6d1a..3f71e9f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java
+++ b/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java
@@ -23,7 +23,9 @@
import de.ids_mannheim.korap.core.entity.AnnotationLayer;
import de.ids_mannheim.korap.dao.AnnotationDao;
-/** Parser for extracting annotation descriptions from Kalamar javascripts
+/**
+ * Parser for extracting annotation descriptions from Kalamar
+ * javascripts
*
* @author margaretha
*
@@ -47,23 +49,23 @@
private Set<Annotation> values = new HashSet<>();
public void run () throws IOException {
- PathMatchingResourcePatternResolver resolver =
- new PathMatchingResourcePatternResolver(
- getClass().getClassLoader());
+ PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
+ getClass().getClassLoader());
Resource[] resources = resolver
.getResources("classpath:annotation-scripts/foundries/*.js");
- if (resources.length < 1) return;
+ if (resources.length < 1)
+ return;
for (Resource r : resources) {
-// log.debug(r.getFilename());
+ // log.debug(r.getFilename());
readFile(r.getInputStream());
}
}
private void readFile (InputStream inputStream) throws IOException {
- BufferedReader br =
- new BufferedReader(new InputStreamReader(inputStream), 1024);
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(inputStream), 1024);
foundry = null;
@@ -128,8 +130,8 @@
Annotation layer = retrieveOrCreateAnnotation(code, annotationType,
null, array.get(0));
try {
- AnnotationLayer annotationLayer =
- annotationDao.retrieveAnnotationLayer(foundry.getCode(),
+ AnnotationLayer annotationLayer = annotationDao
+ .retrieveAnnotationLayer(foundry.getCode(),
layer.getCode());
if (annotationLayer == null) {
annotationDao.createAnnotationLayer(foundry, layer);
@@ -161,8 +163,8 @@
annotationType, array.get(1), array.get(2));
}
if (annotation != null) {
- AnnotationKey annotationKey =
- annotationDao.retrieveAnnotationKey(layer, annotation);
+ AnnotationKey annotationKey = annotationDao
+ .retrieveAnnotationKey(layer, annotation);
if (annotationKey == null) {
annotationDao.createAnnotationKey(layer, annotation);
}
@@ -203,8 +205,8 @@
if (layerCode.endsWith("=")) {
layerCode = layerCode.substring(0, layerCode.length() - 1);
}
- this.layer =
- annotationDao.retrieveAnnotationLayer(codes[0], layerCode);
+ this.layer = annotationDao.retrieveAnnotationLayer(codes[0],
+ layerCode);
if (layer == null) {
log.warn("Layer is null for " + code);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java b/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java
index 8740919..09d652c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java
+++ b/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java
@@ -22,8 +22,7 @@
@Deprecated
public class ArrayVariables {
- public static HashMap<String, List<Annotation>> annotationMap =
- new HashMap<>();
+ public static HashMap<String, List<Annotation>> annotationMap = new HashMap<>();
public static void main (String[] args) throws IOException {
ArrayVariables variables = new ArrayVariables();
@@ -53,7 +52,8 @@
public void extractVariables () throws IOException {
String dir = "annotation-scripts/variables";
- if (dir.isEmpty()) return;
+ if (dir.isEmpty())
+ return;
File d = new File(dir);
if (!d.isDirectory()) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/annotation/FreeResourceParser.java b/full/src/main/java/de/ids_mannheim/korap/annotation/FreeResourceParser.java
index f6a0ee5..bb7beec 100644
--- a/full/src/main/java/de/ids_mannheim/korap/annotation/FreeResourceParser.java
+++ b/full/src/main/java/de/ids_mannheim/korap/annotation/FreeResourceParser.java
@@ -21,7 +21,8 @@
import de.ids_mannheim.korap.dao.ResourceDao;
import de.ids_mannheim.korap.exceptions.KustvaktException;
-/** Parser for extracting data from free-resources.json containing
+/**
+ * Parser for extracting data from free-resources.json containing
* listing free (non-licensed) corpora.
*
* @author margaretha
@@ -40,12 +41,12 @@
public static ObjectMapper mapper = new ObjectMapper();
public void run () throws IOException, KustvaktException {
- InputStream is=null;
+ InputStream is = null;
File f = new File(FREE_RESOURCE_FILE);
- if (f.exists()){
+ if (f.exists()) {
is = new FileInputStream(f);
}
- else{
+ else {
is = FreeResourceParser.class.getClassLoader()
.getResourceAsStream(FREE_RESOURCE_FILE);
}
@@ -53,7 +54,7 @@
JsonNode node = mapper.readTree(is);
for (JsonNode resource : node) {
String resourceId = resource.at("/id").asText();
-// log.debug(resourceId);
+ // log.debug(resourceId);
Set<AnnotationLayer> layers = parseLayers(resource.at("/layers"));
try {
Resource r = resourceDao.retrieveResource(resourceId);
@@ -74,8 +75,8 @@
Set<AnnotationLayer> layerSet = new HashSet<>(layers.size());
for (JsonNode layer : layers) {
String[] codes = layer.asText().split("/");
- AnnotationLayer annotationLayer =
- annotationDao.retrieveAnnotationLayer(codes[0], codes[1]);
+ AnnotationLayer annotationLayer = annotationDao
+ .retrieveAnnotationLayer(codes[0], codes[1]);
layerSet.add(annotationLayer);
}
return layerSet;
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java b/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
index ef9db77..d78c55d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
@@ -31,7 +31,7 @@
private static Logger jlog = LogManager.getLogger(APIAuthentication.class);
public static boolean DEBUG = false;
-
+
private JWTSigner signedToken;
public APIAuthentication (FullConfiguration config) throws JOSEException {
@@ -65,7 +65,6 @@
return context;
}
-
@Override
public TokenContext createTokenContext (User user, Map<String, Object> attr)
throws KustvaktException {
@@ -75,7 +74,7 @@
try {
c.setExpirationTime(
jwt.getJWTClaimsSet().getExpirationTime().getTime());
- if (DEBUG ) {
+ if (DEBUG) {
jlog.debug(jwt.getJWTClaimsSet()
.getClaim(Attributes.AUTHENTICATION_TIME));
}
@@ -94,7 +93,6 @@
return c;
}
-
@Override
public TokenType getTokenType () {
return TokenType.API;
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationIface.java b/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationIface.java
index 04f5a6a..de0137a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationIface.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationIface.java
@@ -9,17 +9,15 @@
public interface AuthenticationIface {
- public TokenContext getTokenContext(String authToken) throws KustvaktException;
-
-
- public TokenContext createTokenContext(User user, Map<String, Object> attr)
+ public TokenContext getTokenContext (String authToken)
throws KustvaktException;
+ public TokenContext createTokenContext (User user, Map<String, Object> attr)
+ throws KustvaktException;
-// void removeUserSession (String token) throws KustvaktException;
-//
-// public TokenContext refresh (TokenContext context) throws KustvaktException;
-
+ // void removeUserSession (String token) throws KustvaktException;
+ //
+ // public TokenContext refresh (TokenContext context) throws KustvaktException;
public TokenType getTokenType ();
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationManager.java b/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationManager.java
index f11aa52..6ee6dc6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationManager.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/AuthenticationManager.java
@@ -23,9 +23,9 @@
public AuthenticationManager () {
super();
}
-
+
public AuthenticationManager (String cache) {
- super(cache, "key:"+cache);
+ super(cache, "key:" + cache);
this.providers = new HashMap<>();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java b/full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java
index 52f2885..026b5b3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java
@@ -61,9 +61,9 @@
throws KustvaktException {
String[] values = transferEncoding.decodeBase64(authToken);
User user = dao.getAccount(values[0]);
- ZonedDateTime authenticationTime =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
-
+ ZonedDateTime authenticationTime = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+
if (user != null) {
TokenContext c = new TokenContext();
c.setUsername(values[0]);
@@ -84,7 +84,6 @@
return null;
}
-
// not supported!
@Override
public TokenContext createTokenContext (User user, Map<String, Object> attr)
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/DummyAuthenticationManager.java b/full/src/main/java/de/ids_mannheim/korap/authentication/DummyAuthenticationManager.java
index 5934667..83b979c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/DummyAuthenticationManager.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/DummyAuthenticationManager.java
@@ -20,7 +20,7 @@
private KustvaktConfiguration config;
public DummyAuthenticationManager () {}
-
+
@Override
public TokenContext getTokenContext (TokenType type, String token,
String host, String useragent) throws KustvaktException {
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java b/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
index 590fb9f..e5f5a54 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
@@ -38,99 +38,103 @@
import jakarta.ws.rs.core.MultivaluedMap;
/**
- * contains the logic to authentication and registration processes. Uses
- * interface implementations (AuthenticationIface) for different databases and
+ * contains the logic to authentication and registration processes.
+ * Uses
+ * interface implementations (AuthenticationIface) for different
+ * databases and
* handlers
*
* @author hanl
*/
public class KustvaktAuthenticationManager extends AuthenticationManager {
- private static Logger jlog = LogManager.getLogger(KustvaktAuthenticationManager.class);
- public static boolean DEBUG = false;
-
- private EncryptionIface crypto;
- private EntityHandlerIface entHandler;
- @Autowired
- private FullConfiguration config;
- @Autowired
- private Validator validator;
-
- public KustvaktAuthenticationManager(EncryptionIface crypto,
- FullConfiguration config) {
- super("id_tokens");
- this.config = config;
- this.crypto = crypto;
- // todo: load via beancontext
-// try {
-// this.validator = new ApacheValidator();
-// } catch (IOException e) {
-// e.printStackTrace();
-// }
- }
+ private static Logger jlog = LogManager
+ .getLogger(KustvaktAuthenticationManager.class);
+ public static boolean DEBUG = false;
- /**
- * get session object if token was a session token
- *
- * @param token
- * @param host
- * @param useragent
- * @return
- * @throws KustvaktException
- */
- @Override
- public TokenContext getTokenContext(TokenType type, String token,
- String host, String userAgent) throws KustvaktException {
+ private EncryptionIface crypto;
+ private EntityHandlerIface entHandler;
+ @Autowired
+ private FullConfiguration config;
+ @Autowired
+ private Validator validator;
- AuthenticationIface provider = getProvider(type , null);
+ public KustvaktAuthenticationManager (EncryptionIface crypto,
+ FullConfiguration config) {
+ super("id_tokens");
+ this.config = config;
+ this.crypto = crypto;
+ // todo: load via beancontext
+ // try {
+ // this.validator = new ApacheValidator();
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ }
- if (provider == null){
- throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT,
- "Authentication provider for token type "+type
- +" is not found.", type.displayName());
- }
-
- TokenContext context = provider.getTokenContext(token);
- context.setHostAddress(host);
- context.setUserAgent(userAgent);
- // if (!matchStatus(host, useragent, context))
- // provider.removeUserSession(token);
- return context;
- }
+ /**
+ * get session object if token was a session token
+ *
+ * @param token
+ * @param host
+ * @param useragent
+ * @return
+ * @throws KustvaktException
+ */
+ @Override
+ public TokenContext getTokenContext (TokenType type, String token,
+ String host, String userAgent) throws KustvaktException {
- @Override
- public User getUser(String username) throws KustvaktException {
- // User user;
- // Object value = this.getCacheValue(username);
+ AuthenticationIface provider = getProvider(type, null);
- if (User.UserFactory.isDemo(username))
- return User.UserFactory.getDemoUser();
+ if (provider == null) {
+ throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT,
+ "Authentication provider for token type " + type
+ + " is not found.",
+ type.displayName());
+ }
- // if (value != null) {
- // Map map = (Map) value;
- // user = User.UserFactory.toUser(map);
- // }
- // else {
- // user = entHandler.getAccount(username);
- // this.storeInCache(username, user.toCache());
- // todo: not valid. for the duration of the session, the host should not
- // change!
- // }
- // todo:
- // user.addField(Attributes.HOST, context.getHostAddress());
- // user.addField(Attributes.USER_AGENT, context.getUserAgent());
-
- //EM:copied from EntityDao
- KorAPUser user = new KorAPUser(); // oder eigentlich new DemoUser oder new DefaultUser.
+ TokenContext context = provider.getTokenContext(token);
+ context.setHostAddress(host);
+ context.setUserAgent(userAgent);
+ // if (!matchStatus(host, useragent, context))
+ // provider.removeUserSession(token);
+ return context;
+ }
+
+ @Override
+ public User getUser (String username) throws KustvaktException {
+ // User user;
+ // Object value = this.getCacheValue(username);
+
+ if (User.UserFactory.isDemo(username))
+ return User.UserFactory.getDemoUser();
+
+ // if (value != null) {
+ // Map map = (Map) value;
+ // user = User.UserFactory.toUser(map);
+ // }
+ // else {
+ // user = entHandler.getAccount(username);
+ // this.storeInCache(username, user.toCache());
+ // todo: not valid. for the duration of the session, the host should not
+ // change!
+ // }
+ // todo:
+ // user.addField(Attributes.HOST, context.getHostAddress());
+ // user.addField(Attributes.USER_AGENT, context.getUserAgent());
+
+ //EM:copied from EntityDao
+ KorAPUser user = new KorAPUser(); // oder eigentlich new DemoUser oder new DefaultUser.
user.setUsername(username);
return user;
-// return entHandler.getAccount(username);
- }
-
- @Override
+ // return entHandler.getAccount(username);
+ }
+
+ @Override
public User getUser (String username, String method)
throws KustvaktException {
- KorAPUser user = new KorAPUser();
+ KorAPUser user = new KorAPUser();
user.setUsername(username);
String email = null;
switch (method.toLowerCase()) {
@@ -145,99 +149,108 @@
return user;
}
- public TokenContext refresh(TokenContext context) throws KustvaktException {
- AuthenticationIface provider = getProvider(context.getTokenType(), null);
- if (provider == null) {
- // todo:
- }
+ public TokenContext refresh (TokenContext context)
+ throws KustvaktException {
+ AuthenticationIface provider = getProvider(context.getTokenType(),
+ null);
+ if (provider == null) {
+ // todo:
+ }
- try {
-// provider.removeUserSession(context.getToken());
- User user = getUser(context.getUsername());
- return provider.createTokenContext(user, context.params());
- } catch (KustvaktException e) {
- throw new WrappedException(e, StatusCodes.LOGIN_FAILED);
- }
- }
+ try {
+ // provider.removeUserSession(context.getToken());
+ User user = getUser(context.getUsername());
+ return provider.createTokenContext(user, context.params());
+ }
+ catch (KustvaktException e) {
+ throw new WrappedException(e, StatusCodes.LOGIN_FAILED);
+ }
+ }
- /** EM: fix type is not flexible
- * @param type
- * @param attributes
- * contains username and password to authenticate the user.
- * Depending of the authentication schema, may contain other
- * values as well
- * @return User
- * @throws KustvaktException
- */
- @Override
- public User authenticate(AuthenticationMethod method, String username, String password, Map<String, Object> attributes)
- throws KustvaktException {
- User user;
- switch (method) {
- case SHIBBOLETH:
- // todo:
- user = authenticateShib(attributes);
- break;
- case LDAP:
- // IdM/LDAP: (09.02.17/FB)
- user = authenticateIdM(username, password, attributes);
- break;
- // EM: added a dummy authentication for testing
- case TEST:
- user = getUser(username);
- break;
- default:
- user = authenticate(username, password, attributes);
- break;
- }
- return user;
- }
+ /**
+ * EM: fix type is not flexible
+ *
+ * @param type
+ * @param attributes
+ * contains username and password to authenticate the
+ * user.
+ * Depending of the authentication schema, may contain
+ * other
+ * values as well
+ * @return User
+ * @throws KustvaktException
+ */
+ @Override
+ public User authenticate (AuthenticationMethod method, String username,
+ String password, Map<String, Object> attributes)
+ throws KustvaktException {
+ User user;
+ switch (method) {
+ case SHIBBOLETH:
+ // todo:
+ user = authenticateShib(attributes);
+ break;
+ case LDAP:
+ // IdM/LDAP: (09.02.17/FB)
+ user = authenticateIdM(username, password, attributes);
+ break;
+ // EM: added a dummy authentication for testing
+ case TEST:
+ user = getUser(username);
+ break;
+ default:
+ user = authenticate(username, password, attributes);
+ break;
+ }
+ return user;
+ }
- // a. set location depending on X-Forwarded-For.
- // X-Forwarded-For: clientIP, ProxyID, ProxyID...
- // the following private address spaces may be used to define intranet
- // spaces:
- // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
- // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
- // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
- // b. set corpusAccess depending on location:
- // c. DemoUser only gets corpusAccess=FREE.
- // 16.05.17/FB
+ // a. set location depending on X-Forwarded-For.
+ // X-Forwarded-For: clientIP, ProxyID, ProxyID...
+ // the following private address spaces may be used to define intranet
+ // spaces:
+ // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
+ // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
+ // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
+ // b. set corpusAccess depending on location:
+ // c. DemoUser only gets corpusAccess=FREE.
+ // 16.05.17/FB
- @Override
- public void setAccessAndLocation(User user, HttpHeaders headers) {
- MultivaluedMap<String, String> headerMap = headers.getRequestHeaders();
- Location location = Location.EXTERN;
- CorpusAccess corpusAccess = CorpusAccess.FREE;
-
- if( user instanceof DemoUser )
- {
- // to be absolutely sure:
- user.setCorpusAccess(User.CorpusAccess.FREE);
+ @Override
+ public void setAccessAndLocation (User user, HttpHeaders headers) {
+ MultivaluedMap<String, String> headerMap = headers.getRequestHeaders();
+ Location location = Location.EXTERN;
+ CorpusAccess corpusAccess = CorpusAccess.FREE;
+
+ if (user instanceof DemoUser) {
+ // to be absolutely sure:
+ user.setCorpusAccess(User.CorpusAccess.FREE);
if (DEBUG) {
jlog.debug("setAccessAndLocation: DemoUser: location="
+ user.locationtoString() + " access="
+ user.accesstoString());
}
- return;
- }
-
- if (headerMap != null && headerMap.containsKey(HttpHeader.X_FORWARDED_FOR.toString())) {
+ return;
+ }
- String[] vals = headerMap.getFirst(HttpHeader.X_FORWARDED_FOR.toString()).split(",");
- String clientAddress = vals[0];
+ if (headerMap != null && headerMap
+ .containsKey(HttpHeader.X_FORWARDED_FOR.toString())) {
- try {
- InetAddress ip = InetAddress.getByName(clientAddress);
- if (ip.isSiteLocalAddress()){
- location = Location.INTERN;
- corpusAccess = CorpusAccess.ALL;
- }
- else{
- corpusAccess = CorpusAccess.PUB;
- }
-
- if (DEBUG){
+ String[] vals = headerMap
+ .getFirst(HttpHeader.X_FORWARDED_FOR.toString()).split(",");
+ String clientAddress = vals[0];
+
+ try {
+ InetAddress ip = InetAddress.getByName(clientAddress);
+ if (ip.isSiteLocalAddress()) {
+ location = Location.INTERN;
+ corpusAccess = CorpusAccess.ALL;
+ }
+ else {
+ corpusAccess = CorpusAccess.PUB;
+ }
+
+ if (DEBUG) {
jlog.debug(String.format(
"X-Forwarded-For : '%s' (%d values) -> %s\n",
Arrays.toString(vals), vals.length, vals[0]));
@@ -249,278 +262,319 @@
: "FREE"));
}
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ }
+ catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
- user.setLocation(location);
- user.setCorpusAccess(corpusAccess);
-
+ user.setLocation(location);
+ user.setCorpusAccess(corpusAccess);
+
if (DEBUG) {
jlog.debug("setAccessAndLocation: KorAPUser: location="
+ user.locationtoString() + ", access="
+ user.accesstoString());
}
- }
- } // getAccess
+ }
+ } // getAccess
- @Override
- public TokenContext createTokenContext(User user, Map<String, Object> attr, TokenType type)
- throws KustvaktException {
- // use api token
- AuthenticationIface provider = getProvider(type, TokenType.API);
+ @Override
+ public TokenContext createTokenContext (User user, Map<String, Object> attr,
+ TokenType type) throws KustvaktException {
+ // use api token
+ AuthenticationIface provider = getProvider(type, TokenType.API);
- // EM: not in the new DB
-// if (attr.get(Attributes.SCOPES) != null)
-// this.getUserData(user, UserDetails.class);
+ // EM: not in the new DB
+ // if (attr.get(Attributes.SCOPES) != null)
+ // this.getUserData(user, UserDetails.class);
- TokenContext context = provider.createTokenContext(user, attr);
- if (context == null)
- throw new KustvaktException(StatusCodes.NOT_SUPPORTED);
- context.setUserAgent((String) attr.get(Attributes.USER_AGENT));
- context.setHostAddress(Attributes.HOST);
- return context;
- }
+ TokenContext context = provider.createTokenContext(user, attr);
+ if (context == null)
+ throw new KustvaktException(StatusCodes.NOT_SUPPORTED);
+ context.setUserAgent((String) attr.get(Attributes.USER_AGENT));
+ context.setHostAddress(Attributes.HOST);
+ return context;
+ }
- @Deprecated
- private User authenticateShib(Map<String, Object> attributes) throws KustvaktException {
- // todo use persistent id, since eppn is not unique
- String eppn = (String) attributes.get(Attributes.EPPN);
+ @Deprecated
+ private User authenticateShib (Map<String, Object> attributes)
+ throws KustvaktException {
+ // todo use persistent id, since eppn is not unique
+ String eppn = (String) attributes.get(Attributes.EPPN);
- if (eppn == null || eppn.isEmpty())
- throw new KustvaktException(StatusCodes.INVALID_REQUEST);
+ if (eppn == null || eppn.isEmpty())
+ throw new KustvaktException(StatusCodes.INVALID_REQUEST);
- if (!attributes.containsKey(Attributes.EMAIL) && validator.isValid(eppn, Attributes.EMAIL))
- attributes.put(Attributes.EMAIL, eppn);
+ if (!attributes.containsKey(Attributes.EMAIL)
+ && validator.isValid(eppn, Attributes.EMAIL))
+ attributes.put(Attributes.EMAIL, eppn);
- User user = null;
- return user;
- }
+ User user = null;
+ return user;
+ }
- // todo: what if attributes null?
- private User authenticate(String username, String password, Map<String, Object> attr) throws KustvaktException {
+ // todo: what if attributes null?
+ private User authenticate (String username, String password,
+ Map<String, Object> attr) throws KustvaktException {
- Map<String, Object> attributes = validator.validateMap(attr);
- User unknown;
- // just to make sure that the plain password does not appear anywhere in
- // the logs!
+ Map<String, Object> attributes = validator.validateMap(attr);
+ User unknown;
+ // just to make sure that the plain password does not appear anywhere in
+ // the logs!
- try {
- validator.validateEntry(username, Attributes.USERNAME);
- } catch (KustvaktException e) {
- throw new WrappedException(e, StatusCodes.LOGIN_FAILED, username);
- }
+ try {
+ validator.validateEntry(username, Attributes.USERNAME);
+ }
+ catch (KustvaktException e) {
+ throw new WrappedException(e, StatusCodes.LOGIN_FAILED, username);
+ }
- if (username == null || username.isEmpty())
- throw new WrappedException(new KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
- StatusCodes.LOGIN_FAILED);
- else {
- try {
- unknown = entHandler.getAccount(username);
- } catch (EmptyResultException e) {
- // mask exception to disable user guessing in possible attacks
- throw new WrappedException(new KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
- StatusCodes.LOGIN_FAILED, username);
- } catch (KustvaktException e) {
- jlog.error("Error: {}", e);
- throw new WrappedException(e, StatusCodes.LOGIN_FAILED, attributes.toString());
- }
- }
+ if (username == null || username.isEmpty())
+ throw new WrappedException(
+ new KustvaktException(username,
+ StatusCodes.BAD_CREDENTIALS),
+ StatusCodes.LOGIN_FAILED);
+ else {
+ try {
+ unknown = entHandler.getAccount(username);
+ }
+ catch (EmptyResultException e) {
+ // mask exception to disable user guessing in possible attacks
+ throw new WrappedException(
+ new KustvaktException(username,
+ StatusCodes.BAD_CREDENTIALS),
+ StatusCodes.LOGIN_FAILED, username);
+ }
+ catch (KustvaktException e) {
+ jlog.error("Error: {}", e);
+ throw new WrappedException(e, StatusCodes.LOGIN_FAILED,
+ attributes.toString());
+ }
+ }
if (DEBUG) {
jlog.debug(
"Authentication: found username " + unknown.getUsername());
}
- if (unknown instanceof KorAPUser) {
- if (password == null || password.isEmpty())
- throw new WrappedException(new KustvaktException(unknown.getId(), StatusCodes.BAD_CREDENTIALS),
- StatusCodes.LOGIN_FAILED, username);
+ if (unknown instanceof KorAPUser) {
+ if (password == null || password.isEmpty())
+ throw new WrappedException(
+ new KustvaktException(unknown.getId(),
+ StatusCodes.BAD_CREDENTIALS),
+ StatusCodes.LOGIN_FAILED, username);
- KorAPUser user = (KorAPUser) unknown;
- boolean check = crypto.checkHash(password, user.getPassword());
+ KorAPUser user = (KorAPUser) unknown;
+ boolean check = crypto.checkHash(password, user.getPassword());
- if (!check) {
- // the fail counter only applies for wrong password
- jlog.warn("Wrong Password!");
- throw new WrappedException(new KustvaktException(user.getId(), StatusCodes.BAD_CREDENTIALS),
- StatusCodes.LOGIN_FAILED, username);
- }
+ if (!check) {
+ // the fail counter only applies for wrong password
+ jlog.warn("Wrong Password!");
+ throw new WrappedException(
+ new KustvaktException(user.getId(),
+ StatusCodes.BAD_CREDENTIALS),
+ StatusCodes.LOGIN_FAILED, username);
+ }
- // bad credentials error has precedence over account locked or
- // unconfirmed codes
- // since latter can lead to account guessing of third parties
- if (user.isAccountLocked()) {
- URIParam param = (URIParam) user.getField(URIParam.class);
+ // bad credentials error has precedence over account locked or
+ // unconfirmed codes
+ // since latter can lead to account guessing of third parties
+ if (user.isAccountLocked()) {
+ URIParam param = (URIParam) user.getField(URIParam.class);
- if (param.hasValues()) {
+ if (param.hasValues()) {
if (DEBUG) {
jlog.debug("Account is not yet activated for user '"
+ user.getUsername() + "'");
}
- if (TimeUtils.getNow().isAfter(param.getUriExpiration())) {
- jlog.error("URI token is expired. Deleting account for user "+ user.getUsername());
- throw new WrappedException(
- new KustvaktException(unknown.getId(), StatusCodes.EXPIRED,
- "account confirmation uri has expired!", param.getUriFragment()),
- StatusCodes.LOGIN_FAILED, username);
- }
- throw new WrappedException(
- new KustvaktException(unknown.getId(), StatusCodes.ACCOUNT_NOT_CONFIRMED),
- StatusCodes.LOGIN_FAILED, username);
- }
- jlog.error("ACCESS DENIED: account not active for '"+unknown.getUsername()+"'");
- throw new WrappedException(new KustvaktException(unknown.getId(), StatusCodes.ACCOUNT_DEACTIVATED),
- StatusCodes.LOGIN_FAILED, username);
- }
+ if (TimeUtils.getNow().isAfter(param.getUriExpiration())) {
+ jlog.error(
+ "URI token is expired. Deleting account for user "
+ + user.getUsername());
+ throw new WrappedException(
+ new KustvaktException(unknown.getId(),
+ StatusCodes.EXPIRED,
+ "account confirmation uri has expired!",
+ param.getUriFragment()),
+ StatusCodes.LOGIN_FAILED, username);
+ }
+ throw new WrappedException(
+ new KustvaktException(unknown.getId(),
+ StatusCodes.ACCOUNT_NOT_CONFIRMED),
+ StatusCodes.LOGIN_FAILED, username);
+ }
+ jlog.error("ACCESS DENIED: account not active for '"
+ + unknown.getUsername() + "'");
+ throw new WrappedException(
+ new KustvaktException(unknown.getId(),
+ StatusCodes.ACCOUNT_DEACTIVATED),
+ StatusCodes.LOGIN_FAILED, username);
+ }
- } else if (unknown instanceof ShibbolethUser) {
- // todo
- }
+ }
+ else if (unknown instanceof ShibbolethUser) {
+ // todo
+ }
if (DEBUG) {
jlog.debug("Authentication done: " + unknown);
}
- return unknown;
- }
+ return unknown;
+ }
- /**
- * authenticate using IdM (Identitätsmanagement) accessed by LDAP.
- *
- * @param username
- * @param password
- * @param attr
- * @return
- * @throws KustvaktException
- * @date 09.02.17/FB
- */
- // todo: what if attributes null?
+ /**
+ * authenticate using IdM (Identitätsmanagement) accessed by LDAP.
+ *
+ * @param username
+ * @param password
+ * @param attr
+ * @return
+ * @throws KustvaktException
+ * @date 09.02.17/FB
+ */
+ // todo: what if attributes null?
- private User authenticateIdM(String username, String password, Map<String, Object> attr) throws KustvaktException {
+ private User authenticateIdM (String username, String password,
+ Map<String, Object> attr) throws KustvaktException {
- User unknown = null;
- // just to make sure that the plain password does not appear anywhere in
- // the logs!
- if (DEBUG){
- jlog.debug("Debug: authenticateIdM: entering for '%s'...\n", username);
- }
- /**
- * wozu Apache Validatoren für User/Passwort für IdM/LDAP? siehe
- * validation.properties. Abgeschaltet 21.04.17/FB try {
- * validator.validateEntry(username, Attributes.USERNAME); } catch
- * (KustvaktException e) { throw new WrappedException(e,
- * StatusCodes.LOGIN_FAILED, username); }
- */
- if (username == null || username.isEmpty() || password == null || password.isEmpty())
- throw new WrappedException(new KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
- StatusCodes.LOGIN_FAILED);
+ User unknown = null;
+ // just to make sure that the plain password does not appear anywhere in
+ // the logs!
+ if (DEBUG) {
+ jlog.debug("Debug: authenticateIdM: entering for '%s'...\n",
+ username);
+ }
+ /**
+ * wozu Apache Validatoren für User/Passwort für IdM/LDAP?
+ * siehe
+ * validation.properties. Abgeschaltet 21.04.17/FB try {
+ * validator.validateEntry(username, Attributes.USERNAME); }
+ * catch
+ * (KustvaktException e) { throw new WrappedException(e,
+ * StatusCodes.LOGIN_FAILED, username); }
+ */
+ if (username == null || username.isEmpty() || password == null
+ || password.isEmpty())
+ throw new WrappedException(
+ new KustvaktException(username,
+ StatusCodes.BAD_CREDENTIALS),
+ StatusCodes.LOGIN_FAILED);
- // LDAP Access:
- try {
- // todo: unknown = ...
- int ret = LdapAuth3.login(username, password, config.getLdapConfig());
- if (DEBUG){
- jlog.debug("Debug: autenticationIdM: Ldap.login(%s) returns: %d.\n", username, ret);
- }
- if (ret != LdapAuth3.LDAP_AUTH_ROK) {
- jlog.error("LdapAuth3.login(username='"+username+"') returns '"+ret+"'='"+LdapAuth3.getErrMessage(ret)+"'!");
+ // LDAP Access:
+ try {
+ // todo: unknown = ...
+ int ret = LdapAuth3.login(username, password,
+ config.getLdapConfig());
+ if (DEBUG) {
+ jlog.debug(
+ "Debug: autenticationIdM: Ldap.login(%s) returns: %d.\n",
+ username, ret);
+ }
+ if (ret != LdapAuth3.LDAP_AUTH_ROK) {
+ jlog.error("LdapAuth3.login(username='" + username
+ + "') returns '" + ret + "'='"
+ + LdapAuth3.getErrMessage(ret) + "'!");
- // mask exception to disable user guessing in possible attacks
- /*
- * by Hanl throw new WrappedException(new
- * KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
- * StatusCodes.LOGIN_FAILED, username);
- */
- throw new WrappedException(new KustvaktException(username, StatusCodes.LDAP_BASE_ERRCODE + ret,
- LdapAuth3.getErrMessage(ret), null), StatusCodes.LOGIN_FAILED, username);
- }
- } catch (LDAPException e) {
+ // mask exception to disable user guessing in possible attacks
+ /*
+ * by Hanl throw new WrappedException(new
+ * KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
+ * StatusCodes.LOGIN_FAILED, username);
+ */
+ throw new WrappedException(
+ new KustvaktException(username,
+ StatusCodes.LDAP_BASE_ERRCODE + ret,
+ LdapAuth3.getErrMessage(ret), null),
+ StatusCodes.LOGIN_FAILED, username);
+ }
+ }
+ catch (LDAPException e) {
- jlog.error("Error: username='"+username+"' -> '"+e+"'!");
- // mask exception to disable user guessing in possible attacks
- /*
- * by Hanl: throw new WrappedException(new
- * KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
- * StatusCodes.LOGIN_FAILED, username);
- */
- throw new WrappedException(
- new KustvaktException(username, StatusCodes.LDAP_BASE_ERRCODE + LdapAuth3.LDAP_AUTH_RINTERR,
- LdapAuth3.getErrMessage(LdapAuth3.LDAP_AUTH_RINTERR), null),
- StatusCodes.LOGIN_FAILED, username);
- }
+ jlog.error("Error: username='" + username + "' -> '" + e + "'!");
+ // mask exception to disable user guessing in possible attacks
+ /*
+ * by Hanl: throw new WrappedException(new
+ * KustvaktException(username, StatusCodes.BAD_CREDENTIALS),
+ * StatusCodes.LOGIN_FAILED, username);
+ */
+ throw new WrappedException(new KustvaktException(username,
+ StatusCodes.LDAP_BASE_ERRCODE + LdapAuth3.LDAP_AUTH_RINTERR,
+ LdapAuth3.getErrMessage(LdapAuth3.LDAP_AUTH_RINTERR), null),
+ StatusCodes.LOGIN_FAILED, username);
+ }
- // Create a User
- // TODO: KorAPUser für solche mit einem bestehenden Account
- // DefaultUser sonst.
- User user = new KorAPUser();
- user.setUsername(username);
- /*
- * folgender Code funktioniert hier noch nicht, da die Headers noch
- * nicht ausgewertet worden sind - 23.05.17/FB Object o =
- * attr.get(Attributes.LOCATION); String loc = (String)o.toString(); int
- * location = Integer.parseInt(loc); user.setLocation(location);
- * user.setCorpusAccess(Integer.parseInt(attr.get(Attributes.
- * CORPUS_ACCESS).toString()));
- */
- unknown = user;
+ // Create a User
+ // TODO: KorAPUser für solche mit einem bestehenden Account
+ // DefaultUser sonst.
+ User user = new KorAPUser();
+ user.setUsername(username);
+ /*
+ * folgender Code funktioniert hier noch nicht, da die Headers noch
+ * nicht ausgewertet worden sind - 23.05.17/FB Object o =
+ * attr.get(Attributes.LOCATION); String loc = (String)o.toString(); int
+ * location = Integer.parseInt(loc); user.setLocation(location);
+ * user.setCorpusAccess(Integer.parseInt(attr.get(Attributes.
+ * CORPUS_ACCESS).toString()));
+ */
+ unknown = user;
if (DEBUG) {
jlog.trace(
"Authentication: found username " + unknown.getUsername());
}
- if (unknown instanceof KorAPUser) {
- /*
- * password already checked using LDAP: if (password == null ||
- * password.isEmpty()) throw new WrappedException(new
- * KustvaktException( unknown.getId(), StatusCodes.BAD_CREDENTIALS),
- * StatusCodes.LOGIN_FAILED, username);
- *
- * KorAPUser user = (KorAPUser) unknown; boolean check =
- * crypto.checkHash(password, user.getPassword());
- *
- * if (!check) { // the fail counter only applies for wrong password
- * jlog.warn("Wrong Password!"); processLoginFail(unknown); throw
- * new WrappedException(new KustvaktException(user.getId(),
- * StatusCodes.BAD_CREDENTIALS), StatusCodes.LOGIN_FAILED,
- * username); }
- */
- // bad credentials error has precedence over account locked or
- // unconfirmed codes
- // since latter can lead to account guessing of third parties
- /*
- * if (user.isAccountLocked()) {
- *
- * URIParam param = (URIParam) user.getField(URIParam.class);
- *
- * if (param.hasValues()) {
- * jlog.debug("Account is not yet activated for user '{}'",
- * user.getUsername()); if
- * (TimeUtils.getNow().isAfter(param.getUriExpiration())) {
- * jlog.error( "URI token is expired. Deleting account for user {}",
- * user.getUsername()); deleteAccount(user); throw new
- * WrappedException(new KustvaktException( unknown.getId(),
- * StatusCodes.EXPIRED, "account confirmation uri has expired!",
- * param.getUriFragment()), StatusCodes.LOGIN_FAILED, username); }
- * throw new WrappedException(new KustvaktException(
- * unknown.getId(), StatusCodes.ACCOUNT_NOT_CONFIRMED),
- * StatusCodes.LOGIN_FAILED, username); }
- * jlog.error("ACCESS DENIED: account not active for '{}'",
- * unknown.getUsername()); throw new WrappedException(new
- * KustvaktException( unknown.getId(),
- * StatusCodes.ACCOUNT_DEACTIVATED), StatusCodes.LOGIN_FAILED,
- * username); }
- */
+ if (unknown instanceof KorAPUser) {
+ /*
+ * password already checked using LDAP: if (password == null ||
+ * password.isEmpty()) throw new WrappedException(new
+ * KustvaktException( unknown.getId(), StatusCodes.BAD_CREDENTIALS),
+ * StatusCodes.LOGIN_FAILED, username);
+ *
+ * KorAPUser user = (KorAPUser) unknown; boolean check =
+ * crypto.checkHash(password, user.getPassword());
+ *
+ * if (!check) { // the fail counter only applies for wrong password
+ * jlog.warn("Wrong Password!"); processLoginFail(unknown); throw
+ * new WrappedException(new KustvaktException(user.getId(),
+ * StatusCodes.BAD_CREDENTIALS), StatusCodes.LOGIN_FAILED,
+ * username); }
+ */
+ // bad credentials error has precedence over account locked or
+ // unconfirmed codes
+ // since latter can lead to account guessing of third parties
+ /*
+ * if (user.isAccountLocked()) {
+ *
+ * URIParam param = (URIParam) user.getField(URIParam.class);
+ *
+ * if (param.hasValues()) {
+ * jlog.debug("Account is not yet activated for user '{}'",
+ * user.getUsername()); if
+ * (TimeUtils.getNow().isAfter(param.getUriExpiration())) {
+ * jlog.error( "URI token is expired. Deleting account for user {}",
+ * user.getUsername()); deleteAccount(user); throw new
+ * WrappedException(new KustvaktException( unknown.getId(),
+ * StatusCodes.EXPIRED, "account confirmation uri has expired!",
+ * param.getUriFragment()), StatusCodes.LOGIN_FAILED, username); }
+ * throw new WrappedException(new KustvaktException(
+ * unknown.getId(), StatusCodes.ACCOUNT_NOT_CONFIRMED),
+ * StatusCodes.LOGIN_FAILED, username); }
+ * jlog.error("ACCESS DENIED: account not active for '{}'",
+ * unknown.getUsername()); throw new WrappedException(new
+ * KustvaktException( unknown.getId(),
+ * StatusCodes.ACCOUNT_DEACTIVATED), StatusCodes.LOGIN_FAILED,
+ * username); }
+ */
- }
-// else if (unknown instanceof ShibbolethUser) {
-// // todo
-// }
+ }
+ // else if (unknown instanceof ShibbolethUser) {
+ // // todo
+ // }
if (DEBUG) {
jlog.debug("Authentication done: " + username);
}
- return unknown;
+ return unknown;
- } // authenticateIdM
+ } // authenticateIdM
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/LDAPConfig.java b/full/src/main/java/de/ids_mannheim/korap/authentication/LDAPConfig.java
index 92ae6d6..79a9462 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/LDAPConfig.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/LDAPConfig.java
@@ -22,43 +22,55 @@
public final String authFilter;
public final String userNotBlockedFilter;
- public LDAPConfig(String ldapConfigFilename) throws LdapConfigurationException {
+ public LDAPConfig (String ldapConfigFilename)
+ throws LdapConfigurationException {
Map<String, String> ldapConfig = null;
try {
ldapConfig = loadProp(ldapConfigFilename);
- } catch (IOException e) {
- System.out.println("Error: LDAPAuth.login: cannot load Property file!");
+ }
+ catch (IOException e) {
+ System.out.println(
+ "Error: LDAPAuth.login: cannot load Property file!");
}
- useSSL = Boolean.parseBoolean(ldapConfig.getOrDefault("useSSL", "false"));
+ useSSL = Boolean
+ .parseBoolean(ldapConfig.getOrDefault("useSSL", "false"));
host = ldapConfig.getOrDefault("host", "localhost");
- port = Integer.parseInt(ldapConfig.getOrDefault("port", (useSSL ? "636" : "389")));
+ port = Integer.parseInt(
+ ldapConfig.getOrDefault("port", (useSSL ? "636" : "389")));
searchBase = getConfigOrThrow(ldapConfig, "searchBase");
sLoginDN = getConfigOrThrow(ldapConfig, "sLoginDN");
searchFilter = getConfigOrThrow(ldapConfig, "searchFilter");
authFilter = ldapConfig.getOrDefault("authFilter", null);
- userNotBlockedFilter = ldapConfig.getOrDefault("userNotBlockedFilter", null);
+ userNotBlockedFilter = ldapConfig.getOrDefault("userNotBlockedFilter",
+ null);
sPwd = ldapConfig.getOrDefault("pwd", "");
trustStorePath = ldapConfig.getOrDefault("trustStore", "");
- additionalCipherSuites = ldapConfig.getOrDefault("additionalCipherSuites", "");
- useEmbeddedServer = Boolean.parseBoolean(ldapConfig.getOrDefault("useEmbeddedServer", "false"));
+ additionalCipherSuites = ldapConfig
+ .getOrDefault("additionalCipherSuites", "");
+ useEmbeddedServer = Boolean.parseBoolean(
+ ldapConfig.getOrDefault("useEmbeddedServer", "false"));
emailAttribute = ldapConfig.getOrDefault("emailAttribute", "mail");
ldif = ldapConfig.getOrDefault("ldifFile", null);
}
- static HashMap<String, String> typeCastConvert(Properties prop) {
+ static HashMap<String, String> typeCastConvert (Properties prop) {
Map<String, String> step2 = (Map<String, String>) (Map) prop;
return new HashMap<>(step2);
}
- public static HashMap<String, String> loadProp(String sConfFile) throws IOException {
+ public static HashMap<String, String> loadProp (String sConfFile)
+ throws IOException {
FileInputStream in;
Properties prop;
try {
in = new FileInputStream(sConfFile);
- } catch (IOException ex) {
- System.err.printf("Error: LDAP.loadProp: cannot load Property file '%s'!\n", sConfFile);
+ }
+ catch (IOException ex) {
+ System.err.printf(
+ "Error: LDAP.loadProp: cannot load Property file '%s'!\n",
+ sConfFile);
ex.printStackTrace();
return null;
}
@@ -68,21 +80,25 @@
try {
prop.load(in);
return typeCastConvert(prop);
- } catch (IOException ex) {
+ }
+ catch (IOException ex) {
ex.printStackTrace();
}
return new HashMap<>();
}
- private String getConfigOrThrow(Map<String, String> ldapConfig, String attribute) throws LdapConfigurationException {
+ private String getConfigOrThrow (Map<String, String> ldapConfig,
+ String attribute) throws LdapConfigurationException {
String value = ldapConfig.get(attribute);
- if (value != null) return value;
- else throw new LdapConfigurationException(attribute + " is not set");
+ if (value != null)
+ return value;
+ else
+ throw new LdapConfigurationException(attribute + " is not set");
}
private class LdapConfigurationException extends RuntimeException {
- public LdapConfigurationException(String s) {
+ public LdapConfigurationException (String s) {
super(s);
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/LdapAuth3.java b/full/src/main/java/de/ids_mannheim/korap/authentication/LdapAuth3.java
index 15b1b56..845a6d5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/LdapAuth3.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/LdapAuth3.java
@@ -34,7 +34,6 @@
import de.ids_mannheim.korap.server.EmbeddedLdapServer;
-
/**
* LDAP Login
*
@@ -54,7 +53,7 @@
private static Logger jlog = LogManager.getLogger(LdapAuth3.class);
- public static String getErrMessage(int code) {
+ public static String getErrMessage (int code) {
switch (code) {
case LDAP_AUTH_ROK:
return "LDAP Authentication successful.";
@@ -77,7 +76,8 @@
}
}
- public static int login(String login, String password, String ldapConfigFilename) throws LDAPException {
+ public static int login (String login, String password,
+ String ldapConfigFilename) throws LDAPException {
LDAPConfig ldapConfig = new LDAPConfig(ldapConfigFilename);
login = Filter.encodeValue(login);
@@ -86,16 +86,21 @@
if (ldapConfig.useEmbeddedServer) {
try {
EmbeddedLdapServer.startIfNotRunning(ldapConfig);
- } catch (GeneralSecurityException | UnknownHostException | LDAPException e) {
+ }
+ catch (GeneralSecurityException | UnknownHostException
+ | LDAPException e) {
throw new RuntimeException(e);
}
}
- LdapAuth3Result ldapAuth3Result = search(login, password, ldapConfig, !ldapConfig.searchFilter.contains("${password}"), true);
+ LdapAuth3Result ldapAuth3Result = search(login, password, ldapConfig,
+ !ldapConfig.searchFilter.contains("${password}"), true);
SearchResult srchRes = ldapAuth3Result.getSearchResultValue();
- if (ldapAuth3Result.getErrorCode() != 0 || srchRes == null || srchRes.getEntryCount() == 0) {
- if (DEBUGLOG) System.out.printf("Finding '%s': no entry found!\n", login);
+ if (ldapAuth3Result.getErrorCode() != 0 || srchRes == null
+ || srchRes.getEntryCount() == 0) {
+ if (DEBUGLOG)
+ System.out.printf("Finding '%s': no entry found!\n", login);
return ldapAuth3Result.getErrorCode();
}
@@ -103,7 +108,9 @@
}
@NotNull
- public static LdapAuth3Result search(String login, String password, LDAPConfig ldapConfig, boolean bindWithFoundDN, boolean applyExtraFilters) {
+ public static LdapAuth3Result search (String login, String password,
+ LDAPConfig ldapConfig, boolean bindWithFoundDN,
+ boolean applyExtraFilters) {
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("login", login);
valuesMap.put("password", password);
@@ -117,7 +124,8 @@
if (DEBUGLOG) {
//System.out.printf("LDAP Version = %d.\n", LDAPConnection.LDAP_V3);
- System.out.printf("LDAP Host & Port = '%s':%d.\n", ldapConfig.host, ldapConfig.port);
+ System.out.printf("LDAP Host & Port = '%s':%d.\n", ldapConfig.host,
+ ldapConfig.port);
System.out.printf("Login User = '%s'\n", login);
System.out.println("LDAPS " + ldapConfig.useSSL);
}
@@ -127,81 +135,117 @@
if (ldapConfig.useSSL) {
try {
SSLUtil sslUtil;
- if (ldapConfig.trustStorePath != null && !ldapConfig.trustStorePath.isEmpty()) {
- sslUtil = new SSLUtil(new TrustStoreTrustManager(ldapConfig.trustStorePath));
- } else {
+ if (ldapConfig.trustStorePath != null
+ && !ldapConfig.trustStorePath.isEmpty()) {
+ sslUtil = new SSLUtil(new TrustStoreTrustManager(
+ ldapConfig.trustStorePath));
+ }
+ else {
sslUtil = new SSLUtil(new TrustAllTrustManager());
}
- if (ldapConfig.additionalCipherSuites != null && !ldapConfig.additionalCipherSuites.isEmpty()) {
+ if (ldapConfig.additionalCipherSuites != null
+ && !ldapConfig.additionalCipherSuites.isEmpty()) {
addSSLCipherSuites(ldapConfig.additionalCipherSuites);
}
- SSLSocketFactory socketFactory = sslUtil.createSSLSocketFactory();
+ SSLSocketFactory socketFactory = sslUtil
+ .createSSLSocketFactory();
lc = new LDAPConnection(socketFactory);
- } catch (GeneralSecurityException e) {
- System.err.printf("Error: login: Connecting to LDAPS Server: failed: '%s'!\n", e);
+ }
+ catch (GeneralSecurityException e) {
+ System.err.printf(
+ "Error: login: Connecting to LDAPS Server: failed: '%s'!\n",
+ e);
ldapTerminate(null);
return new LdapAuth3Result(null, LDAP_AUTH_RCONNECT);
}
- } else {
+ }
+ else {
lc = new LDAPConnection();
}
try {
lc.connect(ldapConfig.host, ldapConfig.port);
- if (DEBUGLOG && ldapConfig.useSSL) System.out.println("LDAPS Connection = OK\n");
- if (DEBUGLOG && !ldapConfig.useSSL) System.out.println("LDAP Connection = OK\n");
- } catch (LDAPException e) {
- String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
- System.err.printf("Error: login: Connecting to LDAP Server: failed: '%s'!\n", fullStackTrace);
+ if (DEBUGLOG && ldapConfig.useSSL)
+ System.out.println("LDAPS Connection = OK\n");
+ if (DEBUGLOG && !ldapConfig.useSSL)
+ System.out.println("LDAP Connection = OK\n");
+ }
+ catch (LDAPException e) {
+ String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils
+ .getFullStackTrace(e);
+ System.err.printf(
+ "Error: login: Connecting to LDAP Server: failed: '%s'!\n",
+ fullStackTrace);
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RCONNECT);
}
- if (DEBUGLOG) System.out.printf("Debug: isConnected=%d\n", lc.isConnected() ? 1 : 0);
+ if (DEBUGLOG)
+ System.out.printf("Debug: isConnected=%d\n",
+ lc.isConnected() ? 1 : 0);
try {
// bind to server:
- if (DEBUGLOG) System.out.printf("Binding with '%s' ...\n", ldapConfig.sLoginDN);
+ if (DEBUGLOG)
+ System.out.printf("Binding with '%s' ...\n",
+ ldapConfig.sLoginDN);
lc.bind(ldapConfig.sLoginDN, ldapConfig.sPwd);
- if (DEBUGLOG) System.out.print("Binding: OK.\n");
- } catch (LDAPException e) {
+ if (DEBUGLOG)
+ System.out.print("Binding: OK.\n");
+ }
+ catch (LDAPException e) {
System.err.printf("Error: login: Binding failed: '%s'!\n", e);
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RINTERR);
}
- if (DEBUGLOG) System.out.printf("Debug: isConnected=%d\n", lc.isConnected() ? 1 : 0);
+ if (DEBUGLOG)
+ System.out.printf("Debug: isConnected=%d\n",
+ lc.isConnected() ? 1 : 0);
- if (DEBUGLOG) System.out.printf("Finding user '%s'...\n", login);
+ if (DEBUGLOG)
+ System.out.printf("Finding user '%s'...\n", login);
SearchResult srchRes = null;
try {
- if (DEBUGLOG) System.out.printf("Searching with searchFilter: '%s'.\n", insensitiveSearchFilter);
+ if (DEBUGLOG)
+ System.out.printf("Searching with searchFilter: '%s'.\n",
+ insensitiveSearchFilter);
- srchRes = lc.search(ldapConfig.searchBase, SearchScope.SUB, searchFilterInstance);
+ srchRes = lc.search(ldapConfig.searchBase, SearchScope.SUB,
+ searchFilterInstance);
- if (DEBUGLOG) System.out.printf("Found '%s': %d entries.\n", login, srchRes.getEntryCount());
- } catch (LDAPSearchException e) {
+ if (DEBUGLOG)
+ System.out.printf("Found '%s': %d entries.\n", login,
+ srchRes.getEntryCount());
+ }
+ catch (LDAPSearchException e) {
System.err.printf("Error: Search for User failed: '%s'!\n", e);
}
if (srchRes == null || srchRes.getEntryCount() == 0) {
- if (DEBUGLOG) System.out.printf("Finding '%s': no entry found!\n", login);
+ if (DEBUGLOG)
+ System.out.printf("Finding '%s': no entry found!\n", login);
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RUNKNOWN);
}
if (bindWithFoundDN) {
String matchedDN = srchRes.getSearchEntries().get(0).getDN();
- if (DEBUGLOG) System.out.printf("Requested bind for found user %s' failed.\n", matchedDN);
+ if (DEBUGLOG)
+ System.out.printf("Requested bind for found user %s' failed.\n",
+ matchedDN);
try {
// bind to server:
- if (DEBUGLOG) System.out.printf("Binding with '%s' ...\n", matchedDN);
+ if (DEBUGLOG)
+ System.out.printf("Binding with '%s' ...\n", matchedDN);
BindResult bindResult = lc.bind(matchedDN, password);
- if (DEBUGLOG) System.out.print("Binding: OK.\n");
+ if (DEBUGLOG)
+ System.out.print("Binding: OK.\n");
if (!bindResult.getResultCode().equals(ResultCode.SUCCESS)) {
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RUNKNOWN);
}
- } catch (LDAPException e) {
+ }
+ catch (LDAPException e) {
System.err.printf("Error: login: Binding failed: '%s'!\n", e);
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RUNKNOWN);
@@ -209,16 +253,21 @@
}
if (applyExtraFilters) {
- if (ldapConfig.authFilter != null && !ldapConfig.authFilter.isEmpty()) {
- srchRes = applyAdditionalFilter(login, ldapConfig, ldapConfig.authFilter, searchFilterInstance, lc);
+ if (ldapConfig.authFilter != null
+ && !ldapConfig.authFilter.isEmpty()) {
+ srchRes = applyAdditionalFilter(login, ldapConfig,
+ ldapConfig.authFilter, searchFilterInstance, lc);
if (srchRes == null || srchRes.getEntryCount() == 0) {
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RNOTREG);
}
}
- if (ldapConfig.userNotBlockedFilter != null && !ldapConfig.userNotBlockedFilter.isEmpty()) {
- srchRes = applyAdditionalFilter(login, ldapConfig, ldapConfig.userNotBlockedFilter, searchFilterInstance, lc);
+ if (ldapConfig.userNotBlockedFilter != null
+ && !ldapConfig.userNotBlockedFilter.isEmpty()) {
+ srchRes = applyAdditionalFilter(login, ldapConfig,
+ ldapConfig.userNotBlockedFilter, searchFilterInstance,
+ lc);
if (srchRes == null || srchRes.getEntryCount() == 0) {
ldapTerminate(lc);
return new LdapAuth3Result(null, LDAP_AUTH_RLOCKED);
@@ -230,26 +279,37 @@
return new LdapAuth3Result(srchRes, LDAP_AUTH_ROK);
}
- private static SearchResult applyAdditionalFilter(String login, LDAPConfig ldapConfig, String searchFilterInstance, String extraFilter, LDAPConnection lc) {
+ private static SearchResult applyAdditionalFilter (String login,
+ LDAPConfig ldapConfig, String searchFilterInstance,
+ String extraFilter, LDAPConnection lc) {
SearchResult srchRes;
srchRes = null;
try {
- String combindedFilterInstance = "(&" + searchFilterInstance + extraFilter + ")";
- if (DEBUGLOG) System.out.printf("Searching with additional Filter: '%s'.\n", extraFilter);
- srchRes = lc.search(ldapConfig.searchBase, SearchScope.SUB, combindedFilterInstance);
- if (DEBUGLOG) System.out.printf("Found '%s': %d entries.\n", login, srchRes.getEntryCount());
- } catch (LDAPSearchException e) {
+ String combindedFilterInstance = "(&" + searchFilterInstance
+ + extraFilter + ")";
+ if (DEBUGLOG)
+ System.out.printf("Searching with additional Filter: '%s'.\n",
+ extraFilter);
+ srchRes = lc.search(ldapConfig.searchBase, SearchScope.SUB,
+ combindedFilterInstance);
+ if (DEBUGLOG)
+ System.out.printf("Found '%s': %d entries.\n", login,
+ srchRes.getEntryCount());
+ }
+ catch (LDAPSearchException e) {
System.err.printf("Error: Search for User failed: '%s'!\n", e);
}
return srchRes;
}
- public static String getEmail(String sUserDN, String ldapConfigFilename) throws LDAPException {
+ public static String getEmail (String sUserDN, String ldapConfigFilename)
+ throws LDAPException {
String sUserPwd = "*";
LDAPConfig ldapConfig = new LDAPConfig(ldapConfigFilename);
final String emailAttribute = ldapConfig.emailAttribute;
- SearchResult searchResult = search(sUserDN, sUserPwd, ldapConfig, false, false).getSearchResultValue();
+ SearchResult searchResult = search(sUserDN, sUserPwd, ldapConfig, false,
+ false).getSearchResultValue();
if (searchResult == null) {
return null;
@@ -263,41 +323,44 @@
}
return null;
}
-
- public static String getUsername(String sUserDN, String ldapConfigFilename) throws LDAPException {
+
+ public static String getUsername (String sUserDN, String ldapConfigFilename)
+ throws LDAPException {
String sUserPwd = "*";
LDAPConfig ldapConfig = new LDAPConfig(ldapConfigFilename);
final String idsC2Attribute = "idsC2Profile";
final String uidAttribute = "uid";
-
- SearchResult searchResult = search(sUserDN, sUserPwd, ldapConfig, false, false)
- .getSearchResultValue();
+
+ SearchResult searchResult = search(sUserDN, sUserPwd, ldapConfig, false,
+ false).getSearchResultValue();
if (searchResult == null) {
return null;
}
-
+
String username = null;
for (SearchResultEntry entry : searchResult.getSearchEntries()) {
username = entry.getAttributeValue(idsC2Attribute);
if (username == null) {
username = entry.getAttributeValue(uidAttribute);
- jlog.warn("idsC2Profile not found for uid: "+username);
+ jlog.warn("idsC2Profile not found for uid: " + username);
}
}
return username;
}
- public static void ldapTerminate(LDAPConnection lc) {
- if (DEBUGLOG) System.out.println("Terminating...");
+ public static void ldapTerminate (LDAPConnection lc) {
+ if (DEBUGLOG)
+ System.out.println("Terminating...");
if (lc != null) {
lc.close(null);
}
- if (DEBUGLOG) System.out.println("closing connection: done.\n");
+ if (DEBUGLOG)
+ System.out.println("closing connection: done.\n");
}
- private static void addSSLCipherSuites(String ciphersCsv) {
+ private static void addSSLCipherSuites (String ciphersCsv) {
// add e.g. TLS_RSA_WITH_AES_256_GCM_SHA384
Set<String> ciphers = new HashSet<>();
ciphers.addAll(SSLUtil.getEnabledSSLCipherSuites());
@@ -309,21 +372,20 @@
final int errorCode;
final Object value;
-
- public LdapAuth3Result(Object value, int errorCode) {
+ public LdapAuth3Result (Object value, int errorCode) {
this.errorCode = errorCode;
this.value = value;
}
- public int getErrorCode() {
+ public int getErrorCode () {
return errorCode;
}
- public Object getValue() {
+ public Object getValue () {
return value;
}
- public SearchResult getSearchResultValue() {
+ public SearchResult getSearchResultValue () {
return (SearchResult) value;
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/LoginCounter.java b/full/src/main/java/de/ids_mannheim/korap/authentication/LoginCounter.java
index aeb2856..1e08647 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/LoginCounter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/LoginCounter.java
@@ -30,12 +30,10 @@
this.failedLogins = new HashMap<>();
}
-
public void resetFailedCounter (String username) {
failedLogins.remove(username);
}
-
public void registerFail (String username) {
long expires = TimeUtils.plusSeconds(config.getLoginAttemptTTL())
.getMillis();
@@ -49,11 +47,10 @@
set[1] = expires;
failedLogins.put(username, set);
- jlog.warn("user failed to login "+
- Arrays.asList(failedLogins.get(username)));
+ jlog.warn("user failed to login "
+ + Arrays.asList(failedLogins.get(username)));
}
-
public boolean validate (String username) {
Long[] set = failedLogins.get(username);
if (set != null) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/OAuth2Authentication.java b/full/src/main/java/de/ids_mannheim/korap/authentication/OAuth2Authentication.java
index 80a3773..3f569fb 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/OAuth2Authentication.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/OAuth2Authentication.java
@@ -16,7 +16,8 @@
import de.ids_mannheim.korap.security.context.TokenContext;
import de.ids_mannheim.korap.user.User;
-/** Authentication provider for Bearer tokens
+/**
+ * Authentication provider for Bearer tokens
*
* @author margaretha
*
@@ -44,7 +45,8 @@
TokenContext c = new TokenContext();
c.setUsername(accessToken.getUserId());
- c.setExpirationTime(accessToken.getExpiryDate().toInstant().toEpochMilli());
+ c.setExpirationTime(
+ accessToken.getExpiryDate().toInstant().toEpochMilli());
c.setToken(authToken);
c.setTokenType(TokenType.BEARER);
c.addContextParameter(Attributes.SCOPE, scopes);
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/SessionAuthentication.java b/full/src/main/java/de/ids_mannheim/korap/authentication/SessionAuthentication.java
index f4aa637..7d63c56 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/SessionAuthentication.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/SessionAuthentication.java
@@ -30,13 +30,12 @@
private static final Logger jlog = LogManager
.getLogger(SessionAuthentication.class);
public static boolean DEBUG = false;
-
+
public static SessionFactory sessions;
private ScheduledThreadPoolExecutor scheduled;
private EncryptionIface crypto;
private KustvaktConfiguration config;
-
public SessionAuthentication (KustvaktConfiguration config,
EncryptionIface crypto) {
jlog.info("initialize session authentication handler");
@@ -50,9 +49,8 @@
this.config.getInactiveTime(), TimeUnit.SECONDS);
}
-
@Override
- public TokenContext getTokenContext(String authenticationToken)
+ public TokenContext getTokenContext (String authenticationToken)
throws KustvaktException {
if (DEBUG) {
jlog.debug(
@@ -61,9 +59,8 @@
return this.sessions.getSession(authenticationToken);
}
-
@Override
- public TokenContext createTokenContext(User user, Map<String, Object> attr)
+ public TokenContext createTokenContext (User user, Map<String, Object> attr)
throws KustvaktException {
DateTime now = TimeUtils.getNow();
DateTime ex = TimeUtils.getExpiration(now.getMillis(),
@@ -74,23 +71,22 @@
ctx.setUsername(user.getUsername());
ctx.setTokenType(TokenType.SESSION);
ctx.setToken(token);
- ctx.setExpirationTime(ex.getMillis()+(1000));
+ ctx.setExpirationTime(ex.getMillis() + (1000));
ctx.setHostAddress(attr.get(Attributes.HOST).toString());
ctx.setUserAgent(attr.get(Attributes.USER_AGENT).toString());
this.sessions.putSession(token, ctx);
if (DEBUG) {
jlog.debug(ctx.toJson());
- jlog.debug("session " +sessions.getSession(token).toString());
+ jlog.debug("session " + sessions.getSession(token).toString());
jlog.info("create session for user: " + user.getUsername());
}
return ctx;
}
-
-// @Override
-// public void removeUserSession (String token) {
-// this.sessions.removeSession(token);
-// }
+ // @Override
+ // public void removeUserSession (String token) {
+ // this.sessions.removeSession(token);
+ // }
@Override
public TokenType getTokenType () {
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/SessionFactory.java b/full/src/main/java/de/ids_mannheim/korap/authentication/SessionFactory.java
index 62c7442..55b3e42 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/SessionFactory.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/SessionFactory.java
@@ -42,7 +42,6 @@
private final boolean multipleEnabled;
private final int inactive;
-
public SessionFactory (boolean multipleEnabled, int inactive) {
if (DEBUG) {
jlog.debug("allow multiple sessions per user: " + multipleEnabled);
@@ -54,7 +53,6 @@
this.loggedInRecord = new ConcurrentMultiMap<>();
}
-
public boolean hasSession (TokenContext context) {
if (context.getUsername().equalsIgnoreCase(DemoUser.DEMOUSER_NAME))
return false;
@@ -79,10 +77,9 @@
throw new KustvaktException(StatusCodes.EXPIRED);
}
- return context;
+ return context;
}
-
//todo: ?!
@CacheEvict(value = "session", key = "#session.token")
public void putSession (final String token, final TokenContext activeUser)
@@ -98,7 +95,6 @@
}
}
-
public void removeAll (final TokenContext activeUser) {
for (String existing : loggedInRecord.get(activeUser.getUsername())) {
timeCheck.remove(existing);
@@ -107,7 +103,6 @@
loggedInRecord.remove(activeUser.getUsername());
}
-
@CacheEvict(value = "session", key = "#session.token")
public void removeSession (String token) {
String username = sessionsObject.get(token).getUsername();
@@ -118,7 +113,6 @@
sessionsObject.remove(token);
}
-
/**
* reset inactive time interval to 0
*
@@ -128,7 +122,6 @@
timeCheck.put(token, TimeUtils.getNow());
}
-
/**
* if user possesses a valid non-expired session token
*
@@ -137,19 +130,22 @@
*/
private boolean isUserSessionValid (String token) {
if (timeCheck.containsKey(token)) {
- if (TimeUtils.plusSeconds(timeCheck.get(token).getMillis(),
- inactive).isAfterNow()) {
- if (DEBUG){ jlog.debug("user has session");}
+ if (TimeUtils
+ .plusSeconds(timeCheck.get(token).getMillis(), inactive)
+ .isAfterNow()) {
+ if (DEBUG) {
+ jlog.debug("user has session");
+ }
return true;
}
- else if (DEBUG){
- jlog.debug("user with token "+token+" has an invalid session");
+ else if (DEBUG) {
+ jlog.debug(
+ "user with token " + token + " has an invalid session");
}
}
return false;
}
-
/**
* clean inactive sessions from session object
* TODO: persist userdata to database when session times out!
@@ -160,22 +156,21 @@
for (Entry<String, DateTime> entry : timeCheck.entrySet()) {
if (!isUserSessionValid(entry.getKey())) {
TokenContext user = sessionsObject.get(entry.getKey());
- jlog.trace("removing user session for user "+
- user.getUsername());
+ jlog.trace(
+ "removing user session for user " + user.getUsername());
inactive.add(user.getUsername());
removeSession(entry.getKey());
}
}
// fixme: not doing anything!
- if (inactive.size() > 0){
- if (DEBUG){
- jlog.trace("removing inactive user session for users "+
- inactive);
+ if (inactive.size() > 0) {
+ if (DEBUG) {
+ jlog.trace(
+ "removing inactive user session for users " + inactive);
}
}
}
-
/**
* run cleanup-thread
*/
@@ -183,6 +178,6 @@
public void run () {
timeoutMaintenance();
if (loggedInRecord.size() > 0)
- jlog.debug("logged users: "+ loggedInRecord.toString());
+ jlog.debug("logged users: " + loggedInRecord.toString());
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/http/AuthorizationData.java b/full/src/main/java/de/ids_mannheim/korap/authentication/http/AuthorizationData.java
index 236f26a..a0ebd57 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/http/AuthorizationData.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/http/AuthorizationData.java
@@ -4,7 +4,9 @@
import lombok.Getter;
import lombok.Setter;
-/** Describes the values stored in Authorization header of HTTP requests.
+/**
+ * Describes the values stored in Authorization header of HTTP
+ * requests.
*
* @author margaretha
*
@@ -19,4 +21,3 @@
private String password;
}
-
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/http/TransferEncoding.java b/full/src/main/java/de/ids_mannheim/korap/authentication/http/TransferEncoding.java
index 52d1a90..305406c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/http/TransferEncoding.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/http/TransferEncoding.java
@@ -6,19 +6,24 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.ParameterChecker;
-/** TransferEncoding contains encoding and decoding methods for data transfer,
- * e.g. transfering credentials using basic Http authentication.
- *
+/**
+ * TransferEncoding contains encoding and decoding methods for data
+ * transfer,
+ * e.g. transfering credentials using basic Http authentication.
+ *
* @author margaretha
*
*/
@Component
public class TransferEncoding {
- /** Encodes username and password using Base64.
+ /**
+ * Encodes username and password using Base64.
*
- * @param username username
- * @param password password
+ * @param username
+ * username
+ * @param password
+ * password
* @return
*/
public static String encodeBase64 (String username, String password) {
@@ -26,11 +31,12 @@
return new String(Base64.encodeBase64(s.getBytes()));
}
- /** Decodes the given string using Base64.
+ /**
+ * Decodes the given string using Base64.
*
- * @param encodedStr
+ * @param encodedStr
* @return username and password as an array of strings.
- * @throws KustvaktException
+ * @throws KustvaktException
*/
public static String[] decodeBase64 (String encodedStr)
throws KustvaktException {
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/Attributes.java b/full/src/main/java/de/ids_mannheim/korap/config/Attributes.java
index e2e4ed5..dde3291 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/Attributes.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/Attributes.java
@@ -4,17 +4,17 @@
public static final String AUTHENTICATION_TIME = "auth_time";
public static final String DEFAULT_TIME_ZONE = "Europe/Berlin";
-
+
public static final String AUTHORIZATION = "Authorization";
// moved to de.ids_mannheim.korap.config.AuthenticationScheme
-// public static final String SESSION_AUTHENTICATION = "session_token";
-// public static final String API_AUTHENTICATION = "api_token";
-// public static final String OAUTH2_AUTHORIZATION = "bearer";
-// public static final String BASIC_AUTHENTICATION = "basic";
+ // public static final String SESSION_AUTHENTICATION = "session_token";
+ // public static final String API_AUTHENTICATION = "api_token";
+ // public static final String OAUTH2_AUTHORIZATION = "bearer";
+ // public static final String BASIC_AUTHENTICATION = "basic";
public static final String LOCATION = "location"; // location of Client: User.INTERN/EXTERN
public static final String CORPUS_ACCESS = "corpusAccess"; // User.ALL/PUB/FREE.
-
+
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String SCOPE = "scope";
@@ -99,7 +99,7 @@
public static final String TEXT_SIGLE = "textSigle";
public static final String AVAILABILITY = "availability";
-
+
public static final String REF_CORPUS = "refCorpus";
public static final String QUERY = "query";
public static final String CACHE = "cache";
@@ -147,7 +147,7 @@
public static final String DEFAULT_FOUNDRY_RELATION = "relation-foundry";
public static final String DEFAULT_FOUNDRY_MORPHOLOGY = "morphology-foundry";
public static final String DEFAULT_FOUNDRY_STRUCTURE = "structure-foundry";
-
+
/**
* db column keys
*/
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/BeansFactory.java b/full/src/main/java/de/ids_mannheim/korap/config/BeansFactory.java
index 46d319e..2616870 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/BeansFactory.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/BeansFactory.java
@@ -20,33 +20,29 @@
private static ContextHolder beanHolder;
-
//todo: allow this for external plugin systems that are not kustvakt specific
@Deprecated
public static void setCustomBeansHolder (ContextHolder holder) {
beanHolder = holder;
}
-
public static synchronized ContextHolder getKustvaktContext () {
return beanHolder;
}
-
public static synchronized ContextHolder getKustvaktContext (int i) {
return beanHolder;
}
-
public static synchronized TypeBeanFactory getTypeFactory () {
return new TypeBeanFactory();
}
-
public static int loadClasspathContext (String ... files) {
ApplicationContext context;
if (files.length == 0)
- throw new IllegalArgumentException("Spring XML config file is not specified.");
+ throw new IllegalArgumentException(
+ "Spring XML config file is not specified.");
else
context = new ClassPathXmlApplicationContext(files);
ContextHolder h = new ContextHolder(context) {};
@@ -55,7 +51,6 @@
return 0;
}
-
public static synchronized int addApplicationContext (
ApplicationContext context) {
ContextHolder h = new ContextHolder(context) {};
@@ -64,12 +59,10 @@
return 0;
}
-
public static synchronized void setKustvaktContext (ContextHolder holder) {
BeansFactory.beanHolder = holder;
}
-
public static synchronized int setApplicationContext (
ApplicationContext context) {
ContextHolder h = new ContextHolder(context) {};
@@ -77,7 +70,6 @@
return 0;
}
-
public static synchronized int loadFileContext (String filepath) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"file:" + filepath);
@@ -86,19 +78,16 @@
return 0;
}
-
public static void closeApplication () {
BeansFactory.beanHolder = null;
}
-
//todo: set response handler
@Deprecated
public static CoreResponseHandler getResponseHandler () {
return null;
}
-
public BeansFactory () {}
public static class TypeBeanFactory {
@@ -116,7 +105,6 @@
+ "'");
}
-
@Deprecated
public <T> T getTypedBean (Collection objs, Class type) {
for (Object o : objs) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/ConfigLoader.java b/full/src/main/java/de/ids_mannheim/korap/config/ConfigLoader.java
index 9fcc3bd..a8ec0a0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/ConfigLoader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/ConfigLoader.java
@@ -16,10 +16,8 @@
private static final Logger jlog = LogManager.getLogger(ConfigLoader.class);
-
private ConfigLoader () {}
-
public static InputStream loadConfigStream (String name) {
InputStream stream = null;
try {
@@ -31,25 +29,27 @@
}
else {
jlog.info("Loading config '" + name + "' from classpath!");
- stream = ConfigLoader.class.getClassLoader().getResourceAsStream(
- name);
+ stream = ConfigLoader.class.getClassLoader()
+ .getResourceAsStream(name);
}
}
catch (IOException e) {
// do nothing
}
if (stream == null)
- throw new RuntimeException("Config file '"+name+"' could not be loaded ...");
+ throw new RuntimeException(
+ "Config file '" + name + "' could not be loaded ...");
return stream;
}
-
- public static Properties loadProperties (String name){
+ public static Properties loadProperties (String name) {
Properties p = new Properties();
try {
p.load(loadConfigStream(name));
- } catch (IOException e) {
- throw new RuntimeException("Properties from config file '"+name+"' could not be loaded ...");
+ }
+ catch (IOException e) {
+ throw new RuntimeException("Properties from config file '" + name
+ + "' could not be loaded ...");
}
return p;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java b/full/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
index 7626ec1..3d26bcc 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
@@ -27,7 +27,6 @@
private ApplicationContext context = null;
private DefaultHandler handler;
-
public ContextHolder (ApplicationContext context) {
this.handler = new DefaultHandler();
this.context = context;
@@ -35,7 +34,6 @@
new CoreResponseHandler();
}
-
protected <T> T getBean (Class<T> clazz) {
if (this.context != null) {
try {
@@ -48,7 +46,6 @@
return this.handler.getDefault(clazz);
}
-
protected <T> T getBean (String name) {
T bean = null;
if (this.context != null) {
@@ -64,7 +61,6 @@
return bean;
}
-
@Deprecated
public <T extends KustvaktConfiguration> T getConfiguration () {
return (T) getBean(KUSTVAKT_CONFIG);
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/DefaultHandler.java b/full/src/main/java/de/ids_mannheim/korap/config/DefaultHandler.java
index 982985f..df7be47 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/DefaultHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/DefaultHandler.java
@@ -12,13 +12,11 @@
private Map<String, Object> defaults;
-
public DefaultHandler () {
this.defaults = new HashMap<>();
loadClasses();
}
-
private void loadClasses () {
Set<Class<?>> cls = KustvaktClassLoader
.loadFromAnnotation(Configurable.class);
@@ -34,12 +32,10 @@
}
}
-
public Object getDefault (String name) {
return this.defaults.get(name);
}
-
public <T> T getDefault (Class<T> tClass) {
for (Object o : this.defaults.values()) {
if (o.getClass().equals(tClass))
@@ -48,12 +44,10 @@
return null;
}
-
public void remove (String name) {
this.defaults.remove(name);
}
-
@Override
public String toString () {
return defaults.toString();
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java b/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
index a1ba12f..0a904d3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
@@ -26,7 +26,7 @@
*/
public class FullConfiguration extends KustvaktConfiguration {
- public static Logger jlog = LogManager.getLogger(FullConfiguration.class);
+ public static Logger jlog = LogManager.getLogger(FullConfiguration.class);
// mail configuration
private boolean isMailEnabled;
private String testEmail;
@@ -63,19 +63,19 @@
private int refreshTokenLongExpiry;
private int refreshTokenExpiry;
private int authorizationCodeExpiry;
-
+
private int maxNumberOfUserQueries;
-
+
private URL issuer;
private String namedVCPath;
-
+
private boolean createInitialSuperClient;
public FullConfiguration (Properties properties) throws Exception {
super(properties);
}
-
+
public FullConfiguration () {
super();
}
@@ -97,23 +97,24 @@
setOAuth2Configuration(properties);
setNamedVCPath(properties.getProperty("krill.namedVC", ""));
-
-// Cache cache = CacheManager.newInstance().getCache("named_vc");
-// CacheConfiguration config = cache.getCacheConfiguration();
-// config.setMaxBytesLocalHeap(properties.getProperty("cache.max.bytes.local.heap", "256m"));
-// config.setMaxBytesLocalDisk(properties.getProperty("cache.max.bytes.local.disk", "2G"));
-// jlog.info("max local heap:"+config.getMaxBytesLocalHeapAsString());
-// jlog.info("max local disk:"+config.getMaxBytesLocalDiskAsString());
-
+
+ // Cache cache = CacheManager.newInstance().getCache("named_vc");
+ // CacheConfiguration config = cache.getCacheConfiguration();
+ // config.setMaxBytesLocalHeap(properties.getProperty("cache.max.bytes.local.heap", "256m"));
+ // config.setMaxBytesLocalDisk(properties.getProperty("cache.max.bytes.local.disk", "2G"));
+ // jlog.info("max local heap:"+config.getMaxBytesLocalHeapAsString());
+ // jlog.info("max local disk:"+config.getMaxBytesLocalDiskAsString());
+
setMaxNumberOfUserQueries(Integer.parseInt(
properties.getProperty("max.user.persistent.queries", "20")));
}
- private void setSecurityConfiguration (Properties properties) throws MalformedURLException {
+ private void setSecurityConfiguration (Properties properties)
+ throws MalformedURLException {
setSecureHashAlgorithm(Enum.valueOf(EncryptionIface.Encryption.class,
properties.getProperty("security.secure.hash.algorithm",
"BCRYPT")));
-
+
String issuerStr = properties.getProperty("security.jwt.issuer",
"https://korap.ids-mannheim.de");
@@ -129,8 +130,8 @@
"oauth2.password.authentication", "TEST")));
setNativeClientHost(properties.getProperty("oauth2.native.client.host",
"korap.ids-mannheim.de"));
- setCreateInitialSuperClient(Boolean.valueOf(
- properties.getProperty("oauth2.initial.super.client", "false")));
+ setCreateInitialSuperClient(Boolean.valueOf(properties
+ .getProperty("oauth2.initial.super.client", "false")));
setMaxAuthenticationAttempts(Integer
.parseInt(properties.getProperty("oauth2.max.attempts", "1")));
@@ -146,11 +147,11 @@
properties.getProperty("oauth2.refresh.token.expiry", "90D"));
authorizationCodeExpiry = TimeUtils.convertTimeToSeconds(properties
.getProperty("oauth2.authorization.code.expiry", "10M"));
-
- setAccessTokenLongExpiry(TimeUtils.convertTimeToSeconds(
- properties.getProperty("oauth2.access.token.long.expiry", "365D")));
- setRefreshTokenLongExpiry(TimeUtils.convertTimeToSeconds(
- properties.getProperty("oauth2.refresh.token.long.expiry", "365D")));
+
+ setAccessTokenLongExpiry(TimeUtils.convertTimeToSeconds(properties
+ .getProperty("oauth2.access.token.long.expiry", "365D")));
+ setRefreshTokenLongExpiry(TimeUtils.convertTimeToSeconds(properties
+ .getProperty("oauth2.refresh.token.long.expiry", "365D")));
}
private void setMailConfiguration (Properties properties) {
@@ -476,7 +477,7 @@
public boolean createInitialSuperClient () {
return createInitialSuperClient;
}
-
+
public void setCreateInitialSuperClient (boolean initialSuperClient) {
this.createInitialSuperClient = initialSuperClient;
}
@@ -488,5 +489,5 @@
public void setMaxNumberOfUserQueries (int maxNumberOfUserQueries) {
this.maxNumberOfUserQueries = maxNumberOfUserQueries;
}
-
+
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java b/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
index 63ec65e..d8f3341 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
@@ -40,13 +40,12 @@
private static Logger jlog = LogManager.getLogger(JWTSigner.class);
public static boolean DEBUG = false;
-
+
private URL issuer;
private JWSSigner signer;
private JWSVerifier verifier;
private final int defaultttl;
-
public JWTSigner (final byte[] secret, URL issuer, final int defaulttl)
throws JOSEException {
this.issuer = issuer;
@@ -55,18 +54,15 @@
this.defaultttl = defaulttl;
}
-
public JWTSigner (final byte[] secret, String issuer)
throws MalformedURLException, JOSEException {
this(secret, new URL(issuer), 72 * 60 * 60);
}
-
public SignedJWT createJWT (User user, Map<String, Object> attr) {
return signContent(user, attr, defaultttl);
}
-
public SignedJWT signContent (User user, Map<String, Object> attr,
int ttl) {
String scopes;
@@ -91,11 +87,12 @@
csBuilder.expirationTime(TimeUtils.getNow().plusSeconds(ttl).toDate());
csBuilder.claim(Attributes.AUTHENTICATION_TIME,
attr.get(Attributes.AUTHENTICATION_TIME));
-
+
JWTClaimsSet jwtClaimsSet = csBuilder.build();
- if (DEBUG) jlog.debug(jwtClaimsSet.getClaim(Attributes.AUTHENTICATION_TIME));
- SignedJWT signedJWT =
- new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), jwtClaimsSet);
+ if (DEBUG)
+ jlog.debug(jwtClaimsSet.getClaim(Attributes.AUTHENTICATION_TIME));
+ SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256),
+ jwtClaimsSet);
try {
signedJWT.sign(signer);
}
@@ -105,7 +102,6 @@
return signedJWT;
}
-
/**
* @param username
* @param json
@@ -115,14 +111,16 @@
String json, int ttl) {
Builder cs = new JWTClaimsSet.Builder();
cs.subject(username);
- if (!json.isEmpty()) cs.claim("data", json);
+ if (!json.isEmpty())
+ cs.claim("data", json);
cs.expirationTime(TimeUtils.getNow().plusSeconds(ttl).toDate());
cs.issuer(this.issuer.toString());
- if (!userclient.isEmpty()) cs.claim("userip", userclient);
+ if (!userclient.isEmpty())
+ cs.claim("userip", userclient);
- SignedJWT signedJWT =
- new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), cs.build());
+ SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256),
+ cs.build());
try {
signedJWT.sign(signer);
}
@@ -132,24 +130,20 @@
return signedJWT;
}
-
public SignedJWT signContent (String username, String userclient,
String json) {
return signContent(username, userclient, json, defaultttl);
}
-
public SignedJWT createSignedToken (String username) {
return createSignedToken(username, defaultttl);
}
-
// add client info
public SignedJWT createSignedToken (String username, int ttl) {
return signContent(username, "", "", ttl);
}
-
public SignedJWT verifyToken (String token) throws KustvaktException {
SignedJWT client;
try {
@@ -171,7 +165,6 @@
return client;
}
-
// does not care about expiration times
public String retrieveContent (String signedContent)
throws KustvaktException {
@@ -188,7 +181,6 @@
}
}
-
public TokenContext getTokenContext (String idtoken)
throws ParseException, JOSEException, KustvaktException {
SignedJWT signedJWT = verifyToken(idtoken);
@@ -202,10 +194,10 @@
c.setExpirationTime(
signedJWT.getJWTClaimsSet().getExpirationTime().getTime());
- Instant instant = Instant.ofEpochMilli((long) signedJWT.getJWTClaimsSet()
- .getClaim(Attributes.AUTHENTICATION_TIME));
- ZonedDateTime zonedAuthTime = ZonedDateTime.ofInstant(
- instant, ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ Instant instant = Instant.ofEpochMilli((long) signedJWT
+ .getJWTClaimsSet().getClaim(Attributes.AUTHENTICATION_TIME));
+ ZonedDateTime zonedAuthTime = ZonedDateTime.ofInstant(instant,
+ ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
c.setAuthenticationTime(zonedAuthTime);
c.setToken(idtoken);
c.addParams(signedJWT.getJWTClaimsSet().getClaims());
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktCacheable.java b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktCacheable.java
index a66486f..c8971ea 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktCacheable.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktCacheable.java
@@ -23,37 +23,33 @@
private String prefix;
private String name;
- public KustvaktCacheable(String cache_name, String prefix) {
+ public KustvaktCacheable (String cache_name, String prefix) {
init();
- if(!enabled())
+ if (!enabled())
createDefaultFileCache(cache_name);
this.prefix = prefix;
this.name = cache_name;
}
-
+
public KustvaktCacheable () {
// TODO Auto-generated constructor stub
}
- private static Cache getCache(String name) {
+ private static Cache getCache (String name) {
return CacheManager.getInstance().getCache(name);
}
-
- private void createDefaultFileCache(String name) {
- Cache default_cache = new Cache(
- new CacheConfiguration(name, 20000)
- .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
- .eternal(false)
- .timeToLiveSeconds(15000)
- .timeToIdleSeconds(5000)
- .diskExpiryThreadIntervalSeconds(0)
- .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)));
+ private void createDefaultFileCache (String name) {
+ Cache default_cache = new Cache(new CacheConfiguration(name, 20000)
+ .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
+ .eternal(false).timeToLiveSeconds(15000).timeToIdleSeconds(5000)
+ .diskExpiryThreadIntervalSeconds(0)
+ .persistence(new PersistenceConfiguration().strategy(
+ PersistenceConfiguration.Strategy.LOCALTEMPSWAP)));
if (!CacheManager.getInstance().cacheExists(name))
CacheManager.getInstance().addCache(default_cache);
}
-
public void init () {
if (!loaded) {
if (ServiceInfo.getInfo().getCacheable()) {
@@ -61,62 +57,62 @@
InputStream in = ConfigLoader.loadConfigStream(file);
CacheManager.newInstance(in);
loaded = true;
- } else {
+ }
+ else {
CacheManager.create();
}
}
}
- public boolean hasCacheEntry(Object key) {
+ public boolean hasCacheEntry (Object key) {
return getCache(this.name).isKeyInCache(createKey(key.toString()));
}
-
- public boolean enabled() {
+ public boolean enabled () {
// check that caching is enabled
return ServiceInfo.getInfo().getCacheable();
}
- public Object getCacheValue(Object key) {
+ public Object getCacheValue (Object key) {
Element e = getCache(this.name).get(createKey(key.toString()));
- if (e!= null)
+ if (e != null)
return e.getObjectValue();
return null;
}
- public long getCacheCreationTime(Object key) {
+ public long getCacheCreationTime (Object key) {
Element e = getCache(this.name).get(createKey(key.toString()));
- if (e!= null)
+ if (e != null)
return e.getCreationTime();
return -1;
}
- public void storeInCache(Object key, Object value) {
+ public void storeInCache (Object key, Object value) {
getCache(this.name).put(new Element(createKey(key.toString()), value));
}
- public void removeCacheEntry(Object key) {
+ public void removeCacheEntry (Object key) {
getCache(this.name).remove(createKey(key.toString()));
}
- public void clearCache() {
+ public void clearCache () {
Cache c = getCache(this.name);
if (enabled()) {
c.removeAll();
-// c.clearStatistics();
-
+ // c.clearStatistics();
+
}
}
- private String createKey(String input) {
- return StringUtils.toSHAHash(this.prefix+ "@" + input);
+ private String createKey (String input) {
+ return StringUtils.toSHAHash(this.prefix + "@" + input);
}
-
+
public Map<Object, Element> getAllCacheElements () {
Cache cache = getCache(name);
return cache.getAll(cache.getKeysWithExpiryCheck());
}
-
+
public List getKeysWithExpiryCheck () {
Cache cache = getCache(name);
return cache.getKeysWithExpiryCheck();
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktClassLoader.java b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktClassLoader.java
index 83100bc..860d373 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktClassLoader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktClassLoader.java
@@ -16,10 +16,8 @@
private static final Reflections reflections = new Reflections(
"de.ids_mannheim.korap");
-
private KustvaktClassLoader () {}
-
/**
* loads interface implementations in current classpath
*
@@ -31,13 +29,11 @@
return reflections.getSubTypesOf(iface);
}
-
public static Set<Class<?>> loadFromAnnotation (
Class<? extends Annotation> annotation) {
return reflections.getTypesAnnotatedWith(annotation);
}
-
public static <T> Class<? extends T> getTypeClass (Class type,
Class<T> iface) {
Set<Class<? extends T>> c = KustvaktClassLoader.loadSubTypes(iface);
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
index 40073b8..b838073 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
@@ -22,11 +22,12 @@
import lombok.Setter;
/**
- * Describes configuration for Kustvakt by importing properties
- * from kustvakt.conf file and setting default values if they are
- * not configured.
+ * Describes configuration for Kustvakt by importing properties
+ * from kustvakt.conf file and setting default values if they are
+ * not configured.
*
- * MH: if configuration class is extended, loadSubTypes method should be
+ * MH: if configuration class is extended, loadSubTypes method should
+ * be
* overriden
*
* @author hanl
@@ -41,7 +42,7 @@
public static final String DATA_FOLDER = "data";
private String vcInCaching;
-
+
private String indexDir;
private int port;
// todo: make exclusive so that the containg languages can really
@@ -94,7 +95,7 @@
// deprec?!
private final BACKENDS DEFAULT_ENGINE = BACKENDS.LUCENE;
private String networkEndpointURL;
-
+
// license patterns
protected Pattern publicLicensePattern;
protected Pattern freeLicensePattern;
@@ -107,28 +108,28 @@
// EM: metadata restriction
// another variable might be needed to define which metadata fields are restricted
private boolean isMetadataRestricted = false;
-
+
// EM: Maybe needed when we support pipe registration
@Deprecated
public static Map<String, String> pipes = new HashMap<>();
-
+
public KustvaktConfiguration (Properties properties) throws Exception {
load(properties);
-// readPipesFile("pipes");
+ // readPipesFile("pipes");
KrillProperties.setProp(properties);
}
public KustvaktConfiguration () {}
-
+
public void loadBasicProperties (Properties properties) {
port = Integer.valueOf(properties.getProperty("server.port", "8095"));
baseURL = properties.getProperty("kustvakt.base.url", "/api/*");
- setSecureRandomAlgorithm(properties
- .getProperty("security.secure.random.algorithm", ""));
+ setSecureRandomAlgorithm(
+ properties.getProperty("security.secure.random.algorithm", ""));
setMessageDigestAlgorithm(
properties.getProperty("security.md.algorithm", "MD5"));
}
-
+
/**
* loading of the properties and mapping to parameter variables
*
@@ -139,23 +140,26 @@
protected void load (Properties properties) throws Exception {
loadBasicProperties(properties);
- apiWelcomeMessage = properties.getProperty("api.welcome.message", "Welcome to KorAP API!");
+ apiWelcomeMessage = properties.getProperty("api.welcome.message",
+ "Welcome to KorAP API!");
currentVersion = properties.getProperty("current.api.version", "v1.0");
- String supportedVersions =
- properties.getProperty("supported.api.versions", "");
-
+ String supportedVersions = properties
+ .getProperty("supported.api.versions", "");
+
this.supportedVersions = new HashSet<>();
- if (!supportedVersions.isEmpty()){
- List<String> versionArray = Arrays.asList(supportedVersions.split(" "));
+ if (!supportedVersions.isEmpty()) {
+ List<String> versionArray = Arrays
+ .asList(supportedVersions.split(" "));
this.supportedVersions.addAll(versionArray);
}
this.supportedVersions.add(currentVersion);
maxhits = Integer.valueOf(properties.getProperty("maxhits", "50000"));
- returnhits = Integer.valueOf(properties.getProperty("returnhits", "50000"));
+ returnhits = Integer
+ .valueOf(properties.getProperty("returnhits", "50000"));
indexDir = properties.getProperty("krill.indexDir", "");
-
+
// server options
serverHost = String
.valueOf(properties.getProperty("server.host", "localhost"));
@@ -165,18 +169,19 @@
for (String querylang : qls)
queryLanguages.add(querylang.trim().toUpperCase());
- default_const =
- properties.getProperty("default.foundry.constituent", "corenlp");
- default_dep =
- properties.getProperty("default.foundry.dependency", "malt");
+ default_const = properties.getProperty("default.foundry.constituent",
+ "corenlp");
+ default_dep = properties.getProperty("default.foundry.dependency",
+ "malt");
default_lemma = properties.getProperty("default.foundry.lemma", "tt");
- default_morphology = properties.getProperty("default.foundry.morphology", "marmot");
- default_pos =
- properties.getProperty("default.foundry.partOfSpeech", "tt");
- default_orthography =
- properties.getProperty("default.foundry.orthography", "opennlp");
- defaultStructureFoundry =
- properties.getProperty("default.foundry.structure", "base");
+ default_morphology = properties
+ .getProperty("default.foundry.morphology", "marmot");
+ default_pos = properties.getProperty("default.foundry.partOfSpeech",
+ "tt");
+ default_orthography = properties
+ .getProperty("default.foundry.orthography", "opennlp");
+ defaultStructureFoundry = properties
+ .getProperty("default.foundry.structure", "base");
// security configuration
inactiveTime = TimeUtils.convertTimeToSeconds(
@@ -196,8 +201,8 @@
validationEmaillength = Integer.valueOf(properties
.getProperty("security.validation.emailLength", "40"));
- sharedSecret =
- properties.getProperty("security.sharedSecret", "").getBytes();
+ sharedSecret = properties.getProperty("security.sharedSecret", "")
+ .getBytes();
longTokenTTL = TimeUtils.convertTimeToSeconds(
properties.getProperty("security.longTokenTTL", "100D"));
@@ -205,12 +210,11 @@
properties.getProperty("security.tokenTTL", "72H"));
shortTokenTTL = TimeUtils.convertTimeToSeconds(
properties.getProperty("security.shortTokenTTL", "3H"));
-
+
// network endpoint
- networkEndpointURL =
- properties.getProperty("network.endpoint.url", "");
+ networkEndpointURL = properties.getProperty("network.endpoint.url", "");
}
-
+
@Deprecated
public void readPipesFile (String filename) throws IOException {
File file = new File(filename);
@@ -219,19 +223,18 @@
new InputStreamReader(new FileInputStream(file)));
String line = null;
- while( (line=br.readLine())!=null ){
+ while ((line = br.readLine()) != null) {
String[] parts = line.split("\t");
- if (parts.length !=2){
+ if (parts.length != 2) {
continue;
}
- else{
+ else {
pipes.put(parts[0], parts[1]);
}
}
br.close();
}
}
-
/**
* set properties
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
index f16acbf..fda0ee8 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
@@ -33,7 +33,8 @@
* <p>
* All predefined VC are set as SYSTEM VC. The filenames are used as
* VC names. Acceptable file extensions are .jsonld.gz or .jsonld. The
- * VC should be located at the folder indicated by <em>krill.namedVC</em>
+ * VC should be located at the folder indicated by
+ * <em>krill.namedVC</em>
* specified in kustvakt.conf.
* </p>
*
@@ -41,7 +42,7 @@
*
*/
@Component
-public class NamedVCLoader implements Runnable{
+public class NamedVCLoader implements Runnable {
@Autowired
private FullConfiguration config;
@Autowired
@@ -58,12 +59,13 @@
loadVCToCache();
}
catch (IOException | QueryException e) {
-// e.printStackTrace();
+ // e.printStackTrace();
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
-
- /** Used for testing
+
+ /**
+ * Used for testing
*
* @param filename
* @param filePath
@@ -77,18 +79,18 @@
InputStream is = NamedVCLoader.class.getResourceAsStream(filePath);
String json = IOUtils.toString(is, "utf-8");
if (json != null) {
- cacheVC(filename,json);
- vcService.storeQuery("system",filename, ResourceType.SYSTEM,
+ cacheVC(filename, json);
+ vcService.storeQuery("system", filename, ResourceType.SYSTEM,
QueryType.VIRTUAL_CORPUS, json, null, null, null, true,
"system", null, null);
}
}
- public void loadVCToCache ()
- throws IOException, QueryException {
+ public void loadVCToCache () throws IOException, QueryException {
String dir = config.getNamedVCPath();
- if (dir.isEmpty()) return;
+ if (dir.isEmpty())
+ return;
File d = new File(dir);
if (!d.isDirectory()) {
@@ -96,7 +98,7 @@
}
jlog.info(Arrays.toString(d.list()));
-
+
for (File file : d.listFiles()) {
if (!file.exists()) {
throw new IOException("File " + file + " is not found.");
@@ -107,14 +109,13 @@
filename = strArr[0];
String json = strArr[1];
if (json != null) {
- cacheVC(filename,json);
+ cacheVC(filename, json);
storeVCinDB(filename, json);
}
}
}
- private String[] readFile (File file, String filename)
- throws IOException {
+ private String[] readFile (File file, String filename) throws IOException {
String json = null;
long start = System.currentTimeMillis();
if (filename.endsWith(".jsonld")) {
@@ -123,8 +124,8 @@
}
else if (filename.endsWith(".jsonld.gz")) {
filename = filename.substring(0, filename.length() - 10);
- GZIPInputStream gzipInputStream =
- new GZIPInputStream(new FileInputStream(file));
+ GZIPInputStream gzipInputStream = new GZIPInputStream(
+ new FileInputStream(file));
ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
bos.write(gzipInputStream);
json = bos.toString("utf-8");
@@ -161,7 +162,7 @@
else {
jlog.info("Storing {} in cache ", vcId);
}
-
+
long start, end;
start = System.currentTimeMillis();
VirtualCorpusCache.store(vcId, searchKrill.getIndex());
@@ -169,8 +170,9 @@
jlog.info("Duration : {}", (end - start));
config.setVcInCaching("");
}
-
- /** Stores the VC if it doesn't exist in the database.
+
+ /**
+ * Stores the VC if it doesn't exist in the database.
*
* @param vcId
* @param koralQuery
@@ -196,6 +198,6 @@
throw new RuntimeException(e);
}
}
-
+
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/ParamFields.java b/full/src/main/java/de/ids_mannheim/korap/config/ParamFields.java
index 2d9a255..621bffb 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/ParamFields.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/ParamFields.java
@@ -16,17 +16,14 @@
this.put(param.getClass().getName(), param);
}
-
public <T extends Param> T get (Class<T> cl) {
return (T) this.get(cl.getName());
}
-
public <T extends Param> T remove (Class<T> cl) {
return (T) this.remove(cl.getName());
}
-
public void addAll (Collection<Param> params) {
for (Param p : params)
super.put(p.getClass().getName(), p);
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/QueryBuilderUtil.java b/full/src/main/java/de/ids_mannheim/korap/config/QueryBuilderUtil.java
index bc21668..fb838b1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/QueryBuilderUtil.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/QueryBuilderUtil.java
@@ -9,7 +9,8 @@
public class QueryBuilderUtil {
public static MetaQueryBuilder defaultMetaBuilder (Integer pageIndex,
- Integer pageInteger, Integer pageLength, String ctx, Boolean cutoff) {
+ Integer pageInteger, Integer pageLength, String ctx,
+ Boolean cutoff) {
MetaQueryBuilder meta = new MetaQueryBuilder();
meta.addEntry("startIndex", pageIndex)
.addEntry("startPage", pageInteger)
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/Scopes.java b/full/src/main/java/de/ids_mannheim/korap/config/Scopes.java
index 161d5f6..295cb4d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/Scopes.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/Scopes.java
@@ -28,7 +28,6 @@
private static final Enum[] SERVICE_DEFAULTS = { Scope.account,
Scope.preferences, Scope.search, Scope.queries };
-
public static Scopes getProfileScopes (Userdata values) {
Scopes r = new Scopes();
for (String key : profile) {
@@ -39,7 +38,6 @@
return r;
}
-
/**
* expects space separated values
*
@@ -54,7 +52,6 @@
return s.toArray(new Scope[s.size()]);
}
-
public static Scopes mapScopes (String scopes, Userdata details) {
Scopes m = new Scopes();
if (scopes != null && !scopes.isEmpty()) {
@@ -73,19 +70,16 @@
private Map<String, Object> values;
-
private Scopes () {
this.values = new HashMap<>();
}
-
public String toEntity () throws KustvaktException {
if (this.values.isEmpty())
return "";
return JsonUtils.toJSON(this.values);
}
-
public Map<String, Object> toMap () {
return new HashMap<>(this.values);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/URIParam.java b/full/src/main/java/de/ids_mannheim/korap/config/URIParam.java
index 9fd7911..9cba8b6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/URIParam.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/URIParam.java
@@ -12,13 +12,11 @@
private final String uriFragment;
private final Long uriExpiration;
-
public URIParam (String uri, Long expire) {
this.uriFragment = uri;
this.uriExpiration = expire;
}
-
@Override
public boolean hasValues () {
return this.uriFragment != null && !this.uriFragment.isEmpty()
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java b/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java
index ea91e16..2c6c64d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java
@@ -1,6 +1,7 @@
package de.ids_mannheim.korap.constant;
-/** Defines various annotation types as constants
+/**
+ * Defines various annotation types as constants
*
* @author margaretha
*
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationMethod.java b/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationMethod.java
index cbdc07f..488c676 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationMethod.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationMethod.java
@@ -1,12 +1,13 @@
package de.ids_mannheim.korap.constant;
-/** Lists possible actual authentication methods. Multiple
- * {@link AuthenticationScheme} may use an identical
- * authentication method.
+/**
+ * Lists possible actual authentication methods. Multiple
+ * {@link AuthenticationScheme} may use an identical
+ * authentication method.
*
* @author margaretha
*
- * @see AuthenticationScheme
+ * @see AuthenticationScheme
*
*/
public enum AuthenticationMethod {
@@ -14,5 +15,5 @@
// not available
SHIBBOLETH, DATABASE,
// by pass authentication for testing
- TEST;
+ TEST;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationScheme.java b/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationScheme.java
index 543b3fd..e3068f7 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationScheme.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/AuthenticationScheme.java
@@ -2,8 +2,10 @@
import org.apache.commons.lang.WordUtils;
-/** Lists possible authentication schemes used in the Authorization header
- * of HTTP requests.
+/**
+ * Lists possible authentication schemes used in the Authorization
+ * header
+ * of HTTP requests.
*
* @author margaretha
*
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/GroupMemberStatus.java b/full/src/main/java/de/ids_mannheim/korap/constant/GroupMemberStatus.java
index 11ed922..445e31e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/GroupMemberStatus.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/GroupMemberStatus.java
@@ -1,15 +1,16 @@
package de.ids_mannheim.korap.constant;
-/** Defines possible statuses of a user-group member
+/**
+ * Defines possible statuses of a user-group member
*
* @author margaretha
*
*/
public enum GroupMemberStatus {
- ACTIVE,
+ ACTIVE,
// membership invitation was sent and has not been accepted
// or rejected yet
- PENDING,
+ PENDING,
// either membership invitation was rejected or the member was
// deleted by a user-group admin
DELETED;
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/OAuth2Scope.java b/full/src/main/java/de/ids_mannheim/korap/constant/OAuth2Scope.java
index ee6a09b..f24956b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/OAuth2Scope.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/OAuth2Scope.java
@@ -1,56 +1,37 @@
package de.ids_mannheim.korap.constant;
-/** Defines all possible authorization scopes
+/**
+ * Defines all possible authorization scopes
*
* @author margaretha
*
*/
public enum OAuth2Scope {
-
- ALL,
- @Deprecated
+
+ ALL, @Deprecated
ADMIN,
-
+
AUTHORIZE,
-
- LIST_USER_CLIENT,
- INSTALL_USER_CLIENT,
- UNINSTALL_USER_CLIENT,
-
- CLIENT_INFO,
- REGISTER_CLIENT,
- DEREGISTER_CLIENT,
- RESET_CLIENT_SECRET,
-
- SEARCH,
- SERIALIZE_QUERY,
- MATCH_INFO,
-
+
+ LIST_USER_CLIENT, INSTALL_USER_CLIENT, UNINSTALL_USER_CLIENT,
+
+ CLIENT_INFO, REGISTER_CLIENT, DEREGISTER_CLIENT, RESET_CLIENT_SECRET,
+
+ SEARCH, SERIALIZE_QUERY, MATCH_INFO,
+
USER_INFO,
-
- USER_GROUP_INFO,
- CREATE_USER_GROUP,
- DELETE_USER_GROUP,
-
- DELETE_USER_GROUP_MEMBER,
- ADD_USER_GROUP_MEMBER,
-
- EDIT_USER_GROUP_MEMBER_ROLE,
- ADD_USER_GROUP_MEMBER_ROLE,
- DELETE_USER_GROUP_MEMBER_ROLE,
-
- CREATE_VC,
- VC_INFO,
- EDIT_VC,
- DELETE_VC,
-
- SHARE_VC,
- DELETE_VC_ACCESS,
- VC_ACCESS_INFO,
-
- CREATE_DEFAULT_SETTING,
- READ_DEFAULT_SETTING,
- DELETE_DEFAULT_SETTING;
+
+ USER_GROUP_INFO, CREATE_USER_GROUP, DELETE_USER_GROUP,
+
+ DELETE_USER_GROUP_MEMBER, ADD_USER_GROUP_MEMBER,
+
+ EDIT_USER_GROUP_MEMBER_ROLE, ADD_USER_GROUP_MEMBER_ROLE, DELETE_USER_GROUP_MEMBER_ROLE,
+
+ CREATE_VC, VC_INFO, EDIT_VC, DELETE_VC,
+
+ SHARE_VC, DELETE_VC_ACCESS, VC_ACCESS_INFO,
+
+ CREATE_DEFAULT_SETTING, READ_DEFAULT_SETTING, DELETE_DEFAULT_SETTING;
@Override
public String toString () {
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/PredefinedRole.java b/full/src/main/java/de/ids_mannheim/korap/constant/PredefinedRole.java
index d1e363b..f91e511 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/PredefinedRole.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/PredefinedRole.java
@@ -1,26 +1,28 @@
package de.ids_mannheim.korap.constant;
-/** Defines some predefined roles used in the system.
+/**
+ * Defines some predefined roles used in the system.
*
* @author margaretha
*
*/
public enum PredefinedRole {
- USER_GROUP_ADMIN(1), USER_GROUP_MEMBER(2), VC_ACCESS_ADMIN(3), VC_ACCESS_MEMBER(4),
- QUERY_ACCESS_ADMIN(5), QUERY_ACCESS_MEMBER(6);
-
+ USER_GROUP_ADMIN(1), USER_GROUP_MEMBER(2), VC_ACCESS_ADMIN(
+ 3), VC_ACCESS_MEMBER(
+ 4), QUERY_ACCESS_ADMIN(5), QUERY_ACCESS_MEMBER(6);
+
private int id;
private String name;
PredefinedRole (int i) {
this.id = i;
- this.name = name().toLowerCase().replace("_", " ");
+ this.name = name().toLowerCase().replace("_", " ");
}
-
+
public int getId () {
return id;
}
-
+
@Override
public String toString () {
return this.name;
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/PrivilegeType.java b/full/src/main/java/de/ids_mannheim/korap/constant/PrivilegeType.java
index f9900b3..0466fa2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/PrivilegeType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/PrivilegeType.java
@@ -3,7 +3,8 @@
import de.ids_mannheim.korap.entity.Privilege;
import de.ids_mannheim.korap.entity.Role;
-/** Defines the privilege or permissions of users or admins
+/**
+ * Defines the privilege or permissions of users or admins
* based on their roles.
*
* @author margaretha
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/QueryAccessStatus.java b/full/src/main/java/de/ids_mannheim/korap/constant/QueryAccessStatus.java
index de78d54..3b4f786 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/QueryAccessStatus.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/QueryAccessStatus.java
@@ -2,7 +2,8 @@
import de.ids_mannheim.korap.entity.QueryAccess;
-/** Defines possible statuses of {@link QueryAccess}
+/**
+ * Defines possible statuses of {@link QueryAccess}
*
* @author margaretha
* @see QueryAccess
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/QueryType.java b/full/src/main/java/de/ids_mannheim/korap/constant/QueryType.java
index cd47332..5251bde 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/QueryType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/QueryType.java
@@ -4,9 +4,8 @@
public enum QueryType {
- QUERY,
- VIRTUAL_CORPUS;
-
+ QUERY, VIRTUAL_CORPUS;
+
public String displayName () {
return StringUtils.capitalize(name().toLowerCase().replace("_", " "));
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/ResourceType.java b/full/src/main/java/de/ids_mannheim/korap/constant/ResourceType.java
index 8c2e2ac..327e0ab 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/ResourceType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/ResourceType.java
@@ -2,7 +2,8 @@
import de.ids_mannheim.korap.entity.QueryDO;
-/** Defines types of {@link QueryDO}
+/**
+ * Defines types of {@link QueryDO}
*
* @author margaretha
*
@@ -16,21 +17,22 @@
/**
* available for all
*/
- SYSTEM,
+ SYSTEM,
//
- /** available to project group members
+ /**
+ * available to project group members
*
*/
- PROJECT,
+ PROJECT,
/**
* available only for the creator
*/
- PRIVATE,
+ PRIVATE,
/**
- * available for all, but not listed for all
+ * available for all, but not listed for all
*/
PUBLISHED;
-
+
public String displayName () {
return name().toLowerCase();
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/TokenType.java b/full/src/main/java/de/ids_mannheim/korap/constant/TokenType.java
index bd4ad76..d238ac2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/TokenType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/TokenType.java
@@ -4,19 +4,21 @@
import de.ids_mannheim.korap.security.context.TokenContext;
-/** Defines the types of authentication tokens. Token types are used to
- * create {@link TokenContext} and determine which authentication provider
- * must be used to create a TokenContext and parse given tokens.
+/**
+ * Defines the types of authentication tokens. Token types are used to
+ * create {@link TokenContext} and determine which authentication
+ * provider
+ * must be used to create a TokenContext and parse given tokens.
*
* @author margaretha
*
*/
public enum TokenType {
- BASIC, API, SESSION,
+ BASIC, API, SESSION,
// OAuth2 access_token
BEARER,
// OAuth2 client
- CLIENT;
+ CLIENT;
public String displayName () {
return StringUtils.capitalize(name().toLowerCase());
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/UserGroupStatus.java b/full/src/main/java/de/ids_mannheim/korap/constant/UserGroupStatus.java
index a1507ed..03eedcb 100644
--- a/full/src/main/java/de/ids_mannheim/korap/constant/UserGroupStatus.java
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/UserGroupStatus.java
@@ -2,13 +2,14 @@
import de.ids_mannheim.korap.entity.UserGroup;
-/** Defines possible statuses of {@link UserGroup}s
+/**
+ * Defines possible statuses of {@link UserGroup}s
*
* @author margaretha
*
*/
public enum UserGroupStatus {
- ACTIVE, DELETED,
+ ACTIVE, DELETED,
// group members cannot see the group
HIDDEN;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationKey.java b/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationKey.java
index d4184a4..fb3012d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationKey.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationKey.java
@@ -28,8 +28,8 @@
@Setter
@Getter
@Entity
-@Table(name = "annotation_key", uniqueConstraints = @UniqueConstraint(
- columnNames = { "layer_id", "key_id" }))
+@Table(name = "annotation_key", uniqueConstraints = @UniqueConstraint(columnNames = {
+ "layer_id", "key_id" }))
public class AnnotationKey {
@Id
@@ -49,13 +49,8 @@
private Annotation key;
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "annotation_value",
- joinColumns = @JoinColumn(name = "key_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "value_id",
- referencedColumnName = "id"),
- uniqueConstraints = @UniqueConstraint(
- columnNames = { "key_id", "value_id" }))
+ @JoinTable(name = "annotation_value", joinColumns = @JoinColumn(name = "key_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "value_id", referencedColumnName = "id"), uniqueConstraints = @UniqueConstraint(columnNames = {
+ "key_id", "value_id" }))
private Set<Annotation> values;
public AnnotationKey () {}
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationLayer.java b/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationLayer.java
index 06caf6a..9beb694 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationLayer.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/entity/AnnotationLayer.java
@@ -31,8 +31,8 @@
@Setter
@Getter
@Entity
-@Table(name = "annotation_layer", uniqueConstraints = @UniqueConstraint(
- columnNames = { "foundry_id", "layer_id" }))
+@Table(name = "annotation_layer", uniqueConstraints = @UniqueConstraint(columnNames = {
+ "foundry_id", "layer_id" }))
public class AnnotationLayer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -54,8 +54,7 @@
@JoinColumn(name = "layer_id", insertable = false, updatable = false)
private Annotation layer;
- @OneToMany(mappedBy = "layer", fetch = FetchType.EAGER,
- cascade = CascadeType.REMOVE)
+ @OneToMany(mappedBy = "layer", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
private Set<AnnotationKey> keys;
@Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/entity/Resource.java b/full/src/main/java/de/ids_mannheim/korap/core/entity/Resource.java
index 99c572b..e002451 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/entity/Resource.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/entity/Resource.java
@@ -40,11 +40,7 @@
private String englishDescription;
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "resource_layer",
- joinColumns = @JoinColumn(name = "resource_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "layer_id",
- referencedColumnName = "id"))
+ @JoinTable(name = "resource_layer", joinColumns = @JoinColumn(name = "resource_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "layer_id", referencedColumnName = "id"))
private Set<AnnotationLayer> layers;
public Resource () {}
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/service/AnnotationService.java b/full/src/main/java/de/ids_mannheim/korap/core/service/AnnotationService.java
index 4730a4f..e7680e2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/service/AnnotationService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/service/AnnotationService.java
@@ -17,7 +17,9 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
-/** AnnotationService defines the logic behind {@link AnnotationController}.
+/**
+ * AnnotationService defines the logic behind
+ * {@link AnnotationController}.
*
* @author margaretha
*
@@ -27,8 +29,7 @@
private static final boolean DEBUG = false;
- private static Logger jlog =
- LogManager.getLogger(AnnotationService.class);
+ private static Logger jlog = LogManager.getLogger(AnnotationService.class);
@Autowired
private AnnotationDao annotationDao;
@@ -38,7 +39,7 @@
public List<LayerDto> getLayerDtos () {
List<AnnotationLayer> layers = annotationDao.getAllFoundryLayerPairs();
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("/layers " + layers.toString());
}
List<LayerDto> layerDto = annotationConverter.convertToLayerDto(layers);
@@ -50,14 +51,14 @@
List<AnnotationLayer> annotationPairs = null;
String foundry = "", layer = "";
if (codes.contains("*")) {
- annotationPairs =
- annotationDao.getAnnotationDescriptions(foundry, layer);
+ annotationPairs = annotationDao.getAnnotationDescriptions(foundry,
+ layer);
}
else {
String[] annotationCode;
annotationPairs = new ArrayList<AnnotationLayer>();
for (String code : codes) {
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("code " + code);
}
annotationCode = code.split("/");
@@ -82,7 +83,7 @@
if (annotationPairs != null && !annotationPairs.isEmpty()) {
List<FoundryDto> foundryDtos = annotationConverter
.convertToFoundryDto(annotationPairs, language);
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("/description " + annotationPairs.toString());
}
return foundryDtos;
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/service/BasicService.java b/full/src/main/java/de/ids_mannheim/korap/core/service/BasicService.java
index c1072dd..e833321 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/service/BasicService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/service/BasicService.java
@@ -6,7 +6,7 @@
protected String combineMultipleCorpusQuery (List<String> cqList) {
String combinedCorpusQuery = null;
- if (cqList!=null && cqList.size() > 0) {
+ if (cqList != null && cqList.size() > 0) {
combinedCorpusQuery = cqList.get(0);
for (int i = 1; i < cqList.size(); i++) {
combinedCorpusQuery += "&" + cqList.get(i);
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/service/SearchService.java b/full/src/main/java/de/ids_mannheim/korap/core/service/SearchService.java
index c940cab..03f186d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/service/SearchService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/service/SearchService.java
@@ -42,12 +42,12 @@
import jakarta.ws.rs.core.UriBuilder;
@Service
-public class SearchService extends BasicService{
-
- public class TotalResultCache extends KustvaktCacheable{
-
+public class SearchService extends BasicService {
+
+ public class TotalResultCache extends KustvaktCacheable {
+
public TotalResultCache () {
- super("total_results","key:hashedKoralQuery");
+ super("total_results", "key:hashedKoralQuery");
}
}
@@ -69,14 +69,14 @@
private SearchNetworkEndpoint searchNetwork;
private ClientsHandler graphDBhandler;
-
+
private TotalResultCache totalResultCache;
@PostConstruct
private void doPostConstruct () {
UriBuilder builder = UriBuilder.fromUri("http://10.0.10.13").port(9997);
this.graphDBhandler = new ClientsHandler(builder.build());
-
+
totalResultCache = new TotalResultCache();
}
@@ -84,21 +84,25 @@
return searchKrill.getIndex().getVersion();
}
-
+
@SuppressWarnings("unchecked")
public String serializeQuery (String q, String ql, String v, String cq,
Integer pageIndex, Integer startPage, Integer pageLength,
String context, Boolean cutoff, boolean accessRewriteDisabled)
throws KustvaktException {
QuerySerializer ss = new QuerySerializer().setQuery(q, ql, v);
- if (cq != null) ss.setCollection(cq);
+ if (cq != null)
+ ss.setCollection(cq);
MetaQueryBuilder meta = new MetaQueryBuilder();
- if (pageIndex != null) meta.addEntry("startIndex", pageIndex);
+ if (pageIndex != null)
+ meta.addEntry("startIndex", pageIndex);
if (pageIndex == null && startPage != null)
meta.addEntry("startPage", startPage);
- if (pageLength != null) meta.addEntry("count", pageLength);
- if (context != null) meta.setSpanContext(context);
+ if (pageLength != null)
+ meta.addEntry("count", pageLength);
+ if (context != null)
+ meta.setSpanContext(context);
meta.addEntry("cutOff", cutoff);
ss.setMeta(meta.raw());
@@ -127,12 +131,12 @@
User user = createUser(username, headers);
- JsonNode node = JsonUtils.readTree(jsonld);
+ JsonNode node = JsonUtils.readTree(jsonld);
node = node.at("/meta/snippets");
- if (node !=null && node.asBoolean()){
+ if (node != null && node.asBoolean()) {
user.setCorpusAccess(CorpusAccess.ALL);
}
-
+
String query = this.rewriteHandler.processQuery(jsonld, user);
// MH: todo: should be possible to add the meta part to
// the query serialization
@@ -146,42 +150,42 @@
String q, String ql, String v, List<String> cqList, String fields,
String pipes, Integer pageIndex, Integer pageInteger, String ctx,
Integer pageLength, Boolean cutoff, boolean accessRewriteDisabled,
- boolean showTokens, boolean showSnippet)
- throws KustvaktException {
+ boolean showTokens, boolean showSnippet) throws KustvaktException {
if (pageInteger != null && pageInteger < 1) {
throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
"page must start from 1", "page");
}
-
+
String[] pipeArray = null;
- if (pipes!=null && !pipes.isEmpty()){
+ if (pipes != null && !pipes.isEmpty()) {
pipeArray = pipes.split(",");
}
-
+
User user = createUser(username, headers);
CorpusAccess corpusAccess = user.getCorpusAccess();
-
+
// EM: TODO: check if requested fields are public metadata. Currently
// it is not needed because all metadata are public.
- if (accessRewriteDisabled){
+ if (accessRewriteDisabled) {
corpusAccess = CorpusAccess.ALL;
user.setCorpusAccess(CorpusAccess.ALL);
}
-
+
QuerySerializer serializer = new QuerySerializer();
serializer.setQuery(q, ql, v);
String cq = combineMultipleCorpusQuery(cqList);
- if (cq != null) serializer.setCollection(cq);
+ if (cq != null)
+ serializer.setCollection(cq);
List<String> fieldList = convertFieldsToList(fields);
handleNonPublicFields(fieldList, accessRewriteDisabled, serializer);
-
+
MetaQueryBuilder meta = createMetaQuery(pageIndex, pageInteger, ctx,
- pageLength, cutoff, corpusAccess, fieldList, accessRewriteDisabled,
- showTokens, showSnippet);
+ pageLength, cutoff, corpusAccess, fieldList,
+ accessRewriteDisabled, showTokens, showSnippet);
serializer.setMeta(meta.raw());
-
+
// There is an error in query processing
// - either query, corpus or meta
if (serializer.hasErrors()) {
@@ -189,7 +193,7 @@
}
String query = serializer.toJSON();
-
+
if (accessRewriteDisabled && showTokens) {
Notifications n = new Notifications();
n.addWarning(StatusCodes.NOT_ALLOWED,
@@ -197,21 +201,22 @@
JsonNode warning = n.toJsonNode();
query = addWarning(query, warning);
}
-
- query = runPipes(query,pipeArray);
-
+
+ query = runPipes(query, pipeArray);
+
query = this.rewriteHandler.processQuery(query, user);
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("the serialized query " + query);
}
int hashedKoralQuery = createTotalResultCacheKey(query);
boolean hasCutOff = hasCutOff(query);
if (!hasCutOff) {
- query = precheckTotalResultCache(hashedKoralQuery,query);
+ query = precheckTotalResultCache(hashedKoralQuery, query);
}
- KustvaktConfiguration.BACKENDS searchEngine = this.config.chooseBackend(engine);
+ KustvaktConfiguration.BACKENDS searchEngine = this.config
+ .chooseBackend(engine);
String result;
if (searchEngine.equals(KustvaktConfiguration.BACKENDS.NEO4J)) {
result = searchNeo4J(query, pageLength, meta, false);
@@ -223,15 +228,15 @@
result = searchKrill.search(query);
}
// jlog.debug("Query result: " + result);
-
- result = afterCheckTotalResultCache(hashedKoralQuery,result);
+
+ result = afterCheckTotalResultCache(hashedKoralQuery, result);
if (!hasCutOff) {
result = removeCutOff(result);
}
return result;
}
-
+
private String removeCutOff (String result) throws KustvaktException {
ObjectNode resultNode = (ObjectNode) JsonUtils.readTree(result);
ObjectNode meta = (ObjectNode) resultNode.at("/meta");
@@ -239,7 +244,8 @@
return resultNode.toString();
}
- public int createTotalResultCacheKey (String query) throws KustvaktException {
+ public int createTotalResultCacheKey (String query)
+ throws KustvaktException {
ObjectNode queryNode = (ObjectNode) JsonUtils.readTree(query);
queryNode.remove("meta");
return queryNode.hashCode();
@@ -247,9 +253,9 @@
private String afterCheckTotalResultCache (int hashedKoralQuery,
String result) throws KustvaktException {
-
- String totalResults =
- (String) totalResultCache.getCacheValue(hashedKoralQuery);
+
+ String totalResults = (String) totalResultCache
+ .getCacheValue(hashedKoralQuery);
if (totalResults != null) {
ObjectNode queryNode = (ObjectNode) JsonUtils.readTree(result);
ObjectNode meta = (ObjectNode) queryNode.at("/meta");
@@ -264,9 +270,8 @@
else {
JsonNode node = JsonUtils.readTree(result);
totalResults = node.at("/meta/totalResults").asText();
- if (totalResults != null &&
- !totalResults.isEmpty() &&
- Integer.parseInt(totalResults) > 0)
+ if (totalResults != null && !totalResults.isEmpty()
+ && Integer.parseInt(totalResults) > 0)
totalResultCache.storeInCache(hashedKoralQuery, totalResults);
}
return result;
@@ -274,8 +279,8 @@
public String precheckTotalResultCache (int hashedKoralQuery, String query)
throws KustvaktException {
- String totalResults =
- (String) totalResultCache.getCacheValue(hashedKoralQuery);
+ String totalResults = (String) totalResultCache
+ .getCacheValue(hashedKoralQuery);
if (totalResults != null) {
// add cutoff
ObjectNode queryNode = (ObjectNode) JsonUtils.readTree(query);
@@ -285,7 +290,7 @@
}
return query;
}
-
+
private boolean hasCutOff (String query) throws KustvaktException {
JsonNode queryNode = JsonUtils.readTree(query);
JsonNode cutOff = queryNode.at("/meta/cutOff");
@@ -300,33 +305,40 @@
/**
* Pipes are service URLs for modifying KoralQuery. A POST request
* with Content-Type application/json will be sent for each pipe.
- * Kustvakt expects a KoralQuery in JSON format as the pipe response.
+ * Kustvakt expects a KoralQuery in JSON format as the pipe
+ * response.
*
- * @param query the original koral query
- * @param pipeArray the pipe service URLs
- * @param serializer the query serializer
+ * @param query
+ * the original koral query
+ * @param pipeArray
+ * the pipe service URLs
+ * @param serializer
+ * the query serializer
* @return a modified koral query
- * @throws KustvaktException
+ * @throws KustvaktException
*/
- private String runPipes (String query, String[] pipeArray) throws KustvaktException {
- if (pipeArray !=null){
- for (int i=0; i<pipeArray.length; i++){
+ private String runPipes (String query, String[] pipeArray)
+ throws KustvaktException {
+ if (pipeArray != null) {
+ for (int i = 0; i < pipeArray.length; i++) {
String pipeURL = pipeArray[i];
try {
URL url = new URL(pipeURL);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ HttpURLConnection connection = (HttpURLConnection) url
+ .openConnection();
connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ connection.setRequestProperty("Content-Type",
+ "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
byte[] input = query.getBytes("utf-8");
- os.write(input, 0, input.length);
-
+ os.write(input, 0, input.length);
+
String entity = null;
if (connection.getResponseCode() == HttpStatus.SC_OK) {
- BufferedReader br =
- new BufferedReader(new InputStreamReader(
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(
connection.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
@@ -346,39 +358,37 @@
}
}
catch (Exception e) {
- query = handlePipeError(query, pipeURL,
- e.getMessage());
+ query = handlePipeError(query, pipeURL, e.getMessage());
}
}
}
return query;
}
-
- private String handlePipeError (String query, String url,
- String message) throws KustvaktException {
- jlog.warn("Failed running the pipe at " + url + ". Message: "+ message);
-
+
+ private String handlePipeError (String query, String url, String message)
+ throws KustvaktException {
+ jlog.warn(
+ "Failed running the pipe at " + url + ". Message: " + message);
+
Notifications n = new Notifications();
- n.addWarning(StatusCodes.PIPE_FAILED,
- "Pipe failed", url, message);
+ n.addWarning(StatusCodes.PIPE_FAILED, "Pipe failed", url, message);
JsonNode warning = n.toJsonNode();
-
+
query = addWarning(query, warning);
- return query;
+ return query;
}
-
private String addWarning (String query, JsonNode warning)
throws KustvaktException {
-
+
ObjectNode node = (ObjectNode) JsonUtils.readTree(query);
- if (node.has("warnings")){
+ if (node.has("warnings")) {
warning = warning.at("/warnings/0");
ArrayNode arrayNode = (ArrayNode) node.get("warnings");
arrayNode.add(warning);
node.set("warnings", arrayNode);
}
- else{
+ else {
node.setAll((ObjectNode) warning);
}
return node.toString();
@@ -386,9 +396,9 @@
private void handleNonPublicFields (List<String> fieldList,
boolean accessRewriteDisabled, QuerySerializer serializer) {
- List<String> nonPublicFields = new ArrayList<>();
+ List<String> nonPublicFields = new ArrayList<>();
nonPublicFields.add("snippet");
-
+
List<String> ignoredFields = new ArrayList<>();
if (accessRewriteDisabled && !fieldList.isEmpty()) {
for (String field : fieldList) {
@@ -403,12 +413,12 @@
}
}
}
-
+
private MetaQueryBuilder createMetaQuery (Integer pageIndex,
- Integer pageInteger, String ctx, Integer pageLength,
- Boolean cutoff, CorpusAccess corpusAccess, List<String> fieldList,
- boolean accessRewriteDisabled,
- boolean showTokens, boolean showSnippet) {
+ Integer pageInteger, String ctx, Integer pageLength, Boolean cutoff,
+ CorpusAccess corpusAccess, List<String> fieldList,
+ boolean accessRewriteDisabled, boolean showTokens,
+ boolean showSnippet) {
MetaQueryBuilder meta = new MetaQueryBuilder();
meta.addEntry("startIndex", pageIndex);
meta.addEntry("startPage", pageInteger);
@@ -420,20 +430,20 @@
if (!accessRewriteDisabled) {
meta.addEntry("tokens", showTokens);
}
-
+
// meta.addMeta(pageIndex, pageInteger, pageLength, ctx,
// cutoff);
// fixme: should only apply to CQL queries per default!
// meta.addEntry("itemsPerResource", 1);
-
- if (corpusAccess.equals(CorpusAccess.FREE)){
+
+ if (corpusAccess.equals(CorpusAccess.FREE)) {
meta.addEntry("timeout", 10000);
}
- else{
+ else {
meta.addEntry("timeout", 90000);
}
-
- if (fieldList != null && !fieldList.isEmpty()){
+
+ if (fieldList != null && !fieldList.isEmpty()) {
meta.addEntry("fields", fieldList);
}
return meta;
@@ -452,7 +462,7 @@
return new ArrayList<>();
}
}
-
+
private String searchNeo4J (String query, int pageLength,
MetaQueryBuilder meta, boolean raw) throws KustvaktException {
@@ -488,25 +498,22 @@
}
return p;
}
-
- public String retrieveMatchInfo (
- String corpusId, String docId,
- String textId, String matchId, boolean info, Set<String> foundries,
- String username, HttpHeaders headers, Set<String> layers,
- boolean spans,
- boolean snippet, boolean tokens,
- boolean sentenceExpansion,
- boolean highlights
- ) throws KustvaktException {
- String matchid =
- searchKrill.getMatchId(corpusId, docId, textId, matchId);
+
+ public String retrieveMatchInfo (String corpusId, String docId,
+ String textId, String matchId, boolean info, Set<String> foundries,
+ String username, HttpHeaders headers, Set<String> layers,
+ boolean spans, boolean snippet, boolean tokens,
+ boolean sentenceExpansion, boolean highlights)
+ throws KustvaktException {
+ String matchid = searchKrill.getMatchId(corpusId, docId, textId,
+ matchId);
User user = createUser(username, headers);
Pattern p = determineAvailabilityPattern(user);
-// boolean match_only = foundries == null || foundries.isEmpty();
+ // boolean match_only = foundries == null || foundries.isEmpty();
String results;
-// try {
+ // try {
ArrayList<String> foundryList = null;
ArrayList<String> layerList = null;
@@ -524,24 +531,23 @@
foundryList.addAll(foundries);
layerList.addAll(layers);
}
- } else {
+ }
+ else {
sentenceExpansion = false;
spans = false;
info = false;
highlights = true;
};
-
- results = searchKrill.getMatch(
- matchid, info, foundryList, layerList,
- spans, snippet, tokens, highlights,
- sentenceExpansion, p);
-// }
-// catch (Exception e) {
-// jlog.error("Exception in the MatchInfo service encountered!", e);
-// throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT,
-// e.getMessage());
-// }
- if (DEBUG){
+
+ results = searchKrill.getMatch(matchid, info, foundryList, layerList,
+ spans, snippet, tokens, highlights, sentenceExpansion, p);
+ // }
+ // catch (Exception e) {
+ // jlog.error("Exception in the MatchInfo service encountered!", e);
+ // throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT,
+ // e.getMessage());
+ // }
+ if (DEBUG) {
jlog.debug("MatchInfo results: " + results);
}
return results;
@@ -551,22 +557,22 @@
String textId, String fields, String username, HttpHeaders headers)
throws KustvaktException {
List<String> fieldList = null;
- if (fields != null && !fields.isEmpty()){
+ if (fields != null && !fields.isEmpty()) {
fieldList = convertFieldsToList(fields);
}
Pattern p = null;
- if (config.isMetadataRestricted()){
+ if (config.isMetadataRestricted()) {
User user = createUser(username, headers);
p = determineAvailabilityPattern(user);
}
String textSigle = searchKrill.getTextSigle(corpusId, docId, textId);
return searchKrill.getFields(textSigle, fieldList, p);
}
-
+
public String getCollocationBase (String query) throws KustvaktException {
return graphDBhandler.getResponse("distCollo", "q", query);
}
-
+
public void closeIndexReader () throws KustvaktException {
searchKrill.closeIndexReader();
}
@@ -577,7 +583,7 @@
public String getIndexFingerprint () {
return searchKrill.getIndexFingerprint();
}
-
+
public TotalResultCache getTotalResultCache () {
return totalResultCache;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/service/StatisticService.java b/full/src/main/java/de/ids_mannheim/korap/core/service/StatisticService.java
index 54f5e1a..6f0a3f0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/service/StatisticService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/service/StatisticService.java
@@ -49,7 +49,7 @@
node.setAll(warning);
stats = node.toString();
}
-
+
if (stats.contains("-1")) {
throw new KustvaktException(StatusCodes.NO_RESULT_FOUND);
}
@@ -89,7 +89,7 @@
else {
stats = searchKrill.getStatistics(null);
}
-
+
if (stats.contains("-1")) {
throw new KustvaktException(StatusCodes.NO_RESULT_FOUND);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/AnnotationController.java b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/AnnotationController.java
index c337c5e..1f75d3c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/AnnotationController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/AnnotationController.java
@@ -34,7 +34,8 @@
*/
@Controller
@Path("/{version}/annotation/")
-@ResourceFilters({APIVersionFilter.class, DemoUserFilter.class, PiwikFilter.class })
+@ResourceFilters({ APIVersionFilter.class, DemoUserFilter.class,
+ PiwikFilter.class })
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class AnnotationController {
@@ -55,7 +56,6 @@
return annotationService.getLayerDtos();
}
-
/**
* Returns a list of foundry descriptions.
*
@@ -71,8 +71,8 @@
@Consumes(MediaType.APPLICATION_JSON)
public List<FoundryDto> getFoundryDescriptions (String json) {
if (json == null || json.isEmpty()) {
- throw kustvaktResponseHandler
- .throwit(new KustvaktException(StatusCodes.MISSING_PARAMETER,
+ throw kustvaktResponseHandler.throwit(
+ new KustvaktException(StatusCodes.MISSING_PARAMETER,
"Missing a json string.", ""));
}
@@ -122,4 +122,3 @@
}
}
}
-
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/SearchController.java b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/SearchController.java
index 7e4ed94..042f412 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/SearchController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/SearchController.java
@@ -1,5 +1,6 @@
package de.ids_mannheim.korap.core.web.controller;// package
- // de.ids_mannheim.korap.ext.web;
+
+// de.ids_mannheim.korap.ext.web;
import java.util.HashMap;
import java.util.HashSet;
@@ -61,7 +62,7 @@
private static Logger jlog = LogManager.getLogger(SearchController.class);
private @Context ServletContext context;
-
+
@Autowired
private KustvaktResponseHandler kustvaktResponseHandler;
@@ -71,20 +72,19 @@
private OAuth2ScopeService scopeService;
@Autowired
private KustvaktConfiguration config;
-
+
@GET
@Path("{version}")
- public Response index (){
- return Response
- .ok(config.getApiWelcomeMessage())
- .header("X-Index-Revision", searchService.getIndexFingerprint())
- .build();
+ public Response index () {
+ return Response.ok(config.getApiWelcomeMessage())
+ .header("X-Index-Revision", searchService.getIndexFingerprint())
+ .build();
}
-
+
@GET
@Path("{version}/info")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
- public Response info (){
+ public Response info () {
Map<String, Object> m = new HashMap<>();
m.put("latest_api_version", config.getCurrentVersion());
m.put("supported_api_versions", config.getSupportedVersions());
@@ -98,12 +98,12 @@
throw kustvaktResponseHandler.throwit(e);
}
}
-
+
@POST
@Path("{version}/index/close")
// overrides the whole filters
- @ResourceFilters({APIVersionFilter.class,AdminFilter.class})
- public Response closeIndexReader (){
+ @ResourceFilters({ APIVersionFilter.class, AdminFilter.class })
+ public Response closeIndexReader () {
try {
searchService.closeIndexReader();
}
@@ -112,16 +112,15 @@
}
return Response.ok().build();
}
-
-
-// EM: This web service is DISABLED until there is a need for it.
-// ND: In case rewrite is supported, it could be used to check the authorization
-// scope without searching etc. In case not, it helps to compare queries in
-// different query languages.
-// MH: ref query parameter removed!
-// @GET
-// @Path("{version}/query")
-// @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+
+ // EM: This web service is DISABLED until there is a need for it.
+ // ND: In case rewrite is supported, it could be used to check the authorization
+ // scope without searching etc. In case not, it helps to compare queries in
+ // different query languages.
+ // MH: ref query parameter removed!
+ // @GET
+ // @Path("{version}/query")
+ // @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response serializeQuery (@Context Locale locale,
@Context SecurityContext securityContext, @QueryParam("q") String q,
@QueryParam("ql") String ql, @QueryParam("v") String v,
@@ -138,7 +137,7 @@
String result = searchService.serializeQuery(q, ql, v, cq,
pageIndex, startPage, pageLength, context, cutoff,
accessRewriteDisabled);
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("Query: " + result);
}
return Response.ok(result).build();
@@ -148,21 +147,19 @@
}
}
-
-// This web service is DISABLED until there is a need for it.
+ // This web service is DISABLED until there is a need for it.
@POST
@Path("{version}/search")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@SearchResourceFilters
public Response searchPost (@Context SecurityContext context,
- @Context Locale locale,
- @Context HttpHeaders headers,
+ @Context Locale locale, @Context HttpHeaders headers,
String jsonld) {
-
- if (DEBUG){
+
+ if (DEBUG) {
jlog.debug("Serialized search: " + jsonld);
}
-
+
TokenContext ctx = (TokenContext) context.getUserPrincipal();
try {
scopeService.verifyScope(ctx, OAuth2Scope.SEARCH);
@@ -175,7 +172,8 @@
}
}
- /** Performs for the given query
+ /**
+ * Performs for the given query
*
* @param securityContext
* @param request
@@ -194,8 +192,9 @@
* or not (default false)
* @param pageLength
* the number of results should be included in a page
- * @param pageIndex
- * @param pageInteger page number
+ * @param pageIndex
+ * @param pageInteger
+ * page number
* @param fields
* metadata fields to be included, separated by comma
* @param pipes
@@ -214,10 +213,10 @@
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@SearchResourceFilters
public Response searchGet (@Context SecurityContext securityContext,
- @Context HttpServletRequest request,
- @Context HttpHeaders headers, @Context Locale locale,
- @QueryParam("q") String q, @QueryParam("ql") String ql,
- @QueryParam("v") String v, @QueryParam("context") String ctx,
+ @Context HttpServletRequest request, @Context HttpHeaders headers,
+ @Context Locale locale, @QueryParam("q") String q,
+ @QueryParam("ql") String ql, @QueryParam("v") String v,
+ @QueryParam("context") String ctx,
@QueryParam("cutoff") Boolean cutoff,
@QueryParam("count") Integer pageLength,
@QueryParam("offset") Integer pageIndex,
@@ -227,19 +226,19 @@
@QueryParam("access-rewrite-disabled") boolean accessRewriteDisabled,
@QueryParam("show-tokens") boolean showTokens,
@DefaultValue("true") @QueryParam("show-snippet") boolean showSnippet,
- @QueryParam("cq") List<String> cq,
+ @QueryParam("cq") List<String> cq,
@QueryParam("engine") String engine) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
String result;
try {
scopeService.verifyScope(context, OAuth2Scope.SEARCH);
result = searchService.search(engine, context.getUsername(),
headers, q, ql, v, cq, fields, pipes, pageIndex,
- pageInteger, ctx, pageLength, cutoff,
- accessRewriteDisabled, showTokens, showSnippet);
+ pageInteger, ctx, pageLength, cutoff, accessRewriteDisabled,
+ showTokens, showSnippet);
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
@@ -262,15 +261,15 @@
@PathParam("matchId") String matchId,
@QueryParam("foundry") Set<String> foundries,
@QueryParam("layer") Set<String> layers,
- @QueryParam("spans") Boolean spans,
+ @QueryParam("spans") Boolean spans,
// Highlights may also be a list of valid highlight classes
@QueryParam("hls") Boolean highlights) throws KustvaktException {
return retrieveMatchInfo(ctx, headers, locale, corpusId, docId, textId,
- matchId, foundries, layers, spans, "true", "false",
- "sentence", highlights);
+ matchId, foundries, layers, spans, "true", "false", "sentence",
+ highlights);
}
-
+
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Path("{version}/corpus/{corpusId}/{docId}/{textId}/{matchId}")
@@ -283,10 +282,10 @@
@PathParam("matchId") String matchId,
@QueryParam("foundry") Set<String> foundries,
@QueryParam("layer") Set<String> layers,
- @QueryParam("spans") Boolean spans,
- @DefaultValue("true") @QueryParam("show-snippet") String snippetStr,
- @DefaultValue("false") @QueryParam("show-tokens") String tokensStr,
- @QueryParam("expand") String expansion,
+ @QueryParam("spans") Boolean spans,
+ @DefaultValue("true") @QueryParam("show-snippet") String snippetStr,
+ @DefaultValue("false") @QueryParam("show-tokens") String tokensStr,
+ @QueryParam("expand") String expansion,
// Highlights may also be a list of valid highlight classes
@QueryParam("hls") Boolean highlights) throws KustvaktException {
@@ -342,10 +341,8 @@
public Response getMetadata (@PathParam("corpusId") String corpusId,
@PathParam("docId") String docId,
@PathParam("textId") String textId,
- @QueryParam("fields") String fields,
- @Context SecurityContext ctx,
- @Context HttpHeaders headers
- ) throws KustvaktException {
+ @QueryParam("fields") String fields, @Context SecurityContext ctx,
+ @Context HttpHeaders headers) throws KustvaktException {
TokenContext tokenContext = (TokenContext) ctx.getUserPrincipal();
try {
String results = searchService.retrieveDocMetadata(corpusId, docId,
@@ -357,10 +354,10 @@
}
}
-// EM: This web service requires Karang and is DISABLED.
-// @POST
-// @Path("{version}/colloc")
-// @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+ // EM: This web service requires Karang and is DISABLED.
+ // @POST
+ // @Path("{version}/colloc")
+ // @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response getCollocationBase (@QueryParam("q") String query) {
String result;
try {
diff --git a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/StatisticController.java b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/StatisticController.java
index 30ccaa4..6f86d2c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/core/web/controller/StatisticController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/core/web/controller/StatisticController.java
@@ -41,8 +41,8 @@
public class StatisticController {
private static final boolean DEBUG = false;
- private static Logger jlog =
- LogManager.getLogger(StatisticController.class);
+ private static Logger jlog = LogManager
+ .getLogger(StatisticController.class);
@Autowired
private CoreResponseHandler kustvaktResponseHandler;
@Autowired
@@ -81,10 +81,9 @@
jlog.debug("Stats: " + stats);
}
- return Response
- .ok(stats)
- .header("X-Index-Revision", service.getIndexFingerprint())
- .build();
+ return Response.ok(stats)
+ .header("X-Index-Revision", service.getIndexFingerprint())
+ .build();
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
@@ -98,10 +97,9 @@
String koralQuery) {
try {
String stats = service.retrieveStatisticsForKoralQuery(koralQuery);
- return Response
- .ok(stats)
- .header("X-Index-Revision", service.getIndexFingerprint())
- .build();
+ return Response.ok(stats)
+ .header("X-Index-Revision", service.getIndexFingerprint())
+ .build();
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
index 0ebfe42..4aa7cd4 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
@@ -24,7 +24,8 @@
import jakarta.persistence.criteria.Root;
/**
- * AnnotationDao manages queries to database regarding annotations including
+ * AnnotationDao manages queries to database regarding annotations
+ * including
* foundry and layer pairs.
*
* @author margaretha
@@ -44,8 +45,8 @@
@SuppressWarnings("unchecked")
public List<AnnotationLayer> getAllFoundryLayerPairs () {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AnnotationLayer> query =
- criteriaBuilder.createQuery(AnnotationLayer.class);
+ CriteriaQuery<AnnotationLayer> query = criteriaBuilder
+ .createQuery(AnnotationLayer.class);
Root<AnnotationLayer> layer = query.from(AnnotationLayer.class);
layer.fetch(AnnotationLayer_.foundry);
layer.fetch(AnnotationLayer_.layer);
@@ -72,8 +73,8 @@
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> query = criteriaBuilder.createQuery();
- Root<AnnotationLayer> annotationPair =
- query.from(AnnotationLayer.class);
+ Root<AnnotationLayer> annotationPair = query
+ .from(AnnotationLayer.class);
annotationPair.fetch(AnnotationLayer_.foundry);
annotationPair.fetch(AnnotationLayer_.layer);
annotationPair.fetch(AnnotationLayer_.keys);
@@ -97,8 +98,8 @@
Predicate layerPredicate = criteriaBuilder.equal(annotationPair
.get(AnnotationLayer_.layer).get(Annotation_.code),
layer);
- Predicate andPredicate =
- criteriaBuilder.and(foundryPredicate, layerPredicate);
+ Predicate andPredicate = criteriaBuilder.and(foundryPredicate,
+ layerPredicate);
query.where(andPredicate);
}
}
@@ -109,8 +110,8 @@
public Annotation retrieveAnnotation (String code, String type) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Annotation> query =
- criteriaBuilder.createQuery(Annotation.class);
+ CriteriaQuery<Annotation> query = criteriaBuilder
+ .createQuery(Annotation.class);
Root<Annotation> annotation = query.from(Annotation.class);
Predicate predicates = criteriaBuilder.and(
@@ -132,8 +133,8 @@
Annotation ann2 = retrieveAnnotation(layer, AnnotationType.LAYER);
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AnnotationLayer> query =
- criteriaBuilder.createQuery(AnnotationLayer.class);
+ CriteriaQuery<AnnotationLayer> query = criteriaBuilder
+ .createQuery(AnnotationLayer.class);
Root<AnnotationLayer> annotation = query.from(AnnotationLayer.class);
Predicate predicates = criteriaBuilder.and(
@@ -188,8 +189,8 @@
@Transactional
public AnnotationKey createAnnotationKey (AnnotationLayer layer,
Annotation key) {
- AnnotationKey annotation =
- new AnnotationKey(layer.getId(), key.getId());
+ AnnotationKey annotation = new AnnotationKey(layer.getId(),
+ key.getId());
entityManager.persist(annotation);
return annotation;
}
@@ -198,8 +199,8 @@
Annotation key) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AnnotationKey> query =
- criteriaBuilder.createQuery(AnnotationKey.class);
+ CriteriaQuery<AnnotationKey> query = criteriaBuilder
+ .createQuery(AnnotationKey.class);
Root<AnnotationKey> annotation = query.from(AnnotationKey.class);
Predicate predicates = criteriaBuilder.and(
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/DefaultSettingDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/DefaultSettingDao.java
index f99990e..a6bfeee 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/DefaultSettingDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/DefaultSettingDao.java
@@ -60,7 +60,7 @@
throws KustvaktException {
ParameterChecker.checkObjectValue(username, "defaultSetting");
DefaultSetting defaultSetting = retrieveDefaultSetting(username);
- if (defaultSetting != null){
+ if (defaultSetting != null) {
entityManager.remove(defaultSetting);
}
}
@@ -70,8 +70,8 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<DefaultSetting> query =
- criteriaBuilder.createQuery(DefaultSetting.class);
+ CriteriaQuery<DefaultSetting> query = criteriaBuilder
+ .createQuery(DefaultSetting.class);
Root<DefaultSetting> defaultSetting = query.from(DefaultSetting.class);
query.select(defaultSetting);
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/PrivilegeDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/PrivilegeDao.java
index f9c05e6..ad1e77b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/PrivilegeDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/PrivilegeDao.java
@@ -57,8 +57,8 @@
@SuppressWarnings("unchecked")
public List<Privilege> retrievePrivilegeByRoleId (int roleId) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Privilege> query =
- criteriaBuilder.createQuery(Privilege.class);
+ CriteriaQuery<Privilege> query = criteriaBuilder
+ .createQuery(Privilege.class);
Root<Privilege> root = query.from(Privilege.class);
root.fetch(Privilege_.role);
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/QueryAccessDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/QueryAccessDao.java
index d341f38..5448b49 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/QueryAccessDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/QueryAccessDao.java
@@ -49,22 +49,19 @@
ParameterChecker.checkIntegerValue(accessId, "accessId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
query.select(access);
- query.where(
- builder.equal(access.get(QueryAccess_.id), accessId));
+ query.where(builder.equal(access.get(QueryAccess_.id), accessId));
Query q = entityManager.createQuery(query);
- try{
+ try {
return (QueryAccess) q.getSingleResult();
}
catch (NoResultException e) {
throw new KustvaktException(StatusCodes.NO_RESOURCE_FOUND,
- "Query access is not found",
- String.valueOf(accessId));
+ "Query access is not found", String.valueOf(accessId));
}
}
@@ -74,13 +71,12 @@
ParameterChecker.checkIntegerValue(queryId, "queryId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, QueryDO> accessQuery =
- access.join(QueryAccess_.query);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, QueryDO> accessQuery = access
+ .join(QueryAccess_.query);
Predicate p = builder.and(
builder.equal(accessQuery.get(QueryDO_.id), queryId),
@@ -98,17 +94,17 @@
ParameterChecker.checkStringValue(queryName, "queryName");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, QueryDO> accessQuery =
- access.join(QueryAccess_.query);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, QueryDO> accessQuery = access
+ .join(QueryAccess_.query);
Predicate p = builder.and(
builder.equal(accessQuery.get(QueryDO_.name), queryName),
- builder.equal(accessQuery.get(QueryDO_.createdBy), queryCreator),
+ builder.equal(accessQuery.get(QueryDO_.createdBy),
+ queryCreator),
builder.equal(access.get(QueryAccess_.status),
QueryAccessStatus.ACTIVE));
query.select(access);
@@ -116,15 +112,13 @@
TypedQuery<QueryAccess> q = entityManager.createQuery(query);
return q.getResultList();
}
-
- public List<QueryAccess> retrieveAllAccess ()
- throws KustvaktException {
+
+ public List<QueryAccess> retrieveAllAccess () throws KustvaktException {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
query.select(access);
TypedQuery<QueryAccess> q = entityManager.createQuery(query);
return q.getResultList();
@@ -136,13 +130,12 @@
ParameterChecker.checkStringValue(queryName, "queryName");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, QueryDO> accessQuery =
- access.join(QueryAccess_.query);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, QueryDO> accessQuery = access
+ .join(QueryAccess_.query);
Predicate conditions = builder.and(
builder.equal(accessQuery.get(QueryDO_.createdBy),
@@ -159,13 +152,12 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, UserGroup> accessQuery =
- access.join(QueryAccess_.userGroup);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, UserGroup> accessQuery = access
+ .join(QueryAccess_.userGroup);
query.select(access);
query.where(builder.equal(accessQuery.get(UserGroup_.id), groupId));
@@ -178,18 +170,17 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, UserGroup> accessQuery =
- access.join(QueryAccess_.userGroup);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, UserGroup> accessQuery = access
+ .join(QueryAccess_.userGroup);
- Predicate p =
- builder.and(builder.equal(accessQuery.get(UserGroup_.id), groupId),
- builder.equal(access.get(QueryAccess_.status),
- QueryAccessStatus.ACTIVE));
+ Predicate p = builder.and(
+ builder.equal(accessQuery.get(UserGroup_.id), groupId),
+ builder.equal(access.get(QueryAccess_.status),
+ QueryAccessStatus.ACTIVE));
query.select(access);
query.where(p);
@@ -212,13 +203,12 @@
ParameterChecker.checkIntegerValue(queryId, "queryId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> query =
- builder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> query = builder
+ .createQuery(QueryAccess.class);
- Root<QueryAccess> access =
- query.from(QueryAccess.class);
- Join<QueryAccess, QueryDO> accessQuery =
- access.join(QueryAccess_.query);
+ Root<QueryAccess> access = query.from(QueryAccess.class);
+ Join<QueryAccess, QueryDO> accessQuery = access
+ .join(QueryAccess_.query);
Predicate p = builder.and(
builder.equal(accessQuery.get(QueryDO_.id), queryId),
@@ -241,9 +231,8 @@
}
}
- public void createAccessToQuery (QueryDO query,
- UserGroup userGroup, String createdBy,
- QueryAccessStatus status) {
+ public void createAccessToQuery (QueryDO query, UserGroup userGroup,
+ String createdBy, QueryAccessStatus status) {
QueryAccess queryAccess = new QueryAccess();
queryAccess.setQuery(query);
queryAccess.setUserGroup(userGroup);
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/QueryDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/QueryDao.java
index 366188b..e17582a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/QueryDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/QueryDao.java
@@ -53,11 +53,11 @@
@PersistenceContext
private EntityManager entityManager;
- public int createQuery (String name, ResourceType type,
- QueryType queryType, CorpusAccess requiredAccess, String koralQuery,
- String definition, String description, String status,
- boolean isCached, String createdBy, String query,
- String queryLanguage) throws KustvaktException {
+ public int createQuery (String name, ResourceType type, QueryType queryType,
+ CorpusAccess requiredAccess, String koralQuery, String definition,
+ String description, String status, boolean isCached,
+ String createdBy, String query, String queryLanguage)
+ throws KustvaktException {
QueryDO q = new QueryDO();
q.setName(name);
@@ -103,18 +103,17 @@
if (status != null && !status.isEmpty()) {
queryDO.setStatus(status);
}
- if(queryStr!=null && !queryStr.isEmpty()) {
+ if (queryStr != null && !queryStr.isEmpty()) {
queryDO.setQuery(queryStr);
}
- if(queryLanguage!=null && !queryLanguage.isEmpty()) {
+ if (queryLanguage != null && !queryLanguage.isEmpty()) {
queryDO.setQueryLanguage(queryLanguage);
}
queryDO.setCached(isCached);
entityManager.merge(queryDO);
}
- public void deleteQuery (QueryDO query)
- throws KustvaktException {
+ public void deleteQuery (QueryDO query) throws KustvaktException {
if (!entityManager.contains(query)) {
query = entityManager.merge(query);
}
@@ -141,23 +140,23 @@
String createdBy, QueryType queryType) throws KustvaktException {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> criteriaQuery =
- criteriaBuilder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> criteriaQuery = criteriaBuilder
+ .createQuery(QueryDO.class);
Root<QueryDO> query = criteriaQuery.from(QueryDO.class);
Predicate conditions = criteriaBuilder
.equal(query.get(QueryDO_.queryType), queryType);
if (createdBy != null && !createdBy.isEmpty()) {
- conditions = criteriaBuilder.and(conditions, criteriaBuilder.equal(
- query.get(QueryDO_.createdBy), createdBy));
+ conditions = criteriaBuilder.and(conditions, criteriaBuilder
+ .equal(query.get(QueryDO_.createdBy), createdBy));
if (type != null) {
- conditions = criteriaBuilder.and(conditions, criteriaBuilder
- .equal(query.get(QueryDO_.type), type));
+ conditions = criteriaBuilder.and(conditions,
+ criteriaBuilder.equal(query.get(QueryDO_.type), type));
}
}
else if (type != null) {
- conditions = criteriaBuilder.and(conditions, criteriaBuilder
- .equal(query.get(QueryDO_.type), type));
+ conditions = criteriaBuilder.and(conditions,
+ criteriaBuilder.equal(query.get(QueryDO_.type), type));
}
criteriaQuery.select(query);
@@ -170,12 +169,11 @@
ParameterChecker.checkIntegerValue(id, "id");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> criteriaQuery =
- criteriaBuilder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> criteriaQuery = criteriaBuilder
+ .createQuery(QueryDO.class);
Root<QueryDO> query = criteriaQuery.from(QueryDO.class);
criteriaQuery.select(query);
- criteriaQuery.where(criteriaBuilder.equal(query.get(QueryDO_.id),
- id));
+ criteriaQuery.where(criteriaBuilder.equal(query.get(QueryDO_.id), id));
QueryDO qe = null;
try {
@@ -196,14 +194,13 @@
ParameterChecker.checkStringValue(queryName, "queryName");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> criteriaQuery =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> criteriaQuery = builder
+ .createQuery(QueryDO.class);
Root<QueryDO> query = criteriaQuery.from(QueryDO.class);
Predicate condition = builder.and(
- builder.equal(query.get(QueryDO_.createdBy),
- createdBy),
+ builder.equal(query.get(QueryDO_.createdBy), createdBy),
builder.equal(query.get(QueryDO_.name), queryName));
criteriaQuery.select(query);
@@ -228,20 +225,17 @@
}
@SuppressWarnings("unchecked")
- public List<QueryDO> retrieveOwnerQuery (String userId,
- QueryType queryType) throws KustvaktException {
+ public List<QueryDO> retrieveOwnerQuery (String userId, QueryType queryType)
+ throws KustvaktException {
ParameterChecker.checkStringValue(userId, "userId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> cq =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> cq = builder.createQuery(QueryDO.class);
Root<QueryDO> query = cq.from(QueryDO.class);
Predicate conditions = builder.and(
- builder.equal(query.get(QueryDO_.createdBy),
- userId),
- builder.equal(query.get(QueryDO_.queryType),
- queryType));
+ builder.equal(query.get(QueryDO_.createdBy), userId),
+ builder.equal(query.get(QueryDO_.queryType), queryType));
cq.select(query);
cq.where(conditions);
@@ -256,15 +250,13 @@
ParameterChecker.checkStringValue(userId, "userId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> cq =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> cq = builder.createQuery(QueryDO.class);
Root<QueryDO> query = cq.from(QueryDO.class);
cq.select(query);
Predicate p = builder.and(
- builder.equal(query.get(QueryDO_.createdBy),
- userId),
+ builder.equal(query.get(QueryDO_.createdBy), userId),
builder.equal(query.get(QueryDO_.type), type));
cq.where(p);
@@ -273,17 +265,15 @@
}
@SuppressWarnings("unchecked")
- public List<QueryDO> retrieveGroupQueryByUser (String userId, QueryType queryType)
- throws KustvaktException {
+ public List<QueryDO> retrieveGroupQueryByUser (String userId,
+ QueryType queryType) throws KustvaktException {
ParameterChecker.checkStringValue(userId, "userId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> cq =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> cq = builder.createQuery(QueryDO.class);
Root<QueryDO> query = cq.from(QueryDO.class);
- Join<QueryDO, QueryAccess> access =
- query.join(QueryDO_.queryAccess);
+ Join<QueryDO, QueryAccess> access = query.join(QueryDO_.queryAccess);
// Predicate corpusStatus = builder.and(
// builder.notEqual(access.get(QueryAccess_.status),
@@ -291,28 +281,27 @@
// builder.notEqual(access.get(QueryAccess_.status),
// VirtualCorpusAccessStatus.DELETED));
- Predicate type = builder
- .equal(query.get(QueryDO_.queryType), queryType);
-
- Predicate accessStatus =
- builder.notEqual(access.get(QueryAccess_.status),
- QueryAccessStatus.DELETED);
+ Predicate type = builder.equal(query.get(QueryDO_.queryType),
+ queryType);
- Predicate userGroupStatus =
- builder.notEqual(access.get(QueryAccess_.userGroup)
- .get(UserGroup_.status), UserGroupStatus.DELETED);
+ Predicate accessStatus = builder.notEqual(
+ access.get(QueryAccess_.status), QueryAccessStatus.DELETED);
+
+ Predicate userGroupStatus = builder.notEqual(
+ access.get(QueryAccess_.userGroup).get(UserGroup_.status),
+ UserGroupStatus.DELETED);
Join<UserGroup, UserGroupMember> members = access
.join(QueryAccess_.userGroup).join(UserGroup_.members);
Predicate memberStatus = builder.equal(
members.get(UserGroupMember_.status), GroupMemberStatus.ACTIVE);
- Predicate user =
- builder.equal(members.get(UserGroupMember_.userId), userId);
+ Predicate user = builder.equal(members.get(UserGroupMember_.userId),
+ userId);
cq.select(query);
- cq.where(
- builder.and(type, accessStatus, userGroupStatus, memberStatus, user));
+ cq.where(builder.and(type, accessStatus, userGroupStatus, memberStatus,
+ user));
Query q = entityManager.createQuery(cq);
return q.getResultList();
@@ -324,15 +313,13 @@
ParameterChecker.checkObjectValue(queryType, "queryType");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> criteriaQuery =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> criteriaQuery = builder
+ .createQuery(QueryDO.class);
Root<QueryDO> query = criteriaQuery.from(QueryDO.class);
Predicate predicate = builder.and(
- builder.equal(query.get(QueryDO_.queryType),
- queryType),
- builder.or(builder.equal(
- query.get(QueryDO_.createdBy), userId),
+ builder.equal(query.get(QueryDO_.queryType), queryType),
+ builder.or(builder.equal(query.get(QueryDO_.createdBy), userId),
builder.equal(query.get(QueryDO_.type),
ResourceType.SYSTEM)));
@@ -361,17 +348,18 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryDO> criteriaQuery =
- builder.createQuery(QueryDO.class);
+ CriteriaQuery<QueryDO> criteriaQuery = builder
+ .createQuery(QueryDO.class);
Root<QueryDO> query = criteriaQuery.from(QueryDO.class);
- Join<QueryDO, QueryAccess> queryAccess =
- query.join(QueryDO_.queryAccess);
- Join<QueryAccess, UserGroup> accessGroup =
- queryAccess.join(QueryAccess_.userGroup);
+ Join<QueryDO, QueryAccess> queryAccess = query
+ .join(QueryDO_.queryAccess);
+ Join<QueryAccess, UserGroup> accessGroup = queryAccess
+ .join(QueryAccess_.userGroup);
criteriaQuery.select(query);
- criteriaQuery.where(builder.equal(accessGroup.get(UserGroup_.id), groupId));
+ criteriaQuery
+ .where(builder.equal(accessGroup.get(UserGroup_.id), groupId));
Query q = entityManager.createQuery(criteriaQuery);
return q.getResultList();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/ResourceDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/ResourceDao.java
index 002d4ea..c121669 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/ResourceDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/ResourceDao.java
@@ -40,8 +40,8 @@
*/
public List<Resource> getAllResources () {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Resource> query =
- criteriaBuilder.createQuery(Resource.class);
+ CriteriaQuery<Resource> query = criteriaBuilder
+ .createQuery(Resource.class);
Root<Resource> resource = query.from(Resource.class);
query.select(resource);
@@ -51,8 +51,8 @@
public Resource retrieveResource (String id) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Resource> query =
- criteriaBuilder.createQuery(Resource.class);
+ CriteriaQuery<Resource> query = criteriaBuilder
+ .createQuery(Resource.class);
Root<Resource> resource = query.from(Resource.class);
query.select(resource);
query.where(criteriaBuilder.equal(resource.get(Resource_.id), id));
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
index 47ddd18..5481d30 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
@@ -87,8 +87,8 @@
CriteriaQuery<Role> query = criteriaBuilder.createQuery(Role.class);
Root<Role> root = query.from(Role.class);
- ListJoin<Role, UserGroupMember> memberRole =
- root.join(Role_.userGroupMembers);
+ ListJoin<Role, UserGroupMember> memberRole = root
+ .join(Role_.userGroupMembers);
query.select(root);
query.where(criteriaBuilder.equal(memberRole.get(UserGroupMember_.id),
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/UserDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/UserDao.java
index 51ab9c1..61c24af 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/UserDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/UserDao.java
@@ -5,7 +5,8 @@
import de.ids_mannheim.korap.user.KorAPUser;
import de.ids_mannheim.korap.user.User;
-/** Dummy DAO for testing using basic authentication.
+/**
+ * Dummy DAO for testing using basic authentication.
*
* @author margaretha
*
@@ -19,5 +20,4 @@
return user;
}
-
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupDao.java
index 82ec01e..8a91e9c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupDao.java
@@ -55,8 +55,8 @@
@Autowired
private RoleDao roleDao;
- public int createGroup (String name, String description,
- String createdBy, UserGroupStatus status) throws KustvaktException {
+ public int createGroup (String name, String description, String createdBy,
+ UserGroupStatus status) throws KustvaktException {
ParameterChecker.checkStringValue(name, "name");
ParameterChecker.checkStringValue(createdBy, "createdBy");
ParameterChecker.checkObjectValue(status, "UserGroupStatus");
@@ -117,7 +117,7 @@
ParameterChecker.checkObjectValue(group, "user-group");
entityManager.merge(group);
}
-
+
/**
* Retrieves the UserGroup by the given group id. This methods
* does not
@@ -140,8 +140,8 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroup> query =
- criteriaBuilder.createQuery(UserGroup.class);
+ CriteriaQuery<UserGroup> query = criteriaBuilder
+ .createQuery(UserGroup.class);
Root<UserGroup> root = query.from(UserGroup.class);
if (fetchMembers) {
@@ -176,13 +176,13 @@
ParameterChecker.checkStringValue(userId, "userId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroup> query =
- criteriaBuilder.createQuery(UserGroup.class);
+ CriteriaQuery<UserGroup> query = criteriaBuilder
+ .createQuery(UserGroup.class);
Root<UserGroup> root = query.from(UserGroup.class);
- ListJoin<UserGroup, UserGroupMember> members =
- root.join(UserGroup_.members);
+ ListJoin<UserGroup, UserGroupMember> members = root
+ .join(UserGroup_.members);
Predicate restrictions = criteriaBuilder.and(
criteriaBuilder.equal(root.get(UserGroup_.status),
UserGroupStatus.ACTIVE),
@@ -207,13 +207,13 @@
}
}
- public UserGroup retrieveGroupByName (String groupName, boolean fetchMembers)
- throws KustvaktException {
+ public UserGroup retrieveGroupByName (String groupName,
+ boolean fetchMembers) throws KustvaktException {
ParameterChecker.checkStringValue(groupName, "groupName");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroup> query =
- criteriaBuilder.createQuery(UserGroup.class);
+ CriteriaQuery<UserGroup> query = criteriaBuilder
+ .createQuery(UserGroup.class);
Root<UserGroup> root = query.from(UserGroup.class);
if (fetchMembers) {
@@ -238,14 +238,12 @@
ParameterChecker.checkIntegerValue(queryId, "queryId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroup> criteriaQuery =
- criteriaBuilder.createQuery(UserGroup.class);
+ CriteriaQuery<UserGroup> criteriaQuery = criteriaBuilder
+ .createQuery(UserGroup.class);
Root<UserGroup> root = criteriaQuery.from(UserGroup.class);
- Join<UserGroup, QueryAccess> access =
- root.join(UserGroup_.queryAccess);
- Join<QueryAccess, QueryDO> query =
- access.join(QueryAccess_.query);
+ Join<UserGroup, QueryAccess> access = root.join(UserGroup_.queryAccess);
+ Join<QueryAccess, QueryDO> query = access.join(QueryAccess_.query);
Predicate p = criteriaBuilder.and(
criteriaBuilder.equal(root.get(UserGroup_.status),
@@ -283,8 +281,8 @@
UserGroupStatus status) throws KustvaktException {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroup> query =
- criteriaBuilder.createQuery(UserGroup.class);
+ CriteriaQuery<UserGroup> query = criteriaBuilder
+ .createQuery(UserGroup.class);
Root<UserGroup> root = query.from(UserGroup.class);
@@ -292,8 +290,8 @@
if (userId != null && !userId.isEmpty()) {
- ListJoin<UserGroup, UserGroupMember> members =
- root.join(UserGroup_.members);
+ ListJoin<UserGroup, UserGroupMember> members = root
+ .join(UserGroup_.members);
restrictions = criteriaBuilder.and(criteriaBuilder
.equal(members.get(UserGroupMember_.userId), userId));
@@ -303,8 +301,8 @@
}
}
else if (status != null) {
- restrictions =
- criteriaBuilder.equal(root.get(UserGroup_.status), status);
+ restrictions = criteriaBuilder.equal(root.get(UserGroup_.status),
+ status);
}
@@ -335,9 +333,8 @@
entityManager.persist(accessGroup);
}
- public void addQueryToGroup (List<QueryDO> queries,
- String createdBy, UserGroup group,
- QueryAccessStatus status) {
+ public void addQueryToGroup (List<QueryDO> queries, String createdBy,
+ UserGroup group, QueryAccessStatus status) {
for (QueryDO q : queries) {
addQueryToGroup(q, createdBy, status, group);
@@ -350,25 +347,22 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<QueryAccess> criteriaQuery =
- criteriaBuilder.createQuery(QueryAccess.class);
+ CriteriaQuery<QueryAccess> criteriaQuery = criteriaBuilder
+ .createQuery(QueryAccess.class);
Root<QueryAccess> root = criteriaQuery.from(QueryAccess.class);
- Join<QueryAccess, QueryDO> queryAccess =
- root.join(QueryAccess_.query);
- Join<QueryAccess, UserGroup> group =
- root.join(QueryAccess_.userGroup);
+ Join<QueryAccess, QueryDO> queryAccess = root.join(QueryAccess_.query);
+ Join<QueryAccess, UserGroup> group = root.join(QueryAccess_.userGroup);
- Predicate query = criteriaBuilder
- .equal(queryAccess.get(QueryDO_.id), queryId);
- Predicate userGroup =
- criteriaBuilder.equal(group.get(UserGroup_.id), groupId);
+ Predicate query = criteriaBuilder.equal(queryAccess.get(QueryDO_.id),
+ queryId);
+ Predicate userGroup = criteriaBuilder.equal(group.get(UserGroup_.id),
+ groupId);
criteriaQuery.select(root);
criteriaQuery.where(criteriaBuilder.and(query, userGroup));
Query q = entityManager.createQuery(criteriaQuery);
- QueryAccess access =
- (QueryAccess) q.getSingleResult();
+ QueryAccess access = (QueryAccess) q.getSingleResult();
entityManager.remove(access);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupMemberDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupMemberDao.java
index 7fe96c5..c399fd6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupMemberDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/UserGroupMemberDao.java
@@ -78,8 +78,8 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroupMember> query =
- criteriaBuilder.createQuery(UserGroupMember.class);
+ CriteriaQuery<UserGroupMember> query = criteriaBuilder
+ .createQuery(UserGroupMember.class);
Root<UserGroupMember> root = query.from(UserGroupMember.class);
@@ -110,8 +110,8 @@
ParameterChecker.checkIntegerValue(groupId, "groupId");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroupMember> query =
- criteriaBuilder.createQuery(UserGroupMember.class);
+ CriteriaQuery<UserGroupMember> query = criteriaBuilder
+ .createQuery(UserGroupMember.class);
Root<UserGroupMember> root = query.from(UserGroupMember.class);
Join<UserGroupMember, Role> memberRole = root.join("roles");
@@ -146,8 +146,8 @@
public List<UserGroupMember> retrieveMemberByGroupId (int groupId,
boolean isAdmin) throws KustvaktException {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- CriteriaQuery<UserGroupMember> query =
- criteriaBuilder.createQuery(UserGroupMember.class);
+ CriteriaQuery<UserGroupMember> query = criteriaBuilder
+ .createQuery(UserGroupMember.class);
Root<UserGroupMember> root = query.from(UserGroupMember.class);
@@ -169,7 +169,7 @@
}
catch (NoResultException e) {
throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
- "No member in group " + groupId+" is found",
+ "No member in group " + groupId + " is found",
String.valueOf(groupId));
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
index c8f68b5..beb344c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
@@ -30,7 +30,7 @@
@Getter
@Setter
@JsonInclude(Include.NON_EMPTY)
-// @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
+ // @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
public class Layer {
private String code;
private String description;
@@ -40,8 +40,8 @@
@Getter
@Setter
@JsonInclude(Include.NON_EMPTY)
-// @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
- public class Key implements Comparable<Key>{
+ // @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
+ public class Key implements Comparable<Key> {
private String code;
private String description;
@@ -50,10 +50,10 @@
public Key (String code) {
this.code = code;
}
-
+
@Override
public int compareTo (Key k) {
- return this.code.compareTo(k.code);
+ return this.code.compareTo(k.code);
}
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/InstalledPluginDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/InstalledPluginDto.java
index eb17a8e..ac31ba0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/InstalledPluginDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/InstalledPluginDto.java
@@ -24,7 +24,7 @@
private String redirectUri;
@JsonProperty("installed_date")
private String installedDate;
-
+
public InstalledPluginDto (InstalledPlugin plugin) {
OAuth2Client client = plugin.getClient();
setClientId(client.getId());
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/QueryAccessDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/QueryAccessDto.java
index 9687317..84b8b3f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/QueryAccessDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/QueryAccessDto.java
@@ -22,8 +22,9 @@
@Override
public String toString () {
- return "accessId=" + accessId + ", createdBy=" + createdBy + " , queryId="
- + queryId + ", queryName=" + queryName + ", userGroupId=" + userGroupId
- + ", userGroupName=" + userGroupName;
+ return "accessId=" + accessId + ", createdBy=" + createdBy
+ + " , queryId=" + queryId + ", queryName=" + queryName
+ + ", userGroupId=" + userGroupId + ", userGroupName="
+ + userGroupName;
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/QueryDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/QueryDto.java
index fe221cf..6d31fd6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/QueryDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/QueryDto.java
@@ -8,8 +8,9 @@
import lombok.Getter;
import lombok.Setter;
-/** Defines the structure of {@link QueryDO} description to be
- * sent as JSON objects in HTTP responses.
+/**
+ * Defines the structure of {@link QueryDO} description to be
+ * sent as JSON objects in HTTP responses.
*
* @author margaretha
*
@@ -26,12 +27,12 @@
private String description;
private String requiredAccess;
private String createdBy;
-
+
private int numberOfDoc;
private int numberOfParagraphs;
private int numberOfSentences;
private int numberOfTokens;
-
+
private String query;
private String queryLanguage;
private JsonNode koralQuery;
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupDto.java
index a2b2732..273d52e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupDto.java
@@ -9,8 +9,9 @@
import lombok.Getter;
import lombok.Setter;
-/** Defines the structure of UserGroup description, e.g.
- * to be sent as JSON objects in HTTP response.
+/**
+ * Defines the structure of UserGroup description, e.g.
+ * to be sent as JSON objects in HTTP response.
*
* @author margaretha
*
@@ -24,10 +25,10 @@
private String description;
private String owner;
private UserGroupStatus status;
-
+
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<UserGroupMemberDto> members;
-
+
private GroupMemberStatus userMemberStatus;
private List<String> userRoles;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupMemberDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupMemberDto.java
index bf3cfea..23cfa3d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupMemberDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/UserGroupMemberDto.java
@@ -6,8 +6,10 @@
import lombok.Getter;
import lombok.Setter;
-/** Defines UserGroupMember description, e.g. to be sent as
- * JSON objects in HTTP Responses.
+/**
+ * Defines UserGroupMember description, e.g. to be sent as
+ * JSON objects in HTTP Responses.
+ *
* @author margaretha
*
*/
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java b/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
index b192cfd..a1cc536 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
@@ -94,7 +94,7 @@
for (AnnotationKey ak : f.getKeys()) {
Annotation a = ak.getKey();
Map<String, String> values = new TreeMap<>();
-
+
Key key = dto.new Key(a.getCode());
if (language.equals("de")) {
key.setDescription(a.getGermanDescription());
@@ -136,16 +136,14 @@
private Map<String, List<AnnotationLayer>> createFoundryMap (
List<AnnotationLayer> pairs) {
- Map<String, List<AnnotationLayer>> foundries =
- new HashMap<String, List<AnnotationLayer>>();
+ Map<String, List<AnnotationLayer>> foundries = new HashMap<String, List<AnnotationLayer>>();
for (AnnotationLayer p : pairs) {
String foundryCode = p.getFoundry().getCode();
if (foundries.containsKey(foundryCode)) {
foundries.get(foundryCode).add(p);
}
else {
- List<AnnotationLayer> foundryList =
- new ArrayList<AnnotationLayer>();
+ List<AnnotationLayer> foundryList = new ArrayList<AnnotationLayer>();
foundryList.add(p);
foundries.put(foundryCode, foundryList);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java b/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
index b4ff8eb..d04576c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
@@ -23,8 +23,8 @@
public class ResourceConverter {
public List<ResourceDto> convertToResourcesDto (List<Resource> resources) {
- List<ResourceDto> resourceDtoList =
- new ArrayList<ResourceDto>(resources.size());
+ List<ResourceDto> resourceDtoList = new ArrayList<ResourceDto>(
+ resources.size());
ResourceDto dto;
Map<String, String> titles;
HashMap<Integer, String> layers;
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/converter/UserGroupConverter.java b/full/src/main/java/de/ids_mannheim/korap/dto/converter/UserGroupConverter.java
index cf5878f..706cc21 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/converter/UserGroupConverter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/converter/UserGroupConverter.java
@@ -43,8 +43,8 @@
}
if (members != null) {
- ArrayList<UserGroupMemberDto> memberDtos =
- new ArrayList<>(members.size());
+ ArrayList<UserGroupMemberDto> memberDtos = new ArrayList<>(
+ members.size());
for (UserGroupMember member : members) {
UserGroupMemberDto memberDto = new UserGroupMemberDto();
diff --git a/full/src/main/java/de/ids_mannheim/korap/encryption/DefaultEncryption.java b/full/src/main/java/de/ids_mannheim/korap/encryption/DefaultEncryption.java
index aaee8d2..6792ff3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/encryption/DefaultEncryption.java
+++ b/full/src/main/java/de/ids_mannheim/korap/encryption/DefaultEncryption.java
@@ -17,56 +17,47 @@
private SecureRandom randomizer;
-
public DefaultEncryption () {
randomizer = new SecureRandom();
}
-
@Override
public String secureHash (String input, String salt)
throws KustvaktException {
return null;
}
-
@Override
public String secureHash (String input) {
return null;
}
-
@Override
public boolean checkHash (String plain, String hash, String salt) {
return false;
}
-
@Override
public boolean checkHash (String plain, String hash) {
return false;
}
-
@Override
public String createToken (boolean hash, Object ... obj) {
return createToken();
}
-
@Override
public String createToken () {
return new BigInteger(100, randomizer).toString(20);
}
-
@Override
public String createRandomNumber (Object ... obj) {
return createToken();
}
-
@Override
public String encodeBase () {
return null;
diff --git a/full/src/main/java/de/ids_mannheim/korap/encryption/KustvaktEncryption.java b/full/src/main/java/de/ids_mannheim/korap/encryption/KustvaktEncryption.java
index 211e6e5..610f69c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/encryption/KustvaktEncryption.java
+++ b/full/src/main/java/de/ids_mannheim/korap/encryption/KustvaktEncryption.java
@@ -18,18 +18,15 @@
public class KustvaktEncryption implements EncryptionIface {
private static final String ALGORITHM = "SHA-256";
- private static Logger jlog = LogManager
- .getLogger(KustvaktEncryption.class);
+ private static Logger jlog = LogManager.getLogger(KustvaktEncryption.class);
private final FullConfiguration config;
-
public KustvaktEncryption (FullConfiguration config) {
jlog.info("initializing KorAPEncryption implementation");
this.config = config;
}
-
public static boolean matchTokenByteCode (Object param) {
if (!(param instanceof String))
return false;
@@ -38,12 +35,10 @@
return 64 == bytes.length;
}
-
private String encodeBase (byte[] bytes) throws EncoderException {
return Base64.encodeBase64String(bytes);
}
-
@Override
public String encodeBase () {
try {
@@ -54,12 +49,10 @@
}
}
-
public String secureHash (String input) {
return secureHash(input, "");
}
-
@Override
public String secureHash (String input, String salt) {
String hashString = "";
@@ -75,7 +68,8 @@
for (byte b : digest)
hashString += String.format("%02x", b);
}
- catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
+ catch (UnsupportedEncodingException
+ | NoSuchAlgorithmException e) {
e.printStackTrace();
}
break;
@@ -83,14 +77,12 @@
hashString = bcryptHash(input, salt);
break;
default:
- jlog.warn("Invalid value: "+ config.getSecureHashAlgorithm());
+ jlog.warn("Invalid value: " + config.getSecureHashAlgorithm());
break;
}
return hashString;
}
-
-
public String hash (String input) {
String hashString = "";
MessageDigest md;
@@ -113,7 +105,6 @@
return hashString;
}
-
/**
* // some sort of algorithm to create token and isSystem
* regularly the integrity
@@ -136,9 +127,9 @@
return SecureRGenerator.getNextSecureRandom(size);
}
-
/**
* does this need to be equal for every iteration?!
+ *
* @param hash
* @param obj
* @return
@@ -162,19 +153,17 @@
}
-
@Override
public String createToken () {
return RandomStringUtils.randomAlphanumeric(64);
-
- // EM: code from MH
-// String encoded;
-// String v = RandomStringUtils.randomAlphanumeric(64);
-// encoded = hash(v);
-// jlog.trace("creating new token {}", encoded);
-// return encoded;
- }
+ // EM: code from MH
+ // String encoded;
+ // String v = RandomStringUtils.randomAlphanumeric(64);
+ // encoded = hash(v);
+ // jlog.trace("creating new token {}", encoded);
+ // return encoded;
+ }
@Override
public String createRandomNumber (Object ... obj) {
@@ -187,7 +176,6 @@
return createToken(false, obj);
}
-
@Override
public boolean checkHash (String plain, String hash, String salt) {
String pw = "";
@@ -209,7 +197,6 @@
return pw.equals(hash);
}
-
@Override
public boolean checkHash (String plain, String hash) {
switch (config.getSecureHashAlgorithm()) {
@@ -228,14 +215,12 @@
return false;
}
-
private String bcryptHash (String text, String salt) {
if (salt == null || salt.isEmpty())
salt = BCrypt.gensalt(config.getLoadFactor());
return BCrypt.hashpw(text, salt);
}
-
@Override
public String toString () {
return this.getClass().getCanonicalName();
@@ -248,8 +233,8 @@
protected static final int ID_RANDOM_SIZE = 128;
protected static final int CORPUS_RANDOM_SIZE = 64;
private static final char[] HEX_DIGIT = { '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'z', 'x',
- 'h', 'q', 'w' };
+ '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'z', 'x', 'h',
+ 'q', 'w' };
private static final SecureRandom sRandom__;
static {
@@ -261,7 +246,6 @@
}
}
-
public static byte[] getNextSecureRandom (int bits) {
if (bits % 8 != 0) {
throw new IllegalArgumentException(
@@ -275,7 +259,6 @@
return bytes;
}
-
public static String toHex (byte[] bytes) {
if (bytes == null) {
return null;
@@ -289,7 +272,6 @@
return buffer.toString();
}
-
private static String byteToHex (byte b) {
char[] array = { HEX_DIGIT[(b >> 4 & 0xF)], HEX_DIGIT[(b & 0xF)] };
return new String(array);
diff --git a/full/src/main/java/de/ids_mannheim/korap/encryption/RandomCodeGenerator.java b/full/src/main/java/de/ids_mannheim/korap/encryption/RandomCodeGenerator.java
index fe7bab7..e6ff6e0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/encryption/RandomCodeGenerator.java
+++ b/full/src/main/java/de/ids_mannheim/korap/encryption/RandomCodeGenerator.java
@@ -35,13 +35,13 @@
public static List<Character> charList = alphanumeric.chars()
.mapToObj(c -> (char) c).collect(Collectors.toList());
- public final static List<String> LIMITED_CHARACTERS =
- Arrays.asList(new String[] { "3", "4", "6", "7", "9", "b", "d", "f",
- "h", "m", "n", "p", "r", "t", "F", "G", "H", "J", "L", "M",
- "N", "P", "R", "T" });
+ public final static List<String> LIMITED_CHARACTERS = Arrays
+ .asList(new String[] { "3", "4", "6", "7", "9", "b", "d", "f", "h",
+ "m", "n", "p", "r", "t", "F", "G", "H", "J", "L", "M", "N",
+ "P", "R", "T" });
private Logger log = LogManager.getLogger(RandomCodeGenerator.class);
-
+
@Autowired
public KustvaktConfiguration config;
@@ -56,8 +56,7 @@
else {
secureRandom = new SecureRandom();
}
- log.info(
- "Secure random algorithm: " + secureRandom.getAlgorithm());
+ log.info("Secure random algorithm: " + secureRandom.getAlgorithm());
}
public String createRandomCode (KustvaktConfiguration c)
@@ -95,8 +94,7 @@
StringBuffer s = new StringBuffer();
for (char c : code.toCharArray()) {
if (!charList.contains(c)) {
- int n = ThreadLocalRandom.current().nextInt(0,
- charList.size());
+ int n = ThreadLocalRandom.current().nextInt(0, charList.size());
c = charList.get(n);
}
s.append(c);
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/Admin.java b/full/src/main/java/de/ids_mannheim/korap/entity/Admin.java
index 66a90aa..b0cbed9 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/Admin.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/Admin.java
@@ -10,7 +10,8 @@
import lombok.Getter;
import lombok.Setter;
-/** Describes admin users
+/**
+ * Describes admin users
*
* @author margaretha
*
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/InstalledPlugin.java b/full/src/main/java/de/ids_mannheim/korap/entity/InstalledPlugin.java
index efc0a01..12e19ce 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/InstalledPlugin.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/InstalledPlugin.java
@@ -20,7 +20,7 @@
@Getter
@Entity
@Table(name = "installed_plugin")
-public class InstalledPlugin implements Comparable<InstalledPlugin>{
+public class InstalledPlugin implements Comparable<InstalledPlugin> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -29,11 +29,11 @@
private String installedBy;
@Column(name = "installed_date")
private ZonedDateTime installedDate;
-
+
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "client_id")
private OAuth2Client client;
-
+
// where a plugin is installed
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "super_client_id")
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/QueryAccess.java b/full/src/main/java/de/ids_mannheim/korap/entity/QueryAccess.java
index b0c0c29..42c7968 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/QueryAccess.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/QueryAccess.java
@@ -16,9 +16,10 @@
import lombok.Getter;
import lombok.Setter;
-/** Describes the relationship between virtual corpora and user groups,
- * i.e. which groups may access which virtual corpora, and the history
- * of group-access management.
+/**
+ * Describes the relationship between virtual corpora and user groups,
+ * i.e. which groups may access which virtual corpora, and the history
+ * of group-access management.
*
* @author margaretha
* @see QueryDO
@@ -51,10 +52,8 @@
@JoinColumn(name = "user_group_id", referencedColumnName = "id")
private UserGroup userGroup;
-
@Override
public String toString () {
- return "id=" + id + ", query= " + query
- + ", userGroup= " + userGroup;
+ return "id=" + id + ", query= " + query + ", userGroup= " + userGroup;
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/QueryDO.java b/full/src/main/java/de/ids_mannheim/korap/entity/QueryDO.java
index 4c1b09e..77d8102 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/QueryDO.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/QueryDO.java
@@ -56,7 +56,7 @@
private String createdBy;
@Column(name = "is_cached")
private boolean isCached;
-
+
@Enumerated(EnumType.STRING)
@Column(name = "query_type")
private QueryType queryType;
@@ -64,8 +64,7 @@
@Column(name = "query_language")
private String queryLanguage;
- @OneToMany(mappedBy = "query", fetch = FetchType.LAZY,
- cascade = CascadeType.REMOVE)
+ @OneToMany(mappedBy = "query", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<QueryAccess> queryAccess;
@Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/Role.java b/full/src/main/java/de/ids_mannheim/korap/entity/Role.java
index 43e1770..f096c80 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/Role.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/Role.java
@@ -37,8 +37,7 @@
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
private List<UserGroupMember> userGroupMembers;
- @OneToMany(mappedBy = "role", fetch = FetchType.EAGER,
- cascade = CascadeType.REMOVE)
+ @OneToMany(mappedBy = "role", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
private List<Privilege> privileges;
public String toString () {
@@ -64,7 +63,7 @@
}
return false;
}
-
+
@Override
public int hashCode () {
int hash = 7;
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/UserGroup.java b/full/src/main/java/de/ids_mannheim/korap/entity/UserGroup.java
index 74f0beb..9a7db7d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/UserGroup.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/UserGroup.java
@@ -50,12 +50,10 @@
@Enumerated(EnumType.STRING)
private UserGroupStatus status;
- @OneToMany(mappedBy = "group", fetch = FetchType.LAZY,
- cascade = CascadeType.REMOVE)
+ @OneToMany(mappedBy = "group", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<UserGroupMember> members;
- @OneToMany(mappedBy = "userGroup", fetch = FetchType.LAZY,
- cascade = CascadeType.REMOVE)
+ @OneToMany(mappedBy = "userGroup", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<QueryAccess> queryAccess;
@Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/UserGroupMember.java b/full/src/main/java/de/ids_mannheim/korap/entity/UserGroupMember.java
index 760277c..e1cc3e5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/UserGroupMember.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/UserGroupMember.java
@@ -24,19 +24,20 @@
import lombok.Getter;
import lombok.Setter;
-/** Describes members of user groups. Only member of predefined role
- * group admin can see the rest of members.
+/**
+ * Describes members of user groups. Only member of predefined role
+ * group admin can see the rest of members.
*
- * @author margaretha
- * @see UserGroup
- * @see Role
- * @see PredefinedRole
+ * @author margaretha
+ * @see UserGroup
+ * @see Role
+ * @see PredefinedRole
*/
@Setter
@Getter
@Entity
-@Table(name = "user_group_member",
- indexes = { @Index(unique = true, columnList = "user_id, group_id") })
+@Table(name = "user_group_member", indexes = {
+ @Index(unique = true, columnList = "user_id, group_id") })
public class UserGroupMember {
@Id
@@ -48,7 +49,7 @@
private String createdBy;
@Column(name = "deleted_by")
private String deletedBy;
-
+
// auto update in the database
@Column(name = "status_date")
private ZonedDateTime statusDate;
@@ -60,17 +61,14 @@
@JoinColumn(name = "group_id")
private UserGroup group;
- /** Information about roles is deemed to be always necessary to describe a member.
+ /**
+ * Information about roles is deemed to be always necessary to
+ * describe a member.
*
*/
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "group_member_role",
- joinColumns = @JoinColumn(name = "group_member_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "role_id",
- referencedColumnName = "id"),
- uniqueConstraints = @UniqueConstraint(
- columnNames = { "group_member_id", "role_id" }))
+ @JoinTable(name = "group_member_role", joinColumns = @JoinColumn(name = "group_member_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), uniqueConstraints = @UniqueConstraint(columnNames = {
+ "group_member_id", "role_id" }))
private Set<Role> roles;
@Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/exceptions/DatabaseException.java b/full/src/main/java/de/ids_mannheim/korap/exceptions/DatabaseException.java
index a142ea7..f0c9bcf 100644
--- a/full/src/main/java/de/ids_mannheim/korap/exceptions/DatabaseException.java
+++ b/full/src/main/java/de/ids_mannheim/korap/exceptions/DatabaseException.java
@@ -9,26 +9,26 @@
public class DatabaseException extends KustvaktException {
private DatabaseException (Object userid, Integer status, String message,
- String args, Exception e) {
+ String args, Exception e) {
super(String.valueOf(userid), status, message, args, e);
}
- public DatabaseException (Object userid, String target, Integer status, String message,
- String ... args) {
+ public DatabaseException (Object userid, String target, Integer status,
+ String message, String ... args) {
this(null, userid, target, status, message);
}
- public DatabaseException (Exception e, Object userid, String target, Integer status, String message,
- String ... args) {
+ public DatabaseException (Exception e, Object userid, String target,
+ Integer status, String message, String ... args) {
this(userid, status, message, Arrays.asList(args).toString(), e);
}
-
- public DatabaseException (KustvaktException e, Integer status, String ... args) {
- this(e.getUserid(), e.getStatusCode(), e.getMessage(), e.getEntity(), e);
+ public DatabaseException (KustvaktException e, Integer status,
+ String ... args) {
+ this(e.getUserid(), e.getStatusCode(), e.getMessage(), e.getEntity(),
+ e);
}
-
@Override
public String string () {
return "DBExcpt{" + "status=" + getStatusCode() + ", message="
diff --git a/full/src/main/java/de/ids_mannheim/korap/exceptions/EmptyResultException.java b/full/src/main/java/de/ids_mannheim/korap/exceptions/EmptyResultException.java
index d52238b..d687d39 100644
--- a/full/src/main/java/de/ids_mannheim/korap/exceptions/EmptyResultException.java
+++ b/full/src/main/java/de/ids_mannheim/korap/exceptions/EmptyResultException.java
@@ -12,7 +12,6 @@
super(StatusCodes.NO_RESULT_FOUND, message, entity);
}
-
public EmptyResultException (String entity) {
super(StatusCodes.NO_RESULT_FOUND, "No entity found for id", entity);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/exceptions/KustvaktException.java b/full/src/main/java/de/ids_mannheim/korap/exceptions/KustvaktException.java
index 0915bb5..0311878 100644
--- a/full/src/main/java/de/ids_mannheim/korap/exceptions/KustvaktException.java
+++ b/full/src/main/java/de/ids_mannheim/korap/exceptions/KustvaktException.java
@@ -21,18 +21,18 @@
private String userid;
private Integer statusCode;
private int responseStatus;
-
+
private String entity;
private String notification;
private boolean isNotification;
-// private TokenType authType;
+ // private TokenType authType;
private URI redirectUri;
private ErrorObject oauth2Error;
public KustvaktException (int status) {
this.statusCode = status;
}
-
+
public KustvaktException (int status, String ... args) {
super(args[0]);
this.statusCode = status;
@@ -40,12 +40,13 @@
this.entity = Arrays.asList(subarray).toString();
}
- public KustvaktException (int status, String notification, boolean isNotification) {
+ public KustvaktException (int status, String notification,
+ boolean isNotification) {
this.statusCode = status;
this.notification = notification;
this.isNotification = isNotification;
}
-
+
public boolean hasNotification () {
return isNotification;
}
@@ -61,7 +62,6 @@
this(userid, status, message, entity, null);
}
-
public KustvaktException (Object userid, int status, String message,
String entity, Exception e) {
super(message, e);
@@ -70,7 +70,6 @@
this.userid = String.valueOf(userid);
}
-
public KustvaktException (Object userid, int status, String entity) {
super(StatusCodes.getMessage(status));
this.statusCode = status;
@@ -83,20 +82,21 @@
this.statusCode = status;
this.entity = entity;
}
-
- public KustvaktException (int status, String message, String entity, Throwable e) {
+
+ public KustvaktException (int status, String message, String entity,
+ Throwable e) {
super(message, e);
this.statusCode = status;
this.entity = entity;
}
-
+
public KustvaktException (int status, String message, Throwable e) {
super(message, e);
this.statusCode = status;
}
public KustvaktException (int status, String message,
- ErrorObject oauth2Error) {
+ ErrorObject oauth2Error) {
super(message);
this.statusCode = status;
this.oauth2Error = oauth2Error;
@@ -108,14 +108,11 @@
this.statusCode = status;
}
-
public KustvaktException (String message, Throwable cause, int status) {
super(message, cause);
this.statusCode = status;
}
-
-
public KustvaktException (String notification) {
this.notification = notification;
isNotification = true;
diff --git a/full/src/main/java/de/ids_mannheim/korap/exceptions/StatusCodes.java b/full/src/main/java/de/ids_mannheim/korap/exceptions/StatusCodes.java
index 73f1c62..94778c6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/exceptions/StatusCodes.java
+++ b/full/src/main/java/de/ids_mannheim/korap/exceptions/StatusCodes.java
@@ -32,7 +32,7 @@
public static final int CACHING_VC = 116;
public static final int NETWORK_ENDPOINT_NOT_AVAILABLE = 117;
public static final int SEARCH_NETWORK_ENDPOINT_FAILED = 118;
-
+
/**
* 200 status codes general JSON serialization error
*/
@@ -45,18 +45,19 @@
/**
* 300 status codes for query language and serialization
- * see Koral (de.ids_mannheim.korap.query.serialize.util.StatusCodes)
+ * see Koral
+ * (de.ids_mannheim.korap.query.serialize.util.StatusCodes)
*/
/**
- * 400 status codes for rewrite functions
+ * 400 status codes for rewrite functions
*/
public static final int REWRITE_ERROR_DEFAULT = 400;
public static final int NON_PUBLIC_FIELD_IGNORED = 401;
public static final int PIPE_FAILED = 402;
-
-// public static final int UNSUPPORTED_RESOURCE = 402;
+
+ // public static final int UNSUPPORTED_RESOURCE = 402;
// public static final int REWRITE_FAILED = 403;
//public static final int UNSUPPORTED_FOUNDRY = 403;
//public static final int UNSUPPORTED_CORPUS = 404;
@@ -67,12 +68,10 @@
//public static final int FOUNDRY_REWRITE = 408;
//public static final int FOUNDRY_INJECTION = 409;
// public static final int MISSING_RESOURCE = 405;
-// public static final int NO_POLICY_TARGET = 406;
-// public static final int NO_POLICY_CONDITION = 407;
-// public static final int NO_POLICY_PERMISSION = 408;
-// public static final int NO_POLICIES = 409;
-
-
+ // public static final int NO_POLICY_TARGET = 406;
+ // public static final int NO_POLICY_CONDITION = 407;
+ // public static final int NO_POLICY_PERMISSION = 408;
+ // public static final int NO_POLICIES = 409;
/**
* 500 status codes for access control related components (also
@@ -81,7 +80,6 @@
// todo: extend according to policy rewrite possible!
// policy errors
-
// database codes
public static final int DB_GET_FAILED = 500;
public static final int DB_INSERT_FAILED = 501;
@@ -94,7 +92,6 @@
public static final int DB_UPDATE_SUCCESSFUL = 507;
public static final int DB_ENTRY_EXISTS = 508;
-
// public static final int ARGUMENT_VALIDATION_FAILURE = 700;
// public static final int ARGUMENT_VALIDATION_FAILURE = 701;
@@ -109,14 +106,12 @@
public static final int GET_ACCOUNT_SUCCESSFUL = 706;
public static final int GET_ACCOUNT_FAILED = 707;
-
public static final int STATUS_OK = 1000;
public static final int NOTHING_CHANGED = 1001;
public static final int INVALID_REQUEST = 1002;
-
-// public static final int ACCESS_DENIED = 1003;
-
+ // public static final int ACCESS_DENIED = 1003;
+
// User group and member
public static final int GROUP_MEMBER_EXISTS = 1601;
public static final int GROUP_MEMBER_INACTIVE = 1602;
@@ -124,13 +119,13 @@
public static final int GROUP_MEMBER_NOT_FOUND = 1604;
public static final int INVITATION_EXPIRED = 1605;
public static final int GROUP_DELETED = 1606;
-
+
/**
* 1800 Oauth2
*/
public static final int OAUTH2_SYSTEM_ERROR = 1800;
-
+
public static final int CLIENT_REGISTRATION_FAILED = 1801;
public static final int CLIENT_DEREGISTRATION_FAILED = 1802;
public static final int CLIENT_AUTHENTICATION_FAILED = 1803;
@@ -141,23 +136,22 @@
public static final int INVALID_SCOPE = 1808;
public static final int INVALID_AUTHORIZATION = 1809;
public static final int INVALID_REFRESH_TOKEN = 1810;
-
+
public static final int UNSUPPORTED_GRANT_TYPE = 1811;
public static final int UNSUPPORTED_AUTHENTICATION_METHOD = 1812;
public static final int UNSUPPORTED_RESPONSE_TYPE = 1813;
-
+
public static final int USER_REAUTHENTICATION_REQUIRED = 1822;
-
+
public static final int INVALID_REFRESH_TOKEN_EXPIRY = 1830;
-
+
/**
* 1850 Plugins
*/
public static final int PLUGIN_NOT_PERMITTED = 1850;
public static final int PLUGIN_HAS_BEEN_INSTALLED = 1851;
-
-
+
/**
* 1900 User account and logins
*/
@@ -174,15 +168,15 @@
/**
* 2000 status and error codes concerning authentication
*
- * Response with WWW-Authenticate header will be created
- * for all KustvaktExceptions with status codes 2001 or greater
- *
+ * Response with WWW-Authenticate header will be created
+ * for all KustvaktExceptions with status codes 2001 or greater
+ *
* MH: service level messages and callbacks
*/
@Deprecated
public static final int INCORRECT_ADMIN_TOKEN = 2000;
-
+
public static final int AUTHENTICATION_FAILED = 2001;
public static final int LOGIN_FAILED = 2002;
public static final int EXPIRED = 2003;
@@ -206,13 +200,13 @@
this.props = ConfigLoader.loadProperties("codes.info");
}
-
public static final String getMessage (int code) {
return getCodes().props.getProperty(String.valueOf(code));
}
public static StatusCodes getCodes () {
- if (codes == null) codes = new StatusCodes();
+ if (codes == null)
+ codes = new StatusCodes();
return codes;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/exceptions/WrappedException.java b/full/src/main/java/de/ids_mannheim/korap/exceptions/WrappedException.java
index ed091f3..2d12165 100644
--- a/full/src/main/java/de/ids_mannheim/korap/exceptions/WrappedException.java
+++ b/full/src/main/java/de/ids_mannheim/korap/exceptions/WrappedException.java
@@ -12,21 +12,19 @@
private static final long serialVersionUID = 1L;
-
private WrappedException (Object userid, Integer status, String message,
String args, Exception rootCause) {
super(String.valueOf(userid), status, message, args, rootCause);
}
-
public WrappedException (Object userid, Integer status, String ... args) {
this(userid, status, "", Arrays.asList(args).toString(), null);
}
-
public WrappedException (KustvaktException e, Integer status,
String ... args) {
- this(e.getUserid(), e.getStatusCode(), e.getMessage(), e.getEntity(), e);
+ this(e.getUserid(), e.getStatusCode(), e.getMessage(), e.getEntity(),
+ e);
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/handlers/BatchBuilder.java b/full/src/main/java/de/ids_mannheim/korap/handlers/BatchBuilder.java
index bdc622d..c362773 100644
--- a/full/src/main/java/de/ids_mannheim/korap/handlers/BatchBuilder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/handlers/BatchBuilder.java
@@ -25,12 +25,10 @@
private JdbcOperations operations;
-
public BatchBuilder (JdbcOperations operations) {
this.operations = operations;
}
-
public <T> List<T> selectFromIDs (String query, Collection ids,
RowMapper<T> mapper) {
List l = new ArrayList(ids);
diff --git a/full/src/main/java/de/ids_mannheim/korap/handlers/RowMapperFactory.java b/full/src/main/java/de/ids_mannheim/korap/handlers/RowMapperFactory.java
index d2240ed..47ad065 100644
--- a/full/src/main/java/de/ids_mannheim/korap/handlers/RowMapperFactory.java
+++ b/full/src/main/java/de/ids_mannheim/korap/handlers/RowMapperFactory.java
@@ -18,7 +18,7 @@
*/
public class RowMapperFactory {
- public static class UserMapMapper implements RowMapper<Map<?,?>> {
+ public static class UserMapMapper implements RowMapper<Map<?, ?>> {
@Override
public Map<?, ?> mapRow (ResultSet rs, int rowNum) throws SQLException {
@@ -36,23 +36,23 @@
case 0:
user = getKorAP(rs);
break;
-// case 1:
-// user = getShib(rs);
-// break;
+ // case 1:
+ // user = getShib(rs);
+ // break;
default:
user = User.UserFactory.getDemoUser();
user.setId(rs.getInt("id"));
- user.setAccountCreation(rs.getTimestamp(
- Attributes.ACCOUNT_CREATION).getTime());
+ user.setAccountCreation(
+ rs.getTimestamp(Attributes.ACCOUNT_CREATION)
+ .getTime());
return user;
}
return user;
}
-
private KorAPUser getKorAP (ResultSet rs) throws SQLException {
- KorAPUser user = User.UserFactory.getUser(rs
- .getString(Attributes.USERNAME));
+ KorAPUser user = User.UserFactory
+ .getUser(rs.getString(Attributes.USERNAME));
user.setPassword(rs.getString(Attributes.PASSWORD));
user.setId(rs.getInt(Attributes.ID));
user.setAccountLocked(rs.getBoolean(Attributes.ACCOUNTLOCK));
@@ -60,21 +60,19 @@
user.setAccountLink(rs.getString(Attributes.ACCOUNTLINK));
long l = rs.getLong(Attributes.URI_EXPIRATION);
- URIParam param = new URIParam(
- rs.getString(Attributes.URI_FRAGMENT), l == 0 ? -1
- : new Timestamp(l).getTime());
+ URIParam param = new URIParam(rs.getString(Attributes.URI_FRAGMENT),
+ l == 0 ? -1 : new Timestamp(l).getTime());
user.addField(param);
return user;
}
-
-// private ShibbolethUser getShib (ResultSet rs) throws SQLException {
-// ShibbolethUser user = User.UserFactory.getShibInstance(
-// rs.getString(Attributes.USERNAME),
-// rs.getString(Attributes.MAIL), rs.getString(Attributes.CN));
-// user.setId(rs.getInt(Attributes.ID));
-// return user;
-// }
+ // private ShibbolethUser getShib (ResultSet rs) throws SQLException {
+ // ShibbolethUser user = User.UserFactory.getShibInstance(
+ // rs.getString(Attributes.USERNAME),
+ // rs.getString(Attributes.MAIL), rs.getString(Attributes.CN));
+ // user.setId(rs.getInt(Attributes.ID));
+ // return user;
+ // }
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/interfaces/EncryptionIface.java b/full/src/main/java/de/ids_mannheim/korap/interfaces/EncryptionIface.java
index 46f519a..fe0c722 100644
--- a/full/src/main/java/de/ids_mannheim/korap/interfaces/EncryptionIface.java
+++ b/full/src/main/java/de/ids_mannheim/korap/interfaces/EncryptionIface.java
@@ -10,11 +10,10 @@
public interface EncryptionIface {
public enum Encryption {
- @Deprecated
+ @Deprecated
SIMPLE, ESAPICYPHER, BCRYPT
}
-
/**
* One-way hashing of String input. Used to canonicalize
*
@@ -25,10 +24,8 @@
public String secureHash (String input, String salt)
throws KustvaktException;
-
public String secureHash (String input);
-
/**
* @param plain
* @param hash
@@ -37,10 +34,8 @@
*/
public boolean checkHash (String plain, String hash, String salt);
-
public boolean checkHash (String plain, String hash);
-
/**
* create random String to be used as authentication token
*
@@ -48,10 +43,8 @@
*/
public String createToken (boolean hash, Object ... obj);
-
public String createToken ();
-
/**
* create a random Integer to be used as ID for databases
*
@@ -59,15 +52,12 @@
*/
public String createRandomNumber (Object ... obj);
-
public String encodeBase ();
-
- // @Deprecated
+ // @Deprecated
//public Map<String, Object> validateMap (Map<String, Object> map)
// throws KustvaktException;
-
//@Deprecated
//public String validateEntry (String input, String type)
// throws KustvaktException;
diff --git a/full/src/main/java/de/ids_mannheim/korap/interfaces/EntityHandlerIface.java b/full/src/main/java/de/ids_mannheim/korap/interfaces/EntityHandlerIface.java
index 9bcf614..5a3bcfe 100644
--- a/full/src/main/java/de/ids_mannheim/korap/interfaces/EntityHandlerIface.java
+++ b/full/src/main/java/de/ids_mannheim/korap/interfaces/EntityHandlerIface.java
@@ -11,26 +11,20 @@
*/
public interface EntityHandlerIface {
- User getAccount (String username) throws EmptyResultException,
- KustvaktException;
-
+ User getAccount (String username)
+ throws EmptyResultException, KustvaktException;
int updateAccount (User user) throws KustvaktException;
-
int createAccount (User user) throws KustvaktException;
-
int deleteAccount (Integer userid) throws KustvaktException;
-
int truncate () throws KustvaktException;
-
int resetPassphrase (String username, String uriToken, String passphrase)
throws KustvaktException;
-
int activateAccount (String username, String uriToken)
throws KustvaktException;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2ClientType.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2ClientType.java
index dd1da81..b682883 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2ClientType.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2ClientType.java
@@ -4,7 +4,7 @@
* Defines possible OAuth2 client types.
*
* Quoted from RFC 6749:
- * <ul>
+ * <ul>
*
* <li> <b>Confidential clients</b> are clients capable of maintaining
* the confidentiality of their
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2Error.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2Error.java
index 4b76a26..aeb1cc8 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2Error.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/constant/OAuth2Error.java
@@ -54,8 +54,7 @@
* The authorization grant type is not supported by the
* authorization server.
*/
- public static final String UNSUPPORTED_GRANT_TYPE =
- "unsupported_grant_type";
+ public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
/**
* The requested scope is invalid, unknown, or malformed.
@@ -74,8 +73,7 @@
* The authorization server does not support obtaining an
* authorization code using this method.
*/
- public static final String UNSUPPORTED_RESPONSE_TYPE =
- "unsupported_response_type";
+ public static final String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
/**
* The authorization server encountered an unexpected
@@ -94,8 +92,7 @@
* Service Unavailable HTTP status code cannot be returned
* to the client via an HTTP redirect.)
*/
- public static final String TEMPORARILY_UNAVAILABLE =
- "temporarily_unavailable";
+ public static final String TEMPORARILY_UNAVAILABLE = "temporarily_unavailable";
/**
* The request requires higher privileges than provided by the
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessScopeDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessScopeDao.java
index 9a2579c..77a578d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessScopeDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessScopeDao.java
@@ -33,8 +33,8 @@
@SuppressWarnings("unchecked")
public List<AccessScope> retrieveAccessScopes () {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessScope> query =
- builder.createQuery(AccessScope.class);
+ CriteriaQuery<AccessScope> query = builder
+ .createQuery(AccessScope.class);
Root<AccessScope> root = query.from(AccessScope.class);
query.select(root);
Query q = entityManager.createQuery(query);
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessTokenDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessTokenDao.java
index b2fec0b..35b2b75 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessTokenDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AccessTokenDao.java
@@ -65,8 +65,8 @@
ParameterChecker.checkObjectValue(authenticationTime,
"authentication time");
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
ZonedDateTime expiry;
AccessToken accessToken = new AccessToken();
@@ -91,16 +91,17 @@
entityManager.persist(accessToken);
}
- public void storeAccessToken (AccessToken accessToken)
- throws KustvaktException {
+ public void storeAccessToken (AccessToken accessToken)
+ throws KustvaktException {
ParameterChecker.checkObjectValue(accessToken, "access token");
entityManager.persist(accessToken);
}
+
public AccessToken updateAccessToken (AccessToken accessToken)
throws KustvaktException {
ParameterChecker.checkObjectValue(accessToken, "access_token");
- AccessToken cachedToken =
- (AccessToken) this.getCacheValue(accessToken.getToken());
+ AccessToken cachedToken = (AccessToken) this
+ .getCacheValue(accessToken.getToken());
if (cachedToken != null) {
this.removeCacheEntry(accessToken.getToken());
}
@@ -118,8 +119,8 @@
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessToken> query =
- builder.createQuery(AccessToken.class);
+ CriteriaQuery<AccessToken> query = builder
+ .createQuery(AccessToken.class);
Root<AccessToken> root = query.from(AccessToken.class);
query.select(root);
query.where(builder.equal(root.get(AccessToken_.token), accessToken));
@@ -145,8 +146,8 @@
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessToken> query =
- builder.createQuery(AccessToken.class);
+ CriteriaQuery<AccessToken> query = builder
+ .createQuery(AccessToken.class);
Root<AccessToken> root = query.from(AccessToken.class);
Predicate condition = builder.and(
@@ -172,12 +173,12 @@
OAuth2Client client = clientDao.retrieveClientById(clientId);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessToken> query =
- builder.createQuery(AccessToken.class);
+ CriteriaQuery<AccessToken> query = builder
+ .createQuery(AccessToken.class);
Root<AccessToken> root = query.from(AccessToken.class);
- Predicate condition =
- builder.equal(root.get(AccessToken_.client), client);
+ Predicate condition = builder.equal(root.get(AccessToken_.client),
+ client);
if (username != null && !username.isEmpty()) {
condition = builder.and(condition,
builder.equal(root.get(AccessToken_.userId), username));
@@ -194,8 +195,8 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessToken> query =
- builder.createQuery(AccessToken.class);
+ CriteriaQuery<AccessToken> query = builder
+ .createQuery(AccessToken.class);
Root<AccessToken> root = query.from(AccessToken.class);
root.fetch(AccessToken_.client);
@@ -222,11 +223,11 @@
List<AccessToken> invalidAccessTokens = retrieveInvalidAccessTokens();
invalidAccessTokens.forEach(token -> entityManager.remove(token));
}
-
+
public List<AccessToken> retrieveInvalidAccessTokens () {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<AccessToken> query =
- builder.createQuery(AccessToken.class);
+ CriteriaQuery<AccessToken> query = builder
+ .createQuery(AccessToken.class);
Root<AccessToken> root = query.from(AccessToken.class);
Predicate condition = builder.or(
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AuthorizationDaoImpl.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AuthorizationDaoImpl.java
index b66037b..ed7f218 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AuthorizationDaoImpl.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/AuthorizationDaoImpl.java
@@ -63,8 +63,8 @@
authorization.setUserAuthenticationTime(authenticationTime);
authorization.setNonce(nonce);
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
authorization.setCreatedDate(now);
authorization.setExpiryDate(
now.plusSeconds(config.getAuthorizationCodeExpiry()));
@@ -79,12 +79,12 @@
ParameterChecker.checkStringValue(code, "code");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Authorization> query =
- builder.createQuery(Authorization.class);
+ CriteriaQuery<Authorization> query = builder
+ .createQuery(Authorization.class);
Root<Authorization> root = query.from(Authorization.class);
- Predicate restrictions =
- builder.equal(root.get(Authorization_.code), code);
+ Predicate restrictions = builder.equal(root.get(Authorization_.code),
+ code);
query.select(root);
query.where(restrictions);
@@ -111,12 +111,12 @@
public List<Authorization> retrieveAuthorizationsByClientId (
String clientId) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<Authorization> query =
- builder.createQuery(Authorization.class);
+ CriteriaQuery<Authorization> query = builder
+ .createQuery(Authorization.class);
Root<Authorization> root = query.from(Authorization.class);
- Predicate restrictions =
- builder.equal(root.get(Authorization_.clientId), clientId);
+ Predicate restrictions = builder
+ .equal(root.get(Authorization_.clientId), clientId);
query.select(root);
query.where(restrictions);
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/CachedAuthorizationDaoImpl.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/CachedAuthorizationDaoImpl.java
index 5f74aed..20453fd 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/CachedAuthorizationDaoImpl.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/CachedAuthorizationDaoImpl.java
@@ -58,8 +58,8 @@
authorization.setUserAuthenticationTime(authenticationTime);
authorization.setNonce(nonce);
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
authorization.setCreatedDate(now);
authorization.setExpiryDate(
now.plusSeconds(config.getAuthorizationCodeExpiry()));
@@ -87,8 +87,8 @@
throws KustvaktException {
this.storeInCache(authorization.getCode(), authorization);
- Authorization auth =
- (Authorization) this.getCacheValue(authorization.getCode());
+ Authorization auth = (Authorization) this
+ .getCacheValue(authorization.getCode());
return auth;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/InstalledPluginDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/InstalledPluginDao.java
index b2dfb39..46bc06b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/InstalledPluginDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/InstalledPluginDao.java
@@ -53,8 +53,8 @@
ParameterChecker.checkStringValue(installedBy, "installedBy");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<InstalledPlugin> query =
- builder.createQuery(InstalledPlugin.class);
+ CriteriaQuery<InstalledPlugin> query = builder
+ .createQuery(InstalledPlugin.class);
Root<InstalledPlugin> root = query.from(InstalledPlugin.class);
query.select(root);
@@ -82,8 +82,8 @@
ParameterChecker.checkStringValue(installedBy, "installedBy");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<InstalledPlugin> query =
- builder.createQuery(InstalledPlugin.class);
+ CriteriaQuery<InstalledPlugin> query = builder
+ .createQuery(InstalledPlugin.class);
Root<InstalledPlugin> root = query.from(InstalledPlugin.class);
query.select(root);
@@ -104,8 +104,8 @@
public void uninstallPlugin (String superClientId, String clientId,
String username) throws KustvaktException {
- InstalledPlugin plugin =
- retrieveInstalledPlugin(superClientId, clientId, username);
+ InstalledPlugin plugin = retrieveInstalledPlugin(superClientId,
+ clientId, username);
entityManager.remove(plugin);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
index 9aa7bb8..0e118d5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/OAuth2ClientDao.java
@@ -85,19 +85,21 @@
client.setPermitted(true);
}
if (refreshTokenExpiry <= 0) {
- if (type.equals(OAuth2ClientType.CONFIDENTIAL)){
+ if (type.equals(OAuth2ClientType.CONFIDENTIAL)) {
refreshTokenExpiry = config.getRefreshTokenLongExpiry();
}
}
- else if (type.equals(OAuth2ClientType.PUBLIC)){
- throw new KustvaktException(StatusCodes.INVALID_REFRESH_TOKEN_EXPIRY,
+ else if (type.equals(OAuth2ClientType.PUBLIC)) {
+ throw new KustvaktException(
+ StatusCodes.INVALID_REFRESH_TOKEN_EXPIRY,
"Custom refresh token expiry is only applicable for confidential clients");
}
- else if (refreshTokenExpiry > 31536000 ){
- throw new KustvaktException(StatusCodes.INVALID_REFRESH_TOKEN_EXPIRY,
+ else if (refreshTokenExpiry > 31536000) {
+ throw new KustvaktException(
+ StatusCodes.INVALID_REFRESH_TOKEN_EXPIRY,
"Maximum refresh token expiry is 31536000 seconds (1 year)");
}
-
+
client.setRefreshTokenExpiry(refreshTokenExpiry);
entityManager.persist(client);
}
@@ -108,8 +110,8 @@
ParameterChecker.checkStringValue(clientId, "client_id");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<OAuth2Client> query =
- builder.createQuery(OAuth2Client.class);
+ CriteriaQuery<OAuth2Client> query = builder
+ .createQuery(OAuth2Client.class);
Root<OAuth2Client> root = query.from(OAuth2Client.class);
query.select(root);
@@ -148,12 +150,12 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<OAuth2Client> query =
- builder.createQuery(OAuth2Client.class);
+ CriteriaQuery<OAuth2Client> query = builder
+ .createQuery(OAuth2Client.class);
Root<OAuth2Client> client = query.from(OAuth2Client.class);
- Join<OAuth2Client, RefreshToken> refreshToken =
- client.join(OAuth2Client_.refreshTokens);
+ Join<OAuth2Client, RefreshToken> refreshToken = client
+ .join(OAuth2Client_.refreshTokens);
Predicate condition = builder.and(
builder.equal(refreshToken.get(RefreshToken_.userId), username),
builder.equal(refreshToken.get(RefreshToken_.isRevoked), false),
@@ -174,12 +176,12 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<OAuth2Client> query =
- builder.createQuery(OAuth2Client.class);
+ CriteriaQuery<OAuth2Client> query = builder
+ .createQuery(OAuth2Client.class);
Root<OAuth2Client> client = query.from(OAuth2Client.class);
- Join<OAuth2Client, AccessToken> accessToken =
- client.join(OAuth2Client_.accessTokens);
+ Join<OAuth2Client, AccessToken> accessToken = client
+ .join(OAuth2Client_.accessTokens);
Predicate condition = builder.and(
builder.equal(accessToken.get(AccessToken_.userId), username),
builder.equal(accessToken.get(AccessToken_.isRevoked), false),
@@ -200,8 +202,8 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<OAuth2Client> query =
- builder.createQuery(OAuth2Client.class);
+ CriteriaQuery<OAuth2Client> query = builder
+ .createQuery(OAuth2Client.class);
Root<OAuth2Client> client = query.from(OAuth2Client.class);
query.select(client);
@@ -215,12 +217,12 @@
public List<OAuth2Client> retrievePlugins (boolean isPermittedOnly)
throws KustvaktException {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<OAuth2Client> query =
- builder.createQuery(OAuth2Client.class);
+ CriteriaQuery<OAuth2Client> query = builder
+ .createQuery(OAuth2Client.class);
Root<OAuth2Client> client = query.from(OAuth2Client.class);
- Predicate restrictions =
- builder.isNotNull(client.get(OAuth2Client_.SOURCE));
+ Predicate restrictions = builder
+ .isNotNull(client.get(OAuth2Client_.SOURCE));
if (isPermittedOnly) {
restrictions = builder.and(restrictions,
builder.isTrue(client.get(OAuth2Client_.IS_PERMITTED)));
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/RefreshTokenDao.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/RefreshTokenDao.java
index 0c68485..19da4ff 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/RefreshTokenDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dao/RefreshTokenDao.java
@@ -50,8 +50,8 @@
ParameterChecker.checkObjectValue(client, "client");
ParameterChecker.checkObjectValue(scopes, "scopes");
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
RefreshToken token = new RefreshToken();
token.setToken(refreshToken);
@@ -79,8 +79,8 @@
ParameterChecker.checkStringValue(token, "refresh_token");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<RefreshToken> query =
- builder.createQuery(RefreshToken.class);
+ CriteriaQuery<RefreshToken> query = builder
+ .createQuery(RefreshToken.class);
Root<RefreshToken> root = query.from(RefreshToken.class);
root.fetch(RefreshToken_.client);
@@ -97,8 +97,8 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<RefreshToken> query =
- builder.createQuery(RefreshToken.class);
+ CriteriaQuery<RefreshToken> query = builder
+ .createQuery(RefreshToken.class);
Root<RefreshToken> root = query.from(RefreshToken.class);
Predicate condition = builder.and(
@@ -122,12 +122,12 @@
OAuth2Client client = clientDao.retrieveClientById(clientId);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<RefreshToken> query =
- builder.createQuery(RefreshToken.class);
+ CriteriaQuery<RefreshToken> query = builder
+ .createQuery(RefreshToken.class);
Root<RefreshToken> root = query.from(RefreshToken.class);
- Predicate condition =
- builder.equal(root.get(RefreshToken_.client), client);
+ Predicate condition = builder.equal(root.get(RefreshToken_.client),
+ client);
if (username != null && !username.isEmpty()) {
condition = builder.and(condition,
builder.equal(root.get(RefreshToken_.userId), username));
@@ -144,8 +144,8 @@
ParameterChecker.checkStringValue(username, "username");
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<RefreshToken> query =
- builder.createQuery(RefreshToken.class);
+ CriteriaQuery<RefreshToken> query = builder
+ .createQuery(RefreshToken.class);
Root<RefreshToken> root = query.from(RefreshToken.class);
root.fetch(RefreshToken_.client);
@@ -172,11 +172,11 @@
List<RefreshToken> invalidRefreshTokens = retrieveInvalidRefreshTokens();
invalidRefreshTokens.forEach(token -> entityManager.remove(token));
}
-
+
public List<RefreshToken> retrieveInvalidRefreshTokens () {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery<RefreshToken> query =
- builder.createQuery(RefreshToken.class);
+ CriteriaQuery<RefreshToken> query = builder
+ .createQuery(RefreshToken.class);
Root<RefreshToken> root = query.from(RefreshToken.class);
Predicate condition = builder.or(
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2TokenDto.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2TokenDto.java
index 6afb4ca..684acd5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2TokenDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2TokenDto.java
@@ -90,8 +90,7 @@
return userAuthenticationTime;
}
- public void setUserAuthenticationTime (
- String userAuthenticationTime) {
+ public void setUserAuthenticationTime (String userAuthenticationTime) {
this.userAuthenticationTime = userAuthenticationTime;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2UserClientDto.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2UserClientDto.java
index c417a60..f499fe0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2UserClientDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/dto/OAuth2UserClientDto.java
@@ -11,9 +11,10 @@
import de.ids_mannheim.korap.utils.JsonUtils;
/**
- * Please use {@link OAuth2ClientInfoDto} instead.
+ * Please use {@link OAuth2ClientInfoDto} instead.
*
- * This class is not used anymore to describe OAuth2 clients of a user.
+ * This class is not used anymore to describe OAuth2 clients of a
+ * user.
*
* @author margaretha
*
@@ -37,7 +38,7 @@
private String registrationDate;
@JsonProperty("refresh_token_expiry")
private int refreshTokenExpiry;
-
+
private boolean permitted;
private JsonNode source;
@@ -55,11 +56,11 @@
this.setRefreshTokenExpiry(client.getRefreshTokenExpiry());
}
String source = client.getSource();
- if (source!=null) {
+ if (source != null) {
this.setSource(JsonUtils.readTree(client.getSource()));
}
}
-
+
public String getClientName () {
return clientName;
}
@@ -119,20 +120,23 @@
public JsonNode getSource () {
return source;
}
+
public void setSource (JsonNode source) {
this.source = source;
}
-
+
public String getRegistrationDate () {
return registrationDate;
}
+
public void setRegistrationDate (String registrationDate) {
this.registrationDate = registrationDate;
}
-
+
public int getRefreshTokenExpiry () {
return refreshTokenExpiry;
}
+
public void setRefreshTokenExpiry (int refreshTokenExpiry) {
this.refreshTokenExpiry = refreshTokenExpiry;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessScope.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessScope.java
index 7903146..85f0fcf 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessScope.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessScope.java
@@ -63,8 +63,8 @@
return false;
}
-
-@Override
+
+ @Override
public int hashCode () {
return this.getId().hashCode();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessToken.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessToken.java
index 04acc5e..9e0fd8d 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessToken.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/AccessToken.java
@@ -45,8 +45,8 @@
private ZonedDateTime expiryDate;
@Column(name = "user_id")
private String userId;
-// @Column(name = "client_id")
-// private String clientId;
+ // @Column(name = "client_id")
+ // private String clientId;
@Column(name = "is_revoked")
private boolean isRevoked;
@Column(name = "user_auth_time", updatable = false)
@@ -57,19 +57,14 @@
// private Authorization authorization;
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "oauth2_access_token_scope",
- joinColumns = @JoinColumn(name = "token_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "scope_id",
- referencedColumnName = "id"),
- uniqueConstraints = @UniqueConstraint(
- columnNames = { "token_id", "scope_id" }))
+ @JoinTable(name = "oauth2_access_token_scope", joinColumns = @JoinColumn(name = "token_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "scope_id", referencedColumnName = "id"), uniqueConstraints = @UniqueConstraint(columnNames = {
+ "token_id", "scope_id" }))
private Set<AccessScope> scopes;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "refresh_token")
private RefreshToken refreshToken;
-
+
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "client")
private OAuth2Client client;
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/Authorization.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/Authorization.java
index 386434f..acaf081 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/Authorization.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/Authorization.java
@@ -54,13 +54,8 @@
private String nonce;
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "oauth2_authorization_scope",
- joinColumns = @JoinColumn(name = "authorization_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "scope_id",
- referencedColumnName = "id"),
- uniqueConstraints = @UniqueConstraint(
- columnNames = { "authorization_id", "scope_id" }))
+ @JoinTable(name = "oauth2_authorization_scope", joinColumns = @JoinColumn(name = "authorization_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "scope_id", referencedColumnName = "id"), uniqueConstraints = @UniqueConstraint(columnNames = {
+ "authorization_id", "scope_id" }))
private Set<AccessScope> scopes;
@Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/OAuth2Client.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/OAuth2Client.java
index eac5d31..5f29815 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/OAuth2Client.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/OAuth2Client.java
@@ -15,14 +15,15 @@
import de.ids_mannheim.korap.entity.InstalledPlugin;
import de.ids_mannheim.korap.oauth2.constant.OAuth2ClientType;
-/** Describe oauth2_client database table mapping.
+/**
+ * Describe oauth2_client database table mapping.
*
* @author margaretha
*
*/
@Entity
@Table(name = "oauth2_client")
-public class OAuth2Client implements Comparable<OAuth2Client>{
+public class OAuth2Client implements Comparable<OAuth2Client> {
@Id
private String id;
@@ -39,28 +40,28 @@
private String registeredBy;
@Column(name = "registration_date", updatable = false)
private ZonedDateTime registrationDate;
-
+
// How long a refresh token for this client should be valid
// in seconds. Maximum 31536000 seconds equivalent to 1 year
@Column(name = "refresh_token_expiry")
private int refreshTokenExpiry;
-
+
private String description;
private String url;
private String source;
@Column(name = "is_permitted")
private boolean isPermitted;
-
+
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
private List<RefreshToken> refreshTokens;
-
+
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
private List<AccessToken> accessTokens;
-
+
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
private List<InstalledPlugin> installedPlugins;
-
+
@Override
public String toString () {
return "id=" + id + ", name=" + name + ", secret=" + secret + ", type="
@@ -73,7 +74,7 @@
public int compareTo (OAuth2Client o) {
return this.getName().compareTo(o.getName());
}
-
+
public boolean isSuper () {
return isSuper;
}
@@ -129,10 +130,11 @@
public void setRegisteredBy (String registeredBy) {
this.registeredBy = registeredBy;
}
-
+
public ZonedDateTime getRegistrationDate () {
return registrationDate;
}
+
public void setRegistrationDate (ZonedDateTime registrationDate) {
this.registrationDate = registrationDate;
}
@@ -164,14 +166,15 @@
public boolean isPermitted () {
return isPermitted;
}
-
+
public void setPermitted (boolean isPermitted) {
this.isPermitted = isPermitted;
}
-
+
public int getRefreshTokenExpiry () {
return refreshTokenExpiry;
}
+
public void setRefreshTokenExpiry (int refreshTokenExpiry) {
this.refreshTokenExpiry = refreshTokenExpiry;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/RefreshToken.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/RefreshToken.java
index ff22e25..db70d6a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/RefreshToken.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/entity/RefreshToken.java
@@ -19,7 +19,8 @@
/**
* Describes oauth2_refresh_token database table mapping and refresh
- * token relations to access scopes, access tokens, and oauth2 clients.
+ * token relations to access scopes, access tokens, and oauth2
+ * clients.
*
* @author margaretha
*
@@ -53,13 +54,8 @@
private OAuth2Client client;
@ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "oauth2_refresh_token_scope",
- joinColumns = @JoinColumn(name = "token_id",
- referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "scope_id",
- referencedColumnName = "id"),
- uniqueConstraints = @UniqueConstraint(
- columnNames = { "token_id", "scope_id" }))
+ @JoinTable(name = "oauth2_refresh_token_scope", joinColumns = @JoinColumn(name = "token_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "scope_id", referencedColumnName = "id"), uniqueConstraints = @UniqueConstraint(columnNames = {
+ "token_id", "scope_id" }))
private Set<AccessScope> scopes;
public String getToken () {
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/DummyOAuth2ScopeServiceImpl.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/DummyOAuth2ScopeServiceImpl.java
index d1e7945..38e039a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/DummyOAuth2ScopeServiceImpl.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/DummyOAuth2ScopeServiceImpl.java
@@ -7,7 +7,7 @@
public class DummyOAuth2ScopeServiceImpl implements OAuth2ScopeService {
- @Override
+ @Override
public void verifyScope (TokenContext context, OAuth2Scope requiredScope)
throws KustvaktException {
// TODO Auto-generated method stub
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2AuthorizationService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2AuthorizationService.java
index 19cf2e1..36b027f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2AuthorizationService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2AuthorizationService.java
@@ -33,7 +33,8 @@
import de.ids_mannheim.korap.oauth2.entity.Authorization;
import de.ids_mannheim.korap.oauth2.entity.OAuth2Client;
-/** Describes business logic behind OAuth2 authorization requests.
+/**
+ * Describes business logic behind OAuth2 authorization requests.
*
* @author margaretha
*
@@ -41,11 +42,11 @@
@Service(value = "authorizationService")
public class OAuth2AuthorizationService {
- public static Logger jlog =
- LogManager.getLogger(OAuth2AuthorizationService.class);
+ public static Logger jlog = LogManager
+ .getLogger(OAuth2AuthorizationService.class);
public static boolean DEBUG = false;
-
+
@Autowired
private RandomCodeGenerator codeGenerator;
@Autowired
@@ -59,25 +60,24 @@
@Autowired
protected FullConfiguration config;
-
+
public State createAuthorizationState (String state) {
State authState = null;
- if (state!=null && !state.isEmpty())
+ if (state != null && !state.isEmpty())
authState = new State(state);
return authState;
}
-
+
public AuthorizationErrorResponse createAuthorizationError (
KustvaktException e, String state) {
State authState = createAuthorizationState(state);
ErrorObject error = e.getOauth2Error();
error = error.setDescription(e.getMessage());
- AuthorizationErrorResponse errorResponse =
- new AuthorizationErrorResponse(e.getRedirectUri(),
- error,authState, null);
+ AuthorizationErrorResponse errorResponse = new AuthorizationErrorResponse(
+ e.getRedirectUri(), error, authState, null);
return errorResponse;
}
-
+
public URI requestAuthorizationCode (URI requestURI, String clientId,
String redirectUri, String scope, String state, String username,
ZonedDateTime authenticationTime) throws KustvaktException {
@@ -95,7 +95,7 @@
createAuthorization(username, clientId, redirectUri, scope,
code.toString(), authenticationTime, null);
return responseURI;
-
+
}
catch (KustvaktException e) {
e.setRedirectUri(redirectURI);
@@ -104,8 +104,7 @@
}
private URI createAuthorizationResponse (URI requestURI, URI redirectURI,
- String code, String state)
- throws KustvaktException {
+ String code, String state) throws KustvaktException {
AuthorizationRequest authRequest = null;
try {
authRequest = AuthorizationRequest.parse(requestURI);
@@ -114,10 +113,9 @@
.equals(new ResponseType(ResponseType.Value.CODE))) {
State authState = createAuthorizationState(state);
- AuthorizationSuccessResponse response =
- new AuthorizationSuccessResponse(redirectURI,
- new AuthorizationCode(code), null, authState,
- null);
+ AuthorizationSuccessResponse response = new AuthorizationSuccessResponse(
+ redirectURI, new AuthorizationCode(code), null,
+ authState, null);
return response.toURI();
}
else {
@@ -129,13 +127,14 @@
}
}
catch (ParseException e) {
- KustvaktException ke =
- new KustvaktException(StatusCodes.INVALID_REQUEST,
- e.getMessage(), OAuth2Error.INVALID_REQUEST_URI);
+ KustvaktException ke = new KustvaktException(
+ StatusCodes.INVALID_REQUEST, e.getMessage(),
+ OAuth2Error.INVALID_REQUEST_URI);
throw ke;
}
}
+
@Deprecated
public String createAuthorization (String username, String clientId,
String redirectUri, Set<String> scopeSet, String code,
@@ -152,7 +151,7 @@
scopes, redirectUri, authenticationTime, nonce);
return String.join(" ", scopeSet);
}
-
+
/**
* Authorization code request does not require client
* authentication, but only checks if the client id exists.
@@ -176,7 +175,8 @@
throw new KustvaktException(StatusCodes.MISSING_PARAMETER,
"scope is required", OAuth2Error.INVALID_SCOPE);
}
- Set<AccessScope> accessScopes = scopeService.convertToAccessScope(scope);
+ Set<AccessScope> accessScopes = scopeService
+ .convertToAccessScope(scope);
authorizationDao.storeAuthorizationCode(clientId, username, code,
accessScopes, redirectUri, authenticationTime, nonce);
@@ -217,19 +217,19 @@
throws KustvaktException {
String registeredUri = client.getRedirectURI();
-
+
if (redirectUri != null && !redirectUri.isEmpty()) {
// check if the redirect URI the same as that in DB
- if (!redirectURIValidator.isValid(redirectUri) ||
- (registeredUri != null && !registeredUri.isEmpty()
- && !redirectUri.equals(registeredUri))) {
+ if (!redirectURIValidator.isValid(redirectUri)
+ || (registeredUri != null && !registeredUri.isEmpty()
+ && !redirectUri.equals(registeredUri))) {
throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
"Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
}
}
// redirect_uri is not required in client registration
else if (registeredUri != null && !registeredUri.isEmpty()) {
- redirectUri = registeredUri;
+ redirectUri = registeredUri;
}
else {
throw new KustvaktException(StatusCodes.MISSING_REDIRECT_URI,
@@ -244,14 +244,14 @@
throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
"Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
}
-
+
return redirectURI;
}
-
+
public KustvaktException checkRedirectUri (KustvaktException e,
- String clientId, String redirectUri){
+ String clientId, String redirectUri) {
int statusCode = e.getStatusCode();
- if (clientId!=null && !clientId.isEmpty()
+ if (clientId != null && !clientId.isEmpty()
&& statusCode != StatusCodes.CLIENT_NOT_FOUND
&& statusCode != StatusCodes.AUTHORIZATION_FAILED
&& statusCode != StatusCodes.INVALID_REDIRECT_URI) {
@@ -265,16 +265,20 @@
if (redirectUri != null && !redirectUri.isEmpty()) {
if (registeredUri != null && !registeredUri.isEmpty()
&& !redirectUri.equals(registeredUri)) {
- return new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
- "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
+ return new KustvaktException(
+ StatusCodes.INVALID_REDIRECT_URI,
+ "Invalid redirect URI",
+ OAuth2Error.INVALID_REQUEST);
}
else {
try {
e.setRedirectUri(new URI(redirectUri));
}
catch (URISyntaxException e1) {
- return new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
- "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
+ return new KustvaktException(
+ StatusCodes.INVALID_REDIRECT_URI,
+ "Invalid redirect URI",
+ OAuth2Error.INVALID_REQUEST);
}
e.setResponseStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
}
@@ -284,14 +288,17 @@
e.setRedirectUri(new URI(registeredUri));
}
catch (URISyntaxException e1) {
- return new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
- "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
+ return new KustvaktException(
+ StatusCodes.INVALID_REDIRECT_URI,
+ "Invalid redirect URI",
+ OAuth2Error.INVALID_REQUEST);
}
e.setResponseStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
}
else {
return new KustvaktException(StatusCodes.MISSING_REDIRECT_URI,
- "Missing parameter: redirect URI", OAuth2Error.INVALID_REQUEST);
+ "Missing parameter: redirect URI",
+ OAuth2Error.INVALID_REQUEST);
}
}
@@ -327,7 +334,7 @@
if (redirectURI == null || redirectURI.isEmpty()) {
throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
"Missing redirect URI", OAuth2Error.INVALID_GRANT);
- }
+ }
if (!authorizedUri.equals(redirectURI)) {
throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
"Invalid redirect URI", OAuth2Error.INVALID_GRANT);
@@ -355,8 +362,8 @@
}
private boolean isExpired (ZonedDateTime expiryDate) {
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
if (DEBUG) {
jlog.debug("createdDate: " + expiryDate);
jlog.debug("expiration: " + expiryDate + ", now: " + now);
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
index 55d85ab..3781458 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ClientService.java
@@ -60,10 +60,10 @@
*/
@Service
public class OAuth2ClientService {
-
-// public static final UrlValidator redirectURIValidator =
-// new UrlValidator(new String[] { "http", "https" },
-// UrlValidator.NO_FRAGMENTS + UrlValidator.ALLOW_LOCAL_URLS);
+
+ // public static final UrlValidator redirectURIValidator =
+ // new UrlValidator(new String[] { "http", "https" },
+ // UrlValidator.NO_FRAGMENTS + UrlValidator.ALLOW_LOCAL_URLS);
@Autowired
private OAuth2TokenService tokenService;
@@ -93,15 +93,18 @@
public OAuth2ClientDto registerClient (OAuth2ClientJson clientJson,
String registeredBy) throws KustvaktException {
try {
- ParameterChecker.checkNameValue(clientJson.getName(), "client_name");
- ParameterChecker.checkObjectValue(clientJson.getType(), "client_type");
- ParameterChecker.checkStringValue(clientJson.getName(), "client_description");
+ ParameterChecker.checkNameValue(clientJson.getName(),
+ "client_name");
+ ParameterChecker.checkObjectValue(clientJson.getType(),
+ "client_type");
+ ParameterChecker.checkStringValue(clientJson.getName(),
+ "client_description");
}
catch (KustvaktException e) {
throw new KustvaktException(e.getStatusCode(), e.getMessage(),
OAuth2Error.INVALID_REQUEST);
}
-
+
String url = clientJson.getUrl();
if (url != null && !url.isEmpty()) {
if (!urlValidator.isValid(url)) {
@@ -114,7 +117,7 @@
if (redirectURI != null && !redirectURI.isEmpty()
&& !redirectURIValidator.isValid(redirectURI)) {
throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI,
- "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
+ "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
}
// boolean isNative = isNativeClient(url, redirectURI);
@@ -140,17 +143,16 @@
String id = codeGenerator.createRandomCode();
id = codeGenerator.filterRandomCode(id);
-
+
try {
clientDao.registerClient(id, secretHashcode, clientJson.getName(),
clientJson.getType(), url, redirectURI, registeredBy,
clientJson.getDescription(),
- clientJson.getRefreshTokenExpiry(),
- clientJson.getSource());
+ clientJson.getRefreshTokenExpiry(), clientJson.getSource());
}
catch (KustvaktException e) {
- throw new KustvaktException(e.getStatusCode(),
- e.getMessage(), OAuth2Error.INVALID_REQUEST);
+ throw new KustvaktException(e.getStatusCode(), e.getMessage(),
+ OAuth2Error.INVALID_REQUEST);
}
catch (Exception e) {
Throwable cause = e;
@@ -212,7 +214,7 @@
throws KustvaktException {
OAuth2Client client = clientDao.retrieveClientById(clientId);
-
+
if (adminDao.isAdmin(username)
|| client.getRegisteredBy().equals(username)) {
@@ -229,23 +231,23 @@
throws KustvaktException {
// revoke all related authorization codes
- List<Authorization> authList =
- authorizationDao.retrieveAuthorizationsByClientId(clientId);
+ List<Authorization> authList = authorizationDao
+ .retrieveAuthorizationsByClientId(clientId);
for (Authorization authorization : authList) {
authorization.setRevoked(true);
authorizationDao.updateAuthorization(authorization);
}
// revoke all related access tokens
- List<AccessToken> tokens =
- tokenDao.retrieveAccessTokenByClientId(clientId,null);
+ List<AccessToken> tokens = tokenDao
+ .retrieveAccessTokenByClientId(clientId, null);
for (AccessToken token : tokens) {
token.setRevoked(true);
tokenDao.updateAccessToken(token);
}
- List<RefreshToken> refreshTokens =
- refreshDao.retrieveRefreshTokenByClientId(clientId,null);
+ List<RefreshToken> refreshTokens = refreshDao
+ .retrieveRefreshTokenByClientId(clientId, null);
for (RefreshToken token : refreshTokens) {
token.setRevoked(true);
refreshDao.updateRefreshToken(token);
@@ -281,18 +283,18 @@
String clientSecret) throws KustvaktException {
return authenticateClient(clientId, clientSecret, false);
}
-
+
public OAuth2Client authenticateClient (String clientId,
String clientSecret, boolean isSuper) throws KustvaktException {
String errorClient = "client";
if (isSuper) {
errorClient = "super_client";
}
-
+
if (clientId == null || clientId.isEmpty()) {
throw new KustvaktException(
StatusCodes.CLIENT_AUTHENTICATION_FAILED,
- "Missing parameter: "+errorClient+"_id",
+ "Missing parameter: " + errorClient + "_id",
OAuth2Error.INVALID_REQUEST);
}
@@ -307,7 +309,7 @@
if (client.getType().equals(OAuth2ClientType.CONFIDENTIAL)) {
throw new KustvaktException(
StatusCodes.CLIENT_AUTHENTICATION_FAILED,
- "Missing parameter: "+errorClient+"_secret",
+ "Missing parameter: " + errorClient + "_secret",
OAuth2Error.INVALID_REQUEST);
}
}
@@ -315,14 +317,15 @@
if (client.getType().equals(OAuth2ClientType.CONFIDENTIAL)) {
throw new KustvaktException(
StatusCodes.CLIENT_AUTHENTICATION_FAILED,
- errorClient+"_secret was not registered",
+ errorClient + "_secret was not registered",
OAuth2Error.INVALID_CLIENT);
}
}
else if (!encryption.checkHash(clientSecret, client.getSecret())) {
throw new KustvaktException(
StatusCodes.CLIENT_AUTHENTICATION_FAILED,
- "Invalid "+errorClient+" credentials", OAuth2Error.INVALID_CLIENT);
+ "Invalid " + errorClient + " credentials",
+ OAuth2Error.INVALID_CLIENT);
}
}
@@ -341,14 +344,14 @@
public OAuth2ClientInfoDto retrieveClientInfo (String clientId)
throws KustvaktException {
OAuth2Client client = clientDao.retrieveClientById(clientId);
-// if (adminDao.isAdmin(username)
-// || username.equals(client.getRegisteredBy())) {
- return new OAuth2ClientInfoDto(client);
-// }
-// else {
-// throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
-// "Unauthorized operation for user: " + username, username);
-// }
+ // if (adminDao.isAdmin(username)
+ // || username.equals(client.getRegisteredBy())) {
+ return new OAuth2ClientInfoDto(client);
+ // }
+ // else {
+ // throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
+ // "Unauthorized operation for user: " + username, username);
+ // }
}
public OAuth2Client retrieveClient (String clientId)
@@ -358,33 +361,32 @@
public List<OAuth2ClientInfoDto> listUserAuthorizedClients (String username)
throws KustvaktException {
- List<OAuth2Client> userClients =
- clientDao.retrieveUserAuthorizedClients(username);
+ List<OAuth2Client> userClients = clientDao
+ .retrieveUserAuthorizedClients(username);
userClients.addAll(clientDao.retrieveClientsByAccessTokens(username));
-
+
List<String> clientIds = new ArrayList<>();
List<OAuth2Client> uniqueClients = new ArrayList<>();
- for (OAuth2Client c : userClients){
+ for (OAuth2Client c : userClients) {
String id = c.getId();
- if (!clientIds.contains(id)){
+ if (!clientIds.contains(id)) {
clientIds.add(id);
uniqueClients.add(c);
- }
+ }
}
-
+
Collections.sort(uniqueClients);
return createClientDtos(uniqueClients);
}
-
+
public List<OAuth2ClientInfoDto> listUserRegisteredClients (String username)
throws KustvaktException {
- List<OAuth2Client> userClients =
- clientDao.retrieveUserRegisteredClients(username);
+ List<OAuth2Client> userClients = clientDao
+ .retrieveUserRegisteredClients(username);
Collections.sort(userClients);
return createClientDtos(userClients);
}
-
-
+
public List<OAuth2ClientInfoDto> listPlugins (boolean isPermitted)
throws KustvaktException {
@@ -392,46 +394,47 @@
Collections.sort(plugins);
return createClientDtos(plugins);
}
-
+
public List<InstalledPluginDto> listInstalledPlugins (String superClientId,
String username) throws KustvaktException {
- List<InstalledPlugin> plugins =
- pluginDao.retrieveInstalledPlugins(superClientId, username);
+ List<InstalledPlugin> plugins = pluginDao
+ .retrieveInstalledPlugins(superClientId, username);
Collections.sort(plugins); // by client name
-
- List<InstalledPluginDto> list = new ArrayList<InstalledPluginDto>(plugins.size());
+
+ List<InstalledPluginDto> list = new ArrayList<InstalledPluginDto>(
+ plugins.size());
for (InstalledPlugin p : plugins) {
list.add(new InstalledPluginDto(p));
}
-
+
return list;
}
-
+
public InstalledPluginDto installPlugin (String superClientId,
String clientId, String installedBy) throws KustvaktException {
-
+
OAuth2Client client = clientDao.retrieveClientById(clientId);
if (!client.isPermitted()) {
throw new KustvaktException(StatusCodes.PLUGIN_NOT_PERMITTED,
"Plugin is not permitted", clientId);
}
-
- if (isPluginInstalled(superClientId,clientId,installedBy)) {
+
+ if (isPluginInstalled(superClientId, clientId, installedBy)) {
throw new KustvaktException(StatusCodes.PLUGIN_HAS_BEEN_INSTALLED,
"Plugin has been installed", clientId);
}
-
+
OAuth2Client superClient = clientDao.retrieveClientById(superClientId);
- InstalledPlugin plugin =
- pluginDao.storeUserPlugin(superClient, client, installedBy);
-
+ InstalledPlugin plugin = pluginDao.storeUserPlugin(superClient, client,
+ installedBy);
+
InstalledPluginDto dto = new InstalledPluginDto(plugin);
return dto;
}
-
- public void uninstallPlugin (String superClientId,
- String clientId, String username) throws KustvaktException {
+
+ public void uninstallPlugin (String superClientId, String clientId,
+ String username) throws KustvaktException {
pluginDao.uninstallPlugin(superClientId, clientId, username);
tokenService.revokeAllClientTokensForUser(clientId, username);
}
@@ -452,7 +455,8 @@
List<OAuth2Client> userClients) throws KustvaktException {
List<OAuth2ClientInfoDto> dtoList = new ArrayList<>(userClients.size());
for (OAuth2Client uc : userClients) {
- if (uc.isSuper()) continue;
+ if (uc.isSuper())
+ continue;
OAuth2ClientInfoDto dto = new OAuth2ClientInfoDto(uc);
dtoList.add(dto);
}
@@ -465,7 +469,7 @@
public void verifySuperClient (String clientId, String clientSecret)
throws KustvaktException {
- OAuth2Client client = authenticateClient(clientId, clientSecret,true);
+ OAuth2Client client = authenticateClient(clientId, clientSecret, true);
if (!client.isSuper()) {
throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED,
"Only super client is allowed to use this service",
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2InitClientService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2InitClientService.java
index 3846cdf..25b07dd 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2InitClientService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2InitClientService.java
@@ -23,10 +23,9 @@
@Service
public class OAuth2InitClientService {
- private static Logger log =
- LogManager.getLogger(OAuth2InitClientService.class);
- public static String OAUTH2_CLIENT_JSON_INPUT_FILE =
- "initial_super_client.json";
+ private static Logger log = LogManager
+ .getLogger(OAuth2InitClientService.class);
+ public static String OAUTH2_CLIENT_JSON_INPUT_FILE = "initial_super_client.json";
public static String OUTPUT_FILENAME = "super_client_info";
public static String TEST_OUTPUT_FILENAME = "test_super_client_info";
@@ -50,35 +49,35 @@
if (!f.exists()) {
OAuth2ClientJson json = readOAuth2ClientJsonFile();
- OAuth2ClientDto clientDto =
- clientService.registerClient(json, "system");
+ OAuth2ClientDto clientDto = clientService.registerClient(json,
+ "system");
String clientId = clientDto.getClient_id();
OAuth2Client client = clientService.retrieveClient(clientId);
client.setSuper(true);
clientDao.updateClient(client);
JsonUtils.writeFile(path, clientDto);
-
+
log.info(
- "Initial super client has been successfully registered. See "+path);
+ "Initial super client has been successfully registered. See "
+ + path);
}
else {
JsonNode node = JsonUtils.readFile(path, JsonNode.class);
String existingClientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
String secretHashcode = encryption.secureHash(clientSecret);
-
+
try {
clientService.retrieveClient(existingClientId);
- log.info(
- "Super client info file exists. Initial super client "
+ log.info("Super client info file exists. Initial super client "
+ "registration is cancelled.");
}
catch (Exception e) {
log.info("Super client info file exists but the client "
+ "doesn't exist in the database.");
OAuth2ClientJson json = readOAuth2ClientJsonFile();
- OAuth2ClientDto clientDto =
- clientService.registerClient(json, "system");
+ OAuth2ClientDto clientDto = clientService.registerClient(json,
+ "system");
String clientId = clientDto.getClient_id();
OAuth2Client client = clientService.retrieveClient(clientId);
client.setSuper(true);
@@ -89,15 +88,16 @@
}
}
- private OAuth2ClientJson readOAuth2ClientJsonFile () throws IOException, KustvaktException {
+ private OAuth2ClientJson readOAuth2ClientJsonFile ()
+ throws IOException, KustvaktException {
File f = new File(OAUTH2_CLIENT_JSON_INPUT_FILE);
if (f.exists()) {
return JsonUtils.readFile(OAUTH2_CLIENT_JSON_INPUT_FILE,
OAuth2ClientJson.class);
}
else {
- InputStream is = getClass().getClassLoader()
- .getResourceAsStream("json/"+OAUTH2_CLIENT_JSON_INPUT_FILE);
+ InputStream is = getClass().getClassLoader().getResourceAsStream(
+ "json/" + OAUTH2_CLIENT_JSON_INPUT_FILE);
return JsonUtils.read(is, OAuth2ClientJson.class);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeService.java
index 53bfaf0..e51b83a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeService.java
@@ -14,8 +14,10 @@
* Verifies whether the given token context contains the required
* scope
*
- * @param context a token context containing authorized scopes
- * @param requiredScope the required scope
+ * @param context
+ * a token context containing authorized scopes
+ * @param requiredScope
+ * the required scope
* @throws KustvaktException
*/
void verifyScope (TokenContext context, OAuth2Scope requiredScope)
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeServiceImpl.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeServiceImpl.java
index f8430aa..acf236b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeServiceImpl.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2ScopeServiceImpl.java
@@ -22,7 +22,8 @@
import de.ids_mannheim.korap.oauth2.entity.AccessScope;
import de.ids_mannheim.korap.security.context.TokenContext;
-/** Defines business logic related to OAuth2 scopes.
+/**
+ * Defines business logic related to OAuth2 scopes.
*
* @author margaretha
*
@@ -47,26 +48,24 @@
throws KustvaktException {
List<AccessScope> definedScopes = accessScopeDao.retrieveAccessScopes();
- Set<AccessScope> requestedScopes =
- new HashSet<AccessScope>(scopes.size());
+ Set<AccessScope> requestedScopes = new HashSet<AccessScope>(
+ scopes.size());
int index;
OAuth2Scope oauth2Scope = null;
for (String scope : scopes) {
try {
- oauth2Scope =
- Enum.valueOf(OAuth2Scope.class, scope.toUpperCase());
+ oauth2Scope = Enum.valueOf(OAuth2Scope.class,
+ scope.toUpperCase());
}
catch (IllegalArgumentException e) {
throw new KustvaktException(StatusCodes.INVALID_SCOPE,
- "Invalid scope",
- OAuth2Error.INVALID_SCOPE);
+ "Invalid scope", OAuth2Error.INVALID_SCOPE);
}
index = definedScopes.indexOf(new AccessScope(oauth2Scope));
if (index == -1) {
throw new KustvaktException(StatusCodes.INVALID_SCOPE,
- "Invalid scope",
- OAuth2Error.INVALID_SCOPE);
+ "Invalid scope", OAuth2Error.INVALID_SCOPE);
}
else {
requestedScopes.add(definedScopes.get(index));
@@ -74,32 +73,30 @@
}
return requestedScopes;
}
-
+
public Set<AccessScope> convertToAccessScope (String scopes)
throws KustvaktException {
String[] scopeArray = scopes.split("\\s+");
List<AccessScope> definedScopes = accessScopeDao.retrieveAccessScopes();
- Set<AccessScope> requestedScopes =
- new HashSet<AccessScope>(scopeArray.length);
+ Set<AccessScope> requestedScopes = new HashSet<AccessScope>(
+ scopeArray.length);
int index;
OAuth2Scope oauth2Scope = null;
for (String scope : scopeArray) {
try {
- oauth2Scope =
- Enum.valueOf(OAuth2Scope.class, scope.toUpperCase());
+ oauth2Scope = Enum.valueOf(OAuth2Scope.class,
+ scope.toUpperCase());
}
catch (IllegalArgumentException e) {
throw new KustvaktException(StatusCodes.INVALID_SCOPE,
- "Invalid scope",
- OAuth2Error.INVALID_SCOPE);
+ "Invalid scope", OAuth2Error.INVALID_SCOPE);
}
index = definedScopes.indexOf(new AccessScope(oauth2Scope));
if (index == -1) {
throw new KustvaktException(StatusCodes.INVALID_SCOPE,
- "Invalid scope",
- OAuth2Error.INVALID_SCOPE);
+ "Invalid scope", OAuth2Error.INVALID_SCOPE);
}
else {
requestedScopes.add(definedScopes.get(index));
@@ -131,9 +128,9 @@
public Set<String> filterScopes (Set<String> scopes,
Set<String> defaultScopes) {
Stream<String> stream = scopes.stream();
- Set<String> filteredScopes =
- stream.filter(scope -> defaultScopes.contains(scope))
- .collect(Collectors.toSet());
+ Set<String> filteredScopes = stream
+ .filter(scope -> defaultScopes.contains(scope))
+ .collect(Collectors.toSet());
return filteredScopes;
}
@@ -147,7 +144,7 @@
throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
"Authentication required. Please log in!");
}
-
+
if (!adminDao.isAdmin(context.getUsername())
&& context.getTokenType().equals(TokenType.BEARER)) {
Map<String, Object> parameters = context.getParameters();
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2TokenService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2TokenService.java
index 0af4df4..48faecd 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2TokenService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/service/OAuth2TokenService.java
@@ -69,7 +69,7 @@
protected FullConfiguration config;
@Autowired
private AuthenticationManager authenticationManager;
-
+
@Autowired
private RandomCodeGenerator randomGenerator;
@@ -95,12 +95,12 @@
* @return an authorization
* @throws KustvaktException
*/
- protected Authorization retrieveAuthorization (
- String authorizationCode, String redirectURI, String clientId,
- String clientSecret) throws KustvaktException {
+ protected Authorization retrieveAuthorization (String authorizationCode,
+ String redirectURI, String clientId, String clientSecret)
+ throws KustvaktException {
- Authorization authorization =
- authorizationService.retrieveAuthorization(authorizationCode);
+ Authorization authorization = authorizationService
+ .retrieveAuthorization(authorizationCode);
try {
clientService.authenticateClient(clientId, clientSecret);
authorization = authorizationService
@@ -113,7 +113,6 @@
return authorization;
}
-
public ZonedDateTime authenticateUser (String username, String password,
Set<String> scopes) throws KustvaktException {
if (username == null || username.isEmpty()) {
@@ -133,34 +132,32 @@
config.getOAuth2passwordAuthentication(), username, password,
attributes);
- ZonedDateTime authenticationTime =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime authenticationTime = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
return authenticationTime;
}
- public AccessTokenResponse requestAccessToken (
- TokenRequest tokenRequest, String clientId, String clientSecret)
- throws KustvaktException {
+ public AccessTokenResponse requestAccessToken (TokenRequest tokenRequest,
+ String clientId, String clientSecret) throws KustvaktException {
AuthorizationGrant authGrant = tokenRequest.getAuthorizationGrant();
GrantType grantType = authGrant.getType();
Scope scope = tokenRequest.getScope();
Set<String> scopeSet = new HashSet<>();
- if (scope !=null)
+ if (scope != null)
scopeSet.addAll(scope.toStringList());
-
+
if (grantType.equals(GrantType.AUTHORIZATION_CODE)) {
AuthorizationCodeGrant codeGrant = (AuthorizationCodeGrant) authGrant;
String authCode = codeGrant.getAuthorizationCode().getValue();
URI uri = codeGrant.getRedirectionURI();
String redirectionURI = (uri != null) ? uri.toString() : null;
-
+
return requestAccessTokenWithAuthorizationCode(authCode,
redirectionURI, clientId, clientSecret);
}
else if (grantType.equals(GrantType.PASSWORD)) {
- ResourceOwnerPasswordCredentialsGrant passwordGrant =
- (ResourceOwnerPasswordCredentialsGrant) authGrant;
+ ResourceOwnerPasswordCredentialsGrant passwordGrant = (ResourceOwnerPasswordCredentialsGrant) authGrant;
String username = passwordGrant.getUsername();
String password = passwordGrant.getPassword().getValue();
return requestAccessTokenWithPassword(clientId, clientSecret,
@@ -183,7 +180,6 @@
}
}
-
/**
* Revokes all access token associated with the given refresh
@@ -207,8 +203,7 @@
*/
private AccessTokenResponse requestAccessTokenWithRefreshToken (
String refreshTokenStr, Set<String> requestScopes, String clientId,
- String clientSecret)
- throws KustvaktException {
+ String clientSecret) throws KustvaktException {
if (refreshTokenStr == null || refreshTokenStr.isEmpty()) {
throw new KustvaktException(StatusCodes.MISSING_PARAMETER,
@@ -216,7 +211,8 @@
OAuth2Error.INVALID_REQUEST);
}
- OAuth2Client oAuth2Client = clientService.authenticateClient(clientId, clientSecret);
+ OAuth2Client oAuth2Client = clientService.authenticateClient(clientId,
+ clientSecret);
RefreshToken refreshToken;
try {
@@ -243,11 +239,10 @@
"Refresh token is expired", OAuth2Error.INVALID_GRANT);
}
- Set<AccessScope> tokenScopes =
- new HashSet<>(refreshToken.getScopes());
+ Set<AccessScope> tokenScopes = new HashSet<>(refreshToken.getScopes());
if (requestScopes != null && !requestScopes.isEmpty()) {
- tokenScopes =
- scopeService.verifyRefreshScope(requestScopes, tokenScopes);
+ tokenScopes = scopeService.verifyRefreshScope(requestScopes,
+ tokenScopes);
requestScopes = scopeService
.convertAccessScopesToStringSet(tokenScopes);
}
@@ -283,11 +278,11 @@
* @return an {@link AccessTokenResponse}
* @throws KustvaktException
*/
- private AccessTokenResponse requestAccessTokenWithAuthorizationCode (String code,
- String redirectionURI, String clientId, String clientSecret)
- throws KustvaktException {
- Authorization authorization = retrieveAuthorization(code, redirectionURI,
- clientId, clientSecret);
+ private AccessTokenResponse requestAccessTokenWithAuthorizationCode (
+ String code, String redirectionURI, String clientId,
+ String clientSecret) throws KustvaktException {
+ Authorization authorization = retrieveAuthorization(code,
+ redirectionURI, clientId, clientSecret);
Set<String> scopes = scopeService
.convertAccessScopesToStringSet(authorization.getScopes());
@@ -330,8 +325,8 @@
String clientSecret, String username, String password,
Set<String> scopes) throws KustvaktException {
- OAuth2Client client =
- clientService.authenticateClient(clientId, clientSecret);
+ OAuth2Client client = clientService.authenticateClient(clientId,
+ clientSecret);
if (!client.isSuper()) {
throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED,
"Password grant is not allowed for third party clients",
@@ -344,24 +339,25 @@
// scopes = config.getDefaultAccessScopes();
}
- ZonedDateTime authenticationTime =
- authenticateUser(username, password, scopes);
+ ZonedDateTime authenticationTime = authenticateUser(username, password,
+ scopes);
- Set<AccessScope> accessScopes =
- scopeService.convertToAccessScope(scopes);
-
+ Set<AccessScope> accessScopes = scopeService
+ .convertToAccessScope(scopes);
+
if (config.getOAuth2passwordAuthentication()
.equals(AuthenticationMethod.LDAP)) {
try {
//username = LdapAuth3.getEmail(username, config.getLdapConfig());
- username = LdapAuth3.getUsername(username, config.getLdapConfig());
+ username = LdapAuth3.getUsername(username,
+ config.getLdapConfig());
}
catch (LDAPException e) {
throw new KustvaktException(StatusCodes.LDAP_BASE_ERRCODE,
e.getExceptionMessage());
}
}
-
+
return createsAccessTokenResponse(scopes, accessScopes, clientId,
username, authenticationTime, client);
}
@@ -391,7 +387,8 @@
}
// OAuth2Client client =
- OAuth2Client oAuth2Client = clientService.authenticateClient(clientId, clientSecret);
+ OAuth2Client oAuth2Client = clientService.authenticateClient(clientId,
+ clientSecret);
// if (!client.isNative()) {
// throw new KustvaktException(
@@ -401,15 +398,15 @@
// OAuth2Error.UNAUTHORIZED_CLIENT);
// }
- ZonedDateTime authenticationTime =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime authenticationTime = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
scopes = scopeService.filterScopes(scopes,
config.getClientCredentialsScopes());
- Set<AccessScope> accessScopes =
- scopeService.convertToAccessScope(scopes);
+ Set<AccessScope> accessScopes = scopeService
+ .convertToAccessScope(scopes);
return createsAccessTokenResponse(scopes, accessScopes, clientId, null,
- authenticationTime,oAuth2Client);
+ authenticationTime, oAuth2Client);
}
/**
@@ -420,8 +417,10 @@
* Base64.
*
* <br /><br />
- * Additionally, a refresh token is issued for confidential clients.
- * It can be used to request a new access token without requiring user
+ * Additionally, a refresh token is issued for confidential
+ * clients.
+ * It can be used to request a new access token without requiring
+ * user
* re-authentication.
*
* @param scopes
@@ -446,7 +445,7 @@
String random = randomGenerator.createRandomCode();
random += randomGenerator.createRandomCode();
-
+
if (clientService.isPublicClient(client)) {
// refresh token == null, getAccessTokenLongExpiry
return createsAccessTokenResponse(null, scopes, accessScopes,
@@ -468,30 +467,29 @@
ZonedDateTime authenticationTime) throws KustvaktException {
String accessToken = randomGenerator.createRandomCode();
- accessToken +=randomGenerator.createRandomCode();
+ accessToken += randomGenerator.createRandomCode();
tokenDao.storeAccessToken(accessToken, refreshToken, accessScopes,
userId, clientId, authenticationTime);
Tokens tokens = null;
- if (refreshToken !=null) {
+ if (refreshToken != null) {
BearerAccessToken bearerToken = new BearerAccessToken(accessToken,
(long) config.getAccessTokenExpiry(), Scope.parse(scopes));
- com.nimbusds.oauth2.sdk.token.RefreshToken rf =
- new com.nimbusds.oauth2.sdk.token.RefreshToken(
- refreshToken.getToken());
+ com.nimbusds.oauth2.sdk.token.RefreshToken rf = new com.nimbusds.oauth2.sdk.token.RefreshToken(
+ refreshToken.getToken());
tokens = new Tokens(bearerToken, rf);
}
else {
- BearerAccessToken bearerToken = new BearerAccessToken(accessToken,
- (long) config.getAccessTokenLongExpiry(), Scope.parse(scopes));
- tokens = new Tokens(bearerToken, null);
+ BearerAccessToken bearerToken = new BearerAccessToken(accessToken,
+ (long) config.getAccessTokenLongExpiry(),
+ Scope.parse(scopes));
+ tokens = new Tokens(bearerToken, null);
}
return new AccessTokenResponse(tokens);
- }
+ }
-
- public void revokeToken (String clientId, String clientSecret,
- String token, String tokenType) throws KustvaktException {
+ public void revokeToken (String clientId, String clientSecret, String token,
+ String tokenType) throws KustvaktException {
clientService.authenticateClient(clientId, clientSecret);
if (tokenType != null && tokenType.equals("refresh_token")) {
if (!revokeRefreshToken(token)) {
@@ -518,10 +516,10 @@
throw e;
}
}
-
+
private void revokeAccessToken (AccessToken accessToken)
throws KustvaktException {
- if (accessToken != null){
+ if (accessToken != null) {
accessToken.setRevoked(true);
tokenDao.updateAccessToken(accessToken);
}
@@ -541,10 +539,10 @@
public boolean revokeRefreshToken (RefreshToken refreshToken)
throws KustvaktException {
- if (refreshToken != null){
+ if (refreshToken != null) {
refreshToken.setRevoked(true);
refreshDao.updateRefreshToken(refreshToken);
-
+
Set<AccessToken> accessTokenList = refreshToken.getAccessTokens();
for (AccessToken accessToken : accessTokenList) {
accessToken.setRevoked(true);
@@ -567,13 +565,13 @@
revokeAllClientTokensForUser(clientId, username);
}
-
+
public void revokeAllClientTokensForUser (String clientId, String username)
throws KustvaktException {
OAuth2Client client = clientService.retrieveClient(clientId);
if (clientService.isPublicClient(client)) {
- List<AccessToken> accessTokens =
- tokenDao.retrieveAccessTokenByClientId(clientId, username);
+ List<AccessToken> accessTokens = tokenDao
+ .retrieveAccessTokenByClientId(clientId, username);
for (AccessToken t : accessTokens) {
revokeAccessToken(t);
}
@@ -586,7 +584,7 @@
}
}
}
-
+
public void revokeTokensViaSuperClient (String username,
String superClientId, String superClientSecret, String token)
throws KustvaktException {
@@ -597,30 +595,33 @@
StatusCodes.CLIENT_AUTHENTICATION_FAILED);
}
- RefreshToken refreshToken =
- refreshDao.retrieveRefreshToken(token, username);
+ RefreshToken refreshToken = refreshDao.retrieveRefreshToken(token,
+ username);
if (!revokeRefreshToken(refreshToken)) {
- AccessToken accessToken =
- tokenDao.retrieveAccessToken(token, username);
+ AccessToken accessToken = tokenDao.retrieveAccessToken(token,
+ username);
revokeAccessToken(accessToken);
}
}
-
- public List<OAuth2TokenDto> listUserRefreshToken (String username, String superClientId,
- String superClientSecret, String clientId) throws KustvaktException {
-
- OAuth2Client client = clientService.authenticateClient(superClientId, superClientSecret);
+
+ public List<OAuth2TokenDto> listUserRefreshToken (String username,
+ String superClientId, String superClientSecret, String clientId)
+ throws KustvaktException {
+
+ OAuth2Client client = clientService.authenticateClient(superClientId,
+ superClientSecret);
if (!client.isSuper()) {
throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED,
"Only super client is allowed.",
OAuth2Error.UNAUTHORIZED_CLIENT);
}
- List<RefreshToken> tokens = refreshDao.retrieveRefreshTokenByUser(username, clientId);
+ List<RefreshToken> tokens = refreshDao
+ .retrieveRefreshTokenByUser(username, clientId);
List<OAuth2TokenDto> dtoList = new ArrayList<>(tokens.size());
- for (RefreshToken t : tokens){
+ for (RefreshToken t : tokens) {
OAuth2Client tokenClient = t.getClient();
- if (tokenClient.getId().equals(client.getId())){
+ if (tokenClient.getId().equals(client.getId())) {
continue;
}
OAuth2TokenDto dto = new OAuth2TokenDto();
@@ -628,19 +629,20 @@
dto.setClientName(tokenClient.getName());
dto.setClientUrl(tokenClient.getUrl());
dto.setClientDescription(tokenClient.getDescription());
-
+
DateTimeFormatter f = DateTimeFormatter.ISO_DATE_TIME;
dto.setCreatedDate(t.getCreatedDate().format(f));
- long difference = ChronoUnit.SECONDS.between(ZonedDateTime.now(), t.getExpiryDate());
+ long difference = ChronoUnit.SECONDS.between(ZonedDateTime.now(),
+ t.getExpiryDate());
dto.setExpiresIn(difference);
-
+
dto.setUserAuthenticationTime(
t.getUserAuthenticationTime().format(f));
dto.setToken(t.getToken());
-
+
Set<AccessScope> accessScopes = t.getScopes();
Set<String> scopes = new HashSet<>(accessScopes.size());
- for (AccessScope s : accessScopes){
+ for (AccessScope s : accessScopes) {
scopes.add(s.getId().toString());
}
dto.setScope(scopes);
@@ -648,23 +650,25 @@
}
return dtoList;
}
-
- public List<OAuth2TokenDto> listUserAccessToken (String username, String superClientId,
- String superClientSecret, String clientId) throws KustvaktException {
-
- OAuth2Client superClient = clientService.authenticateClient(superClientId, superClientSecret);
+
+ public List<OAuth2TokenDto> listUserAccessToken (String username,
+ String superClientId, String superClientSecret, String clientId)
+ throws KustvaktException {
+
+ OAuth2Client superClient = clientService
+ .authenticateClient(superClientId, superClientSecret);
if (!superClient.isSuper()) {
throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED,
"Only super client is allowed.",
OAuth2Error.UNAUTHORIZED_CLIENT);
}
- List<AccessToken> tokens =
- tokenDao.retrieveAccessTokenByUser(username, clientId);
+ List<AccessToken> tokens = tokenDao.retrieveAccessTokenByUser(username,
+ clientId);
List<OAuth2TokenDto> dtoList = new ArrayList<>(tokens.size());
- for (AccessToken t : tokens){
+ for (AccessToken t : tokens) {
OAuth2Client tokenClient = t.getClient();
- if (tokenClient.getId().equals(superClient.getId())){
+ if (tokenClient.getId().equals(superClient.getId())) {
continue;
}
OAuth2TokenDto dto = new OAuth2TokenDto();
@@ -672,20 +676,21 @@
dto.setClientName(tokenClient.getName());
dto.setClientUrl(tokenClient.getUrl());
dto.setClientDescription(tokenClient.getDescription());
-
+
DateTimeFormatter f = DateTimeFormatter.ISO_DATE_TIME;
dto.setCreatedDate(t.getCreatedDate().format(f));
-
- long difference = ChronoUnit.SECONDS.between(ZonedDateTime.now(), t.getExpiryDate());
+
+ long difference = ChronoUnit.SECONDS.between(ZonedDateTime.now(),
+ t.getExpiryDate());
dto.setExpiresIn(difference);
-
+
dto.setUserAuthenticationTime(
t.getUserAuthenticationTime().format(f));
dto.setToken(t.getToken());
-
+
Set<AccessScope> accessScopes = t.getScopes();
Set<String> scopes = new HashSet<>(accessScopes.size());
- for (AccessScope s : accessScopes){
+ for (AccessScope s : accessScopes) {
scopes.add(s.getId().toString());
}
dto.setScope(scopes);
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
index 530eb86..f827871 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
@@ -9,7 +9,9 @@
import de.ids_mannheim.korap.user.User;
import edu.emory.mathcs.backport.java.util.Arrays;
-/** EM: not used anymore. This rewrite was to remove an empty koral:doc group in operands.
+/**
+ * EM: not used anymore. This rewrite was to remove an empty koral:doc
+ * group in operands.
*
* @author hanl
* @date 28/07/2015
@@ -23,7 +25,6 @@
return node.wrapNode(jsonNode);
}
-
private JsonNode process (JsonNode root) {
JsonNode sub = root;
if (root.isObject()) {
@@ -50,8 +51,8 @@
if (!root.equals(sub)) {
if (sub.isObject()) {
ObjectNode ob = (ObjectNode) root;
- ob.remove(Arrays.asList(new String[] { "@type",
- "operation", "operands" }));
+ ob.remove(Arrays.asList(
+ new String[] { "@type", "operation", "operands" }));
ob.putAll((ObjectNode) sub);
}
}
@@ -59,13 +60,11 @@
return root;
}
-
@Override
public JsonNode rewriteResult (KoralNode node) {
return null;
}
-
@Override
public String at () {
return "/collection";
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
index 1ce9893..d2d3610 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
@@ -6,8 +6,9 @@
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.user.User;
-/** EM: not used anymore. This rewrite was meant to remove doc from
- * a collection by checking user access to the doc.
+/**
+ * EM: not used anymore. This rewrite was meant to remove doc from
+ * a collection by checking user access to the doc.
*
* @author hanl
* @date 03/07/2015
@@ -21,46 +22,43 @@
if (node.get("key").equals(Attributes.CORPUS_SIGLE)) {
String id = node.get("value");
// EM: MH checks if user has access to corpus
-// KustvaktResource corpus = check(id, user);
-// if (corpus == null)
- node.removeNode(new KoralNode.RewriteIdentifier(
- Attributes.CORPUS_SIGLE, id));
+ // KustvaktResource corpus = check(id, user);
+ // if (corpus == null)
+ node.removeNode(new KoralNode.RewriteIdentifier(
+ Attributes.CORPUS_SIGLE, id));
}
}
return node;
}
-
/**
* @param id
* @param user
* @return boolean if true access granted
*/
-// @Deprecated
-// private KustvaktResource check (String id, User user) {
-// // todo: can be used to circumvent access control if public filter not applied
-// if (user == null)
-// return null;
-//
-// KustvaktResource corpus;
-// try {
-// SecurityManager m = SecurityManager
-// .findbyId(id, user, Corpus.class);
-// corpus = m.getResource();
-// }
-// catch (RuntimeException | KustvaktException e) {
-// return null;
-// }
-// return corpus;
-// }
-
+ // @Deprecated
+ // private KustvaktResource check (String id, User user) {
+ // // todo: can be used to circumvent access control if public filter not applied
+ // if (user == null)
+ // return null;
+ //
+ // KustvaktResource corpus;
+ // try {
+ // SecurityManager m = SecurityManager
+ // .findbyId(id, user, Corpus.class);
+ // corpus = m.getResource();
+ // }
+ // catch (RuntimeException | KustvaktException e) {
+ // return null;
+ // }
+ // return corpus;
+ // }
@Override
public JsonNode rewriteResult (KoralNode node) {
return null;
}
-
@Override
public String path () {
return "collection";
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionRewrite.java
index 43681bd..0c3ee07 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionRewrite.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionRewrite.java
@@ -1,6 +1,5 @@
package de.ids_mannheim.korap.rewrite;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -23,39 +22,40 @@
import de.ids_mannheim.korap.utils.JsonUtils;
import de.ids_mannheim.korap.utils.KoralCollectionQueryBuilder;
-/** CollectionRewrite determines which availability field values are
- * possible for a user with respect to his mean and location of access.
- *
- * <br/><br/>
- * KorAP differentiates 3 kinds of access:
- * <ul>
- * <li>FREE: without login</li>
- * <li>PUB: login outside IDS network</li>
- * <li>ALL: login within IDS network</li>
- * </ul>
- *
- * Each of these accesses corresponds to a regular expression of license
- * formats defined in kustvakt.conf. For a given access, only those
- * resources whose availability field matches its regular expression
- * are allowed to be retrieved.
- *
- *
+/**
+ * CollectionRewrite determines which availability field values are
+ * possible for a user with respect to his mean and location of
+ * access.
+ *
+ * <br/><br/>
+ * KorAP differentiates 3 kinds of access:
+ * <ul>
+ * <li>FREE: without login</li>
+ * <li>PUB: login outside IDS network</li>
+ * <li>ALL: login within IDS network</li>
+ * </ul>
+ *
+ * Each of these accesses corresponds to a regular expression of
+ * license
+ * formats defined in kustvakt.conf. For a given access, only those
+ * resources whose availability field matches its regular expression
+ * are allowed to be retrieved.
+ *
+ *
* @author margaretha
* @last-update 21 Nov 2017
* @see CorpusAccess
*/
public class CollectionRewrite implements RewriteTask.RewriteQuery {
- public static Logger jlog =
- LogManager.getLogger(CollectionRewrite.class);
+ public static Logger jlog = LogManager.getLogger(CollectionRewrite.class);
public static boolean DEBUG = false;
-
+
public CollectionRewrite () {
super();
}
-
private List<String> checkAvailability (JsonNode node,
List<String> originalAvailabilities,
List<String> updatedAvailabilities, boolean isOperationOr) {
@@ -69,8 +69,8 @@
}
if (node.has("operands")) {
- ArrayList<JsonNode> operands =
- Lists.newArrayList(node.at("/operands").elements());
+ ArrayList<JsonNode> operands = Lists
+ .newArrayList(node.at("/operands").elements());
if (node.at("/operation").asText()
.equals(KoralOperation.AND.toString())) {
@@ -78,7 +78,8 @@
updatedAvailabilities = checkAvailability(operands.get(i),
originalAvailabilities, updatedAvailabilities,
false);
- if (updatedAvailabilities.isEmpty()) break;
+ if (updatedAvailabilities.isEmpty())
+ break;
}
}
else {
@@ -113,7 +114,7 @@
updatedAvailabilities.remove(queryAvailability);
}
else if (isOperationOr) {
- if (DEBUG) {
+ if (DEBUG) {
jlog.debug("RESET availabilities 2");
}
updatedAvailabilities.clear();
@@ -153,8 +154,8 @@
JsonNode rewrittenNode;
if (jsonNode.has("collection")) {
- List<String> avalabilityCopy =
- new ArrayList<String>(userAvailabilities.size());
+ List<String> avalabilityCopy = new ArrayList<String>(
+ userAvailabilities.size());
avalabilityCopy.addAll(userAvailabilities);
if (DEBUG) {
jlog.debug("Availabilities: "
@@ -178,20 +179,19 @@
if (DEBUG) {
jlog.debug("corpus query: " + builder.toString());
}
- rewrittenNode =
- JsonUtils.readTree(builder.toJSON()).at("/collection");
+ rewrittenNode = JsonUtils.readTree(builder.toJSON())
+ .at("/collection");
node.set("collection", rewrittenNode, identifier);
}
node = node.at("/collection");
- if (DEBUG) {
+ if (DEBUG) {
jlog.debug("REWRITES: " + node.toString());
}
-
+
return node;
}
-
private String buildAvailability (List<String> userAvailabilities) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userAvailabilities.size(); i++) {
@@ -229,4 +229,3 @@
}
}
-
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
index 9146e5f..73615e0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
@@ -18,28 +18,30 @@
@Autowired
protected LayerMapper mapper;
-
+
@Override
public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
User user) throws KustvaktException {
-
+
if (node.get("@type").equals("koral:span")) {
- if (!node.isMissingNode("/wrap")){
+ if (!node.isMissingNode("/wrap")) {
node = node.at("/wrap");
JsonNode term = rewriteQuery(node, config, user).rawNode();
- node.replaceAt("/wrap", term, new RewriteIdentifier("koral:term", "replace"));
+ node.replaceAt("/wrap", term,
+ new RewriteIdentifier("koral:term", "replace"));
}
}
- else if (node.get("@type").equals("koral:term") && !node.has("foundry")) {
+ else if (node.get("@type").equals("koral:term")
+ && !node.has("foundry")) {
String layer;
- if (node.has("layer")){
+ if (node.has("layer")) {
layer = node.get("layer");
}
- else{
+ else {
layer = node.get("key");
}
UserSettingProcessor settingProcessor = null;
- if (user!=null){
+ if (user != null) {
settingProcessor = user.getUserSettingProcessor();
}
String foundry = mapper.findFoundry(layer, settingProcessor);
@@ -54,7 +56,6 @@
return "query";
}
-
@Override
public JsonNode rewriteResult (KoralNode node) {
return null;
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java
index 60beaaf..c59097c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java
@@ -21,11 +21,10 @@
public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
User user) throws KustvaktException {
String username = user.getUsername();
- String jsonSettings =
- settingService.retrieveDefaultSettings(username);
+ String jsonSettings = settingService.retrieveDefaultSettings(username);
if (jsonSettings != null) {
- UserSettingProcessor processor =
- new UserSettingProcessor(jsonSettings);
+ UserSettingProcessor processor = new UserSettingProcessor(
+ jsonSettings);
user.setUserSettingProcessor(processor);
}
return super.rewriteQuery(node, config, user);
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/IdWriter.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/IdWriter.java
index 1f0dad6..113c176 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/IdWriter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/IdWriter.java
@@ -14,12 +14,10 @@
private int counter;
-
public IdWriter () {
this.counter = 0;
}
-
@Override
public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
User user) {
@@ -31,7 +29,6 @@
return node;
}
-
private String extractToken (JsonNode token) {
JsonNode wrap = token.path("wrap");
if (!wrap.isMissingNode())
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/KoralNode.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/KoralNode.java
index a8870b7..f05f864 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/KoralNode.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/KoralNode.java
@@ -16,40 +16,35 @@
private KoralRewriteBuilder rewrites;
private boolean remove;
-
public KoralNode (JsonNode node) {
this.node = node;
this.rewrites = new KoralRewriteBuilder();
this.remove = false;
}
-
+
public KoralNode (JsonNode node, KoralRewriteBuilder rewrites) {
this.node = node;
this.rewrites = rewrites;
this.remove = false;
}
-
public static KoralNode wrapNode (JsonNode node) {
return new KoralNode(node);
}
-
+
public void buildRewrites (JsonNode node) {
this.rewrites.build(node);
}
-
public void buildRewrites () {
this.rewrites.build(this.node);
}
-
@Override
public String toString () {
return this.node.toString();
}
-
public void put (String name, Object value) {
if (this.node.isObject() && this.node.path(name).isMissingNode()) {
ObjectNode node = (ObjectNode) this.node;
@@ -66,7 +61,6 @@
"node doesn't support this operation");
}
-
public void remove (Object identifier, RewriteIdentifier ident) {
boolean set = false;
if (this.node.isObject() && identifier instanceof String) {
@@ -88,7 +82,6 @@
}
}
-
public void replace (String name, Object value, RewriteIdentifier ident) {
if (this.node.isObject() && this.node.has(name)) {
ObjectNode n = (ObjectNode) this.node;
@@ -105,12 +98,12 @@
this.rewrites.add("override", name);
}
}
-
+
public void replaceAt (String path, Object value, RewriteIdentifier ident) {
if (this.node.isObject() && !this.node.at(path).isMissingNode()) {
ObjectNode n = (ObjectNode) this.node.at(path);
n.removeAll();
- n.putAll((ObjectNode)value);
+ n.putAll((ObjectNode) value);
String name = path;
if (ident != null)
@@ -130,7 +123,6 @@
else if (value instanceof JsonNode)
n.put(name, (JsonNode) value);
-
if (ident != null)
name = ident.toString();
@@ -143,7 +135,7 @@
ObjectNode n = (ObjectNode) this.node;
n.setAll(other);
}
- this.rewrites.add("insertion",null);
+ this.rewrites.add("insertion", null);
}
public String get (String name) {
@@ -152,14 +144,12 @@
return null;
}
-
public KoralNode at (String name) {
-// this.node = this.node.at(name);
-// return this;
+ // this.node = this.node.at(name);
+ // return this;
return new KoralNode(this.node.at(name), this.rewrites);
}
-
public boolean has (Object ident) {
if (ident instanceof String)
return this.node.has((String) ident);
@@ -168,12 +158,10 @@
return false;
}
-
public JsonNode rawNode () {
return this.node;
}
-
public void removeNode (RewriteIdentifier ident) {
this.rewrites.add("deletion", ident.toString());
this.remove = true;
@@ -183,48 +171,40 @@
private String key, value;
-
public RewriteIdentifier (String key, Object value) {
this.key = key;
this.value = value.toString();
}
-
@Override
public String toString () {
return key + "(" + value + ")";
}
-
}
-
public boolean isRemove () {
return this.remove;
}
-
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);
- if (scope !=null){
+ if (scope != null) {
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)
@@ -252,20 +232,16 @@
}
-
-
private static class KoralRewrite {
private Map<String, String> map;
-
private KoralRewrite () {
this.map = new LinkedHashMap<>();
this.map.put("@type", "koral:rewrite");
this.map.put("src", "Kustvakt");
}
-
public KoralRewrite setOperation (String op) {
if (!op.startsWith("operation:"))
op = "operation:" + op;
@@ -273,7 +249,6 @@
return this;
}
-
public KoralRewrite setScope (String scope) {
this.map.put("scope", scope);
return this;
@@ -281,21 +256,17 @@
}
-
public boolean isMissingNode (String string) {
return this.node.at(string).isMissingNode();
}
-
public int size () {
return this.node.size();
}
-
public KoralNode get (int i) {
-// this.node = this.node.get(i);
+ // this.node = this.node.get(i);
return this.wrapNode(this.node.get(i));
}
-
-
+
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
index 29360d9..59eb614 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
@@ -7,11 +7,13 @@
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.user.UserSettingProcessor;
-/** EM:
- * <ul>
- * <li> Added default morphology foundry </li>
- * <li> Made this class as a spring component</li>
- * </ul>
+/**
+ * EM:
+ * <ul>
+ * <li> Added default morphology foundry </li>
+ * <li> Made this class as a spring component</li>
+ * </ul>
+ *
* @author hanl, margaretha
* @date 14/10/2014
*/
@@ -55,10 +57,10 @@
// EM: added
case "s":
return (String) settings
- .get(Attributes.DEFAULT_FOUNDRY_STRUCTURE);
+ .get(Attributes.DEFAULT_FOUNDRY_STRUCTURE);
case "morphology":
return (String) settings
- .get(Attributes.DEFAULT_FOUNDRY_MORPHOLOGY);
+ .get(Attributes.DEFAULT_FOUNDRY_MORPHOLOGY);
default:
// if the layer is not in this specific listing, assume a default layer
// like orth or other tokenization layers
@@ -77,7 +79,7 @@
return config.getDefault_lemma();
case "surface":
return config.getDefault_orthography();
- // refers to "structure" and is used for paragraphs or sentence boundaries
+ // refers to "structure" and is used for paragraphs or sentence boundaries
case "s":
return config.getDefaultStructureFoundry();
//EM: added
@@ -91,23 +93,22 @@
}
}
-
// relevance: map to access control id references. p is usually mapped to pos, l to lemma, etc.
public String translateLayer (String layer) {
switch (layer.toLowerCase().trim()) {
- // case "pos":
- // return "p";
- // case "lemma":
- // return "l";
+ // case "pos":
+ // return "p";
+ // case "lemma":
+ // return "l";
case "m":
return "morphology"; // EM: changed msd to morphology
-// return "msd";
- //todo the orth layer does not need a foundry entry
+ // return "msd";
+ //todo the orth layer does not need a foundry entry
case "orth":
return "surface";
// EM: layer t does not exist at all
-// case "t":
-// return "surface";
+ // case "t":
+ // return "surface";
// EM: this islegacy support
case "const":
return "c";
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/MetaConstraint.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/MetaConstraint.java
index a9380b9..2838f67 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/MetaConstraint.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/MetaConstraint.java
@@ -11,7 +11,6 @@
*/
public class MetaConstraint implements RewriteTask.RewriteNodeAt {
-
@Override
public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
User user) {
@@ -24,13 +23,11 @@
return node;
}
-
@Override
public JsonNode rewriteResult (KoralNode node) {
return null;
}
-
@Override
public String at () {
return "/meta";
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/QueryReferenceRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/QueryReferenceRewrite.java
index f14bf56..9521c72 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/QueryReferenceRewrite.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/QueryReferenceRewrite.java
@@ -20,7 +20,7 @@
* Rewrites query reference with the corresponding koral
* query describing the actual query fragment.
*
- * Based on VirtualCorpusRewrite.
+ * Based on VirtualCorpusRewrite.
*
* @author diewald, margaretha
*
@@ -32,9 +32,8 @@
private QueryService service;
@Override
- public KoralNode rewriteQuery (KoralNode node,
- KustvaktConfiguration config,
- User user) throws KustvaktException {
+ public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
+ User user) throws KustvaktException {
if (node.has("query")) {
node = node.at("/query");
findQueryRef(user.getUsername(), node);
@@ -43,14 +42,13 @@
}
private void findQueryRef (String username, KoralNode koralNode)
- throws KustvaktException {
+ throws KustvaktException {
if (koralNode.has("@type")
- && koralNode.get("@type").equals("koral:queryRef")) {
+ && koralNode.get("@type").equals("koral:queryRef")) {
if (!koralNode.has("ref")) {
throw new KustvaktException(
- de.ids_mannheim.korap.util.StatusCodes.MISSING_QUERY_REFERENCE,
- "ref is not found"
- );
+ de.ids_mannheim.korap.util.StatusCodes.MISSING_QUERY_REFERENCE,
+ "ref is not found");
}
else {
String queryRefName = koralNode.get("ref");
@@ -63,8 +61,8 @@
}
}
- QueryDO qr = service.searchQueryByName(username,
- queryRefName, queryRefOwner, QueryType.QUERY);
+ QueryDO qr = service.searchQueryByName(username, queryRefName,
+ queryRefOwner, QueryType.QUERY);
if (qr == null) {
throw new KustvaktException(StatusCodes.NO_RESOURCE_FOUND,
@@ -76,13 +74,13 @@
// TODO:
// checkVCAcess(q, username);
JsonNode qref = JsonUtils.readTree(qr.getKoralQuery());;
- rewriteQuery(qref,koralNode);
+ rewriteQuery(qref, koralNode);
}
}
-
+
else if (koralNode.has("operands")) {
KoralNode operands = koralNode.at("/operands");
-
+
for (int i = 0; i < operands.size(); i++) {
KoralNode operand = operands.get(i);
this.findQueryRef(username, operand);
@@ -91,9 +89,8 @@
}
}
-
private void rewriteQuery (JsonNode qref, KoralNode koralNode)
- throws KustvaktException {
+ throws KustvaktException {
JsonNode jsonNode = koralNode.rawNode();
koralNode.remove("@type",
new RewriteIdentifier("@type", jsonNode.at("/@type").asText()));
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
index d674ba6..6bad856 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
@@ -27,7 +27,7 @@
*/
// todo: do post processing!
//todo: load rewritenode and rewritequery automatically from classpath by default, but namespaced from package
-public class RewriteHandler{
+public class RewriteHandler {
//implements BeanInjectable {
private static Logger jlog = LogManager.getLogger(RewriteHandler.class);
@@ -41,15 +41,15 @@
public RewriteHandler (List<RewriteTask> rewriteTasks) {
this();
- for (RewriteTask t : rewriteTasks){
+ for (RewriteTask t : rewriteTasks) {
addProcessor(t);
}
}
-
+
// EM: for testing
public RewriteHandler (KustvaktConfiguration config) {
this();
- this.config=config;
+ this.config = config;
}
public RewriteHandler () {
@@ -63,7 +63,6 @@
return this.failed_task_registration;
}
-
public boolean addProcessor (RewriteTask rewriter) {
if (rewriter instanceof RewriteTask.RewriteKoralToken)
return this.token_node_processors
@@ -79,7 +78,6 @@
return false;
}
-
@Override
public String toString () {
StringBuilder b = new StringBuilder();
@@ -93,7 +91,6 @@
return b.toString();
}
-
/**
* expects extended RewriteNode/Query class with empty default
* constructor
@@ -117,8 +114,6 @@
return addProcessor(task);
}
-
-
public String processQuery (JsonNode root, User user)
throws KustvaktException {
RewriteProcess process = new RewriteProcess(root, user);
@@ -126,19 +121,16 @@
return JsonUtils.toJSON(pre);
}
-
public String processQuery (String json, User user)
throws KustvaktException {
return processQuery(JsonUtils.readTree(json), user);
}
-
public String processResult (String json, User user)
throws KustvaktException {
return processResult(JsonUtils.readTree(json), user);
}
-
public String processResult (JsonNode node, User user)
throws KustvaktException {
RewriteProcess process = new RewriteProcess(node, user);
@@ -146,20 +138,16 @@
return JsonUtils.toJSON(pre);
}
-
public void clear () {
this.node_processors.clear();
this.query_processors.clear();
this.token_node_processors.clear();
}
-
-// public <T extends ContextHolder> void insertBeans (T beans) {
-// this.beans = beans;
-// this.config = beans.getConfiguration();
-// }
-
-
+ // public <T extends ContextHolder> void insertBeans (T beans) {
+ // this.beans = beans;
+ // this.config = beans.getConfiguration();
+ // }
public class RewriteProcess {
@@ -167,13 +155,11 @@
private JsonNode root;
private User user;
-
private RewriteProcess (JsonNode root, User user) {
this.root = root;
this.user = user;
}
-
private KoralNode processNode (String key, JsonNode value,
boolean result) throws KustvaktException {
KoralNode kroot = KoralNode.wrapNode(value);
@@ -211,10 +197,9 @@
return kroot;
}
-
private JsonNode start (boolean result) throws KustvaktException {
- if (DEBUG){
- jlog.debug("Running rewrite process on query "+ root);
+ if (DEBUG) {
+ jlog.debug("Running rewrite process on query " + root);
}
if (root != null) {
Iterator<Map.Entry<String, JsonNode>> it = root.fields();
@@ -228,7 +213,6 @@
return root;
}
-
/**
* @param node
* @param tasks
@@ -240,7 +224,8 @@
Collection<? extends RewriteTask> tasks, boolean result)
throws KustvaktException {
if (RewriteHandler.this.config == null)
- throw new RuntimeException("KustvaktConfiguration must be set!");
+ throw new RuntimeException(
+ "KustvaktConfiguration must be set!");
for (RewriteTask task : tasks) {
if (DEBUG) {
@@ -248,15 +233,15 @@
jlog.debug("on processor: " + task.getClass().toString());
}
-// if (RewriteHandler.this.beans != null
-// && task instanceof BeanInjectable)
-// ((BeanInjectable) task)
-// .insertBeans(RewriteHandler.this.beans);
+ // if (RewriteHandler.this.beans != null
+ // && task instanceof BeanInjectable)
+ // ((BeanInjectable) task)
+ // .insertBeans(RewriteHandler.this.beans);
if (task instanceof RewriteTask.IterableRewritePath) {
RewriteTask.IterableRewritePath rw = (RewriteTask.IterableRewritePath) task;
if (rw.path() != null && !rw.path().equals(rootNode)) {
- if (DEBUG){
+ if (DEBUG) {
jlog.debug("skipping node: " + node);
}
continue;
@@ -280,7 +265,6 @@
return node;
}
-
// fixme: merge with processNode!
private void processFixedNode (JsonNode node,
Collection<RewriteTask> tasks, boolean post)
@@ -289,7 +273,8 @@
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()))
+ if ((rwa.at() != null
+ && !node.at(rwa.at()).isMissingNode()))
next = next.at(rwa.at());
}
@@ -303,7 +288,6 @@
}
}
-
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteTask.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteTask.java
index 79065a5..b015c0e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteTask.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/RewriteTask.java
@@ -11,7 +11,6 @@
*/
public interface RewriteTask {
-
/**
* unspecified query rewrite that gets injected the entire root
* node during preprocessing
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/TreeConstraint.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/TreeConstraint.java
index 1315c7a..81f254a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/TreeConstraint.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/TreeConstraint.java
@@ -53,12 +53,10 @@
private String pointer;
-
public TreeConstraint () {
super();
}
-
@Override
public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
User user) {
@@ -67,13 +65,11 @@
return node;
}
-
@Override
public JsonNode rewriteResult (KoralNode node) {
return null;
}
-
@Override
public String at () {
return null;
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewrite.java
index 7ea386f..3a64df9 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewrite.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewrite.java
@@ -70,9 +70,9 @@
+ "caching process",
koralNode.get("ref"));
}
-
- QueryDO vc =
- queryService.searchQueryByName(username, vcName, vcOwner, QueryType.VIRTUAL_CORPUS);
+
+ QueryDO vc = queryService.searchQueryByName(username, vcName,
+ vcOwner, QueryType.VIRTUAL_CORPUS);
if (!vc.isCached()) {
rewriteVC(vc, koralNode);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/security/context/KustvaktContext.java b/full/src/main/java/de/ids_mannheim/korap/security/context/KustvaktContext.java
index bd2843f..ac09489 100644
--- a/full/src/main/java/de/ids_mannheim/korap/security/context/KustvaktContext.java
+++ b/full/src/main/java/de/ids_mannheim/korap/security/context/KustvaktContext.java
@@ -15,30 +15,25 @@
private TokenContext user;
-
public KustvaktContext (final TokenContext user) {
this.user = user;
}
-
@Override
public Principal getUserPrincipal () {
return this.user;
}
-
@Override
public boolean isUserInRole (String role) {
throw new UnsupportedOperationException();
}
-
@Override
public boolean isSecure () {
return false;
}
-
@Override
public String getAuthenticationScheme () {
return SecurityContext.BASIC_AUTH;
diff --git a/full/src/main/java/de/ids_mannheim/korap/security/context/TokenContext.java b/full/src/main/java/de/ids_mannheim/korap/security/context/TokenContext.java
index 23d2fa4..10b60ee 100644
--- a/full/src/main/java/de/ids_mannheim/korap/security/context/TokenContext.java
+++ b/full/src/main/java/de/ids_mannheim/korap/security/context/TokenContext.java
@@ -18,7 +18,7 @@
import lombok.Setter;
/**
- * EM:
+ * EM:
* - change datatype of tokenType from string to enum
* - added authenticationTime
*
@@ -39,13 +39,12 @@
private String token;
private boolean secureRequired;
-// @Getter(AccessLevel.PRIVATE)
+ // @Getter(AccessLevel.PRIVATE)
@Setter(AccessLevel.PRIVATE)
private Map<String, Object> parameters;
private String hostAddress;
private String userAgent;
-
public TokenContext () {
this.parameters = new HashMap<>();
this.setUsername("");
@@ -54,7 +53,6 @@
this.setExpirationTime(-1);
}
-
private Map statusMap () {
Map m = new HashMap();
if (username != null && !username.isEmpty())
@@ -66,11 +64,10 @@
return m;
}
-
public Map<String, Object> params () {
return new HashMap<>(parameters);
}
-
+
public boolean match (TokenContext other) {
if (other.getToken().equals(this.token))
if (this.getHostAddress().equals(this.hostAddress))
@@ -81,28 +78,23 @@
return false;
}
-
public void addContextParameter (String key, String value) {
this.parameters.put(key, value);
}
-
public void addParams (Map<String, Object> map) {
for (Map.Entry<String, Object> e : map.entrySet())
this.parameters.put(e.getKey(), String.valueOf(e.getValue()));
}
-
public void removeContextParameter (String key) {
this.parameters.remove(key);
}
-
public void setExpirationTime (long date) {
this.expirationTime = date;
}
-
// todo: complete
public static TokenContext fromJSON (String s) throws KustvaktException {
JsonNode node = JsonUtils.readTree(s);
@@ -114,7 +106,6 @@
return c;
}
-
public static TokenContext fromOAuth2 (String s) throws KustvaktException {
JsonNode node = JsonUtils.readTree(s);
TokenContext c = new TokenContext();
@@ -129,41 +120,33 @@
return c;
}
-
public boolean isValid () {
return (this.username != null && !this.username.isEmpty())
&& (this.token != null && !this.token.isEmpty())
&& (this.tokenType != null);
}
-
public String getToken () {
return token;
}
-
public String toJson () throws KustvaktException {
return JsonUtils.toJSON(this.statusMap());
}
-
public boolean isDemo () {
return User.UserFactory.isDemo(this.username);
}
-
-
@Override
public String getName () {
return this.getUsername();
}
-
public ZonedDateTime getAuthenticationTime () {
return authenticationTime;
}
-
public void setAuthenticationTime (ZonedDateTime authTime) {
this.authenticationTime = authTime;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/server/EmbeddedLdapServer.java b/full/src/main/java/de/ids_mannheim/korap/server/EmbeddedLdapServer.java
index 88dfe2e..4b1c17e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/server/EmbeddedLdapServer.java
+++ b/full/src/main/java/de/ids_mannheim/korap/server/EmbeddedLdapServer.java
@@ -15,36 +15,56 @@
public class EmbeddedLdapServer {
static InMemoryDirectoryServer server;
- public static void startIfNotRunning(LDAPConfig ldapConfig) throws LDAPException, GeneralSecurityException, UnknownHostException {
+ public static void startIfNotRunning (LDAPConfig ldapConfig)
+ throws LDAPException, GeneralSecurityException,
+ UnknownHostException {
if (server != null) {
return;
}
- InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(ldapConfig.searchBase);
+ InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(
+ ldapConfig.searchBase);
final MessageDigest sha1Digest = CryptoHelper.getMessageDigest("SHA1");
- final MessageDigest sha256Digest = CryptoHelper.getMessageDigest("SHA-256");
- config.setPasswordEncoders(new ClearInMemoryPasswordEncoder("{CLEAR}", null), new ClearInMemoryPasswordEncoder("{HEX}", HexPasswordEncoderOutputFormatter.getLowercaseInstance()), new ClearInMemoryPasswordEncoder("{BASE64}", Base64PasswordEncoderOutputFormatter.getInstance()), new UnsaltedMessageDigestInMemoryPasswordEncoder("{SHA}", Base64PasswordEncoderOutputFormatter.getInstance(), sha1Digest), new UnsaltedMessageDigestInMemoryPasswordEncoder("{SHA256}", Base64PasswordEncoderOutputFormatter.getInstance(), sha256Digest));
- config.addAdditionalBindCredentials(ldapConfig.sLoginDN, ldapConfig.sPwd);
+ final MessageDigest sha256Digest = CryptoHelper
+ .getMessageDigest("SHA-256");
+ config.setPasswordEncoders(
+ new ClearInMemoryPasswordEncoder("{CLEAR}", null),
+ new ClearInMemoryPasswordEncoder("{HEX}",
+ HexPasswordEncoderOutputFormatter
+ .getLowercaseInstance()),
+ new ClearInMemoryPasswordEncoder("{BASE64}",
+ Base64PasswordEncoderOutputFormatter.getInstance()),
+ new UnsaltedMessageDigestInMemoryPasswordEncoder("{SHA}",
+ Base64PasswordEncoderOutputFormatter.getInstance(),
+ sha1Digest),
+ new UnsaltedMessageDigestInMemoryPasswordEncoder("{SHA256}",
+ Base64PasswordEncoderOutputFormatter.getInstance(),
+ sha256Digest));
+ config.addAdditionalBindCredentials(ldapConfig.sLoginDN,
+ ldapConfig.sPwd);
config.setSchema(null);
final SSLUtil clientSslUtil = new SSLUtil(new TrustAllTrustManager());
- config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", // Listener name
- InetAddress.getByName("localhost"), // Listen address. (null = listen on all interfaces)
- ldapConfig.port, // Listen port (0 = automatically choose an available port)
- clientSslUtil.createSSLSocketFactory()));
+ config.setListenerConfigs(
+ InMemoryListenerConfig.createLDAPConfig("LDAP", // Listener name
+ InetAddress.getByName("localhost"), // Listen address. (null = listen on all interfaces)
+ ldapConfig.port, // Listen port (0 = automatically choose an available port)
+ clientSslUtil.createSSLSocketFactory()));
server = new InMemoryDirectoryServer(config);
server.importFromLDIF(true, ldapConfig.ldif);
server.startListening();
}
- public static void startIfNotRunning(String ldapConfigFilename) throws LDAPException, GeneralSecurityException, UnknownHostException {
+ public static void startIfNotRunning (String ldapConfigFilename)
+ throws LDAPException, GeneralSecurityException,
+ UnknownHostException {
LDAPConfig ldapConfig = new LDAPConfig(ldapConfigFilename);
startIfNotRunning(ldapConfig);
}
- public static void stop() {
+ public static void stop () {
if (server != null) {
server.shutDown(true);
server = null;
diff --git a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktBaseServer.java b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktBaseServer.java
index ecd1ac9..db6b7c3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktBaseServer.java
+++ b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktBaseServer.java
@@ -43,7 +43,7 @@
rootPackages = "de.ids_mannheim.korap.core.web; "
+ "de.ids_mannheim.korap.web; "
+ "com.fasterxml.jackson.jaxrs.json;";
-
+
File d = new File(KustvaktConfiguration.DATA_FOLDER);
if (!d.exists()) {
d.mkdir();
@@ -63,8 +63,8 @@
case "--help":
StringBuffer b = new StringBuffer();
- b.append("Parameter description: \n")
- .append("--spring-config <Spring XML configuration>\n")
+ b.append("Parameter description: \n").append(
+ "--spring-config <Spring XML configuration>\n")
.append("--port <Server port number>\n")
.append("--help : This help menu\n");
System.out.println(b.toString());
@@ -82,14 +82,14 @@
kargs.setPort(config.getPort());
}
- String adminToken="";
+ String adminToken = "";
File f = new File("adminToken");
if (!f.exists()) {
RandomCodeGenerator random = new RandomCodeGenerator();
adminToken = random.createRandomCode(config);
FileOutputStream fos = new FileOutputStream(new File("adminToken"));
- OutputStreamWriter writer =
- new OutputStreamWriter(fos, StandardCharsets.UTF_8.name());
+ OutputStreamWriter writer = new OutputStreamWriter(fos,
+ StandardCharsets.UTF_8.name());
writer.append("token=");
writer.append(adminToken);
writer.flush();
@@ -103,11 +103,11 @@
Server server = new Server();
- ServletContextHandler contextHandler =
- new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
+ ServletContextHandler contextHandler = new ServletContextHandler(
+ ServletContextHandler.NO_SESSIONS);
contextHandler.setContextPath("/");
-
- if (kargs.getSpringConfig()!=null) {
+
+ if (kargs.getSpringConfig() != null) {
contextHandler.setInitParameter("contextConfigLocation",
"file:" + kargs.getSpringConfig());
}
@@ -115,14 +115,14 @@
contextHandler.setInitParameter("contextConfigLocation",
"classpath:" + this.springConfig);
}
-
+
ServletContextListener listener = new ContextLoaderListener();
contextHandler.addEventListener(listener);
contextHandler.setInitParameter("adminToken", adminToken);
ServletHolder servletHolder = new ServletHolder(new ServletContainer());
- servletHolder.setInitParameter(
- ServerProperties.PROVIDER_PACKAGES, rootPackages);
+ servletHolder.setInitParameter(ServerProperties.PROVIDER_PACKAGES,
+ rootPackages);
servletHolder.setInitOrder(1);
contextHandler.addServlet(servletHolder, config.getBaseURL());
@@ -130,9 +130,10 @@
connector.setPort(kargs.port);
connector.setIdleTimeout(60000);
connector.getConnectionFactory(HttpConnectionFactory.class)
- .getHttpConfiguration().setRequestHeaderSize(64000);
+ .getHttpConfiguration().setRequestHeaderSize(64000);
- ShutdownHandler shutdownHandler = new ShutdownHandler(adminToken,true,true);
+ ShutdownHandler shutdownHandler = new ShutdownHandler(adminToken, true,
+ true);
HandlerList handlers = new HandlerList();
handlers.addHandler(shutdownHandler);
@@ -152,7 +153,7 @@
System.exit(-1);
}
}
-
+
@Setter
public static class KustvaktArgs {
diff --git a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktLiteServer.java b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktLiteServer.java
index e229cfe..d6b1c80 100644
--- a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktLiteServer.java
+++ b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktLiteServer.java
@@ -13,7 +13,8 @@
KustvaktLiteServer server = new KustvaktLiteServer();
kargs = server.readAttributes(args);
- if (kargs == null) System.exit(0);
+ if (kargs == null)
+ System.exit(0);
File f = new File("kustvakt-lite.conf");
Properties properties = new Properties();
@@ -32,8 +33,8 @@
config = new KustvaktConfiguration();
config.loadBasicProperties(properties);
- springConfig = "default-lite-config.xml";
-
+ springConfig = "default-lite-config.xml";
+
rootPackages = "de.ids_mannheim.korap.core.web; "
+ "de.ids_mannheim.korap.web.filter; "
+ "de.ids_mannheim.korap.web.utils; "
diff --git a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktServer.java b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktServer.java
index 098d68c..392190e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/server/KustvaktServer.java
+++ b/full/src/main/java/de/ids_mannheim/korap/server/KustvaktServer.java
@@ -18,26 +18,27 @@
public static void main (String[] args) throws Exception {
KustvaktServer server = new KustvaktServer();
kargs = server.readAttributes(args);
-
+
File f = new File("kustvakt.conf");
Properties properties = new Properties();
-
+
InputStream in = null;
- if (!f.exists()){
- in = KustvaktServer.class.getClassLoader().getResourceAsStream("kustvakt.conf");
+ if (!f.exists()) {
+ in = KustvaktServer.class.getClassLoader()
+ .getResourceAsStream("kustvakt.conf");
}
- else{
+ else {
in = new FileInputStream(f);
}
-
+
properties.load(in);
in.close();
-
+
config = new FullConfiguration();
config.loadBasicProperties(properties);
- if (kargs == null)
- System.exit(0);
+ if (kargs == null)
+ System.exit(0);
server.start();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
index 96ebeb8..b0ba7d0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
@@ -60,8 +60,8 @@
UserSettingProcessor processor = new UserSettingProcessor();
processor.readQuietly(map, false);
- DefaultSetting defaultSetting =
- settingDao.retrieveDefaultSetting(username);
+ DefaultSetting defaultSetting = settingDao
+ .retrieveDefaultSetting(username);
if (defaultSetting == null) {
createDefaultSetting(username, processor);
return HttpStatus.SC_CREATED;
@@ -80,8 +80,8 @@
public void updateDefaultSetting (DefaultSetting setting,
UserSettingProcessor newProcessor) throws KustvaktException {
- UserSettingProcessor processor =
- new UserSettingProcessor(setting.getSettings());
+ UserSettingProcessor processor = new UserSettingProcessor(
+ setting.getSettings());
processor.update(newProcessor);
String jsonSettings = processor.serialize();
@@ -98,8 +98,8 @@
public String retrieveDefaultSettings (String username)
throws KustvaktException {
- DefaultSetting defaultSetting =
- settingDao.retrieveDefaultSetting(username);
+ DefaultSetting defaultSetting = settingDao
+ .retrieveDefaultSetting(username);
if (defaultSetting == null) {
return null;
}
@@ -109,8 +109,8 @@
public void deleteKey (String username, String contextUsername, String key)
throws KustvaktException {
username = verifiyUsername(username, contextUsername);
- DefaultSetting defaultSetting =
- settingDao.retrieveDefaultSetting(username);
+ DefaultSetting defaultSetting = settingDao
+ .retrieveDefaultSetting(username);
String jsonSettings = defaultSetting.getSettings();
UserSettingProcessor processor = new UserSettingProcessor(jsonSettings);
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/MailAuthenticator.java b/full/src/main/java/de/ids_mannheim/korap/service/MailAuthenticator.java
index 84397d5..21f2202 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/MailAuthenticator.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/MailAuthenticator.java
@@ -3,7 +3,8 @@
import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
-/** Defines Authenticator for creating javax.mail.Session.
+/**
+ * Defines Authenticator for creating javax.mail.Session.
*
* @see src/main/resources/default-config.xml
*
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/MailService.java b/full/src/main/java/de/ids_mannheim/korap/service/MailService.java
index 0a6b2d4..7619a25 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/MailService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/MailService.java
@@ -34,7 +34,7 @@
public static Logger jlog = LogManager.getLogger(MailService.class);
public static boolean DEBUG = false;
-
+
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
@@ -84,7 +84,8 @@
StandardCharsets.UTF_8.name(), context, stringWriter);
String message = stringWriter.toString();
- if (DEBUG) jlog.debug(message);
+ if (DEBUG)
+ jlog.debug(message);
return message;
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java b/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
index 19b57e9..cc5f51b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
@@ -98,8 +98,8 @@
}
}
- public List<QueryDto> listOwnerQuery (String username,
- QueryType queryType) throws KustvaktException {
+ public List<QueryDto> listOwnerQuery (String username, QueryType queryType)
+ throws KustvaktException {
List<QueryDO> list = queryDao.retrieveOwnerQuery(username, queryType);
return createQueryDtos(list, queryType);
}
@@ -120,8 +120,8 @@
public List<QueryDto> listQueryByType (String createdBy, ResourceType type,
QueryType queryType) throws KustvaktException {
- List<QueryDO> virtualCorpora =
- queryDao.retrieveQueryByType(type, createdBy, queryType);
+ List<QueryDO> virtualCorpora = queryDao.retrieveQueryByType(type,
+ createdBy, queryType);
Collections.sort(virtualCorpora);
return createQueryDtos(virtualCorpora, queryType);
@@ -159,8 +159,8 @@
|| adminDao.isAdmin(username)) {
if (query.getType().equals(ResourceType.PUBLISHED)) {
- QueryAccess access =
- accessDao.retrieveHiddenAccess(query.getId());
+ QueryAccess access = accessDao
+ .retrieveHiddenAccess(query.getId());
accessDao.deleteAccess(access, "system");
userGroupService.deleteAutoHiddenGroup(
access.getUserGroup().getId(), "system");
@@ -252,8 +252,8 @@
QueryDO query = queryDao.retrieveQueryById(queryId);
// create and assign a new hidden group
int groupId = userGroupService.createAutoHiddenGroup();
- UserGroup autoHidden =
- userGroupService.retrieveUserGroupById(groupId);
+ UserGroup autoHidden = userGroupService
+ .retrieveUserGroupById(groupId);
accessDao.createAccessToQuery(query, autoHidden, "system",
QueryAccessStatus.HIDDEN);
}
@@ -269,40 +269,42 @@
QueryType queryType = query.getQueryType();
if (!checkNumberOfQueryLimit(username, queryType)) {
String type = queryType.displayName().toLowerCase();
- throw new KustvaktException(StatusCodes.NOT_ALLOWED,
- "Cannot create "+type+". The maximum number "
- + "of "+type+" has been reached.");
+ throw new KustvaktException(StatusCodes.NOT_ALLOWED,
+ "Cannot create " + type + ". The maximum number " + "of "
+ + type + " has been reached.");
}
-
+
String koralQuery = computeKoralQuery(query);
storeQuery(username, queryName, query.getType(), query.getQueryType(),
koralQuery, query.getDefinition(), query.getDescription(),
query.getStatus(), query.isCached(), queryCreator,
query.getQuery(), query.getQueryLanguage());
}
-
+
private boolean checkNumberOfQueryLimit (String username,
QueryType queryType) throws KustvaktException {
Long num = queryDao.countNumberOfQuery(username, queryType);
- if (num < config.getMaxNumberOfUserQueries()) return true;
- else return false;
+ if (num < config.getMaxNumberOfUserQueries())
+ return true;
+ else
+ return false;
}
-
- private String computeKoralQuery (QueryJson query) throws KustvaktException {
+
+ private String computeKoralQuery (QueryJson query)
+ throws KustvaktException {
if (query.getQueryType().equals(QueryType.VIRTUAL_CORPUS)) {
ParameterChecker.checkStringValue(query.getCorpusQuery(),
"corpusQuery");
return serializeCorpusQuery(query.getCorpusQuery());
}
-
+
if (query.getQueryType().equals(QueryType.QUERY)) {
ParameterChecker.checkStringValue(query.getQuery(), "query");
ParameterChecker.checkStringValue(query.getQueryLanguage(),
"queryLanguage");
- return
- serializeQuery(query.getQuery(), query.getQueryLanguage());
+ return serializeQuery(query.getQuery(), query.getQueryLanguage());
}
-
+
return null;
}
@@ -316,9 +318,10 @@
if (!queryNamePattern.matcher(queryName).matches()) {
throw new KustvaktException(StatusCodes.INVALID_ARGUMENT, queryType
- .displayName() + " must consists of alphanumerical characters "
- + "(limited to ASCII), underscores, dashes and periods. "
- + "The name has to start with an alphanumerical character.",
+ .displayName()
+ + " must consists of alphanumerical characters "
+ + "(limited to ASCII), underscores, dashes and periods. "
+ + "The name has to start with an alphanumerical character.",
queryName);
}
@@ -335,8 +338,8 @@
CorpusAccess requiredAccess = CorpusAccess.PUB;
if (queryType.equals(QueryType.VIRTUAL_CORPUS)) {
- requiredAccess =
- determineRequiredAccess(isCached, queryName, koralQuery);
+ requiredAccess = determineRequiredAccess(isCached, queryName,
+ koralQuery);
}
if (DEBUG) {
@@ -401,8 +404,7 @@
String koralQuery) throws KustvaktException {
if (isCached) {
- KoralCollectionQueryBuilder koral =
- new KoralCollectionQueryBuilder();
+ KoralCollectionQueryBuilder koral = new KoralCollectionQueryBuilder();
koral.with("referTo " + name);
koralQuery = koral.toJSON();
if (DEBUG) {
@@ -454,8 +456,8 @@
"Unauthorized operation for user: " + username, username);
}
- UserGroup userGroup =
- userGroupService.retrieveUserGroupByName(groupName);
+ UserGroup userGroup = userGroupService
+ .retrieveUserGroupByName(groupName);
if (!isQueryAccessAdmin(userGroup, username)
&& !adminDao.isAdmin(username)) {
@@ -488,8 +490,8 @@
private boolean isQueryAccessAdmin (UserGroup userGroup, String username)
throws KustvaktException {
- List<UserGroupMember> accessAdmins =
- userGroupService.retrieveQueryAccessAdmins(userGroup);
+ List<UserGroupMember> accessAdmins = userGroupService
+ .retrieveQueryAccessAdmins(userGroup);
for (UserGroupMember m : accessAdmins) {
if (username.equals(m.getUserId())) {
return true;
@@ -521,8 +523,8 @@
accessList = accessDao.retrieveAllAccess();
}
else {
- List<UserGroup> groups =
- userGroupService.retrieveUserGroup(username);
+ List<UserGroup> groups = userGroupService
+ .retrieveUserGroup(username);
for (UserGroup g : groups) {
if (isQueryAccessAdmin(g, username)) {
accessList.addAll(
@@ -538,8 +540,8 @@
List<QueryAccess> accessList;
if (adminDao.isAdmin(username)) {
- accessList =
- accessDao.retrieveAllAccessByQuery(queryCreator, queryName);
+ accessList = accessDao.retrieveAllAccessByQuery(queryCreator,
+ queryName);
}
else {
accessList = accessDao.retrieveActiveAccessByQuery(queryCreator,
@@ -578,16 +580,16 @@
public List<QueryAccessDto> listQueryAccessByGroup (String username,
String groupName) throws KustvaktException {
- UserGroup userGroup =
- userGroupService.retrieveUserGroupByName(groupName);
+ UserGroup userGroup = userGroupService
+ .retrieveUserGroupByName(groupName);
List<QueryAccess> accessList;
if (adminDao.isAdmin(username)) {
accessList = accessDao.retrieveAllAccessByGroup(userGroup.getId());
}
else if (isQueryAccessAdmin(userGroup, username)) {
- accessList =
- accessDao.retrieveActiveAccessByGroup(userGroup.getId());
+ accessList = accessDao
+ .retrieveActiveAccessByGroup(userGroup.getId());
}
else {
throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
@@ -614,8 +616,8 @@
public JsonNode retrieveKoralQuery (String username, String queryName,
String createdBy, QueryType queryType) throws KustvaktException {
- QueryDO query =
- searchQueryByName(username, queryName, createdBy, queryType);
+ QueryDO query = searchQueryByName(username, queryName, createdBy,
+ queryType);
String koralQuery = query.getKoralQuery();
JsonNode kq = JsonUtils.readTree(koralQuery);
return kq;
@@ -624,17 +626,18 @@
public JsonNode retrieveFieldValues (String username, String queryName,
String createdBy, QueryType queryType, String fieldName)
throws KustvaktException {
-
+
ParameterChecker.checkStringValue(fieldName, "fieldName");
-
-// if (!adminDao.isAdmin(username)) {
-// throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
-// "Unauthorized operation for user: " + username, username);
-// }
-
+
+ // if (!adminDao.isAdmin(username)) {
+ // throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
+ // "Unauthorized operation for user: " + username, username);
+ // }
+
if (fieldName.equals("tokens") || fieldName.equals("base")) {
throw new KustvaktException(StatusCodes.NOT_ALLOWED,
- "Retrieving values of field "+fieldName+" is not allowed.");
+ "Retrieving values of field " + fieldName
+ + " is not allowed.");
}
else {
QueryDO query = searchQueryByName(username, queryName, createdBy,
@@ -659,8 +662,8 @@
public QueryDto retrieveQueryByName (String username, String queryName,
String createdBy, QueryType queryType) throws KustvaktException {
- QueryDO query =
- searchQueryByName(username, queryName, createdBy, queryType);
+ QueryDO query = searchQueryByName(username, queryName, createdBy,
+ queryType);
// String json = query.getKoralQuery();
String statistics = null;
// long start,end;
@@ -721,8 +724,8 @@
private boolean hasAccess (String username, int queryId)
throws KustvaktException {
UserGroup userGroup;
- List<QueryAccess> accessList =
- accessDao.retrieveActiveAccessByQuery(queryId);
+ List<QueryAccess> accessList = accessDao
+ .retrieveActiveAccessByQuery(queryId);
for (QueryAccess access : accessList) {
userGroup = access.getUserGroup();
if (userGroupService.isMember(username, userGroup)) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/ResourceService.java b/full/src/main/java/de/ids_mannheim/korap/service/ResourceService.java
index f22ae68..6bfb1af 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/ResourceService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/ResourceService.java
@@ -13,7 +13,9 @@
import de.ids_mannheim.korap.dto.converter.ResourceConverter;
import de.ids_mannheim.korap.web.controller.ResourceController;
-/** ResourceService defines the logic behind {@link ResourceController}.
+/**
+ * ResourceService defines the logic behind
+ * {@link ResourceController}.
*
* @author margaretha
*
@@ -31,8 +33,8 @@
public List<ResourceDto> getResourceDtos () {
List<Resource> resources = resourceDao.getAllResources();
- List<ResourceDto> resourceDtos =
- resourceConverter.convertToResourcesDto(resources);
+ List<ResourceDto> resourceDtos = resourceConverter
+ .convertToResourcesDto(resources);
if (DEBUG) {
jlog.debug("/info " + resourceDtos.toString());
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java b/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
index 92f69c3..22fe070 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
@@ -48,10 +48,10 @@
public static Logger jlog = LogManager.getLogger(UserGroupService.class);
public static boolean DEBUG = false;
-
+
public static Pattern groupNamePattern = Pattern
.compile("[a-zA-Z0-9]+[a-zA-Z_0-9-.]+");
-
+
@Autowired
private UserGroupDao userGroupDao;
@Autowired
@@ -68,7 +68,7 @@
private MailService mailService;
@Autowired
private RandomCodeGenerator random;
-
+
private static Set<Role> memberRoles;
/**
@@ -85,24 +85,24 @@
public List<UserGroup> retrieveUserGroup (String username)
throws KustvaktException {
- List<UserGroup> userGroups =
- userGroupDao.retrieveGroupByUserId(username);
+ List<UserGroup> userGroups = userGroupDao
+ .retrieveGroupByUserId(username);
Collections.sort(userGroups);
return userGroups;
}
-
+
public List<UserGroupDto> retrieveUserGroupDto (String username)
throws KustvaktException {
List<UserGroup> userGroups = retrieveUserGroup(username);
-
+
ArrayList<UserGroupDto> dtos = new ArrayList<>(userGroups.size());
UserGroupMember userAsMember;
List<UserGroupMember> members;
UserGroupDto groupDto;
for (UserGroup group : userGroups) {
members = retrieveMembers(group.getId(), username);
- userAsMember =
- groupMemberDao.retrieveMemberById(username, group.getId());
+ userAsMember = groupMemberDao.retrieveMemberById(username,
+ group.getId());
groupDto = converter.createUserGroupDto(group, members,
userAsMember.getStatus(), userAsMember.getRoles());
dtos.add(groupDto);
@@ -132,7 +132,7 @@
throws KustvaktException {
return userGroupDao.retrieveGroupById(groupId);
}
-
+
public UserGroup retrieveUserGroupByName (String groupName)
throws KustvaktException {
return userGroupDao.retrieveGroupByName(groupName, false);
@@ -146,16 +146,16 @@
public List<UserGroupDto> retrieveUserGroupByStatus (String username,
UserGroupStatus status) throws KustvaktException {
- List<UserGroup> userGroups =
- userGroupDao.retrieveGroupByStatus(username, status);
+ List<UserGroup> userGroups = userGroupDao
+ .retrieveGroupByStatus(username, status);
Collections.sort(userGroups);
ArrayList<UserGroupDto> dtos = new ArrayList<>(userGroups.size());
List<UserGroupMember> members;
UserGroupDto groupDto;
for (UserGroup group : userGroups) {
- members =
- groupMemberDao.retrieveMemberByGroupId(group.getId(), true);
+ members = groupMemberDao.retrieveMemberByGroupId(group.getId(),
+ true);
groupDto = converter.createUserGroupDto(group, members, null, null);
dtos.add(groupDto);
}
@@ -202,8 +202,8 @@
*
*
*/
- public boolean createUpdateUserGroup (String groupName, String description, String createdBy)
- throws KustvaktException {
+ public boolean createUpdateUserGroup (String groupName, String description,
+ String createdBy) throws KustvaktException {
ParameterChecker.checkNameValue(groupName, "groupName");
ParameterChecker.checkStringValue(createdBy, "createdBy");
@@ -214,24 +214,24 @@
+ "The name has to start with an alphanumerical character.",
groupName);
}
-
+
UserGroup userGroup = null;
boolean groupExists = false;
- try{
- userGroup = userGroupDao.retrieveGroupByName(groupName,false);
+ try {
+ userGroup = userGroupDao.retrieveGroupByName(groupName, false);
groupExists = true;
}
catch (KustvaktException e) {
- if (e.getStatusCode() != StatusCodes.NO_RESOURCE_FOUND){
+ if (e.getStatusCode() != StatusCodes.NO_RESOURCE_FOUND) {
throw e;
}
}
-
- if (!groupExists){
+
+ if (!groupExists) {
try {
userGroupDao.createGroup(groupName, description, createdBy,
UserGroupStatus.ACTIVE);
- userGroup = userGroupDao.retrieveGroupByName(groupName,false);
+ userGroup = userGroupDao.retrieveGroupByName(groupName, false);
}
// handle DB exceptions, e.g. unique constraint
catch (Exception e) {
@@ -257,7 +257,8 @@
public void deleteGroup (String groupName, String username)
throws KustvaktException {
- UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName,false);
+ UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName,
+ false);
if (userGroup.getStatus() == UserGroupStatus.DELETED) {
// EM: should this be "not found" instead?
throw new KustvaktException(StatusCodes.GROUP_DELETED,
@@ -278,7 +279,7 @@
public int createAutoHiddenGroup () throws KustvaktException {
String code = random.createRandomCode();
- String groupName = "auto-"+code;
+ String groupName = "auto-" + code;
int groupId = userGroupDao.createGroup(groupName, "auto-hidden-group",
"system", UserGroupStatus.HIDDEN);
@@ -309,7 +310,8 @@
* @param userGroup
* a user group
* @param createdBy
- * the user (query-access admin/system) adding the user the user-group
+ * the user (query-access admin/system) adding the user
+ * the user-group
* @param status
* the status of the membership
* @throws KustvaktException
@@ -333,8 +335,8 @@
int groupId = userGroup.getId();
ParameterChecker.checkIntegerValue(groupId, "userGroupId");
- GroupMemberStatus existingStatus =
- memberExists(username, groupId, status);
+ GroupMemberStatus existingStatus = memberExists(username, groupId,
+ status);
if (existingStatus != null) {
throw new KustvaktException(StatusCodes.GROUP_MEMBER_EXISTS,
"Username " + username + " with status " + existingStatus
@@ -355,8 +357,8 @@
GroupMemberStatus status) throws KustvaktException {
UserGroupMember existingMember;
try {
- existingMember =
- groupMemberDao.retrieveMemberById(username, groupId);
+ existingMember = groupMemberDao.retrieveMemberById(username,
+ groupId);
}
catch (KustvaktException e) {
return null;
@@ -403,8 +405,8 @@
private boolean isUserGroupAdmin (String username, UserGroup userGroup)
throws KustvaktException {
- List<UserGroupMember> userGroupAdmins =
- groupMemberDao.retrieveMemberByRole(userGroup.getId(),
+ List<UserGroupMember> userGroupAdmins = groupMemberDao
+ .retrieveMemberByRole(userGroup.getId(),
PredefinedRole.USER_GROUP_ADMIN.getId());
for (UserGroupMember admin : userGroupAdmins) {
@@ -432,15 +434,16 @@
ParameterChecker.checkStringValue(username, "userId");
ParameterChecker.checkStringValue(groupName, "groupId");
- UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName, false);
+ UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName,
+ false);
if (userGroup.getStatus() == UserGroupStatus.DELETED) {
throw new KustvaktException(StatusCodes.GROUP_DELETED,
"Group " + userGroup.getName() + " has been deleted.",
userGroup.getName());
}
- UserGroupMember member =
- groupMemberDao.retrieveMemberById(username, userGroup.getId());
+ UserGroupMember member = groupMemberDao.retrieveMemberById(username,
+ userGroup.getId());
GroupMemberStatus status = member.getStatus();
if (status.equals(GroupMemberStatus.DELETED)) {
throw new KustvaktException(StatusCodes.GROUP_MEMBER_DELETED,
@@ -480,8 +483,8 @@
public boolean isMember (String username, UserGroup userGroup)
throws KustvaktException {
- List<UserGroupMember> members =
- groupMemberDao.retrieveMemberByGroupId(userGroup.getId());
+ List<UserGroupMember> members = groupMemberDao
+ .retrieveMemberByGroupId(userGroup.getId());
for (UserGroupMember member : members) {
if (member.getUserId().equals(username)
&& member.getStatus().equals(GroupMemberStatus.ACTIVE)) {
@@ -494,7 +497,8 @@
public void deleteGroupMember (String memberId, String groupName,
String deletedBy) throws KustvaktException {
- UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName, false);
+ UserGroup userGroup = userGroupDao.retrieveGroupByName(groupName,
+ false);
if (userGroup.getStatus() == UserGroupStatus.DELETED) {
throw new KustvaktException(StatusCodes.GROUP_DELETED,
"Group " + userGroup.getName() + " has been deleted.",
@@ -538,8 +542,8 @@
UserGroup group = userGroupDao.retrieveGroupById(groupId);
- UserGroupMember member =
- groupMemberDao.retrieveMemberById(username, groupId);
+ UserGroupMember member = groupMemberDao.retrieveMemberById(username,
+ groupId);
GroupMemberStatus status = member.getStatus();
if (isSoftDelete && status.equals(GroupMemberStatus.DELETED)) {
throw new KustvaktException(StatusCodes.GROUP_MEMBER_DELETED,
@@ -576,9 +580,8 @@
else if (isUserGroupAdmin(username, userGroup)
|| adminDao.isAdmin(username)) {
- UserGroupMember member =
- groupMemberDao.retrieveMemberById(memberUsername,
- userGroup.getId());
+ UserGroupMember member = groupMemberDao
+ .retrieveMemberById(memberUsername, userGroup.getId());
if (!member.getStatus().equals(GroupMemberStatus.ACTIVE)) {
throw new KustvaktException(StatusCodes.GROUP_MEMBER_INACTIVE,
@@ -617,9 +620,8 @@
else if (isUserGroupAdmin(username, userGroup)
|| adminDao.isAdmin(username)) {
- UserGroupMember member =
- groupMemberDao.retrieveMemberById(memberUsername,
- userGroup.getId());
+ UserGroupMember member = groupMemberDao
+ .retrieveMemberById(memberUsername, userGroup.getId());
if (!member.getStatus().equals(GroupMemberStatus.ACTIVE)) {
throw new KustvaktException(StatusCodes.GROUP_MEMBER_INACTIVE,
@@ -654,9 +656,8 @@
if (isUserGroupAdmin(username, userGroup)
|| adminDao.isAdmin(username)) {
- UserGroupMember member =
- groupMemberDao.retrieveMemberById(memberUsername,
- userGroup.getId());
+ UserGroupMember member = groupMemberDao
+ .retrieveMemberById(memberUsername, userGroup.getId());
Set<Role> roles = member.getRoles();
Iterator<Role> i = roles.iterator();
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/UserService.java b/full/src/main/java/de/ids_mannheim/korap/service/UserService.java
index de94d64..59e5e5b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/UserService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/UserService.java
@@ -9,7 +9,7 @@
public class UserService {
final static ObjectMapper mapper = new ObjectMapper();
-
+
public JsonNode retrieveUserInfo (String username) {
return mapper.createObjectNode().put("username", username);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/DataFactory.java b/full/src/main/java/de/ids_mannheim/korap/user/DataFactory.java
index 21aea9a..07212bd 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/DataFactory.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/DataFactory.java
@@ -34,7 +34,6 @@
return factory;
}
-
/**
* if data string null, returns an empty data holding object
*
@@ -43,39 +42,32 @@
*/
public abstract Object convertData (String data);
-
public abstract int size (Object data);
-
public abstract Set<String> keys (Object data);
-
public abstract Collection<Object> values (Object data);
- public abstract Object validate(Object data, Validator validator) throws KustvaktException;
+ public abstract Object validate (Object data, Validator validator)
+ throws KustvaktException;
@Deprecated
public abstract Map<String, Object> fields (Object data);
-
public abstract Object getValue (Object data, String pointer);
-
public abstract boolean addValue (Object data, String field, Object value);
-
public abstract boolean removeValue (Object data, String field);
-
public abstract String toStringValue (Object data) throws KustvaktException;
- public abstract Object filter(Object data, String ... keys);
+ public abstract Object filter (Object data, String ... keys);
public boolean checkDataType (Object data) {
throw new RuntimeException("Wrong data type for factory setting!");
}
-
/**
* updates data1 with values from data2
*
@@ -87,8 +79,6 @@
*/
public abstract Object merge (Object data1, Object data2);
-
-
private static class DefaultFactory extends DataFactory {
@Override
@@ -103,7 +93,6 @@
}
}
-
@Override
public int size (Object data) {
if (checkDataType(data))
@@ -111,7 +100,6 @@
return -1;
}
-
@Override
public Set<String> keys (Object data) {
Set<String> keys = new HashSet<>();
@@ -123,33 +111,33 @@
return keys;
}
-
@Override
public Collection<Object> values (Object data) {
return new HashSet<>();
}
@Override
- public Object validate(Object data, Validator validator) throws KustvaktException {
+ public Object validate (Object data, Validator validator)
+ throws KustvaktException {
if (checkDataType(data) && ((JsonNode) data).isObject()) {
try {
@SuppressWarnings("unchecked")
- Map<String, Object> mdata = JsonUtils.read(toStringValue(data), HashMap.class);
+ Map<String, Object> mdata = JsonUtils
+ .read(toStringValue(data), HashMap.class);
return validator.validateMap(mdata);
- } catch (IOException e) {
+ }
+ catch (IOException e) {
// do nothing
}
}
return JsonUtils.createObjectNode();
}
-
@Override
public Map<String, Object> fields (Object data) {
return new HashMap<>();
}
-
@Override
public Object getValue (Object data, String key) {
if (checkDataType(data)) {
@@ -169,7 +157,6 @@
return null;
}
-
//fixme: test that this works with different types
@Override
public boolean addValue (Object data, String field, Object value) {
@@ -185,13 +172,13 @@
if (value instanceof JsonNode)
node.set(field, (JsonNode) value);
// EM: added
- if (value instanceof Collection<?>){
+ if (value instanceof Collection<?>) {
Collection<?> list = (Collection<?>) value;
ArrayNode arrayNode = JsonUtils.createArrayNode();
- for (Object o : list){
+ for (Object o : list) {
addValue(arrayNode, null, o);
}
- node.set(field,arrayNode);
+ node.set(field, arrayNode);
}
return true;
}
@@ -209,7 +196,6 @@
return false;
}
-
@Override
public boolean removeValue (Object data, String field) {
if (checkDataType(data) && ((JsonNode) data).isObject()) {
@@ -220,7 +206,6 @@
return false;
}
-
@Override
public String toStringValue (Object data) throws KustvaktException {
if (data instanceof JsonNode)
@@ -229,7 +214,7 @@
}
@Override
- public Object filter(Object data, String... keys) {
+ public Object filter (Object data, String ... keys) {
if (checkDataType(data) && ((JsonNode) data).isObject()) {
ObjectNode node = ((JsonNode) data).deepCopy();
return node.retain(keys);
@@ -237,7 +222,6 @@
return JsonUtils.createObjectNode();
}
-
@Override
public boolean checkDataType (Object data) {
if (!(data instanceof JsonNode))
@@ -245,7 +229,6 @@
return true;
}
-
@Override
public Object merge (Object data1, Object data2) {
if (checkDataType(data1) && checkDataType(data2)) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/DemoUser.java b/full/src/main/java/de/ids_mannheim/korap/user/DemoUser.java
index 5a48bcb..06b1310 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/DemoUser.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/DemoUser.java
@@ -14,14 +14,12 @@
private static final long ACCOUNT_CREATED = 1377102171202L;
public static final String PASSPHRASE = "demo";
-
protected DemoUser () {
super(DEMOUSER_NAME, 2);
this.setId(-1);
this.setAccountCreation(ACCOUNT_CREATED);
}
-
protected User clone () {
return new DemoUser();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/GenericUserData.java b/full/src/main/java/de/ids_mannheim/korap/user/GenericUserData.java
index cf254dd..506e262 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/GenericUserData.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/GenericUserData.java
@@ -5,18 +5,15 @@
*/
public class GenericUserData extends Userdata {
-
public GenericUserData () {
super(-1);
}
-
@Override
public String[] requiredFields () {
return new String[0];
}
-
@Override
public String[] defaultFields () {
return new String[0];
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java b/full/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
index 8f51378..7a4ebec 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
@@ -19,25 +19,21 @@
private String URIFragment;
private Long URIExpiration;
-
public KorAPUser (String username) {
super(username, 0);
this.URIFragment = "";
this.URIExpiration = 0L;
}
-
public KorAPUser (Integer id, String username) {
this(username);
this.setId(id);
}
-
public KorAPUser () {
super();
}
-
@Override
protected User clone () {
KorAPUser user = new KorAPUser(this.getUsername());
@@ -46,7 +42,6 @@
return user;
}
-
@Override
public int hashCode () {
int result = super.hashCode();
@@ -59,7 +54,6 @@
return result;
}
-
@Override
public boolean equals (Object o) {
if (this == o)
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/ShibbolethUser.java b/full/src/main/java/de/ids_mannheim/korap/user/ShibbolethUser.java
index 80d01f5..42c2e57 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/ShibbolethUser.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/ShibbolethUser.java
@@ -19,14 +19,12 @@
// EM: common name
private String commonName;
-
protected ShibbolethUser () {
super(1);
}
-
private ShibbolethUser (String eduPersonID, String mail, String cn,
- String affiliation) {
+ String affiliation) {
this(eduPersonID);
this.setUsername(eduPersonID);
this.setMail(mail);
@@ -34,13 +32,11 @@
this.setCommonName(cn);
}
-
public ShibbolethUser (String username) {
super(username, 1);
}
-
@Override
public String toString () {
final StringBuffer sb = new StringBuffer("ShibbolethUser{");
@@ -51,39 +47,32 @@
return sb.toString();
}
-
@Override
protected User clone () {
- return new ShibbolethUser(this.getUsername(), this.getMail(), this.getCommonName(),
- this.getAffiliation());
+ return new ShibbolethUser(this.getUsername(), this.getMail(),
+ this.getCommonName(), this.getAffiliation());
}
-
public String getMail () {
return mail;
}
-
public void setMail (String mail) {
this.mail = mail;
}
-
public String getAffiliation () {
return affiliation;
}
-
public void setAffiliation (String affiliation) {
this.affiliation = affiliation;
}
-
public String getCommonName () {
return commonName;
}
-
public void setCommonName (String commonName) {
this.commonName = commonName;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/User.java b/full/src/main/java/de/ids_mannheim/korap/user/User.java
index 66b6873..5f46910 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/User.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/User.java
@@ -26,7 +26,7 @@
//EM: add
private String email;
//EM: finish
-
+
private Integer id;
// in local its username, in shib it's edupersonPrincipalName
private String username;
@@ -47,58 +47,53 @@
private UserSettingProcessor userSettingProcessor;
-// private boolean isSystemAdmin;
+ // private boolean isSystemAdmin;
// Values for corpusAccess:
- public enum CorpusAccess {
- FREE, // Access to licence free corpora only, without login
+ public enum CorpusAccess {
+ FREE, // Access to licence free corpora only, without login
PUB, // Access to public (= öffentliche Korpora) only, externes Login.
ALL // Access to all corpora, internes Login.
- };
-
+ };
+
@Getter
@Setter
private CorpusAccess corpusAccess = CorpusAccess.FREE;
-
+
// values for location (set using the X-forwarded-for Header):
- public enum Location {
+ public enum Location {
INTERN, // KorAP accessed by internal Client (inside intranet).
EXTERN // KorAP accessed by external Client (outside intranet).
};
-
+
@Getter
@Setter
private Location location = Location.EXTERN;
-
protected User () {
this.fields = new ParamFields();
this.accountCreation = TimeUtils.getNow().getMillis();
this.isAccountLocked = false;
this.username = "";
this.id = -1;
- this.location = Location.EXTERN;
- this.corpusAccess = CorpusAccess.FREE;
+ this.location = Location.EXTERN;
+ this.corpusAccess = CorpusAccess.FREE;
}
-
protected User (int type) {
this();
this.type = type;
}
-
protected User (String username, int type) {
this(type);
this.username = username;
}
-
public void addField (ParamFields.Param param) {
this.fields.add(param);
}
-
public <T extends ParamFields.Param> T getField (Class<T> cl) {
return this.fields.get(cl);
}
@@ -111,7 +106,6 @@
// this.details.setUserID(this.id);
}
-
public Map<String, Object> toMap () {
Map map = new HashMap();
map.put(Attributes.USERNAME, this.username);
@@ -123,7 +117,6 @@
return map;
}
-
public Map toCache () {
Map map = new HashMap();
map.put(Attributes.ID, this.id);
@@ -135,7 +128,6 @@
return map;
}
-
@Override
public boolean equals (Object o) {
if (this == o)
@@ -148,14 +140,12 @@
return true;
}
-// public boolean isAdmin () {
-// return this.getUsername().equals(ADMINISTRATOR_ID);
-// }
-
+ // public boolean isAdmin () {
+ // return this.getUsername().equals(ADMINISTRATOR_ID);
+ // }
protected abstract User clone ();
-
@Override
public String toString () {
final StringBuffer sb = new StringBuffer();
@@ -164,104 +154,98 @@
return sb.toString();
}
- public String locationtoString()
-
+ public String locationtoString ()
+
{
- if( this.location == Location.INTERN)
- return "INTERN";
- else if( this.location == Location.EXTERN )
- return "EXTERN";
- else
- return "???";
+ if (this.location == Location.INTERN)
+ return "INTERN";
+ else if (this.location == Location.EXTERN)
+ return "EXTERN";
+ else
+ return "???";
}
-
- public String accesstoString()
-
+
+ public String accesstoString ()
+
{
- if( this.corpusAccess == CorpusAccess.ALL )
- return "ALL";
- else if( this.corpusAccess == CorpusAccess.PUB )
- return "PUB";
- else if( this.corpusAccess == CorpusAccess.FREE )
- return "FREE";
- else
- return "???";
+ if (this.corpusAccess == CorpusAccess.ALL)
+ return "ALL";
+ else if (this.corpusAccess == CorpusAccess.PUB)
+ return "PUB";
+ else if (this.corpusAccess == CorpusAccess.FREE)
+ return "FREE";
+ else
+ return "???";
}
-
+
public static class UserFactory {
public static KorAPUser getUser (String username) {
return new KorAPUser(username);
}
-
public static KorAPUser getUser (String username, String password) {
KorAPUser user = new KorAPUser(username);
user.setPassword(password);
return user;
}
-// public static KorAPUser getAdmin () {
-// return new KorAPUser(ADMINISTRATOR_ID, ADMINISTRATOR_NAME);
-// }
-
+ // public static KorAPUser getAdmin () {
+ // return new KorAPUser(ADMINISTRATOR_ID, ADMINISTRATOR_NAME);
+ // }
public static DemoUser getDemoUser () {
return new DemoUser();
}
-
public static DemoUser getDemoUser (Integer id) {
DemoUser demo = new DemoUser();
demo.setId(id);
return demo;
}
-
public static boolean isDemo (String username) {
return new DemoUser().getUsername().equalsIgnoreCase(username);
}
-
-// public static ShibUser getShibInstance (String eduPersonID,
-// String mail, String cn) {
-// ShibUser u = new ShibUser(eduPersonID);
-// u.setAffiliation("");
-// u.setMail(mail);
-// u.setUsername(eduPersonID);
-// u.setCn(cn);
-// return u;
-// }
-
+ // public static ShibUser getShibInstance (String eduPersonID,
+ // String mail, String cn) {
+ // ShibUser u = new ShibUser(eduPersonID);
+ // u.setAffiliation("");
+ // u.setMail(mail);
+ // u.setUsername(eduPersonID);
+ // u.setCn(cn);
+ // return u;
+ // }
public static KorAPUser toKorAPUser (Map<String, Object> map) {
- KorAPUser user = UserFactory.getUser((String) map
- .get(Attributes.USERNAME));
+ KorAPUser user = UserFactory
+ .getUser((String) map.get(Attributes.USERNAME));
user.setPassword((String) map.get(Attributes.PASSWORD));
- int id = map.get(Attributes.ID) == null ? -1 : (int) map
- .get(Attributes.ID);
+ int id = map.get(Attributes.ID) == null ? -1
+ : (int) map.get(Attributes.ID);
if (id != -1)
user.setId(id);
long cr = map.get(Attributes.ACCOUNT_CREATION) == null ? -1
: (long) map.get(Attributes.ACCOUNT_CREATION);
if (cr != -1)
- user.setAccountCreation((Long) map
- .get(Attributes.ACCOUNT_CREATION));
+ user.setAccountCreation(
+ (Long) map.get(Attributes.ACCOUNT_CREATION));
return user;
}
-
public static User toUser (Map<String, Object> map) {
KustvaktMap kmap = new KustvaktMap(map);
- int type = map.get(Attributes.TYPE) == null ? 0 : (Integer) kmap
- .get(Attributes.TYPE, Integer.class);
+ int type = map.get(Attributes.TYPE) == null ? 0
+ : (Integer) kmap.get(Attributes.TYPE, Integer.class);
User user;
long created = -1;
int id = kmap.get(Attributes.ID, Integer.class) == null ? -1
: (Integer) kmap.get(Attributes.ID, Integer.class);
if (map.get(Attributes.ACCOUNT_CREATION) != null)
- created = TimeUtils.getTime(kmap.get(Attributes.ACCOUNT_CREATION))
+ created = TimeUtils
+ .getTime(kmap.get(Attributes.ACCOUNT_CREATION))
.getMillis();
switch (type) {
case 0:
@@ -269,9 +253,10 @@
if (id != -1)
user.setId((Integer) kmap.get(Attributes.ID,
Integer.class));
- user.setAccountLocked(map.get(Attributes.ACCOUNTLOCK) == null ? false
- : (Boolean) kmap.get(Attributes.ACCOUNTLOCK,
- Boolean.class));
+ user.setAccountLocked(
+ map.get(Attributes.ACCOUNTLOCK) == null ? false
+ : (Boolean) kmap.get(Attributes.ACCOUNTLOCK,
+ Boolean.class));
user.setAccountCreation(created);
break;
default:
@@ -281,15 +266,15 @@
return user;
}
-
public static KorAPUser toUser (String value) throws KustvaktException {
JsonNode node = JsonUtils.readTree(value);
- KorAPUser user = UserFactory.getUser(node.path(Attributes.USERNAME)
- .asText());
- user.setAccountLocked(node.path(Attributes.ACCOUNTLOCK).asBoolean());
+ KorAPUser user = UserFactory
+ .getUser(node.path(Attributes.USERNAME).asText());
+ user.setAccountLocked(
+ node.path(Attributes.ACCOUNTLOCK).asBoolean());
user.setAccountLink(node.path(Attributes.ACCOUNTLINK).asText());
- user.setAccountCreation(node.path(Attributes.ACCOUNT_CREATION)
- .asLong());
+ user.setAccountCreation(
+ node.path(Attributes.ACCOUNT_CREATION).asLong());
user.setPassword(node.path(Attributes.PASSWORD).asText());
return user;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/UserDetails.java b/full/src/main/java/de/ids_mannheim/korap/user/UserDetails.java
index 9901592..9559813 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/UserDetails.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/UserDetails.java
@@ -9,12 +9,11 @@
*/
public class UserDetails extends Userdata {
-
- public UserDetails() {
+ public UserDetails () {
}
- public UserDetails(Integer userid) {
+ public UserDetails (Integer userid) {
super(userid);
}
@@ -25,7 +24,6 @@
Attributes.LASTNAME, Attributes.FIRSTNAME };
}
-
@Override
public String[] defaultFields () {
return new String[] { Attributes.EMAIL, Attributes.ADDRESS,
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/UserQuery.java b/full/src/main/java/de/ids_mannheim/korap/user/UserQuery.java
index ad48a2d..10037b2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/UserQuery.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/UserQuery.java
@@ -22,7 +22,6 @@
private String description;
private Integer creator;
-
public UserQuery (Integer id, int creator) {
setId(id);
setCreator(creator);
@@ -32,14 +31,12 @@
setQueryLanguage("");
}
-
public UserQuery (String ql, String query, String description) {
setDescription(description);
setQuery(query);
setQueryLanguage(ql);
}
-
public UserQuery () {
setDescription("");
setQuery("");
@@ -47,14 +44,12 @@
setName("");
}
-
public void setQuery (String query) {
this.query = query;
- setName("Query: "
- + query.substring(0, query.length() > 20 ? 20 : query.length()));
+ setName("Query: " + query.substring(0,
+ query.length() > 20 ? 20 : query.length()));
}
-
// todo: use example queries or store in database
public static List<UserQuery> demoUserQueries () {
@@ -62,7 +57,8 @@
UserQuery q1 = new UserQuery();
q1.setQueryLanguage("COSMAS2");
q1.setQuery("$wegen #IN(L) <s>");
- q1.setDescription("Findet 'wegen' an Satzanfängen. Berücksichtigt auch Groß- und Kleinschreibung");
+ q1.setDescription(
+ "Findet 'wegen' an Satzanfängen. Berücksichtigt auch Groß- und Kleinschreibung");
//todo: change query
UserQuery q2 = new UserQuery();
@@ -90,7 +86,6 @@
return queries;
}
-
//id is irrevelant, since data was coming
// from frontend and thus this object does not contain a id that could be compared!
// same with the userAccount. Not set yet!
@@ -108,7 +103,6 @@
return true;
}
-
@Override
public int hashCode () {
int result = getId() != null ? getId().hashCode() : 0;
@@ -118,7 +112,6 @@
return result;
}
-
@Override
public String toString () {
final StringBuffer sb = new StringBuffer("UserQuery{");
@@ -131,7 +124,6 @@
return sb.toString();
}
-
public Map toMap () {
Map map = new HashMap();
map.put("name", this.name);
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java b/full/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
index 57b5e4b..3fcd976 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
@@ -8,17 +8,17 @@
*/
public class UserSettingProcessor extends Userdata {
- public UserSettingProcessor() {
+ public UserSettingProcessor () {
}
@Deprecated
- public UserSettingProcessor(Integer userid) {
+ public UserSettingProcessor (Integer userid) {
super(userid);
}
// EM: added
- public UserSettingProcessor(String data) {
+ public UserSettingProcessor (String data) {
super(data);
}
@@ -27,7 +27,6 @@
return new String[] {};
}
-
@Override
public String[] defaultFields () {
return new String[] { Attributes.DEFAULT_FOUNDRY_RELATION,
diff --git a/full/src/main/java/de/ids_mannheim/korap/user/Userdata.java b/full/src/main/java/de/ids_mannheim/korap/user/Userdata.java
index e735776..f607112 100644
--- a/full/src/main/java/de/ids_mannheim/korap/user/Userdata.java
+++ b/full/src/main/java/de/ids_mannheim/korap/user/Userdata.java
@@ -17,7 +17,7 @@
public abstract class Userdata {
public DataFactory dataFactory = DataFactory.getFactory();
-
+
@Deprecated
@Getter
@Setter
@@ -28,14 +28,14 @@
@Getter
@Setter
private Integer userId;
-
+
public Userdata () {
this(-1);
}
// EM: replace with username
@Deprecated
- public Userdata(Integer userid) {
+ public Userdata (Integer userid) {
this.userId = userid;
this.id = -1;
this.data = dataFactory.convertData(null);
@@ -49,16 +49,14 @@
return dataFactory.size(this.data);
}
-
public Object get (String key) {
return dataFactory.getValue(this.data, key);
}
- public Object filter(String ... keys) {
+ public Object filter (String ... keys) {
return dataFactory.filter(this.data, keys);
}
-
/**
*
* @return
@@ -67,7 +65,6 @@
return findMissingFields().length == 0;
}
-
public String[] findMissingFields () {
Set<String> missing = new HashSet<>();
Set<String> keys = dataFactory.keys(this.data);
@@ -78,7 +75,6 @@
return missing.toArray(new String[0]);
}
-
public void checkRequired () throws KustvaktException {
String[] fields = findMissingFields();
if (findMissingFields().length != 0) {
@@ -88,36 +84,30 @@
}
}
-
//fixme: if data array, return empty?!
public Set<String> keys () {
return dataFactory.keys(this.data);
}
-
public Collection<Object> values () {
return dataFactory.values(this.data);
}
-
public void setData (String data) {
this.data = dataFactory.convertData(data);
}
-
public void update (Userdata other) {
if (other != null && this.getClass().equals(other.getClass()))
this.data = dataFactory.merge(this.data, other.data);
}
-
public String serialize () throws KustvaktException {
// to have consistency with required fields --> updates/deletion may cause required fields to be missing.
this.checkRequired();
return dataFactory.toStringValue(this.data);
}
-
public void setField (String key, Object value) {
dataFactory.addValue(this.data, key, value);
}
@@ -129,16 +119,14 @@
dataFactory.validate(this.data, validator);
}
-
public void read (Map<String, Object> map, boolean defaults_only)
throws KustvaktException {
this.readQuietly(map, defaults_only);
this.checkRequired();
}
-
public void readQuietly (Map<String, Object> map, boolean defaults_only) {
- if (map != null){
+ if (map != null) {
if (defaults_only) {
for (String k : defaultFields()) {
Object o = map.get(k);
@@ -158,9 +146,8 @@
public boolean removeField (String field) {
return dataFactory.removeValue(this.data, field);
}
-
- public abstract String[] requiredFields ();
+ public abstract String[] requiredFields ();
public abstract String[] defaultFields ();
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/BooleanUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/BooleanUtils.java
index 8dbeb4f..a682dd3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/BooleanUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/BooleanUtils.java
@@ -8,7 +8,6 @@
public static String dbname;
-
public static Object getBoolean (Object val) {
if (val == null)
val = false;
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/CollectionTypes.java b/full/src/main/java/de/ids_mannheim/korap/utils/CollectionTypes.java
index 6cb0dcd..b4572ac 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/CollectionTypes.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/CollectionTypes.java
@@ -15,12 +15,10 @@
private ObjectMapper mapper;
-
public CollectionTypes () {
this.mapper = new ObjectMapper();
}
-
public Map createGroup (String relation, String field, List terms) {
if (relation == null)
return null;
@@ -34,7 +32,6 @@
return kgroup;
}
-
public Map createTerm (String field, String subtype, String value,
String type) {
Map term = new LinkedHashMap<>();
@@ -49,17 +46,14 @@
return term;
}
-
public Map createTerm (String field, String value, String type) {
return createTerm(field, null, value, type);
}
-
public Map createTerm (String field, String value) {
return createTerm(field, value, null);
}
-
public Map createResourceFilter (String resource, Map value) {
Map meta = new LinkedHashMap();
meta.put("@type", "korap:meta-filter");
@@ -68,13 +62,11 @@
return meta;
}
-
public Map createResourceFilter (String resource, String value)
throws IOException {
return createResourceFilter(resource, mapify(value));
}
-
public Map createResourceExtend (String resource, Map value) {
Map meta = new LinkedHashMap();
meta.put("@type", "korap:meta-extend");
@@ -83,7 +75,6 @@
return meta;
}
-
public Map createMetaFilter (Map value) {
Map meta = new LinkedHashMap();
meta.put("@type", "korap:meta-filter");
@@ -91,7 +82,6 @@
return meta;
}
-
public Map createMetaExtend (Map value) {
Map meta = new LinkedHashMap();
meta.put("@type", "korap:meta-extend");
@@ -99,7 +89,6 @@
return meta;
}
-
public Map mapify (String s) throws IOException {
return mapper.readValue(s, Map.class);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/ConcurrentMultiMap.java b/full/src/main/java/de/ids_mannheim/korap/utils/ConcurrentMultiMap.java
index ea02e44..12fc139 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/ConcurrentMultiMap.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/ConcurrentMultiMap.java
@@ -11,7 +11,6 @@
import java.util.Collection;
import java.util.Set;
-
/**
* A general purpose Multimap implementation for delayed processing and concurrent insertion/deletes.
* This code is based on an implementation by Guido Medina!
@@ -32,17 +31,14 @@
private final LockMap<K> locks;
private final ConcurrentMap<K, List<V>> cache;
-
public ConcurrentMultiMap () {
this(16, 64);
}
-
public ConcurrentMultiMap (final int concurrencyLevel) {
this(concurrencyLevel, 64);
}
-
public ConcurrentMultiMap (final int concurrencyLevel,
final int initialCapacity) {
this.initialCapacity = initialCapacity;
@@ -51,7 +47,6 @@
locks = new LockMap<K>(concurrencyLevel, initialCapacity);
}
-
public void put (final K key, final V value) {
synchronized (locks.getLock(key)) {
List<V> set = cache.get(key);
@@ -63,7 +58,6 @@
}
}
-
public void putAll (final K key, final Collection<V> values) {
synchronized (locks.getLock(key)) {
List<V> set = cache.get(key);
@@ -75,14 +69,12 @@
}
}
-
public List<V> remove (final K key) {
synchronized (locks.getLock(key)) {
return cache.remove(key);
}
}
-
public void remove (final K key, final V value) {
List<V> values = cache.get(key);
synchronized (locks.getLock(key)) {
@@ -90,47 +82,38 @@
}
}
-
public Set<K> getKeySet () {
return cache.keySet();
}
-
public int size () {
return cache.size();
}
-
public boolean containsKey (K key) {
return cache.containsKey(key);
}
-
public List<V> get (K key) {
return cache.get(key);
}
-
public class LockMap<K extends Comparable> {
private final ConcurrentMap<K, Object> locks;
-
public LockMap () {
this(16, 64);
}
-
public LockMap (final int concurrencyLevel) {
this(concurrencyLevel, 64);
}
-
public LockMap (final int concurrencyLevel, final int initialCapacity) {
locks = new MapMaker().concurrencyLevel(concurrencyLevel)
.initialCapacity(initialCapacity).weakValues().makeMap();
}
-
public Object getLock (final K key) {
final Object object = new Object();
Object lock = locks.putIfAbsent(key, object);
@@ -139,10 +122,8 @@
}
-
public String toString () {
return cache.toString();
}
-
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/IPNetMask.java b/full/src/main/java/de/ids_mannheim/korap/utils/IPNetMask.java
index c2511a7..133c330 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/IPNetMask.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/IPNetMask.java
@@ -23,7 +23,6 @@
private static final int default_mask = 16;
-
private IPNetMask (Inet4Address i4addr, byte mask) {
this.i4addr = i4addr;
this.maskCtr = mask;
@@ -32,7 +31,6 @@
this.maskInt = ~((1 << (32 - maskCtr)) - 1);
}
-
/**
* IPNetMask factory method.
*
@@ -63,7 +61,6 @@
maskCtr);
}
-
/**
* Test given IPv4 address against this IPNetMask object.
*
@@ -76,7 +73,6 @@
return ((addrInt & maskInt) == (testAddrInt & maskInt));
}
-
/**
* Convenience method that converts String host to IPv4 address.
*
@@ -91,7 +87,6 @@
return matches((Inet4Address) InetAddress.getByName(addr));
}
-
/**
* Converts IPv4 address to integer representation.
*/
@@ -101,13 +96,11 @@
| (ba[3] & 0xFF);
}
-
@Override
public String toString () {
return i4addr.getHostAddress() + "/" + maskCtr;
}
-
@Override
public boolean equals (Object obj) {
if (obj == null)
@@ -118,7 +111,6 @@
return (this.addrInt == that.addrInt && this.maskInt == that.maskInt);
}
-
@Override
public int hashCode () {
return this.maskInt + this.addrInt;
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/JerseyUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/JerseyUtils.java
index c60dfa0..08f73d1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/JerseyUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/JerseyUtils.java
@@ -15,11 +15,14 @@
* This method will ensure that the request entity is buffered
* such that it may be consumed by the application.
*
- * @return the form parameters, if there is a request entity and the
- * content type is "application/x-www-form-urlencoded", otherwise an
- * instance containing no parameters will be returned.
+ * @return the form parameters, if there is a request entity and
+ * the
+ * content type is "application/x-www-form-urlencoded",
+ * otherwise an
+ * instance containing no parameters will be returned.
*/
- public static Form getFormParameters (ContainerRequestContext requestContext) {
+ public static Form getFormParameters (
+ ContainerRequestContext requestContext) {
if (requestContext instanceof ContainerRequest) {
return getFormParameters((ContainerRequest) requestContext);
}
@@ -27,11 +30,13 @@
}
private static Form getFormParameters (ContainerRequest request) {
- if (MediaTypes.typeEqual(MediaType.APPLICATION_FORM_URLENCODED_TYPE, request.getMediaType())) {
+ if (MediaTypes.typeEqual(MediaType.APPLICATION_FORM_URLENCODED_TYPE,
+ request.getMediaType())) {
request.bufferEntity();
Form form = request.readEntity(Form.class);
return (form == null ? new Form() : form);
- } else {
+ }
+ else {
return new Form();
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/JsonUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/JsonUtils.java
index 792a6bb..ab67779 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/JsonUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/JsonUtils.java
@@ -26,7 +26,6 @@
private JsonUtils () {}
-
public static String toJSON (Object values) throws KustvaktException {
try {
return mapper.writeValueAsString(values);
@@ -37,7 +36,6 @@
}
}
-
public static JsonNode readTree (String json) throws KustvaktException {
try {
return mapper.readTree(json);
@@ -47,17 +45,15 @@
"Failed deserializing json object: " + json, json, e);
}
}
-
+
public static ObjectNode createObjectNode () {
return mapper.createObjectNode();
}
-
public static ArrayNode createArrayNode () {
return mapper.createArrayNode();
}
-
public static JsonNode valueToTree (Object value) {
return mapper.valueToTree(value);
}
@@ -75,20 +71,18 @@
return mapper.readValue(is, cl);
}
-
public static <T> T readFile (String path, Class<T> clazz)
throws IOException {
return mapper.readValue(new File(path), clazz);
}
-
public static void writeFile (String path, Object content)
throws IOException {
mapper.writeValue(new File(path), content);
}
-
- public static <T> T convertToClass (String json, Class<T> cl) throws KustvaktException {
+ public static <T> T convertToClass (String json, Class<T> cl)
+ throws KustvaktException {
T t = null;
try {
t = mapper.readValue(json, cl);
@@ -100,7 +94,6 @@
return t;
}
-
public static List<Map<String, Object>> convertToList (String json)
throws JsonProcessingException, KustvaktException {
List d = new ArrayList();
@@ -108,8 +101,8 @@
if (node.isArray()) {
Iterator<JsonNode> nodes = node.iterator();
while (nodes.hasNext()) {
- Map<String, Object> map =
- mapper.treeToValue(nodes.next(), Map.class);
+ Map<String, Object> map = mapper.treeToValue(nodes.next(),
+ Map.class);
d.add(map);
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/KoralCollectionQueryBuilder.java b/full/src/main/java/de/ids_mannheim/korap/utils/KoralCollectionQueryBuilder.java
index a6260cb..7dd99ad 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/KoralCollectionQueryBuilder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/KoralCollectionQueryBuilder.java
@@ -35,7 +35,6 @@
this(false);
}
-
public KoralCollectionQueryBuilder (boolean verbose) {
this.verbose = verbose;
this.builder = new StringBuilder();
@@ -43,7 +42,6 @@
this.mergeOperator = null;
}
-
/**
* raw method for field - value pair adding. Supports all
* operators (leq, geq, contains, etc.)
@@ -64,7 +62,6 @@
return this;
}
-
/**
* element can be a more complex sub query like
* (textClass=freizeit & Attributes.CORPUS_SIGLE=WPD)
@@ -82,31 +79,30 @@
return this;
}
-
-
public KoralCollectionQueryBuilder and () {
- if (this.builder.length() != 0) this.builder.append(" & ");
+ if (this.builder.length() != 0)
+ this.builder.append(" & ");
if (this.base != null && this.mergeOperator == null)
this.mergeOperator = "AND";
return this;
}
-
public KoralCollectionQueryBuilder or () {
- if (this.builder.length() != 0) this.builder.append(" | ");
+ if (this.builder.length() != 0)
+ this.builder.append(" | ");
if (this.base != null && this.mergeOperator == null)
this.mergeOperator = "OR";
return this;
}
-
public JsonNode rebaseCollection () throws KustvaktException {
- if (this.builder.length() == 0 && this.base == null) return null;
+ if (this.builder.length() == 0 && this.base == null)
+ return null;
JsonNode request = null;
if (this.builder.length() != 0) {
- CollectionQueryProcessor tree =
- new CollectionQueryProcessor(this.verbose);
+ CollectionQueryProcessor tree = new CollectionQueryProcessor(
+ this.verbose);
tree.process(this.builder.toString());
if (tree.getErrors().size() > 0) {
// legacy support
@@ -116,15 +112,16 @@
int code = (int) e.get(0);
notif.addError(code, (String[]) e.get(1));
String notificationStr = notif.toJsonString();
- throw new KustvaktException(StatusCodes.SERIALIZATION_FAILED,
+ throw new KustvaktException(
+ StatusCodes.SERIALIZATION_FAILED,
notificationStr, true);
}
- else{
+ else {
break;
}
}
// -- end of legacy support
-
+
Map<String, Object> map = new HashMap<>();
map.put("errors", tree.getErrors());
String errors = JsonUtils.toJSON(map);
@@ -145,7 +142,6 @@
return request;
}
-
public JsonNode mergeWith (JsonNode node) {
if (this.base != null) {
if (node != null) {
@@ -158,10 +154,10 @@
else if (result.isMissingNode() && tobase.isMissingNode())
return base;
else {
- result = JsonBuilder.buildDocGroup(
- this.mergeOperator != null
- ? this.mergeOperator.toLowerCase() : "and",
- result, tobase);
+ result = JsonBuilder
+ .buildDocGroup(this.mergeOperator != null
+ ? this.mergeOperator.toLowerCase()
+ : "and", result, tobase);
}
((ObjectNode) base).put("collection", result);
return base;
@@ -171,38 +167,34 @@
throw new RuntimeException("no query found to merge with!");
}
-
/**
* sets base query. All consequent queries are added to the first
* koral:docGroup within the collection base query
* If no group in base query, consequent queries are skipped.
*
* @param query
- * @throws KustvaktException
+ * @throws KustvaktException
*/
- public KoralCollectionQueryBuilder setBaseQuery (String query) throws KustvaktException {
+ public KoralCollectionQueryBuilder setBaseQuery (String query)
+ throws KustvaktException {
this.base = JsonUtils.readTree(query);
return this;
}
-
public KoralCollectionQueryBuilder setBaseQuery (JsonNode query) {
this.base = query;
return this;
}
-
public String toJSON () throws KustvaktException {
return JsonUtils.toJSON(rebaseCollection());
}
-
@Override
public String toString () {
return this.builder.toString();
}
-
private static class JsonBuilder {
public static ObjectNode buildDoc (String key, String value) {
@@ -215,7 +207,6 @@
return node;
}
-
public static ObjectNode buildDocGroup (String op,
JsonNode ... groups) {
ObjectNode node = JsonUtils.createObjectNode();
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java
index beafb32..dae6908 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/NamingUtils.java
@@ -10,10 +10,6 @@
*/
public class NamingUtils {
-
-
private NamingUtils () {}
-
-
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/ParameterChecker.java b/full/src/main/java/de/ids_mannheim/korap/utils/ParameterChecker.java
index 2673c80..9b98faa 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/ParameterChecker.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/ParameterChecker.java
@@ -22,7 +22,7 @@
name + " is null", name);
}
else if (collection.isEmpty()) {
- throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
+ throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
name + " is empty", name);
}
}
@@ -30,11 +30,11 @@
public static void checkStringValue (String string, String name)
throws KustvaktException {
if (string == null) {
- throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
+ throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
name + " is null", name);
}
else if (string.isEmpty()) {
- throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
+ throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
name + " is empty", name);
}
}
@@ -42,11 +42,11 @@
public static void checkIntegerValue (int integer, String name)
throws KustvaktException {
if (integer == 0) {
- throw new KustvaktException(StatusCodes.MISSING_PARAMETER,
+ throw new KustvaktException(StatusCodes.MISSING_PARAMETER,
name + " is missing", name);
}
}
-
+
public static void checkNameValue (String value, String name)
throws KustvaktException {
if (value == null) {
@@ -55,7 +55,7 @@
}
else if (value.length() < 3) {
throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
- name+" must contain at least 3 characters", name);
+ name + " must contain at least 3 characters", name);
}
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/PrefixTreeMap.java b/full/src/main/java/de/ids_mannheim/korap/utils/PrefixTreeMap.java
index 20e94d5..7cfcb17 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/PrefixTreeMap.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/PrefixTreeMap.java
@@ -9,7 +9,6 @@
*/
public class PrefixTreeMap<V> extends TreeMap<String, V> {
-
public SortedMap<String, V> getPrefixSubMap (String prefix) {
if (prefix != null && prefix.length() > 0) {
SortedMap d = this.subMap(prefix, getEnd(prefix));
@@ -20,14 +19,12 @@
return null;
}
-
private String getEnd (String prefix) {
char nextLetter = (char) (prefix.charAt(prefix.length() - 1) + 1);
return prefix.substring(0, prefix.length() - 1) + nextLetter;
}
-
public V getFirstValue (String prefix) {
if (prefix.length() > 0) {
String first = this.subMap(prefix, getEnd(prefix)).firstKey();
@@ -36,7 +33,6 @@
return null;
}
-
public V getLastValue (String prefix) {
if (prefix.length() > 0) {
String last = this.subMap(prefix, getEnd(prefix)).lastKey();
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/PropertyReader.java b/full/src/main/java/de/ids_mannheim/korap/utils/PropertyReader.java
index 0b16cc0..b377cd1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/PropertyReader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/PropertyReader.java
@@ -31,7 +31,6 @@
return res;
}
-
public abstract void load ();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java b/full/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java
index fa83ebc..7d6f8a3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/ServiceInfo.java
@@ -31,21 +31,19 @@
@Getter
private String cache_store;
-
@Getter
private String krillVersion;
@Getter
private String koralVersion;
-
+
private ServiceInfo () {
load();
}
-
private void load () {
Properties props = new Properties();
try {
-
+
InputStream stream = getStream();
props.load(stream);
stream.close();
@@ -53,13 +51,14 @@
this.name = (String) props.get("kustvakt.name");
this.config = (String) props.get("kustvakt.properties");
this.logger = (String) props.get("kustvakt.logging");
- this.cacheable = Boolean.valueOf((String) props.get("kustvakt.cache"));
+ this.cacheable = Boolean
+ .valueOf((String) props.get("kustvakt.cache"));
this.cache_store = (String) props.get("kustvakt.cache_store");
-
- this.krillVersion=(String) props.get("krill.version");
-
+
+ this.krillVersion = (String) props.get("krill.version");
+
QuerySerializer s = new QuerySerializer();
- this.koralVersion = s.getVersion() ;
+ this.koralVersion = s.getVersion();
}
catch (IOException e) {
this.version = UNKNOWN;
@@ -68,23 +67,21 @@
this.config = UNKNOWN;
this.cacheable = false;
this.cache_store = UNKNOWN;
-
+
this.koralVersion = UNKNOWN;
this.krillVersion = UNKNOWN;
}
}
-
private static InputStream getStream () throws IOException {
String path = "service.properties";
InputStream stream = ConfigLoader.loadConfigStream(path);
if (stream == null)
- throw new IOException("stream for resource " + path
- + " could not be found...");
+ throw new IOException(
+ "stream for resource " + path + " could not be found...");
return stream;
}
-
public static ServiceInfo getInfo () {
return info;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/SqlBuilder.java b/full/src/main/java/de/ids_mannheim/korap/utils/SqlBuilder.java
index fa1314b..5b31f51 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/SqlBuilder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/SqlBuilder.java
@@ -11,13 +11,11 @@
private String[] fields;
private String where;
-
public SqlBuilder (String table) {
this.buffer = new StringBuffer();
this.table = table;
}
-
public SqlBuilder select (String ... fields) {
this.buffer.append("SELECT ");
if (fields.length > 0) {
@@ -33,27 +31,23 @@
return this;
}
-
public SqlBuilder update (String ... fields) {
this.buffer.append("UPDATE ").append(table);
this.fields = fields;
return this;
}
-
public SqlBuilder insert (String ... fields) {
this.buffer.append("INSERT INTO ").append(table);
this.fields = fields;
return this;
}
-
public SqlBuilder delete () {
this.buffer.append("DELETE FROM ").append(table);
return this;
}
-
public SqlBuilder params (String ... values) {
if (values.length != fields.length)
return this;
@@ -84,13 +78,11 @@
return this;
}
-
public SqlBuilder where (String where) {
this.where = where;
return this;
}
-
@Override
public String toString () {
StringBuffer b = new StringBuffer(this.buffer);
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/StringUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/StringUtils.java
index 99c9578..dd6259a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/StringUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/StringUtils.java
@@ -9,13 +9,11 @@
import java.util.*;
public class StringUtils {
- private final static Logger jlog = LogManager
- .getLogger(StringUtils.class);
+ private final static Logger jlog = LogManager.getLogger(StringUtils.class);
private static final String SEP = ";";
private static final String SLASH = "/";
-
public static Collection<UUID> stringToUUIDList (String s) {
String[] array = s.split(SEP);
List<UUID> list = new LinkedList<>();
@@ -25,7 +23,6 @@
return list;
}
-
public static List<String> toList (String values) {
List<String> list = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(values, SEP);
@@ -34,7 +31,6 @@
return list;
}
-
public static Set<String> toSet (String values, String sep) {
Set<String> set = new HashSet<>();
if (values != null && !values.isEmpty()) {
@@ -45,17 +41,14 @@
return set;
}
-
public static Set<String> toSet (String values) {
return toSet(values, SEP);
}
-
public static String toString (Collection<String> values) {
return StringUtils.toString(values, SEP);
}
-
public static String toString (Collection<String> values, String sep) {
StringBuffer b = new StringBuffer();
for (String s : values)
@@ -66,7 +59,6 @@
return b.toString();
}
-
public static String orderedToString (Collection<String> hash) {
Set<String> orderedSet = new TreeSet<>();
orderedSet.addAll(hash);
@@ -84,7 +76,6 @@
}
}
-
public static String UUIDsetToString (Collection<UUID> hash) {
Set<UUID> orderedSet = new TreeSet<>();
orderedSet.addAll(hash);
@@ -102,7 +93,6 @@
}
}
-
public static String buildSQLRegex (String path) {
StringBuilder b = new StringBuilder();
String[] match = path.split("/");
@@ -112,7 +102,6 @@
return b.toString();
}
-
// todo: move to parameter utils
public static boolean isInteger (String value) {
try {
@@ -125,29 +114,24 @@
}
}
-
public static String normalize (String value) {
return value.trim().toLowerCase();
}
-
public static String normalizeHTML (String value) {
return StringEscapeUtils.escapeHtml(value);
}
-
public static String decodeHTML (String value) {
return StringEscapeUtils.unescapeHtml(value);
}
-
public static String getDocSigle (String textSigle) {
if (textSigle != null)
return textSigle.split("\\.")[0];
return null;
}
-
public static String getCorpusSigle (String textSigle) {
//WPD_SSS.07367
if (textSigle != null)
@@ -155,7 +139,6 @@
return null;
}
-
public static Collection<String> joinStringSet (Collection<String> source,
String other) {
Set<String> set = new HashSet<>(source);
@@ -163,7 +146,6 @@
return set;
}
-
public static Collection<UUID> joinUUIDSet (Collection<UUID> source,
UUID other) {
Set<UUID> set = new HashSet<>(source);
@@ -171,7 +153,6 @@
return set;
}
-
public static String joinResources (String first, String second) {
String res;
if (first != null && !first.isEmpty())
@@ -181,7 +162,6 @@
return res.replaceAll("\\s", "");
}
-
public static String[] splitAnnotations (String joined) {
String[] spl = joined.split(SLASH);
if (spl.length == 2)
@@ -190,7 +170,6 @@
return null;
}
-
public static String stripTokenType (String token) {
int idx = token.lastIndexOf(" ");
if (idx == -1)
@@ -198,7 +177,6 @@
return token.substring(idx).replaceAll("\\s", "");
}
-
public static String getTokenType (String token) {
if (token.contains(" "))
return token.substring(0, token.lastIndexOf(" "))
@@ -207,7 +185,7 @@
return null;
}
- public static String toSHAHash(String input) {
+ public static String toSHAHash (String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(input.getBytes());
@@ -215,12 +193,13 @@
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
- sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
+ sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16)
+ .substring(1));
return sb.toString();
- } catch (NoSuchAlgorithmException e) {
+ }
+ catch (NoSuchAlgorithmException e) {
return null;
}
}
-
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java b/full/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
index d6f2daf..0a5f5e3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
@@ -31,11 +31,11 @@
private static DecimalFormat df = new DecimalFormat("#.#############");
private static DateTimeFormatter dtf = DateTimeFormat
.forPattern("dd/MM/yyyy");
- private static final DateTimeZone dtz = DateTimeZone.forID(Attributes.DEFAULT_TIME_ZONE);
+ private static final DateTimeZone dtz = DateTimeZone
+ .forID(Attributes.DEFAULT_TIME_ZONE);
private static final boolean DEBUG = false;
private static Logger jlog = LogManager.getLogger(TimeUtils.class);
-
public static int convertTimeToSeconds (String expirationVal) {
expirationVal = expirationVal.trim();
int finIndex = expirationVal.length() - 1;
@@ -55,8 +55,9 @@
case 'S':
return returnSec;
default:
- if (DEBUG){
- jlog.debug("no time unit specified. Trying to read from default (minutes)");
+ if (DEBUG) {
+ jlog.debug(
+ "no time unit specified. Trying to read from default (minutes)");
}
return Integer.valueOf(expirationVal) * 60;
}
@@ -67,53 +68,50 @@
return DateTime.now(dtz);
}
- public static DateTime getTime(String time) {
+ public static DateTime getTime (String time) {
return DateTime.parse(time).withZone(dtz);
}
- public static DateTime getTime(long time) {
+ public static DateTime getTime (long time) {
return new DateTime(time).withZone(dtz);
}
//returns difference in milliseconds
public static long calcDiff (DateTime now, DateTime future) {
- long diff = (future.withZone(dtz).getMillis() - now.withZone(dtz)
- .getMillis());
+ long diff = (future.withZone(dtz).getMillis()
+ - now.withZone(dtz).getMillis());
return diff;
}
-
- public static boolean isExpired(long time) {
+ public static boolean isExpired (long time) {
return getNow().isAfter(time);
}
-
// returns difference in seconds in floating number
public static float floating (DateTime past, DateTime now) {
- long diff = (now.withZone(dtz).getMillis() - past.withZone(dtz)
- .getMillis());
+ long diff = (now.withZone(dtz).getMillis()
+ - past.withZone(dtz).getMillis());
double fin = diff / 1000.0;
BigDecimal bd = new BigDecimal(fin).setScale(8, RoundingMode.HALF_EVEN);
return bd.floatValue();
}
-
public static DateTime fromCosmas (String date) {
int idx = date.length();
try {
- Integer sec = Integer.valueOf(date.substring((idx = idx - 2),
- date.length()).trim());
- Integer min = Integer.valueOf(date.substring((idx = idx - 2),
- idx + 2).trim());
- Integer hours = Integer.valueOf(date.substring((idx = idx - 2),
- idx + 2).trim());
- Integer day = Integer.valueOf(date.substring((idx = idx - 2),
- idx + 2).trim());
- Integer month = Integer.valueOf(date.substring((idx = idx - 2),
- idx + 2).trim());
- Integer year = Integer.valueOf(date.substring((idx = idx - 4),
- idx + 4).trim());
+ Integer sec = Integer.valueOf(
+ date.substring((idx = idx - 2), date.length()).trim());
+ Integer min = Integer
+ .valueOf(date.substring((idx = idx - 2), idx + 2).trim());
+ Integer hours = Integer
+ .valueOf(date.substring((idx = idx - 2), idx + 2).trim());
+ Integer day = Integer
+ .valueOf(date.substring((idx = idx - 2), idx + 2).trim());
+ Integer month = Integer
+ .valueOf(date.substring((idx = idx - 2), idx + 2).trim());
+ Integer year = Integer
+ .valueOf(date.substring((idx = idx - 4), idx + 4).trim());
return new DateTime(year, month, day, hours, min, sec);
}
catch (NumberFormatException e) {
@@ -121,12 +119,10 @@
}
}
-
public static String formatDiff (DateTime now, DateTime after) {
return df.format(calcDiff(now, after));
}
-
/**
* converts time to the ISO8601 standard.
*
@@ -138,13 +134,11 @@
return fmt.withZone(dtz).print(time);
}
-
public static String format (long time) {
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
return fmt.withZone(dtz).print(time);
}
-
/**
* calculate expiration time
*
@@ -157,12 +151,10 @@
return new DateTime(creation).withZone(dtz).plusSeconds(plus);
}
-
public static DateTime getExpiration (long now, int exp) {
return new DateTime(now).withZone(dtz).plusSeconds(exp);
}
-
/**
* @param plus
* @return
@@ -171,17 +163,14 @@
return getNow().withZone(dtz).plusSeconds(plus);
}
-
public static DateTime plusHours (int hours) {
return getNow().withZone(dtz).plusHours(hours);
}
-
public static DateTime plusMinutes (int minutes) {
return getNow().withZone(dtz).plusMinutes(minutes);
}
-
/**
* create time stamp from long value
*
@@ -193,13 +182,11 @@
return new DateTime(t).withZone(dtz).toLocalDate();
}
-
public static DateTime getDate (int day, int month, int year) {
DateTime date = new DateTime().withZone(dtz);
return date.withDate(year, month, day);
}
-
public static String toString (long val, Locale locale) {
if (locale == Locale.GERMAN)
return new DateTime(val).toString("dd. MMMM yyyy, HH:mm",
@@ -210,7 +197,6 @@
}
-
public static String dateToString (long val, int i) {
switch (i) {
case 1:
diff --git a/full/src/main/java/de/ids_mannheim/korap/validator/ApacheValidator.java b/full/src/main/java/de/ids_mannheim/korap/validator/ApacheValidator.java
index c88a0da..cbf7ffc 100644
--- a/full/src/main/java/de/ids_mannheim/korap/validator/ApacheValidator.java
+++ b/full/src/main/java/de/ids_mannheim/korap/validator/ApacheValidator.java
@@ -20,7 +20,7 @@
/**
* Created by hanl on 09.06.16.
- *
+ *
*/
public class ApacheValidator implements Validator {
@@ -32,12 +32,10 @@
private Map<String, RegexValidator> validators;
-
public ApacheValidator () throws IOException {
this.validators = load();
}
-
private static Map<String, RegexValidator> load () throws IOException {
Map<String, RegexValidator> validatorMap = new HashMap<>();
Properties p = ConfigLoader.loadProperties("validation.properties");
@@ -53,8 +51,6 @@
return validatorMap;
}
-
-
@Override
public Map<String, Object> validateMap (Map<String, Object> map)
throws KustvaktException {
@@ -91,7 +87,6 @@
return safeMap;
}
-
@Override
public String validateEntry (String input, String type)
throws KustvaktException {
@@ -101,7 +96,6 @@
return input;
}
-
@Override
public boolean isValid (String input, String type) {
boolean valid = false;
@@ -124,11 +118,11 @@
else
return this.isValid(input, "string");
}
- if (DEBUG){
- jlog.debug("validating entry "+input+" of type "+type+": "+ (
- valid ? "Is valid!" : "Is not valid!"));
+ if (DEBUG) {
+ jlog.debug("validating entry " + input + " of type " + type + ": "
+ + (valid ? "Is valid!" : "Is not valid!"));
}
-
+
return valid;
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/validator/Validator.java b/full/src/main/java/de/ids_mannheim/korap/validator/Validator.java
index b20cb3b..3bd42a5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/validator/Validator.java
+++ b/full/src/main/java/de/ids_mannheim/korap/validator/Validator.java
@@ -14,13 +14,10 @@
@Component
public interface Validator {
-
- Map<String, Object> validateMap (Map<String, Object> map) throws KustvaktException;
-
-
- String validateEntry (String input, String type)
+ Map<String, Object> validateMap (Map<String, Object> map)
throws KustvaktException;
+ String validateEntry (String input, String type) throws KustvaktException;
boolean isValid (String input, String type);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/ClientsHandler.java b/full/src/main/java/de/ids_mannheim/korap/web/ClientsHandler.java
index 4964913..16cfcd1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/ClientsHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/ClientsHandler.java
@@ -21,26 +21,24 @@
private WebTarget service;
-
public ClientsHandler (URI address) {
Client client = ClientBuilder.newClient();
this.service = client.target(address);
}
-
public String getResponse (String path, String key, Object value)
throws KustvaktException {
try {
- return service.path(path).queryParam(key, value).request().get(String.class);
+ return service.path(path).queryParam(key, value).request()
+ .get(String.class);
}
catch (WebApplicationException e) {
throw new KustvaktException(StatusCodes.INVALID_REQUEST);
}
}
-
- public String getResponse (MultivaluedMap<String, String> map, String ... paths)
- throws KustvaktException {
+ public String getResponse (MultivaluedMap<String, String> map,
+ String ... paths) throws KustvaktException {
try {
WebTarget resource = service;
for (String p : paths)
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/CoreResponseHandler.java b/full/src/main/java/de/ids_mannheim/korap/web/CoreResponseHandler.java
index 3d9cd42..920d38b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/CoreResponseHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/CoreResponseHandler.java
@@ -22,7 +22,7 @@
}
// KustvaktException just wraps another exception
else {
- s=Response.status(Response.Status.BAD_REQUEST)
+ s = Response.status(Response.Status.BAD_REQUEST)
.entity(e.getNotification()).build();
}
}
@@ -38,7 +38,6 @@
.entity(buildNotification(code, "", "")).build());
}
-
public WebApplicationException throwit (int code, String message,
String entity) {
return new WebApplicationException(Response.status(getStatus(code))
@@ -80,7 +79,7 @@
break;
case StatusCodes.CACHING_VC:
status = Response.Status.SERVICE_UNAVAILABLE;
- break;
+ break;
}
return status;
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/KustvaktResponseHandler.java b/full/src/main/java/de/ids_mannheim/korap/web/KustvaktResponseHandler.java
index 79ce3bc..1118b26 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/KustvaktResponseHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/KustvaktResponseHandler.java
@@ -54,7 +54,7 @@
EnumSet<AuthenticationScheme> schemes = EnumSet
.allOf(AuthenticationScheme.class);
schemes.remove(AuthenticationScheme.API);
-
+
for (AuthenticationScheme s : schemes) {
builder = builder.header(HttpHeaders.WWW_AUTHENTICATE,
s.displayName() + " realm=\"Kustvakt\"");
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/OAuth2ResponseHandler.java b/full/src/main/java/de/ids_mannheim/korap/web/OAuth2ResponseHandler.java
index 112b05d..826a625 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/OAuth2ResponseHandler.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/OAuth2ResponseHandler.java
@@ -17,7 +17,8 @@
import jakarta.ws.rs.core.Response.Status;
/**
- * OAuth2ResponseHandler builds {@link Response}s and handles exceptions by building
+ * OAuth2ResponseHandler builds {@link Response}s and handles
+ * exceptions by building
* OAuth error responses accordingly.
*
* <br/><br/>
@@ -42,8 +43,7 @@
Response r = null;
if (responseStatus > 0) {
- r = createResponse(e,
- Status.fromStatusCode(responseStatus), state);
+ r = createResponse(e, Status.fromStatusCode(responseStatus), state);
}
else if (errorCode == null) {
return super.throwit(e);
@@ -69,13 +69,11 @@
r = createResponse(e, Status.FORBIDDEN, state);
}
else if (errorCode.equals(OAuth2Error.SERVER_ERROR.getCode())) {
- r = createResponse(e, Status.INTERNAL_SERVER_ERROR,
- state);
+ r = createResponse(e, Status.INTERNAL_SERVER_ERROR, state);
}
else if (errorCode
.equals(OAuth2Error.TEMPORARILY_UNAVAILABLE.getCode())) {
- r = createResponse(e, Status.SERVICE_UNAVAILABLE,
- state);
+ r = createResponse(e, Status.SERVICE_UNAVAILABLE, state);
}
else {
return super.throwit(e);
@@ -98,7 +96,7 @@
}
return createResponse(statusCode, eo.toJSONObject().toJSONString());
}
-
+
public Response createResponse (AccessTokenResponse tokenResponse) {
String jsonString = tokenResponse.toJSONObject().toJSONString();
return createResponse(Status.OK, jsonString);
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/SearchKrill.java b/full/src/main/java/de/ids_mannheim/korap/web/SearchKrill.java
index 6d6f52b..38e9c9a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/SearchKrill.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/SearchKrill.java
@@ -62,12 +62,10 @@
};
};
-
public KrillIndex getIndex () {
return index;
};
-
public void closeIndexReader () throws KustvaktException {
try {
index.closeReader();
@@ -77,7 +75,6 @@
}
}
-
/**
* Search in the Lucene index.
*
@@ -101,7 +98,6 @@
return kr.toJsonString();
};
-
/**
* Search in the Lucene index and return matches as token lists.
*
@@ -121,7 +117,6 @@
return kr.toJsonString();
};
-
/**
* Get info on a match - by means of a richly annotated html
* snippet.
@@ -152,7 +147,6 @@
return km.toJsonString();
};
-
private void checkAvailability (Pattern licensePattern, String availability,
String id) throws KustvaktException {
if (DEBUG) {
@@ -175,7 +169,6 @@
}
-
/*
* Retrieve the meta fields for a certain document
*/
@@ -208,19 +201,17 @@
return meta.toJsonString();
};
-
- public String getMatch (
- String id, boolean info, List<String> foundries,
- List<String> layers, boolean includeSpans,
- boolean includeSnippet, boolean includeTokens,
- boolean includeHighlights, boolean sentenceExpansion,
- Pattern licensePattern) throws KustvaktException {
+ public String getMatch (String id, boolean info, List<String> foundries,
+ List<String> layers, boolean includeSpans, boolean includeSnippet,
+ boolean includeTokens, boolean includeHighlights,
+ boolean sentenceExpansion, Pattern licensePattern)
+ throws KustvaktException {
Match km;
if (index != null) {
try {
km = index.getMatchInfo(id, "tokens", info, foundries, layers,
- includeSpans, includeSnippet, includeTokens,
- includeHighlights, sentenceExpansion);
+ includeSpans, includeSnippet, includeTokens,
+ includeHighlights, sentenceExpansion);
String availability = km.getAvailability();
checkAvailability(licensePattern, availability, id);
}
@@ -236,7 +227,6 @@
return km.toJsonString();
};
-
/**
* Get info on a match - by means of a richly annotated html
* snippet.
@@ -284,7 +274,6 @@
return km.toJsonString();
};
-
/**
* Get statistics on (virtual) collections.
*
@@ -345,7 +334,6 @@
return sb.toString();
};
-
/**
* Return the match identifier as a string.
* This is a convenient method to deal with legacy instantiation
@@ -361,7 +349,6 @@
return sb.toString();
};
-
/**
* Return the text sigle as a string.
*/
@@ -373,7 +360,6 @@
return sb.toString();
};
-
/**
* Return the fingerprint of the latest index revision.
*/
@@ -384,7 +370,6 @@
return "null";
}
-
public JsonNode getFieldValuesForVC (String koralQuery, String fieldName) {
return new Krill().retrieveFieldValues(koralQuery, index, fieldName);
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
index a777131..0b40e33 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
@@ -54,19 +54,19 @@
* @author margaretha
* @last-update 01/07/2019
*
- * - added user authentication time in token context
- * - added api version filter
- * - changed the response media-type
+ * - added user authentication time in token context
+ * - added api version filter
+ * - changed the response media-type
*/
@Controller
@Path("/{version}/auth")
-@ResourceFilters({APIVersionFilter.class, PiwikFilter.class })
+@ResourceFilters({ APIVersionFilter.class, PiwikFilter.class })
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class AuthenticationController {
@Autowired
private KustvaktResponseHandler kustvaktResponseHandler;
-
+
@Autowired
private HttpAuthorizationHandler authorizationHandler;
@@ -74,8 +74,8 @@
//todo: bootstrap function to transmit certain default configuration settings and examples (example user queries,
// default usersettings, etc.)
- private static Logger jlog =
- LogManager.getLogger(AuthenticationController.class);
+ private static Logger jlog = LogManager
+ .getLogger(AuthenticationController.class);
@Autowired
private AuthenticationManager controller;
@@ -108,7 +108,6 @@
}
}
-
// fixme: moved to user
@GET
@Path("status")
@@ -126,45 +125,44 @@
throw kustvaktResponseHandler.throwit(e);
}
}
-
- // EM: testing using spring security authentication manager
-// @Deprecated
-// @GET
-// @Path("ldap/token")
-// public Response requestToken (@Context HttpHeaders headers,
-// @Context Locale locale,
-// @HeaderParam(ContainerRequest.USER_AGENT) String agent,
-// @HeaderParam(ContainerRequest.HOST) String host,
-// @HeaderParam("referer-url") String referer,
-// @QueryParam("scope") String scopes,
-// // @Context WebServiceContext wsContext, // FB
-// @Context SecurityContext securityContext) {
-//
-// Map<String, Object> attr = new HashMap<>();
-// if (scopes != null && !scopes.isEmpty())
-// attr.put(Attributes.SCOPES, scopes);
-// attr.put(Attributes.HOST, host);
-// attr.put(Attributes.USER_AGENT, agent);
-//
-// User user = new KorAPUser();
-// user.setUsername(securityContext.getUserPrincipal().getName());
-// controller.setAccessAndLocation(user, headers);
-// if (DEBUG_LOG == true) System.out.printf(
-// "Debug: /token/: location=%s, access='%s'.\n",
-// user.locationtoString(), user.accesstoString());
-// attr.put(Attributes.LOCATION, user.getLocation());
-// attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
-//
-// try {
-// TokenContext context = controller.createTokenContext(user, attr,
-// TokenType.API);
-// return Response.ok(context.toJson()).build();
-// }
-// catch (KustvaktException e) {
-// throw kustvaktResponseHandler.throwit(e);
-// }
-// }
+ // EM: testing using spring security authentication manager
+ // @Deprecated
+ // @GET
+ // @Path("ldap/token")
+ // public Response requestToken (@Context HttpHeaders headers,
+ // @Context Locale locale,
+ // @HeaderParam(ContainerRequest.USER_AGENT) String agent,
+ // @HeaderParam(ContainerRequest.HOST) String host,
+ // @HeaderParam("referer-url") String referer,
+ // @QueryParam("scope") String scopes,
+ // // @Context WebServiceContext wsContext, // FB
+ // @Context SecurityContext securityContext) {
+ //
+ // Map<String, Object> attr = new HashMap<>();
+ // if (scopes != null && !scopes.isEmpty())
+ // attr.put(Attributes.SCOPES, scopes);
+ // attr.put(Attributes.HOST, host);
+ // attr.put(Attributes.USER_AGENT, agent);
+ //
+ // User user = new KorAPUser();
+ // user.setUsername(securityContext.getUserPrincipal().getName());
+ // controller.setAccessAndLocation(user, headers);
+ // if (DEBUG_LOG == true) System.out.printf(
+ // "Debug: /token/: location=%s, access='%s'.\n",
+ // user.locationtoString(), user.accesstoString());
+ // attr.put(Attributes.LOCATION, user.getLocation());
+ // attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
+ //
+ // try {
+ // TokenContext context = controller.createTokenContext(user, attr,
+ // TokenType.API);
+ // return Response.ok(context.toJson()).build();
+ // }
+ // catch (KustvaktException e) {
+ // throw kustvaktResponseHandler.throwit(e);
+ // }
+ // }
@Deprecated
@GET
@@ -178,144 +176,144 @@
@QueryParam("scope") String scopes,
// @Context WebServiceContext wsContext, // FB
@Context SecurityContext secCtx) {
-
+
if (DEBUG_LOG == true) {
String warning = "Access to API token (JWT) web service";
-
- List<String> auth =
- headers.getRequestHeader(ContainerRequest.AUTHORIZATION);
- if (auth != null && !auth.isEmpty()) {
- try {
- AuthorizationData authorizationData = authorizationHandler
- .parseAuthorizationHeaderValue(auth.get(0));
- if (authorizationData.getAuthenticationScheme()
- .equals(AuthenticationScheme.BASIC)) {
- authorizationData = authorizationHandler
- .parseBasicToken(authorizationData);
- jlog.warn(warning + " with username:"+authorizationData.getUsername());
- }
- }
- catch (KustvaktException e) {}
- }
- else {
- jlog.warn(warning);
- }
+
+ List<String> auth = headers
+ .getRequestHeader(ContainerRequest.AUTHORIZATION);
+ if (auth != null && !auth.isEmpty()) {
+ try {
+ AuthorizationData authorizationData = authorizationHandler
+ .parseAuthorizationHeaderValue(auth.get(0));
+ if (authorizationData.getAuthenticationScheme()
+ .equals(AuthenticationScheme.BASIC)) {
+ authorizationData = authorizationHandler
+ .parseBasicToken(authorizationData);
+ jlog.warn(warning + " with username:"
+ + authorizationData.getUsername());
+ }
+ }
+ catch (KustvaktException e) {}
+ }
+ else {
+ jlog.warn(warning);
+ }
}
throw kustvaktResponseHandler.throwit(new KustvaktException(
StatusCodes.DEPRECATED,
"API token is no longer supported. Please use OAuth2 procedure instead."));
}
-// List<String> auth =
-// headers.getRequestHeader(ContainerRequest.AUTHORIZATION);
-// if (auth == null || auth.isEmpty()) {
-// throw kustvaktResponseHandler
-// .throwit(new KustvaktException(StatusCodes.MISSING_PARAMETER,
-// "Authorization header is missing.",
-// "Authorization header"));
-// }
-//
-// AuthorizationData authorizationData;
-// try {
-// authorizationData = authorizationHandler.
-// parseAuthorizationHeaderValue(auth.get(0));
-// if (authorizationData.getAuthenticationScheme().equals(AuthenticationScheme.BASIC)){
-// authorizationData = authorizationHandler.parseBasicToken(authorizationData);
-// }
-// else {
-// // EM: throw exception that auth scheme is not supported?
-// }
-//
-// }
-// catch (KustvaktException e) {
-// throw kustvaktResponseHandler.throwit(e);
-// }
-//
-// if (DEBUG_LOG == true) {
-// System.out.printf("Debug: AuthService.requestAPIToken...:\n");
-// System.out.printf("Debug: auth.size=%d\n", auth.size());
-// System.out.printf("auth.get(0)='%s'\n", auth.get(0));
-// /* hide password etc. - FB
-// if( auth.size() > 0 )
-// {
-// Iterator it = auth.iterator();
-// while( it.hasNext() )
-// System.out.printf(" header '%s'\n", it.next());
-// }
-// if( values.length > 0 )
-// {
-// for(int i=0; i< values.length; i++)
-// {
-// System.out.printf(" values[%d]='%s'\n", i, values[i]);
-// }
-// }
-// */
-// MultivaluedMap<String, String> headerMap =
-// headers.getRequestHeaders();
-// if (headerMap != null && headerMap.size() > 0) {
-// Iterator<String> it = headerMap.keySet().iterator();
-// while (it.hasNext()) {
-// String key = (String) it.next();
-// List<String> vals = headerMap.get(key);
-//// System.out.printf("Debug: requestAPIToken: '%s' = '%s'\n",
-//// key, vals);
-// }
-//
-// }
-//// System.out.printf("Debug: requestAPIToken: isSecure = %s.\n",
-//// secCtx.isSecure() ? "yes" : "no");
-// } // DEBUG_LOG
-//
-// if (authorizationData.getUsername() == null ||
-// authorizationData.getUsername().isEmpty() ||
-// authorizationData.getPassword()== null ||
-// authorizationData.getPassword().isEmpty())
-// // is actual an invalid request
-// throw kustvaktResponseHandler.throwit(StatusCodes.REQUEST_INVALID);
-//
-// Map<String, Object> attr = new HashMap<>();
-// if (scopes != null && !scopes.isEmpty())
-// attr.put(Attributes.SCOPE, scopes);
-// attr.put(Attributes.HOST, host);
-// attr.put(Attributes.USER_AGENT, agent);
-//
-// TokenContext context;
-// try {
-// // User user = controller.authenticate(0, values[0], values[1], attr); Implementation by Hanl
-// User user = controller.authenticate(AuthenticationMethod.LDAP,
-// authorizationData.getUsername(), authorizationData.getPassword(), attr); // Implementation with IdM/LDAP
-// // Userdata data = this.controller.getUserData(user, UserDetails.class); // Implem. by Hanl
-// // todo: is this necessary?
-// // attr.putAll(data.fields());
-//
-// // EM: add authentication time
-// Date authenticationTime = TimeUtils.getNow().toDate();
-// attr.put(Attributes.AUTHENTICATION_TIME, authenticationTime);
-// // -- EM
-//
-// controller.setAccessAndLocation(user, headers);
-// if (DEBUG_LOG == true) System.out.printf(
-// "Debug: /apiToken/: location=%s, access='%s'.\n",
-// user.locationtoString(), user.accesstoString());
-// attr.put(Attributes.LOCATION, user.getLocation());
-// attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
-// context = controller.createTokenContext(user, attr,
-// TokenType.API);
-//// context = controller.createTokenContext(user, attr,
-//// Attributes.API_AUTHENTICATION);
-// }
-// catch (KustvaktException e) {
-// throw kustvaktResponseHandler.throwit(e);
-// }
-//
-// try {
-// return Response.ok(context.toJson()).build();
-// }
-// catch (KustvaktException e) {
-// throw kustvaktResponseHandler.throwit(e);
-// }
-// }
-
+ // List<String> auth =
+ // headers.getRequestHeader(ContainerRequest.AUTHORIZATION);
+ // if (auth == null || auth.isEmpty()) {
+ // throw kustvaktResponseHandler
+ // .throwit(new KustvaktException(StatusCodes.MISSING_PARAMETER,
+ // "Authorization header is missing.",
+ // "Authorization header"));
+ // }
+ //
+ // AuthorizationData authorizationData;
+ // try {
+ // authorizationData = authorizationHandler.
+ // parseAuthorizationHeaderValue(auth.get(0));
+ // if (authorizationData.getAuthenticationScheme().equals(AuthenticationScheme.BASIC)){
+ // authorizationData = authorizationHandler.parseBasicToken(authorizationData);
+ // }
+ // else {
+ // // EM: throw exception that auth scheme is not supported?
+ // }
+ //
+ // }
+ // catch (KustvaktException e) {
+ // throw kustvaktResponseHandler.throwit(e);
+ // }
+ //
+ // if (DEBUG_LOG == true) {
+ // System.out.printf("Debug: AuthService.requestAPIToken...:\n");
+ // System.out.printf("Debug: auth.size=%d\n", auth.size());
+ // System.out.printf("auth.get(0)='%s'\n", auth.get(0));
+ // /* hide password etc. - FB
+ // if( auth.size() > 0 )
+ // {
+ // Iterator it = auth.iterator();
+ // while( it.hasNext() )
+ // System.out.printf(" header '%s'\n", it.next());
+ // }
+ // if( values.length > 0 )
+ // {
+ // for(int i=0; i< values.length; i++)
+ // {
+ // System.out.printf(" values[%d]='%s'\n", i, values[i]);
+ // }
+ // }
+ // */
+ // MultivaluedMap<String, String> headerMap =
+ // headers.getRequestHeaders();
+ // if (headerMap != null && headerMap.size() > 0) {
+ // Iterator<String> it = headerMap.keySet().iterator();
+ // while (it.hasNext()) {
+ // String key = (String) it.next();
+ // List<String> vals = headerMap.get(key);
+ //// System.out.printf("Debug: requestAPIToken: '%s' = '%s'\n",
+ //// key, vals);
+ // }
+ //
+ // }
+ //// System.out.printf("Debug: requestAPIToken: isSecure = %s.\n",
+ //// secCtx.isSecure() ? "yes" : "no");
+ // } // DEBUG_LOG
+ //
+ // if (authorizationData.getUsername() == null ||
+ // authorizationData.getUsername().isEmpty() ||
+ // authorizationData.getPassword()== null ||
+ // authorizationData.getPassword().isEmpty())
+ // // is actual an invalid request
+ // throw kustvaktResponseHandler.throwit(StatusCodes.REQUEST_INVALID);
+ //
+ // Map<String, Object> attr = new HashMap<>();
+ // if (scopes != null && !scopes.isEmpty())
+ // attr.put(Attributes.SCOPE, scopes);
+ // attr.put(Attributes.HOST, host);
+ // attr.put(Attributes.USER_AGENT, agent);
+ //
+ // TokenContext context;
+ // try {
+ // // User user = controller.authenticate(0, values[0], values[1], attr); Implementation by Hanl
+ // User user = controller.authenticate(AuthenticationMethod.LDAP,
+ // authorizationData.getUsername(), authorizationData.getPassword(), attr); // Implementation with IdM/LDAP
+ // // Userdata data = this.controller.getUserData(user, UserDetails.class); // Implem. by Hanl
+ // // todo: is this necessary?
+ // // attr.putAll(data.fields());
+ //
+ // // EM: add authentication time
+ // Date authenticationTime = TimeUtils.getNow().toDate();
+ // attr.put(Attributes.AUTHENTICATION_TIME, authenticationTime);
+ // // -- EM
+ //
+ // controller.setAccessAndLocation(user, headers);
+ // if (DEBUG_LOG == true) System.out.printf(
+ // "Debug: /apiToken/: location=%s, access='%s'.\n",
+ // user.locationtoString(), user.accesstoString());
+ // attr.put(Attributes.LOCATION, user.getLocation());
+ // attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
+ // context = controller.createTokenContext(user, attr,
+ // TokenType.API);
+ //// context = controller.createTokenContext(user, attr,
+ //// Attributes.API_AUTHENTICATION);
+ // }
+ // catch (KustvaktException e) {
+ // throw kustvaktResponseHandler.throwit(e);
+ // }
+ //
+ // try {
+ // return Response.ok(context.toJson()).build();
+ // }
+ // catch (KustvaktException e) {
+ // throw kustvaktResponseHandler.throwit(e);
+ // }
+ // }
// todo:
@Deprecated
@@ -336,7 +334,6 @@
return null;
}
-
@GET
@Path("sessionToken")
//@ResourceFilters({HeaderFilter.class})
@@ -344,15 +341,16 @@
@Context Locale locale,
@HeaderParam(ContainerRequest.USER_AGENT) String agent,
@HeaderParam(ContainerRequest.HOST) String host) {
- List<String> auth =
- headers.getRequestHeader(ContainerRequest.AUTHORIZATION);
+ List<String> auth = headers
+ .getRequestHeader(ContainerRequest.AUTHORIZATION);
AuthorizationData authorizationData;
try {
- authorizationData = authorizationHandler.
- parseAuthorizationHeaderValue(auth.get(0));
- authorizationData = authorizationHandler.parseBasicToken(authorizationData);
-
+ authorizationData = authorizationHandler
+ .parseAuthorizationHeaderValue(auth.get(0));
+ authorizationData = authorizationHandler
+ .parseBasicToken(authorizationData);
+
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
@@ -361,10 +359,10 @@
// Implementation Hanl mit '|'. 16.02.17/FB
//if (values[0].equalsIgnoreCase("null")
// | values[1].equalsIgnoreCase("null"))
- if (authorizationData.getUsername() == null ||
- authorizationData.getUsername().isEmpty() ||
- authorizationData.getPassword()== null ||
- authorizationData.getPassword().isEmpty())
+ if (authorizationData.getUsername() == null
+ || authorizationData.getUsername().isEmpty()
+ || authorizationData.getPassword() == null
+ || authorizationData.getPassword().isEmpty())
// is actual an invalid request
throw kustvaktResponseHandler.throwit(StatusCodes.INVALID_REQUEST);
@@ -376,11 +374,12 @@
try {
//EM: authentication scheme default
User user = controller.authenticate(AuthenticationMethod.DATABASE,
- authorizationData.getUsername(), authorizationData.getPassword(), attr);
+ authorizationData.getUsername(),
+ authorizationData.getPassword(), attr);
context = controller.createTokenContext(user, attr,
TokenType.SESSION);
-// context = controller.createTokenContext(user, attr,
-// Attributes.SESSION_AUTHENTICATION);
+ // context = controller.createTokenContext(user, attr,
+ // Attributes.SESSION_AUTHENTICATION);
contextJson = context.toJson();
jlog.debug(contextJson);
}
@@ -390,7 +389,6 @@
return Response.ok().entity(contextJson).build();
}
-
// fixme: security issues: setup shibboleth compatible authentication system
// todo: will be purged with token authentication --> shib is client side
@POST
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuth2Controller.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuth2Controller.java
index e8d7b10..8ab3e2a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuth2Controller.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuth2Controller.java
@@ -77,7 +77,7 @@
private OAuth2TokenService tokenService;
@Autowired
private OAuth2AuthorizationService authorizationService;
-
+
@Autowired
private OAuth2ScopeService scopeService;
@@ -108,8 +108,7 @@
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response requestAuthorizationCode (
@Context HttpServletRequest request,
- @Context SecurityContext context,
- @FormParam("scope") String scope,
+ @Context SecurityContext context, @FormParam("scope") String scope,
@FormParam("state") String state,
@FormParam("client_id") String clientId,
@FormParam("redirect_uri") String redirectUri,
@@ -125,27 +124,26 @@
builder.queryParam(key, form.get(key).toArray());
}
requestURI = builder.build();
-
+
try {
scopeService.verifyScope(tokenContext, OAuth2Scope.AUTHORIZE);
- URI uri = authorizationService.requestAuthorizationCode(
- requestURI, clientId, redirectUri,
- scope, state, username, authTime);
+ URI uri = authorizationService.requestAuthorizationCode(requestURI,
+ clientId, redirectUri, scope, state, username, authTime);
return responseHandler.sendRedirect(uri);
}
catch (KustvaktException e) {
e = authorizationService.checkRedirectUri(e, clientId, redirectUri);
if (e.getRedirectUri() != null) {
- AuthorizationErrorResponse errorResponse =
- authorizationService.createAuthorizationError(e, state);
+ AuthorizationErrorResponse errorResponse = authorizationService
+ .createAuthorizationError(e, state);
return responseHandler.sendRedirect(errorResponse.toURI());
}
else {
throw responseHandler.throwit(e, state);
- }
+ }
}
}
-
+
@GET
@Path("authorize")
public Response requestAuthorizationCode (
@@ -163,7 +161,8 @@
URI requestURI;
try {
- requestURI = new URI(request.getRequestURI()+"?"+request.getQueryString());
+ requestURI = new URI(
+ request.getRequestURI() + "?" + request.getQueryString());
}
catch (URISyntaxException e) {
KustvaktException ke = new KustvaktException(
@@ -171,24 +170,23 @@
OAuth2Error.INVALID_REQUEST_URI);
throw responseHandler.throwit(ke, state);
}
-
+
try {
scopeService.verifyScope(tokenContext, OAuth2Scope.AUTHORIZE);
- URI uri = authorizationService.requestAuthorizationCode(
- requestURI, clientId, redirectUri,
- scope, state, username, authTime);
+ URI uri = authorizationService.requestAuthorizationCode(requestURI,
+ clientId, redirectUri, scope, state, username, authTime);
return responseHandler.sendRedirect(uri);
}
catch (KustvaktException e) {
e = authorizationService.checkRedirectUri(e, clientId, redirectUri);
if (e.getRedirectUri() != null) {
- AuthorizationErrorResponse errorResponse =
- authorizationService.createAuthorizationError(e, state);
+ AuthorizationErrorResponse errorResponse = authorizationService
+ .createAuthorizationError(e, state);
return responseHandler.sendRedirect(errorResponse.toURI());
}
else {
throw responseHandler.throwit(e, state);
- }
+ }
}
}
@@ -256,7 +254,7 @@
*/
@POST
@Path("token")
- @ResourceFilters({APIVersionFilter.class})
+ @ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response requestAccessToken (@Context HttpServletRequest request,
@NotEmpty @FormParam("grant_type") String grantType,
@@ -266,62 +264,64 @@
try {
URI requestURI;
- UriBuilder builder = UriBuilder.fromPath(
- request.getRequestURL().toString());
+ UriBuilder builder = UriBuilder
+ .fromPath(request.getRequestURL().toString());
for (String key : form.keySet()) {
builder.queryParam(key, form.get(key).toArray());
}
requestURI = builder.build();
-
+
try {
- AuthorizationGrant authGrant = AuthorizationGrant.parse(form);
-
+ AuthorizationGrant authGrant = AuthorizationGrant.parse(form);
+
ClientAuthentication clientAuth = null;
String authorizationHeader = request.getHeader("Authorization");
- if (authorizationHeader!=null && !authorizationHeader.isEmpty() ) {
+ if (authorizationHeader != null
+ && !authorizationHeader.isEmpty()) {
clientAuth = ClientSecretBasic.parse(authorizationHeader);
}
else if (authGrant instanceof ClientCredentialsGrant) {
// this doesn't allow public clients
clientAuth = ClientSecretPost.parse(form);
}
-
+
TokenRequest tokenRequest = null;
- if (clientAuth!=null) {
+ if (clientAuth != null) {
ClientAuthenticationMethod method = clientAuth.getMethod();
- if (method.equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
+ if (method.equals(
+ ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
ClientSecretBasic basic = (ClientSecretBasic) clientAuth;
clientSecret = basic.getClientSecret().getValue();
clientId = basic.getClientID().getValue();
}
- else if (method.equals(ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
+ else if (method.equals(
+ ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
ClientSecretPost post = (ClientSecretPost) clientAuth;
clientSecret = post.getClientSecret().getValue();
clientId = post.getClientID().getValue();
}
-
- tokenRequest = new TokenRequest(requestURI,
- clientAuth,
+
+ tokenRequest = new TokenRequest(requestURI, clientAuth,
AuthorizationGrant.parse(form),
Scope.parse(form.getFirst("scope")));
}
else {
// requires ClientAuthentication for client_credentials grant
tokenRequest = new TokenRequest(requestURI,
- new ClientID(clientId),
- AuthorizationGrant.parse(form),
- Scope.parse(form.getFirst("scope")));
+ new ClientID(clientId),
+ AuthorizationGrant.parse(form),
+ Scope.parse(form.getFirst("scope")));
}
-
- AccessTokenResponse r = tokenService.requestAccessToken(tokenRequest,
- clientId, clientSecret);
+
+ AccessTokenResponse r = tokenService.requestAccessToken(
+ tokenRequest, clientId, clientSecret);
return responseHandler.createResponse(r);
}
catch (ParseException | IllegalArgumentException e) {
throw new KustvaktException(StatusCodes.INVALID_REQUEST,
- e.getMessage(), OAuth2Error.INVALID_REQUEST);
+ e.getMessage(), OAuth2Error.INVALID_REQUEST);
}
-
+
}
catch (KustvaktException e) {
throw responseHandler.throwit(e);
@@ -348,7 +348,7 @@
*/
@POST
@Path("revoke")
- @ResourceFilters({APIVersionFilter.class})
+ @ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revokeAccessToken (@Context HttpServletRequest request,
@FormParam("client_id") String clientId,
@@ -359,8 +359,8 @@
try {
ParameterChecker.checkStringValue("client_id", clientId);
ParameterChecker.checkStringValue("token", token);
- tokenService.revokeToken(clientId,clientSecret,token,tokenType);
-
+ tokenService.revokeToken(clientId, clientSecret, token, tokenType);
+
return Response.ok("SUCCESS").build();
}
catch (KustvaktException e) {
@@ -382,10 +382,11 @@
ParameterChecker.checkStringValue("super_client_secret",
superClientSecret);
ParameterChecker.checkStringValue("token", token);
-
- TokenContext tokenContext = (TokenContext) context.getUserPrincipal();
+
+ TokenContext tokenContext = (TokenContext) context
+ .getUserPrincipal();
String username = tokenContext.getUsername();
-
+
tokenService.revokeTokensViaSuperClient(username, superClientId,
superClientSecret, token);
return Response.ok("SUCCESS").build();
@@ -426,7 +427,7 @@
ParameterChecker.checkStringValue("super_client_id", superClientId);
ParameterChecker.checkStringValue("super_client_secret",
superClientSecret);
-
+
tokenService.revokeAllClientTokensViaSuperClient(username,
superClientId, superClientSecret, clientId);
return Response.ok("SUCCESS").build();
@@ -439,8 +440,7 @@
@POST
@Path("token/list")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public List<OAuth2TokenDto> listUserToken (
- @Context SecurityContext context,
+ public List<OAuth2TokenDto> listUserToken (@Context SecurityContext context,
@FormParam("super_client_id") String superClientId,
@FormParam("super_client_secret") String superClientSecret,
@FormParam("client_id") String clientId, // optional
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
index bace018..b530e19 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthClientController.java
@@ -94,8 +94,8 @@
public OAuth2ClientDto registerClient (
@Context SecurityContext securityContext,
OAuth2ClientJson clientJson) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.REGISTER_CLIENT);
return clientService.registerClient(clientJson,
@@ -107,7 +107,7 @@
}
/**
- * Deregisters a client requires client owner authentication.
+ * Deregisters a client requires client owner authentication.
*
*
* @param securityContext
@@ -117,11 +117,10 @@
*/
@DELETE
@Path("deregister/{client_id}")
- public Response deregisterClient (
- @Context SecurityContext securityContext,
+ public Response deregisterClient (@Context SecurityContext securityContext,
@PathParam("client_id") String clientId) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.DEREGISTER_CLIENT);
clientService.deregisterClient(clientId, context.getUsername());
@@ -148,8 +147,8 @@
public OAuth2ClientDto resetClientSecret (
@Context SecurityContext securityContext,
@FormParam("client_id") String clientId) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.RESET_CLIENT_SECRET);
return clientService.resetSecret(clientId, context.getUsername());
@@ -159,11 +158,10 @@
}
}
-
@POST
@Path("{client_id}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- @ResourceFilters({ APIVersionFilter.class})
+ @ResourceFilters({ APIVersionFilter.class })
public OAuth2ClientInfoDto retrieveClientInfo (
@PathParam("client_id") String clientId,
@FormParam("super_client_id") String superClientId,
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/PluginController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/PluginController.java
index c10c4fa..0afda45 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/PluginController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/PluginController.java
@@ -62,12 +62,11 @@
throw responseHandler.throwit(e);
}
}
-
+
@POST
@Path("/install")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public InstalledPluginDto installPlugin (
- @Context SecurityContext context,
+ public InstalledPluginDto installPlugin (@Context SecurityContext context,
@FormParam("super_client_id") String superClientId,
@FormParam("super_client_secret") String superClientSecret,
@FormParam("client_id") String clientId) {
@@ -80,13 +79,14 @@
OAuth2Scope.INSTALL_USER_CLIENT);
clientService.verifySuperClient(superClientId, superClientSecret);
- return clientService.installPlugin(superClientId,clientId, username);
+ return clientService.installPlugin(superClientId, clientId,
+ username);
}
catch (KustvaktException e) {
throw responseHandler.throwit(e);
}
}
-
+
@POST
@Path("/installed")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@@ -109,12 +109,11 @@
throw responseHandler.throwit(e);
}
}
-
+
@POST
@Path("/uninstall")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public Response uninstallPlugin (
- @Context SecurityContext context,
+ public Response uninstallPlugin (@Context SecurityContext context,
@FormParam("super_client_id") String superClientId,
@FormParam("super_client_secret") String superClientSecret,
@FormParam("client_id") String clientId) {
@@ -127,7 +126,7 @@
OAuth2Scope.UNINSTALL_USER_CLIENT);
clientService.verifySuperClient(superClientId, superClientSecret);
- clientService.uninstallPlugin(superClientId,clientId, username);
+ clientService.uninstallPlugin(superClientId, clientId, username);
return Response.ok().build();
}
catch (KustvaktException e) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/QueryReferenceController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/QueryReferenceController.java
index caa059c..af9c395 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/QueryReferenceController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/QueryReferenceController.java
@@ -75,21 +75,21 @@
* @param query
* a json object describing the query and its
* properties
- * @return HTTP Status 201 Created when creating a new query, or 204
+ * @return HTTP Status 201 Created when creating a new query, or
+ * 204
* No Content when updating an existing query.
* @throws KustvaktException
*/
@PUT
@Path("/~{qCreator}/{qName}")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
- public Response createQuery (
- @Context SecurityContext securityContext,
- @PathParam("qCreator") String qCreator,
- @PathParam("qName") String qName,
- QueryJson query) throws KustvaktException {
+ public Response createQuery (@Context SecurityContext securityContext,
+ @PathParam("qCreator") String qCreator,
+ @PathParam("qName") String qName, QueryJson query)
+ throws KustvaktException {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.EDIT_VC);
@@ -104,7 +104,7 @@
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
}
-
+
}
/**
@@ -120,13 +120,13 @@
@GET
@Path("~{createdBy}/{qName}")
@ResourceFilters({ APIVersionFilter.class, AuthenticationFilter.class,
- DemoUserFilter.class, PiwikFilter.class })
+ DemoUserFilter.class, PiwikFilter.class })
public QueryDto retrieveQueryByName (
@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("qName") String qName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
return service.retrieveQueryByName(context.getUsername(), qName,
@@ -149,33 +149,32 @@
* query name
* @return HTTP status 200, if successful
*/
-
+
@DELETE
@Path("~{createdBy}/{qName}")
public Response deleteQueryByName (@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("qName") String qName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.DELETE_VC);
service.deleteQueryByName(context.getUsername(), qName, createdBy,
QueryType.QUERY);
}
catch (KustvaktException e) {
- throw kustvaktResponseHandler.throwit(e);
+ throw kustvaktResponseHandler.throwit(e);
}
return Response.ok().build();
};
-
/**
* Lists all queries available to the authenticated user.
*
* System-admins can list available queries for a specific user by
* specifiying the username parameter.
*
- * Normal users cannot list queries available for other users.
+ * Normal users cannot list queries available for other users.
* Thus, username parameter is optional
* and must be identical to the authenticated username.
*
@@ -189,8 +188,8 @@
public List<QueryDto> listAvailableQuery (
@Context SecurityContext securityContext,
@QueryParam("username") String username) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
List<QueryDto> dtos = service.listAvailableQueryForUser(
@@ -201,39 +200,38 @@
throw kustvaktResponseHandler.throwit(e);
}
}
-
-// // TODO: List all queries of a sepcific user
-// /**
-// * Lists all queries created by a user. This list is only
-// * available to the owner of the queries. Users, except system-admins,
-// * are not allowed to list queries created by other users.
-// *
-// * Thus, the path parameter "createdBy" must be the same as the
-// * authenticated username.
-// *
-// * @param securityContext
-// * @return a list of queries created by the user
-// * in the security context.
-// */
-// @GET
-// @Path("~{createdBy}")
-// @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
-// public List<VirtualCorpusDto> listUserVC (
-// @PathParam("createdBy") String createdBy,
-// @Context SecurityContext securityContext) {
-// TokenContext context =
-// (TokenContext) securityContext.getUserPrincipal();
-// try {
-// scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
-// return service.listOwnerVC(context.getUsername(), createdBy,
-// QueryType.QUERY);
-// }
-// catch (KustvaktException e) {
-// throw kustvaktResponseHandler.throwit(e);
-// }
-// }
-
-
+
+ // // TODO: List all queries of a sepcific user
+ // /**
+ // * Lists all queries created by a user. This list is only
+ // * available to the owner of the queries. Users, except system-admins,
+ // * are not allowed to list queries created by other users.
+ // *
+ // * Thus, the path parameter "createdBy" must be the same as the
+ // * authenticated username.
+ // *
+ // * @param securityContext
+ // * @return a list of queries created by the user
+ // * in the security context.
+ // */
+ // @GET
+ // @Path("~{createdBy}")
+ // @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+ // public List<VirtualCorpusDto> listUserVC (
+ // @PathParam("createdBy") String createdBy,
+ // @Context SecurityContext securityContext) {
+ // TokenContext context =
+ // (TokenContext) securityContext.getUserPrincipal();
+ // try {
+ // scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
+ // return service.listOwnerVC(context.getUsername(), createdBy,
+ // QueryType.QUERY);
+ // }
+ // catch (KustvaktException e) {
+ // throw kustvaktResponseHandler.throwit(e);
+ // }
+ // }
+
// TODO: Some admin routes missing.
// TODO: Some sharing routes missing
};
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/ResourceController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/ResourceController.java
index 074b14b..986f621 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/ResourceController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/ResourceController.java
@@ -23,19 +23,19 @@
*/
@Controller
@Path("{version}/resource")
-@ResourceFilters({APIVersionFilter.class, PiwikFilter.class })
+@ResourceFilters({ APIVersionFilter.class, PiwikFilter.class })
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class ResourceController {
@Autowired
private ResourceService resourceService;
-
- /** Returns descriptions of all free resources stored in
+ /**
+ * Returns descriptions of all free resources stored in
* the database.
*
- * @return a json description of all free resources stored in
- * the database.
+ * @return a json description of all free resources stored in
+ * the database.
*/
@GET
public List<ResourceDto> getAllResourceInfo () {
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
index 8e461f4..09de4c2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
@@ -24,7 +24,7 @@
@Controller
@Path("{version}/user")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
-@ResourceFilters({ AuthenticationFilter.class, APIVersionFilter.class})
+@ResourceFilters({ AuthenticationFilter.class, APIVersionFilter.class })
public class UserController {
@Autowired
@@ -36,16 +36,15 @@
@GET
@Path("/info")
- public JsonNode getUsername (
- @Context SecurityContext securityContext) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
- try {
- scopeService.verifyScope(context, OAuth2Scope.USER_INFO);
- return userService.retrieveUserInfo(context.getUsername());
- }
- catch (KustvaktException e) {
- throw kustvaktResponseHandler.throwit(e);
- }
+ public JsonNode getUsername (@Context SecurityContext securityContext) {
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
+ try {
+ scopeService.verifyScope(context, OAuth2Scope.USER_INFO);
+ return userService.retrieveUserInfo(context.getUsername());
}
+ catch (KustvaktException e) {
+ throw kustvaktResponseHandler.throwit(e);
+ }
+ }
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupAdminController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupAdminController.java
index e5edce5..4ed6266 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupAdminController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupAdminController.java
@@ -31,7 +31,7 @@
private KustvaktResponseHandler kustvaktResponseHandler;
@Autowired
private UserGroupService service;
-
+
/**
* Lists user-groups for system-admin purposes. If username is
* specified, lists user-groups of the given user, otherwise list
@@ -53,14 +53,13 @@
@FormParam("username") String username,
@FormParam("status") UserGroupStatus status) {
try {
- return service.retrieveUserGroupByStatus(username,
- status);
+ return service.retrieveUserGroupByStatus(username, status);
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
}
}
-
+
/**
* Retrieves a specific user-group. Only system admins are
* allowed.
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupController.java
index 19c97d7..b54269a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserGroupController.java
@@ -64,7 +64,8 @@
*
* Not suitable for system-admin, instead use
* {@link UserGroupController#
- * getUserGroupBySystemAdmin(SecurityContext, String, UserGroupStatus)}
+ * getUserGroupBySystemAdmin(SecurityContext, String,
+ * UserGroupStatus)}
*
* @param securityContext
* @return a list of user-groups
@@ -73,8 +74,8 @@
@GET
public List<UserGroupDto> listUserGroups (
@Context SecurityContext securityContext) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.USER_GROUP_INFO);
return service.retrieveUserGroupDto(context.getUsername());
@@ -90,18 +91,20 @@
* context.
*
* @param securityContext
- * @param groupName the name of the group
+ * @param groupName
+ * the name of the group
* @return if a new group created, HTTP response status 201
* Created, otherwise 204 No Content.
*/
@PUT
@Path("@{groupName}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- public Response createUpdateUserGroup (@Context SecurityContext securityContext,
+ public Response createUpdateUserGroup (
+ @Context SecurityContext securityContext,
@PathParam("groupName") String groupName,
@FormParam("description") String description) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.CREATE_USER_GROUP);
boolean groupExists = service.createUpdateUserGroup(groupName,
@@ -131,8 +134,8 @@
@Path("@{groupName}")
public Response deleteUserGroup (@Context SecurityContext securityContext,
@PathParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.DELETE_USER_GROUP);
service.deleteGroup(groupName, context.getUsername());
@@ -161,8 +164,8 @@
@Context SecurityContext securityContext,
@PathParam("memberUsername") String memberUsername,
@PathParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.DELETE_USER_GROUP_MEMBER);
@@ -179,7 +182,7 @@
* Invites users to join a user-group specified by the
* groupName. Only user-group admins and system admins are
* allowed to use this service.
- *
+ *
* The invited users are added as group members with status
* GroupMemberStatus.PENDING.
*
@@ -205,8 +208,8 @@
@Context SecurityContext securityContext,
@PathParam("groupName") String groupName,
@FormParam("members") String members) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.ADD_USER_GROUP_MEMBER);
@@ -239,8 +242,8 @@
@PathParam("groupName") String groupName,
@FormParam("memberUsername") String memberUsername,
@FormParam("roleId") List<Integer> roleIds) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.EDIT_USER_GROUP_MEMBER_ROLE);
@@ -273,8 +276,8 @@
@PathParam("groupName") String groupName,
@FormParam("memberUsername") String memberUsername,
@FormParam("roleId") List<Integer> roleIds) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.ADD_USER_GROUP_MEMBER_ROLE);
@@ -308,8 +311,8 @@
@PathParam("groupName") String groupName,
@FormParam("memberUsername") String memberUsername,
@FormParam("roleId") List<Integer> roleIds) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.DELETE_USER_GROUP_MEMBER_ROLE);
@@ -335,8 +338,8 @@
@Path("@{groupName}/subscribe")
public Response subscribeToGroup (@Context SecurityContext securityContext,
@PathParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.ADD_USER_GROUP_MEMBER);
@@ -364,8 +367,8 @@
public Response unsubscribeFromGroup (
@Context SecurityContext securityContext,
@PathParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context,
OAuth2Scope.DELETE_USER_GROUP_MEMBER);
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
index bf57a1e..af0199f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
@@ -113,7 +113,8 @@
if (settings == null) {
username = tokenContext.getUsername();
throw new KustvaktException(StatusCodes.NO_RESOURCE_FOUND,
- "No default setting for username: " + username+" is found",
+ "No default setting for username: " + username
+ + " is found",
username);
}
return Response.ok(settings).build();
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAdminController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAdminController.java
index c6ffcdf..b4946fb 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAdminController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAdminController.java
@@ -34,20 +34,19 @@
private KustvaktResponseHandler kustvaktResponseHandler;
@Autowired
private QueryService service;
-
+
@Autowired
private NamedVCLoader vcLoader;
-
+
@POST
@Path("load-cache")
public Response loadAndCacheSystemVC () {
Thread t = new Thread(vcLoader);
t.start();
-
+
return Response.status(Status.OK).build();
}
-
-
+
/**
* Lists virtual corpora by creator and type. This is a controller
* for system admin requiring valid system admin authentication.
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
index bd9e13c..b69b09f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
@@ -81,7 +81,7 @@
* VC name cannot be updated.
*
* The VC creator must be the same as the authenticated username,
- * except for system admins. System admins can create or update
+ * except for system admins. System admins can create or update
* system VC and any VC for any users.
*
*
@@ -102,10 +102,10 @@
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response createUpdateVC (@Context SecurityContext securityContext,
@PathParam("vcCreator") String vcCreator,
- @PathParam("vcName") String vcName,
- QueryJson vc) throws KustvaktException {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ @PathParam("vcName") String vcName, QueryJson vc)
+ throws KustvaktException {
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.EDIT_VC);
@@ -120,7 +120,7 @@
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
}
-
+
}
/**
@@ -139,13 +139,12 @@
@GET
@Path("~{createdBy}/{vcName}")
@ResourceFilters({ APIVersionFilter.class, AuthenticationFilter.class,
- DemoUserFilter.class, PiwikFilter.class })
- public QueryDto retrieveVCByName (
- @Context SecurityContext securityContext,
+ DemoUserFilter.class, PiwikFilter.class })
+ public QueryDto retrieveVCByName (@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("vcName") String vcName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
return service.retrieveQueryByName(context.getUsername(), vcName,
@@ -162,8 +161,8 @@
@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("vcName") String vcName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
return service.retrieveKoralQuery(context.getUsername(), vcName,
@@ -173,8 +172,9 @@
throw kustvaktResponseHandler.throwit(e);
}
}
-
- /** Retrieves field values of a virtual corpus, e.g. corpus sigle.
+
+ /**
+ * Retrieves field values of a virtual corpus, e.g. corpus sigle.
*
* This service is restricted to system admin only.
*
@@ -187,13 +187,12 @@
@GET
@Path("/field/~{createdBy}/{vcName}")
@ResourceFilters({ APIVersionFilter.class, AdminFilter.class })
- public JsonNode retrieveVCField (
- @Context SecurityContext securityContext,
+ public JsonNode retrieveVCField (@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("vcName") String vcName,
@QueryParam("fieldName") String fieldName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
return service.retrieveFieldValues(context.getUsername(), vcName,
createdBy, QueryType.VIRTUAL_CORPUS, fieldName);
@@ -202,7 +201,7 @@
throw kustvaktResponseHandler.throwit(e);
}
}
-
+
/**
* Lists all virtual corpora available to the user.
*
@@ -222,28 +221,28 @@
public List<QueryDto> listAvailableVC (
@Context SecurityContext securityContext,
@QueryParam("filter-by") String filter) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
- if (filter !=null && !filter.isEmpty() ) {
+ if (filter != null && !filter.isEmpty()) {
filter = filter.toLowerCase();
if (filter.equals("system")) {
return service.listSystemQuery(QueryType.VIRTUAL_CORPUS);
}
else if (filter.equals("own")) {
return service.listOwnerQuery(context.getUsername(),
- QueryType.VIRTUAL_CORPUS);
+ QueryType.VIRTUAL_CORPUS);
}
else {
- throw new KustvaktException(StatusCodes.UNSUPPORTED_VALUE,
+ throw new KustvaktException(StatusCodes.UNSUPPORTED_VALUE,
"The given filter is unknown or not supported.");
}
}
else {
return service.listAvailableQueryForUser(context.getUsername(),
- QueryType.VIRTUAL_CORPUS);
+ QueryType.VIRTUAL_CORPUS);
}
}
catch (KustvaktException e) {
@@ -276,14 +275,13 @@
public List<QueryDto> listUserOrSystemVC (
@PathParam("createdBy") String createdBy,
@Context SecurityContext securityContext) {
-
+
KustvaktException e = new KustvaktException(StatusCodes.DEPRECATED,
"This service has been deprecated. Please use Virtual Corpus List "
- + "web-service.");
- throw kustvaktResponseHandler.throwit(e);
+ + "web-service.");
+ throw kustvaktResponseHandler.throwit(e);
}
-
-
+
/**
* Only the VC owner and system admins can delete VC. VCA admins
* can delete VC-accesses e.g. of project VC, but not the VC
@@ -301,8 +299,8 @@
public Response deleteVCByName (@Context SecurityContext securityContext,
@PathParam("createdBy") String createdBy,
@PathParam("vcName") String vcName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.DELETE_VC);
service.deleteQueryByName(context.getUsername(), vcName, createdBy,
@@ -335,13 +333,14 @@
@Path("~{vcCreator}/{vcName}/share/@{groupName}")
public Response shareVC (@Context SecurityContext securityContext,
@PathParam("vcCreator") String vcCreator,
- @PathParam("vcName") String vcName,
+ @PathParam("vcName") String vcName,
@PathParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.SHARE_VC);
- service.shareQuery(context.getUsername(), vcCreator, vcName, groupName);
+ service.shareQuery(context.getUsername(), vcCreator, vcName,
+ groupName);
}
catch (KustvaktException e) {
throw kustvaktResponseHandler.throwit(e);
@@ -365,8 +364,8 @@
public Response deleteVCAccessById (
@Context SecurityContext securityContext,
@PathParam("accessId") int accessId) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.DELETE_VC_ACCESS);
service.deleteQueryAccess(accessId, context.getUsername());
@@ -391,12 +390,13 @@
public List<QueryAccessDto> listVCAccesses (
@Context SecurityContext securityContext,
@QueryParam("groupName") String groupName) {
- TokenContext context =
- (TokenContext) securityContext.getUserPrincipal();
+ TokenContext context = (TokenContext) securityContext
+ .getUserPrincipal();
try {
scopeService.verifyScope(context, OAuth2Scope.VC_ACCESS_INFO);
- if (groupName!=null && !groupName.isEmpty()){
- return service.listQueryAccessByGroup(context.getUsername(), groupName);
+ if (groupName != null && !groupName.isEmpty()) {
+ return service.listQueryAccessByGroup(context.getUsername(),
+ groupName);
}
else {
return service.listQueryAccessByUsername(context.getUsername());
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/APIVersionFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/APIVersionFilter.java
index ed0c2c3..e42de93 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/APIVersionFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/APIVersionFilter.java
@@ -20,8 +20,7 @@
*/
@Component
@Priority(Integer.MIN_VALUE)
-public class APIVersionFilter
- implements ContainerRequestFilter {
+public class APIVersionFilter implements ContainerRequestFilter {
@Autowired
private KustvaktConfiguration config;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java
index 18a12d8..e09ebd5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/AdminFilter.java
@@ -49,7 +49,6 @@
}
}
-
private boolean checkAdminToken (String adminToken) {
if (adminToken != null && !adminToken.isEmpty()) {
if (adminToken
@@ -60,7 +59,6 @@
return false;
}
-
private void checkAdminCredentials (TokenContext tokenContext,
String username) {
if (tokenContext != null) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/AuthenticationFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/AuthenticationFilter.java
index e24a7a4..1fb9360 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/AuthenticationFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/AuthenticationFilter.java
@@ -21,8 +21,9 @@
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
-/** Authentication filter extracts an authentication token from
- * authorization header and uses an authentication provider
+/**
+ * Authentication filter extracts an authentication token from
+ * authorization header and uses an authentication provider
* with respect to the token type to create a token context as
* a security context.
*
@@ -32,11 +33,11 @@
*/
@Component
@Priority(Priorities.AUTHENTICATION)
-public class AuthenticationFilter
- implements ContainerRequestFilter {
+public class AuthenticationFilter implements ContainerRequestFilter {
- private static Logger jlog = LogManager.getLogger(AuthenticationFilter.class);
-
+ private static Logger jlog = LogManager
+ .getLogger(AuthenticationFilter.class);
+
@Autowired
private HttpAuthorizationHandler authorizationHandler;
@@ -51,8 +52,8 @@
String host = request.getHeaderString(ContainerRequest.HOST);
String ua = request.getHeaderString(ContainerRequest.USER_AGENT);
- String authorization =
- request.getHeaderString(ContainerRequest.AUTHORIZATION);
+ String authorization = request
+ .getHeaderString(ContainerRequest.AUTHORIZATION);
if (authorization != null && !authorization.isEmpty()) {
TokenContext context = null;
@@ -102,9 +103,8 @@
}
}
-
- private void checkContext (TokenContext context, ContainerRequestContext request)
- throws KustvaktException {
+ private void checkContext (TokenContext context,
+ ContainerRequestContext request) throws KustvaktException {
if (context == null) {
throw new KustvaktException(StatusCodes.AUTHENTICATION_FAILED,
"Context is null.");
@@ -114,7 +114,8 @@
"Context is not valid: "
+ "missing username, password or authentication scheme.");
}
- else if (context.isSecureRequired() && !request.getSecurityContext().isSecure()) {
+ else if (context.isSecureRequired()
+ && !request.getSecurityContext().isSecure()) {
throw new KustvaktException(StatusCodes.AUTHENTICATION_FAILED,
"Request is not secure.");
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/BlockingFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/BlockingFilter.java
index 09c811c..e33f57f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/BlockingFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/BlockingFilter.java
@@ -28,7 +28,6 @@
@Autowired
private KustvaktResponseHandler kustvaktResponseHandler;
-
@Override
public void filter (ContainerRequestContext request) {
TokenContext context;
@@ -38,14 +37,14 @@
context = (TokenContext) securityContext.getUserPrincipal();
}
else {
- throw kustvaktResponseHandler.throwit(new KustvaktException(
- StatusCodes.UNSUPPORTED_OPERATION));
+ throw kustvaktResponseHandler.throwit(
+ new KustvaktException(StatusCodes.UNSUPPORTED_OPERATION));
}
if (context == null || context.isDemo()) {
- throw kustvaktResponseHandler.throwit(new KustvaktException(
- StatusCodes.AUTHORIZATION_FAILED,
- "Unauthorized operation for user: guest", "guest"));
+ throw kustvaktResponseHandler.throwit(
+ new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
+ "Unauthorized operation for user: guest", "guest"));
}
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java
index 55ad2ae..2a3cdf0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoFilter.java
@@ -22,8 +22,8 @@
@Override
public void filter (ContainerRequestContext request) {
- String authentication =
- request.getHeaderString(ContainerRequest.AUTHORIZATION);
+ String authentication = request
+ .getHeaderString(ContainerRequest.AUTHORIZATION);
if (authentication == null || authentication.isEmpty()) {
if (request.getSecurityContext() == null) {
request.setSecurityContext(createContext());
@@ -31,7 +31,6 @@
}
}
-
private SecurityContext createContext () {
TokenContext context = new TokenContext();
String token = null;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
index 330ece2..300c3da 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
@@ -32,7 +32,6 @@
@Autowired
private KustvaktConfiguration config;
-
@Override
public void filter (ContainerRequestContext request) {
String host = request.getHeaderString(ContainerRequest.HOST);
@@ -48,12 +47,11 @@
pr = securityContext.getUserPrincipal();
}
if (pr == null)
- request.setSecurityContext(new KustvaktContext(
- createShorterToken(host, ua)));
+ request.setSecurityContext(
+ new KustvaktContext(createShorterToken(host, ua)));
}
}
-
private TokenContext createShorterToken (String host, String agent) {
User demo = User.UserFactory.getDemoUser();
TokenContext c = new TokenContext();
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/NonDemoBlockingFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/NonDemoBlockingFilter.java
index c69e18e..1e3a05c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/NonDemoBlockingFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/NonDemoBlockingFilter.java
@@ -1,6 +1,5 @@
package de.ids_mannheim.korap.web.filter;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -15,7 +14,8 @@
import jakarta.ws.rs.core.SecurityContext;
/**
- * EM: pretty much identical to {@link BlockingFilter}, should be deleted?
+ * EM: pretty much identical to {@link BlockingFilter}, should be
+ * deleted?
*
* @author hanl
* @date 11/12/2014
@@ -25,8 +25,7 @@
*/
@Component
@Priority(Priorities.AUTHORIZATION)
-public class NonDemoBlockingFilter
- implements ContainerRequestFilter {
+public class NonDemoBlockingFilter implements ContainerRequestFilter {
@Autowired
private KustvaktResponseHandler kustvaktResponseHandler;
@@ -39,8 +38,8 @@
context = (TokenContext) securityContext.getUserPrincipal();
}
else {
- throw kustvaktResponseHandler.throwit(new KustvaktException(
- StatusCodes.UNSUPPORTED_OPERATION));
+ throw kustvaktResponseHandler.throwit(
+ new KustvaktException(StatusCodes.UNSUPPORTED_OPERATION));
}
if (context == null || context.isDemo()) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/filter/PiwikFilter.java b/full/src/main/java/de/ids_mannheim/korap/web/filter/PiwikFilter.java
index 88961f2..42ede2a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/filter/PiwikFilter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/filter/PiwikFilter.java
@@ -41,10 +41,9 @@
@Autowired
private AuthenticationManager authenticationManager;
-
public PiwikFilter () {
-// controller = BeansFactory.getKustvaktContext()
-// .getAuthenticationManager();
+ // controller = BeansFactory.getKustvaktContext()
+ // .getAuthenticationManager();
ClientConfig clientConfig = new ClientConfig();
if (jlog.isDebugEnabled())
clientConfig.register(LoggingFeature.class);
@@ -54,15 +53,13 @@
this.customVars = new HashMap<>();
}
-
private void send (ContainerRequestContext request) {
Random random = new SecureRandom();
Locale l = null;
if (request.getAcceptableLanguages() != null)
l = request.getAcceptableLanguages().get(0);
try {
- service.path("piwik/piwik.php")
- .queryParam("idsite", "2")
+ service.path("piwik/piwik.php").queryParam("idsite", "2")
.queryParam("rec", "1")
//todo check for empty container
.queryParam("_cvar", translateCustomData())
@@ -70,9 +67,9 @@
.queryParam("cookie", "false")
.queryParam("r", String.valueOf(random.nextDouble()))
.queryParam("action_name",
- request.getUriInfo().getRequestUri().toASCIIString())
- .request()
- .accept("text/html")
+ request.getUriInfo().getRequestUri()
+ .toASCIIString())
+ .request().accept("text/html")
.header("Host", request.getHeaderString("Host"))
.header("User-Agent", request.getHeaderString("User-Agent"))
.acceptLanguage(l).method("GET");
@@ -82,11 +79,11 @@
}
}
-
private String translateCustomData () {
final Map<String, List<String>> customVariables = new HashMap<String, List<String>>();
int i = 0;
- for (final Map.Entry<String, String> entry : this.customVars.entrySet()) {
+ for (final Map.Entry<String, String> entry : this.customVars
+ .entrySet()) {
i++;
final List<String> list = new ArrayList<String>();
list.add(entry.getKey());
@@ -104,29 +101,28 @@
return jsonString;
}
-
@Override
public void filter (ContainerRequestContext request) {
if (ENABLED) {
-// try {
-// TokenContext context;
-// SecurityContext securityContext = request.getSecurityContext();
-// if (securityContext != null) {
-// context = (TokenContext) securityContext.getUserPrincipal();
-//
-// if (context.getUsername() != null){
-// // since this is cached, not very expensive!
-// User user = authenticationManager.getUser(context.getUsername());
-// Userdata data = authenticationManager
-// .getUserData(user, UserSettingProcessor.class);
-// if ((Boolean) data.get(Attributes.COLLECT_AUDITING_DATA))
-// customVars.put("username", context.getUsername());
-// }
-// }
-// }
-// catch (KustvaktException e) {
-// //do nothing
-// }
+ // try {
+ // TokenContext context;
+ // SecurityContext securityContext = request.getSecurityContext();
+ // if (securityContext != null) {
+ // context = (TokenContext) securityContext.getUserPrincipal();
+ //
+ // if (context.getUsername() != null){
+ // // since this is cached, not very expensive!
+ // User user = authenticationManager.getUser(context.getUsername());
+ // Userdata data = authenticationManager
+ // .getUserData(user, UserSettingProcessor.class);
+ // if ((Boolean) data.get(Attributes.COLLECT_AUDITING_DATA))
+ // customVars.put("username", context.getUsername());
+ // }
+ // }
+ // }
+ // catch (KustvaktException e) {
+ // //do nothing
+ // }
send(request);
}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/input/OAuth2ClientJson.java b/full/src/main/java/de/ids_mannheim/korap/web/input/OAuth2ClientJson.java
index e6b4490..9630a0e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/input/OAuth2ClientJson.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/input/OAuth2ClientJson.java
@@ -7,7 +7,7 @@
/**
* Defines attributes to register an OAuth2 client. Application name,
- * client type and description are required attributes.
+ * client type and description are required attributes.
*
* To accommodate desktop applications such as R, url and redirectURI
* are not compulsory.
@@ -23,7 +23,7 @@
private String name;
private OAuth2ClientType type;
private String description;
-
+
// optional
private String url;
// redirect URI determines where the OAuth 2.0 service will return
@@ -33,7 +33,7 @@
// Default 365 days
@JsonProperty("refresh_token_expiry")
private int refreshTokenExpiry; // in seconds
-
+
// plugins
private JsonNode source;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/input/QueryJson.java b/full/src/main/java/de/ids_mannheim/korap/web/input/QueryJson.java
index 8badd38..dcc88e3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/input/QueryJson.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/input/QueryJson.java
@@ -1,6 +1,5 @@
package de.ids_mannheim.korap.web.input;
-
import de.ids_mannheim.korap.constant.QueryType;
import de.ids_mannheim.korap.constant.ResourceType;
import de.ids_mannheim.korap.service.QueryService;
@@ -9,7 +8,8 @@
import lombok.Getter;
import lombok.Setter;
-/** Java POJO of JSON input of the virtual corpus and query controllers
+/**
+ * Java POJO of JSON input of the virtual corpus and query controllers
* for creating and editing virtual corpora and query references.
*
* @author margaretha
@@ -22,7 +22,7 @@
public class QueryJson {
// default false
private boolean isCached;
-
+
// required
private ResourceType type;
// required for queryType="VIRTUAL_CORPUS"
@@ -30,7 +30,7 @@
// required for queryType="QUERY"
private String query;
private String queryLanguage;
-
+
// optional
private String definition;
private String description;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/input/UserGroupJson.java b/full/src/main/java/de/ids_mannheim/korap/web/input/UserGroupJson.java
index 6868262..0cc4922 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/input/UserGroupJson.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/input/UserGroupJson.java
@@ -4,7 +4,8 @@
import lombok.Getter;
import lombok.Setter;
-/** Java POJO of JSON input used in the user group controller for
+/**
+ * Java POJO of JSON input used in the user group controller for
* creating user group and managing group members.
*
* @author margaretha
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/FormRequestWrapper.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/FormRequestWrapper.java
index 12c4f01..959ed80 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/FormRequestWrapper.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/FormRequestWrapper.java
@@ -19,7 +19,6 @@
private MultivaluedMap<String, String> form;
-
/**
* Constructs a request object wrapping the given request.
*
@@ -33,17 +32,15 @@
this.form = form;
}
-
@Override
public String getParameter (String name) {
String value = super.getParameter(name);
- if (value == null){
+ if (value == null) {
value = form.getFirst(name);
}
return value;
}
-
@Override
public String[] getParameterValues (String name) {
String[] values = super.getParameterValues(name);
@@ -54,12 +51,10 @@
return values;
}
-
public HashMap<String, Object> singleValueMap () {
return toMap(this.form, false);
}
-
/**
* @param strict
* returns only values with size equal to one. If false
@@ -81,12 +76,10 @@
return map;
}
-
public void put (String key, String value) {
this.form.putSingle(key, value);
}
-
public void put (String key, String ... values) {
this.form.put(key, Arrays.<String> asList(values));
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/HTMLBuilder.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/HTMLBuilder.java
index 543fbae..30e3a5b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/HTMLBuilder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/HTMLBuilder.java
@@ -10,7 +10,6 @@
private StringBuilder body;
private String bodyAttr;
-
public HTMLBuilder () {
html = new StringBuilder();
body = new StringBuilder();
@@ -18,25 +17,21 @@
html.append("<html>");
}
-
public void addHeader (String header, int h) {
html.append("<h" + h + ">");
html.append(header);
html.append("</h" + h + ">");
}
-
public void addToBody (String body) {
this.body.append(body);
}
-
public void addToBody (String body, String attributes) {
this.body.append(body);
bodyAttr = attributes;
}
-
public String build () {
if (bodyAttr.isEmpty())
html.append("<body>");
@@ -52,7 +47,6 @@
return html.toString();
}
-
@Override
public String toString () {
return build();
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/JsonExceptionMapper.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/JsonExceptionMapper.java
index a7efdf8..e5c28a2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/JsonExceptionMapper.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/JsonExceptionMapper.java
@@ -1,6 +1,5 @@
package de.ids_mannheim.korap.web.utils;
-
import com.fasterxml.jackson.databind.JsonMappingException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktMap.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktMap.java
index 8e9de8a..6c5d5ea 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktMap.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktMap.java
@@ -13,30 +13,25 @@
private boolean monoTyped;
private Map<String, Object> values;
-
public KustvaktMap () {
this.values = new HashMap<>();
this.monoTyped = false;
}
-
public KustvaktMap (Map<String, Object> m) {
this();
setMap(m);
}
-
public void setMap (Map<String, Object> m) {
if (!isGeneric(m) | !this.monoTyped)
this.values.putAll(m);
}
-
public boolean isGeneric () {
return !this.monoTyped && isGeneric(this.values);
}
-
private static boolean isGeneric (Map<String, Object> map) {
int i = 0;
for (Object o : map.values()) {
@@ -46,12 +41,10 @@
return !(i == map.size());
}
-
public void setMonoValue (boolean monovalue) {
this.monoTyped = monovalue;
}
-
public String get (String key) {
Object o = this.values.get(key);
if (!isGeneric())
@@ -59,19 +52,16 @@
return String.valueOf(o);
}
-
public Object getRaw (String key) {
return this.values.get(key);
}
-
public <T extends Object> Object get (String key, Class<T> cl) {
if (isGeneric())
return (T) this.values.get(key);
return get(key);
}
-
public Set<String> keySet () {
return this.values.keySet();
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java
index b43adf8..5997787 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/KustvaktResponseBuilder.java
@@ -10,21 +10,17 @@
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/full/src/main/java/de/ids_mannheim/korap/web/utils/LocaleFactory.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/LocaleFactory.java
index 268e7c8..f928701 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/LocaleFactory.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/LocaleFactory.java
@@ -15,7 +15,7 @@
private ContainerRequestContext context;
@Override
- public Locale provide() {
+ public Locale provide () {
final List<Locale> locales = context.getAcceptableLanguages();
if (locales.isEmpty())
return Locale.US;
@@ -23,5 +23,5 @@
}
@Override
- public void dispose(Locale instance) {}
+ public void dispose (Locale instance) {}
}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/MapUtils.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/MapUtils.java
index 497519a..ec11de1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/MapUtils.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/MapUtils.java
@@ -28,7 +28,7 @@
if (multivaluedMap == null) {
return new HashMap<String, String>();
}
-
+
Set<String> keySet = multivaluedMap.keySet();
Map<String, String> map = new HashMap<String, String>(keySet.size());
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/NotFoundMapper.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/NotFoundMapper.java
index 20b6632..b20d124 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/NotFoundMapper.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/NotFoundMapper.java
@@ -32,8 +32,8 @@
public class NotFoundMapper implements ExceptionMapper<NotFoundException> {
private static Logger jlog = LogManager.getLogger(NotFoundMapper.class);
- public static final Pattern VERSION_PATTERN =
- Pattern.compile("/(v[0-9][^/]*)(/.*)");
+ public static final Pattern VERSION_PATTERN = Pattern
+ .compile("/(v[0-9][^/]*)(/.*)");
private static final boolean DEBUG = false;
@Autowired
@@ -44,10 +44,10 @@
@Override
public Response toResponse (NotFoundException exception) {
- ContainerRequestContext requestContext =
- resourceContext.getResource(ContainerRequestContext.class);
+ ContainerRequestContext requestContext = resourceContext
+ .getResource(ContainerRequestContext.class);
- URI notFoundUri = requestContext.getUriInfo().getRequestUri();
+ URI notFoundUri = requestContext.getUriInfo().getRequestUri();
String path = notFoundUri.getPath();
String baseUrl = config.getBaseURL();
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFilters.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFilters.java
index 94e5dc7..fa68084 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFilters.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFilters.java
@@ -6,14 +6,19 @@
import java.lang.annotation.Target;
/**
- * Defines the list of {@link jakarta.ws.rs.container.ContainerRequestFilter}
+ * Defines the list of
+ * {@link jakarta.ws.rs.container.ContainerRequestFilter}
* and {@link jakarta.ws.rs.container.ContainerResponseFilter}
* classes associated with a resource method.
* <p>
- * This annotation can be specified on a class or on method(s). Specifying it
- * at a class level means that it applies to all the methods in the class.
- * Specifying it on a method means that it is applicable to that method only.
- * If applied at both the class and methods level , the method value overrides
+ * This annotation can be specified on a class or on method(s).
+ * Specifying it
+ * at a class level means that it applies to all the methods in the
+ * class.
+ * Specifying it on a method means that it is applicable to that
+ * method only.
+ * If applied at both the class and methods level , the method value
+ * overrides
* the class value.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFiltersFeature.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFiltersFeature.java
index db728e7..9e4a0ce 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFiltersFeature.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/ResourceFiltersFeature.java
@@ -8,16 +8,19 @@
/**
* Registers {@link jakarta.ws.rs.container.ContainerRequestFilter}
* and {@link jakarta.ws.rs.container.ContainerResponseFilter}
- * classes for a resource method annotated with {@link ResourceFilters}.
+ * classes for a resource method annotated with
+ * {@link ResourceFilters}.
*/
@Provider
public class ResourceFiltersFeature implements DynamicFeature {
@Override
public void configure (ResourceInfo resourceInfo, FeatureContext context) {
- ResourceFilters filtersAnnotation = resourceInfo.getResourceMethod().getAnnotation(ResourceFilters.class);
+ ResourceFilters filtersAnnotation = resourceInfo.getResourceMethod()
+ .getAnnotation(ResourceFilters.class);
if (filtersAnnotation == null)
- filtersAnnotation = resourceInfo.getResourceClass().getAnnotation(ResourceFilters.class);
+ filtersAnnotation = resourceInfo.getResourceClass()
+ .getAnnotation(ResourceFilters.class);
if (filtersAnnotation != null) {
for (Class<?> filter : filtersAnnotation.value())
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFilters.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFilters.java
index 1505d0e..60b226a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFilters.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFilters.java
@@ -6,17 +6,21 @@
import java.lang.annotation.Target;
/**
- * Defines the list of {@link jakarta.ws.rs.container.ContainerRequestFilter}
+ * Defines the list of
+ * {@link jakarta.ws.rs.container.ContainerRequestFilter}
* and {@link jakarta.ws.rs.container.ContainerResponseFilter}
* classes associated with a resource method.
* <p>
- * This annotation can be specified on a class or on method(s). Specifying it
- * at a class level means that it applies to all the methods in the class.
- * Specifying it on a method means that it is applicable to that method only.
- * If applied at both the class and methods level , the method value overrides
+ * This annotation can be specified on a class or on method(s).
+ * Specifying it
+ * at a class level means that it applies to all the methods in the
+ * class.
+ * Specifying it on a method means that it is applicable to that
+ * method only.
+ * If applied at both the class and methods level , the method value
+ * overrides
* the class value.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
-public @interface SearchResourceFilters {
-}
+public @interface SearchResourceFilters {}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFiltersFeature.java b/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFiltersFeature.java
index 5c2e6e2..0b44ae8 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFiltersFeature.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/utils/SearchResourceFiltersFeature.java
@@ -16,7 +16,8 @@
/**
* Registers {@link jakarta.ws.rs.container.ContainerRequestFilter}
* and {@link jakarta.ws.rs.container.ContainerResponseFilter}
- * classes for a resource method annotated with {@link ResourceFilters}.
+ * classes for a resource method annotated with
+ * {@link ResourceFilters}.
*/
@Provider
@Component
@@ -24,7 +25,7 @@
@Value("${search.resource.filters:AuthenticationFilter,DemoUserFilter}")
private String[] resourceFilters;
-
+
@Override
public void configure (ResourceInfo resourceInfo, FeatureContext context) {
SearchResourceFilters filters = resourceInfo.getResourceMethod()
@@ -32,25 +33,26 @@
if (filters != null) {
CommonConfig con = (CommonConfig) context.getConfiguration();
con.getComponentBag().clear();
- }
+ }
else {
filters = resourceInfo.getResourceClass()
- .getAnnotation(SearchResourceFilters.class);
+ .getAnnotation(SearchResourceFilters.class);
}
-
+
if (filters != null) {
List<?> list = Arrays.asList(resourceFilters);
if (!list.contains("APIVersionFilter")) {
context.register(APIVersionFilter.class);
}
-
- for(String c : resourceFilters) {
- try {
- context.register(Class.forName("de.ids_mannheim.korap.web.filter." + c));
- }
- catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
+
+ for (String c : resourceFilters) {
+ try {
+ context.register(Class
+ .forName("de.ids_mannheim.korap.web.filter." + c));
+ }
+ catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ }
}
}
}
diff --git a/full/src/main/resources/basic-config.xml b/full/src/main/resources/basic-config.xml
index c8cfdaa..d882532 100644
--- a/full/src/main/resources/basic-config.xml
+++ b/full/src/main/resources/basic-config.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
@@ -15,7 +18,8 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <context:component-scan base-package="de.ids_mannheim.korap" />
+ <context:component-scan
+ base-package="de.ids_mannheim.korap" />
<context:annotation-config />
<bean id="props"
@@ -46,7 +50,8 @@
</property>
</bean>
- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
+ <bean id='cacheManager'
+ class='org.springframework.cache.ehcache.EhCacheCacheManager'
p:cacheManager-ref='ehcache' />
<bean id='ehcache'
@@ -55,9 +60,10 @@
<!--class="org.apache.commons.dbcp2.BasicDataSource" -->
<!-- org.springframework.jdbc.datasource.SingleConnectionDataSource -->
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <bean id="dataSource"
+ class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true">
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -74,7 +80,8 @@
<bean id="sqliteDataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -93,22 +100,26 @@
</bean>
<!-- to configure database for sqlite, mysql, etc. migrations -->
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
<property name="baselineOnMigrate" value="true" />
<!-- <property name="validateOnMigrate" value="false" /> -->
<!-- <property name="cleanOnValidationError" value="true" /> -->
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="dataSource" ref="sqliteDataSource" />
- <property name="outOfOrder" value="true"/>
+ <property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
- <bean id="kustvakt_db" class="de.ids_mannheim.korap.handlers.JDBCClient">
+ <bean id="kustvakt_db"
+ class="de.ids_mannheim.korap.handlers.JDBCClient">
<constructor-arg index="0" ref="dataSource" />
<!-- deprecated property -->
<property name="database" value="${jdbc.database}" />
@@ -129,7 +140,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -151,8 +163,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -162,70 +176,86 @@
<!-- Data access objects -->
<bean id="adminDao" class="de.ids_mannheim.korap.dao.AdminDaoImpl" />
- <bean id="authorizationDao" class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
+ <bean id="authorizationDao"
+ class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
<!-- Services -->
- <bean id="scopeService" class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
-
+ <bean id="scopeService"
+ class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
+
<!-- props are injected from default-config.xml -->
- <bean id="kustvakt_config" class="de.ids_mannheim.korap.config.FullConfiguration">
+ <bean id="kustvakt_config"
+ class="de.ids_mannheim.korap.config.FullConfiguration">
<constructor-arg name="properties" ref="props" />
</bean>
- <bean id="initializator" class="de.ids_mannheim.de.init.Initializator"
- init-method="init">
+ <bean id="initializator"
+ class="de.ids_mannheim.de.init.Initializator" init-method="init">
</bean>
-
+
<!-- Krill -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
- <!-- Validator -->
- <bean id="validator" class="de.ids_mannheim.korap.validator.ApacheValidator"/>
-
+ <!-- Validator -->
+ <bean id="validator"
+ class="de.ids_mannheim.korap.validator.ApacheValidator" />
+
<!-- URLValidator -->
- <bean id="redirectURIValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="redirectURIValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" index="0" />
<constructor-arg index="1" type="long">
<util:constant
static-field="org.apache.commons.validator.routines.UrlValidator.NO_FRAGMENTS" />
</constructor-arg>
</bean>
- <bean id="urlValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="urlValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" />
</bean>
-
+
<!-- Rewrite -->
- <bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
- <bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
- <bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
- <bean id="queryReferenceRewrite" class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite"/>
-
+ <bean id="foundryRewrite"
+ class="de.ids_mannheim.korap.rewrite.FoundryRewrite" />
+ <bean id="collectionRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionRewrite" />
+ <bean id="virtualCorpusRewrite"
+ class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite" />
+ <bean id="queryReferenceRewrite"
+ class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite" />
+
<util:list id="rewriteTasks"
value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
<ref bean="foundryRewrite" />
<ref bean="collectionRewrite" />
<ref bean="virtualCorpusRewrite" />
- <ref bean="queryReferenceRewrite" />
+ <ref bean="queryReferenceRewrite" />
</util:list>
-
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
- <constructor-arg ref="rewriteTasks"/>
+
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+ <constructor-arg ref="rewriteTasks" />
</bean>
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- OAuth -->
- <bean id="oauth2ResponseHandler" class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
+ <bean id="oauth2ResponseHandler"
+ class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
</bean>
- <bean id="kustvakt_userdb" class="de.ids_mannheim.korap.handlers.EntityDao">
+ <bean id="kustvakt_userdb"
+ class="de.ids_mannheim.korap.handlers.EntityDao">
<constructor-arg ref="kustvakt_db" />
</bean>
- <bean name="kustvakt_encryption" class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
+ <bean name="kustvakt_encryption"
+ class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
<constructor-arg ref="kustvakt_config" />
</bean>
@@ -234,8 +264,10 @@
<constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
ref="kustvakt_config" /> </bean> -->
- <bean id="ldap_auth" class="de.ids_mannheim.korap.authentication.LdapAuth3">
- <constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
+ <bean id="ldap_auth"
+ class="de.ids_mannheim.korap.authentication.LdapAuth3">
+ <constructor-arg
+ type="de.ids_mannheim.korap.config.KustvaktConfiguration"
ref="kustvakt_config" />
</bean>
@@ -245,32 +277,33 @@
<bean id="session_auth"
class="de.ids_mannheim.korap.authentication.SessionAuthentication">
- <constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
+ <constructor-arg
+ type="de.ids_mannheim.korap.config.KustvaktConfiguration"
ref="kustvakt_config" />
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
</bean>
<bean id="oauth2_auth"
class="de.ids_mannheim.korap.authentication.OAuth2Authentication" />
-
+
<util:list id="kustvakt_authproviders"
value-type="de.ids_mannheim.korap.interfaces.AuthenticationIface">
<ref bean="basic_auth" />
<ref bean="ldap_auth" />
- <!--
- <ref bean="session_auth" />
- <ref bean="api_auth" />
- -->
+ <!-- <ref bean="session_auth" /> <ref bean="api_auth" /> -->
<ref bean="oauth2_auth" />
</util:list>
- <bean id="userdata_details" class="de.ids_mannheim.korap.handlers.UserDetailsDao">
+ <bean id="userdata_details"
+ class="de.ids_mannheim.korap.handlers.UserDetailsDao">
<constructor-arg ref="kustvakt_db" />
</bean>
- <bean id="userdata_settings" class="de.ids_mannheim.korap.handlers.UserSettingsDao">
+ <bean id="userdata_settings"
+ class="de.ids_mannheim.korap.handlers.UserSettingsDao">
<constructor-arg ref="kustvakt_db" />
</bean>
@@ -283,16 +316,18 @@
<!-- specify type for constructor argument -->
<bean id="authenticationManager"
class="de.ids_mannheim.korap.authentication.KustvaktAuthenticationManager">
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EntityHandlerIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EntityHandlerIface"
ref="kustvakt_userdb" />
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
<constructor-arg ref="kustvakt_config" />
<constructor-arg ref="kustvakt_userdata" />
<!-- inject authentication providers to use -->
<property name="providers" ref="kustvakt_authproviders" />
</bean>
-
+
<!-- todo: if db interfaces not loaded via spring, does transaction even
work then? -->
<!-- the transactional advice (i.e. what 'happens'; see the <aop:advisor/>
@@ -301,7 +336,8 @@
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
- <tx:method name="get*" read-only="true" rollback-for="KorAPException" />
+ <tx:method name="get*" read-only="true"
+ rollback-for="KorAPException" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="KorAPException" />
</tx:attributes>
@@ -323,11 +359,13 @@
</bean>
<!-- mail -->
- <bean id="authenticator" class="de.ids_mannheim.korap.service.MailAuthenticator">
+ <bean id="authenticator"
+ class="de.ids_mannheim.korap.service.MailAuthenticator">
<constructor-arg index="0" value="${mail.username}" />
<constructor-arg index="1" value="${mail.password}" />
</bean>
- <bean id="smtpSession" class="jakarta.mail.Session" factory-method="getInstance">
+ <bean id="smtpSession" class="jakarta.mail.Session"
+ factory-method="getInstance">
<constructor-arg index="0">
<props>
<prop key="mail.smtp.submitter">${mail.username}</prop>
@@ -340,12 +378,14 @@
</constructor-arg>
<constructor-arg index="1" ref="authenticator" />
</bean>
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
+ <bean id="mailSender"
+ class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="session" ref="smtpSession" />
</bean>
- <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine">
+ <bean id="velocityEngine"
+ class="org.apache.velocity.app.VelocityEngine">
<constructor-arg index="0">
<props>
<prop key="resource.loader">class</prop>
diff --git a/full/src/main/resources/default-config.xml b/full/src/main/resources/default-config.xml
index 36925cb..073bf26 100644
--- a/full/src/main/resources/default-config.xml
+++ b/full/src/main/resources/default-config.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
@@ -15,7 +18,8 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
- <context:component-scan base-package="de.ids_mannheim.korap" />
+ <context:component-scan
+ base-package="de.ids_mannheim.korap" />
<context:annotation-config />
<bean id="props"
@@ -46,18 +50,15 @@
</property>
</bean>
- <!-- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
- p:cacheManager-ref='ehcache' />
-
- <bean id='ehcache'
- class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
- p:configLocation='classpath:ehcache.xml' p:shared='true' />
- -->
+ <!-- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
+ p:cacheManager-ref='ehcache' /> <bean id='ehcache' class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
+ p:configLocation='classpath:ehcache.xml' p:shared='true' /> -->
<!--class="org.apache.commons.dbcp2.BasicDataSource" -->
<!-- org.springframework.jdbc.datasource.SingleConnectionDataSource -->
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <bean id="dataSource"
+ class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true">
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -70,8 +71,9 @@
<property name="maxWaitMillis" value="-1" />
<!--<property name="poolPreparedStatements" value="true"/> -->
</bean>
-
- <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
+
+ <bean id="c3p0DataSource"
+ class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" lazy-init="true">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
@@ -88,7 +90,8 @@
<bean id="sqliteDataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -107,26 +110,29 @@
</bean>
<!-- to configure database for sqlite, mysql, etc. migrations -->
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
<property name="baselineOnMigrate" value="true" />
<!-- <property name="validateOnMigrate" value="false" /> -->
<!-- <property name="cleanOnValidationError" value="true" /> -->
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<property name="dataSource" ref="dataSource" />
<!-- <property name="dataSource" ref="sqliteDataSource" /> -->
<!-- <property name="dataSource" ref="c3p0DataSource" /> -->
<property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
depends-on="flyway">
<property name="dataSource" ref="dataSource" />
- <!-- <property name="dataSource" ref="sqliteDataSource" /> -->
+ <!-- <property name="dataSource" ref="sqliteDataSource" /> -->
<!-- <property name="dataSource" ref="c3p0DataSource" /> -->
<property name="packagesToScan">
@@ -139,7 +145,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -160,8 +167,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -171,94 +180,103 @@
<!-- Data access objects -->
<bean id="adminDao" class="de.ids_mannheim.korap.dao.AdminDaoImpl" />
- <bean id="authorizationDao" class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
+ <bean id="authorizationDao"
+ class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
<!-- Filters -->
- <!-- <bean id="authenticationFilter" class="de.ids_mannheim.korap.web.filter.AuthenticationFilter" >
- <property name="authenticationManager" ref="kustvakt_authenticationmanager"/>
- </bean>
- <bean id="piwikFilter" class="de.ids_mannheim.korap.web.filter.PiwikFilter" >
- <property name="authenticationManager" ref="kustvakt_authenticationmanager"/>
- </bean> -->
-
+ <!-- <bean id="authenticationFilter" class="de.ids_mannheim.korap.web.filter.AuthenticationFilter"
+ > <property name="authenticationManager" ref="kustvakt_authenticationmanager"/>
+ </bean> <bean id="piwikFilter" class="de.ids_mannheim.korap.web.filter.PiwikFilter"
+ > <property name="authenticationManager" ref="kustvakt_authenticationmanager"/>
+ </bean> -->
+
<!-- Services -->
- <bean id="scopeService" class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
-
+ <bean id="scopeService"
+ class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
+
<!-- props are injected from default-config.xml -->
- <bean id="kustvakt_config" class="de.ids_mannheim.korap.config.FullConfiguration">
+ <bean id="kustvakt_config"
+ class="de.ids_mannheim.korap.config.FullConfiguration">
<constructor-arg name="properties" ref="props" />
</bean>
- <bean id="initializator" class="de.ids_mannheim.korap.init.Initializator"
- init-method="init">
+ <bean id="initializator"
+ class="de.ids_mannheim.korap.init.Initializator" init-method="init">
</bean>
-
+
<!-- Krill -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
-
+
<!-- Validator -->
- <bean id="validator" class="de.ids_mannheim.korap.validator.ApacheValidator"/>
+ <bean id="validator"
+ class="de.ids_mannheim.korap.validator.ApacheValidator" />
<!-- URLValidator -->
- <bean id="redirectURIValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="redirectURIValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" index="0" />
- <constructor-arg index="1" type="long"
- value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
- T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}"/>
-
- <!-- <constructor-arg index="1" type="long">
- <util:constant
- static-field="org.apache.commons.validator.routines.UrlValidator.NO_FRAGMENTS" />
- </constructor-arg> -->
+ <constructor-arg index="1" type="long"
+ value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
+ T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}" />
+
+ <!-- <constructor-arg index="1" type="long"> <util:constant static-field="org.apache.commons.validator.routines.UrlValidator.NO_FRAGMENTS"
+ /> </constructor-arg> -->
</bean>
- <bean id="urlValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="urlValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" />
</bean>
-
+
<!-- Rewrite -->
- <bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
- <bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
- <bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
- <bean id="queryReferenceRewrite" class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite"/>
-
+ <bean id="foundryRewrite"
+ class="de.ids_mannheim.korap.rewrite.FoundryRewrite" />
+ <bean id="collectionRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionRewrite" />
+ <bean id="virtualCorpusRewrite"
+ class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite" />
+ <bean id="queryReferenceRewrite"
+ class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite" />
+
<util:list id="rewriteTasks"
value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
<ref bean="foundryRewrite" />
<ref bean="collectionRewrite" />
<ref bean="virtualCorpusRewrite" />
- <ref bean="queryReferenceRewrite" />
+ <ref bean="queryReferenceRewrite" />
</util:list>
-
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
- <constructor-arg ref="rewriteTasks"/>
+
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+ <constructor-arg ref="rewriteTasks" />
</bean>
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- OAuth -->
- <bean id="oauth2ResponseHandler" class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
+ <bean id="oauth2ResponseHandler"
+ class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
</bean>
- <bean name="kustvakt_encryption" class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
+ <bean name="kustvakt_encryption"
+ class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
<constructor-arg ref="kustvakt_config" />
</bean>
<!-- authentication providers to use -->
- <!-- <bean id="session_auth"
- class="de.ids_mannheim.korap.authentication.SessionAuthentication">
- <constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
- ref="kustvakt_config" />
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
- ref="kustvakt_encryption" />
- </bean> -->
+ <!-- <bean id="session_auth" class="de.ids_mannheim.korap.authentication.SessionAuthentication">
+ <constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
+ ref="kustvakt_config" /> <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ ref="kustvakt_encryption" /> </bean> -->
<bean id="oauth2_auth"
class="de.ids_mannheim.korap.authentication.OAuth2Authentication" />
-
+
<util:list id="kustvakt_authproviders"
value-type="de.ids_mannheim.korap.interfaces.AuthenticationIface">
<!-- <ref bean="session_auth" /> -->
@@ -269,13 +287,14 @@
<!-- specify type for constructor argument -->
<bean id="authenticationManager"
class="de.ids_mannheim.korap.authentication.KustvaktAuthenticationManager">
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
<constructor-arg ref="kustvakt_config" />
<!-- inject authentication providers to use -->
<property name="providers" ref="kustvakt_authproviders" />
</bean>
-
+
<!-- todo: if db interfaces not loaded via spring, does transaction even
work then? -->
<!-- the transactional advice (i.e. what 'happens'; see the <aop:advisor/>
@@ -284,7 +303,8 @@
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
- <tx:method name="get*" read-only="true" rollback-for="KorAPException" />
+ <tx:method name="get*" read-only="true"
+ rollback-for="KorAPException" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="KorAPException" />
</tx:attributes>
@@ -307,11 +327,13 @@
</bean>
<!-- mail -->
- <bean id="authenticator" class="de.ids_mannheim.korap.service.MailAuthenticator">
+ <bean id="authenticator"
+ class="de.ids_mannheim.korap.service.MailAuthenticator">
<constructor-arg index="0" value="${mail.username}" />
<constructor-arg index="1" value="${mail.password}" />
</bean>
- <bean id="smtpSession" class="jakarta.mail.Session" factory-method="getInstance">
+ <bean id="smtpSession" class="jakarta.mail.Session"
+ factory-method="getInstance">
<constructor-arg index="0">
<props>
<prop key="mail.smtp.submitter">${mail.username}</prop>
@@ -324,12 +346,14 @@
</constructor-arg>
<constructor-arg index="1" ref="authenticator" />
</bean>
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
+ <bean id="mailSender"
+ class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="session" ref="smtpSession" />
</bean>
- <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine">
+ <bean id="velocityEngine"
+ class="org.apache.velocity.app.VelocityEngine">
<constructor-arg index="0">
<props>
<prop key="resource.loader">class</prop>
diff --git a/full/src/main/resources/default-lite-config.xml b/full/src/main/resources/default-lite-config.xml
index 8069c8e..da27995 100644
--- a/full/src/main/resources/default-lite-config.xml
+++ b/full/src/main/resources/default-lite-config.xml
@@ -1,7 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
@@ -11,7 +13,8 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
- <context:component-scan base-package="
+ <context:component-scan
+ base-package="
de.ids_mannheim.korap.core.service,
de.ids_mannheim.korap.core.web,
de.ids_mannheim.korap.web.filter,
@@ -44,8 +47,10 @@
</property>
</bean>
- <bean id="config" class="de.ids_mannheim.korap.config.KustvaktConfiguration">
- <constructor-arg index="0" name="properties" ref="properties" />
+ <bean id="config"
+ class="de.ids_mannheim.korap.config.KustvaktConfiguration">
+ <constructor-arg index="0" name="properties"
+ ref="properties" />
</bean>
<!-- Database -->
@@ -53,7 +58,8 @@
<bean id="sqliteDataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -70,19 +76,22 @@
<!--<property name="initialSize" value="2"/> -->
<!--<property name="poolPreparedStatements" value="true"/> -->
</bean>
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
<property name="baselineOnMigrate" value="true" />
<!-- <property name="validateOnMigrate" value="false" /> -->
<!-- <property name="cleanOnValidationError" value="true" /> -->
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<property name="dataSource" ref="sqliteDataSource" />
<property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
-
+
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
@@ -96,7 +105,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -116,8 +126,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -130,18 +142,17 @@
</bean>
<!-- Initialization -->
- <!--
- <bean id="annotationParser" class="de.ids_mannheim.korap.annotation.AnnotationParser"
- scope="singleton" />
- -->
+ <!-- <bean id="annotationParser" class="de.ids_mannheim.korap.annotation.AnnotationParser"
+ scope="singleton" /> -->
<!-- Search Engine -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
-
+
<!-- Filters -->
- <!-- <bean id="APIVersionFilter" class="de.ids_mannheim.korap.web.APIVersionFilter"
+ <!-- <bean id="APIVersionFilter" class="de.ids_mannheim.korap.web.APIVersionFilter"
scope="singleton" /> -->
<!-- Authentication -->
@@ -149,37 +160,42 @@
class="de.ids_mannheim.korap.authentication.DummyAuthenticationManager" />
<!-- Response handler -->
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- Controllers -->
- <!-- added via component-scan
- <bean id="annotationController"
- class="de.ids_mannheim.korap.web.controller.AnnotationController" />
- <bean id="searchController" class="de.ids_mannheim.korap.web.controller.SearchController" />
- <bean id="statisticController"
- class="de.ids_mannheim.korap.web.controller.StatisticController" />
- -->
+ <!-- added via component-scan <bean id="annotationController" class="de.ids_mannheim.korap.web.controller.AnnotationController"
+ /> <bean id="searchController" class="de.ids_mannheim.korap.web.controller.SearchController"
+ /> <bean id="statisticController" class="de.ids_mannheim.korap.web.controller.StatisticController"
+ /> -->
<!-- Services -->
<bean id="scopeService"
class="de.ids_mannheim.korap.oauth2.service.DummyOAuth2ScopeServiceImpl" />
<!-- DAO -->
- <bean id="adminDao" class="de.ids_mannheim.korap.dao.DummyAdminDaoImpl" />
- <bean id="annotationDao" class="de.ids_mannheim.korap.dao.AnnotationDao" />
+ <bean id="adminDao"
+ class="de.ids_mannheim.korap.dao.DummyAdminDaoImpl" />
+ <bean id="annotationDao"
+ class="de.ids_mannheim.korap.dao.AnnotationDao" />
<!-- DTO Converter -->
- <bean id="annotationConverter" class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
+ <bean id="annotationConverter"
+ class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
<!-- Rewrite -->
- <bean id="layerMapper" class="de.ids_mannheim.korap.rewrite.LayerMapper" />
- <bean id="foundryInject" class="de.ids_mannheim.korap.rewrite.FoundryInject" />
+ <bean id="layerMapper"
+ class="de.ids_mannheim.korap.rewrite.LayerMapper" />
+ <bean id="foundryInject"
+ class="de.ids_mannheim.korap.rewrite.FoundryInject" />
- <util:list id="rewriteTasks" value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+ <util:list id="rewriteTasks"
+ value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
<ref bean="foundryInject" />
</util:list>
-
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
<constructor-arg ref="rewriteTasks" />
</bean>
</beans>
\ No newline at end of file
diff --git a/full/src/main/resources/ehcache.xml b/full/src/main/resources/ehcache.xml
index 22f2f55..077e260 100644
--- a/full/src/main/resources/ehcache.xml
+++ b/full/src/main/resources/ehcache.xml
@@ -1,43 +1,29 @@
-<ehcache xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
+<ehcache
+ xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
updateCheck="true" monitoring="autodetect" dynamicConfig="true">
-
- <defaultCache eternal='true' overflowToDisk='false'/>
- <!--maxBytesLocalHeap="200M"-->
- <diskStore path="./cache_store"/>
-
-
- <!-- EM -->
- <cache name='authorization'
- timeToLiveSeconds="1000"
- eternal='false'
- memoryStoreEvictionPolicy="LRU"
- maxEntriesLocalHeap="100"
- overflowToDisk='false'/>
-
- <cache name='access_token'
- timeToIdleSeconds="3600"
- timeToLiveSeconds="15000"
- eternal='false'
- memoryStoreEvictionPolicy="LRU"
- maxEntriesLocalHeap="500"
- overflowToDisk='false'/>
-
- <!-- <cache name="named_vc"
- eternal="true"
- memoryStoreEvictionPolicy="LRU"
- maxBytesLocalHeap="256M"
- maxBytesLocalDisk="2G"
- diskExpiryThreadIntervalSeconds = "120" >
- <persistence strategy="localTempSwap"/>
- <sizeOfPolicy maxDepth="3000" maxDepthExceededBehavior="abort" />
- -->
-
- <cache name="total_results"
- timeToIdleSeconds="3600"
- timeToLiveSeconds="15000"
- eternal='false'
- memoryStoreEvictionPolicy="LRU"
- overflowToDisk='false'
- maxEntriesLocalHeap="500"
- />
+
+ <defaultCache eternal='true' overflowToDisk='false' />
+ <!--maxBytesLocalHeap="200M" -->
+ <diskStore path="./cache_store" />
+
+
+ <!-- EM -->
+ <cache name='authorization' timeToLiveSeconds="1000"
+ eternal='false' memoryStoreEvictionPolicy="LRU"
+ maxEntriesLocalHeap="100" overflowToDisk='false' />
+
+ <cache name='access_token' timeToIdleSeconds="3600"
+ timeToLiveSeconds="15000" eternal='false'
+ memoryStoreEvictionPolicy="LRU" maxEntriesLocalHeap="500"
+ overflowToDisk='false' />
+
+ <!-- <cache name="named_vc" eternal="true" memoryStoreEvictionPolicy="LRU"
+ maxBytesLocalHeap="256M" maxBytesLocalDisk="2G" diskExpiryThreadIntervalSeconds
+ = "120" > <persistence strategy="localTempSwap"/> <sizeOfPolicy maxDepth="3000"
+ maxDepthExceededBehavior="abort" /> -->
+
+ <cache name="total_results" timeToIdleSeconds="3600"
+ timeToLiveSeconds="15000" eternal='false'
+ memoryStoreEvictionPolicy="LRU" overflowToDisk='false'
+ maxEntriesLocalHeap="500" />
</ehcache>
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
index 3c8f808..eeb3ea6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
@@ -34,9 +34,13 @@
private FullConfiguration config;
@Test
- public void testDeprecatedService() throws KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
- Response response = target().path(API_VERSION).path("auth").path("apiToken").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testDeprecatedService () throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
+ Response response = target().path(API_VERSION).path("auth")
+ .path("apiToken").request()
+ .header(Attributes.AUTHORIZATION, userAuthHeader)
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -44,7 +48,8 @@
}
@Test
- public void testCreateGetTokenContext() throws KustvaktException, IOException, InterruptedException, JOSEException {
+ public void testCreateGetTokenContext () throws KustvaktException,
+ IOException, InterruptedException, JOSEException {
User user = new KorAPUser();
user.setUsername("testUser");
Map<String, Object> attr = new HashMap<>();
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
index 892219b..9e6f120 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
@@ -14,12 +14,16 @@
public class AuthenticationFilterTest extends SpringJerseyTest {
@Test
- public void testAuthenticationWithUnknownScheme() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, "Blah blah").get();
+ public void testAuthenticationWithUnknownScheme ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request().header(Attributes.AUTHORIZATION, "Blah blah").get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
assertEquals(n.at("/errors/0/0").asText(), "2001");
- assertEquals(n.at("/errors/0/1").asText(), "Authentication scheme is not supported.");
+ assertEquals(n.at("/errors/0/1").asText(),
+ "Authentication scheme is not supported.");
assertEquals(n.at("/errors/0/2").asText(), "Blah");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
index f7c8a86..0580bba 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
@@ -19,7 +19,6 @@
import static de.ids_mannheim.korap.authentication.LdapAuth3.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
-
public class LdapAuth3Test {
public static final String TEST_LDAP_CONF = "src/test/resources/test-ldap.conf";
@@ -35,11 +34,17 @@
static InMemoryDirectoryServer server;
@BeforeAll
- static void startDirectoryServer() throws LDAPException, GeneralSecurityException {
- InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=example,dc=com");
- config.addAdditionalBindCredentials("cn=admin,dc=example,dc=com", "adminpassword");
+ static void startDirectoryServer ()
+ throws LDAPException, GeneralSecurityException {
+ InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(
+ "dc=example,dc=com");
+ config.addAdditionalBindCredentials("cn=admin,dc=example,dc=com",
+ "adminpassword");
config.setSchema(null);
- final SSLUtil serverSSLUtil = new SSLUtil(new KeyStoreKeyManager(keyStorePath, "password".toCharArray(), "PKCS12", "server-cert"), new TrustStoreTrustManager(keyStorePath));
+ final SSLUtil serverSSLUtil = new SSLUtil(
+ new KeyStoreKeyManager(keyStorePath, "password".toCharArray(),
+ "PKCS12", "server-cert"),
+ new TrustStoreTrustManager(keyStorePath));
final SSLUtil clientSslUtil = new SSLUtil(new TrustAllTrustManager());
config.setListenerConfigs(// Listener name
InMemoryListenerConfig.createLDAPConfig(// Listener name
@@ -50,7 +55,8 @@
InMemoryListenerConfig.createLDAPSConfig(// Listener name
"LDAPS", // Listen address. (null = listen on all interfaces)
null, // Listen port (0 = automatically choose an available port)
- 3269, serverSSLUtil.createSSLServerSocketFactory(), clientSslUtil.createSSLSocketFactory()));
+ 3269, serverSSLUtil.createSSLServerSocketFactory(),
+ clientSslUtil.createSSLSocketFactory()));
server = new InMemoryDirectoryServer(config);
String configPath = TEST_LDAP_USERS_LDIF;
server.importFromLDIF(true, configPath);
@@ -58,130 +64,167 @@
}
@AfterAll
- static void shutDownDirectoryServer() {
+ static void shutDownDirectoryServer () {
server.shutDown(true);
}
@Test
- public void loginWithExtraProfileNameWorks() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser123", "password", TEST_LDAP_CONF));
+ public void loginWithExtraProfileNameWorks () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser123", "password", TEST_LDAP_CONF));
}
@Test
- public void loginWithUidWorks() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", "password", TEST_LDAP_CONF));
+ public void loginWithUidWorks () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", "password", TEST_LDAP_CONF));
}
@Test
- public void loginWithUidAndBase64PasswordWorks() throws LDAPException {
+ public void loginWithUidAndBase64PasswordWorks () throws LDAPException {
final byte[] passwordBytes = StaticUtils.getBytes("password");
String pw = Base64.encode(passwordBytes);
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", pw, TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", pw, TEST_LDAP_CONF));
}
@Test
- public void loginWithEmailWorks() throws LDAPException {
+ public void loginWithEmailWorks () throws LDAPException {
final byte[] passwordBytes = StaticUtils.getBytes("password");
String pw = Base64.encode(passwordBytes);
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser@example.com", pw, TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser@example.com", pw, TEST_LDAP_CONF));
}
@Test
- public void allLoginPasswordCombinationsWork() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("uid", "userPassword", TEST_LDAP_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("uid", "extraPassword", TEST_LDAP_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("mail@example.org", "userPassword", TEST_LDAP_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("mail@example.org", "extraPassword", TEST_LDAP_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("extraProfile", "userPassword", TEST_LDAP_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("extraProfile", "extraPassword", TEST_LDAP_CONF));
+ public void allLoginPasswordCombinationsWork () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("uid", "userPassword", TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("uid", "extraPassword", TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("mail@example.org",
+ "userPassword", TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("mail@example.org",
+ "extraPassword", TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("extraProfile",
+ "userPassword", TEST_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("extraProfile",
+ "extraPassword", TEST_LDAP_CONF));
}
@Test
- public void loginWithWrongEmailFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("notestuser@example.com", "topsecret", TEST_LDAP_CONF));
+ public void loginWithWrongEmailFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3
+ .login("notestuser@example.com", "topsecret", TEST_LDAP_CONF));
}
@Test
- public void loginWithEmailAndWrongPasswordFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser@example.com", "wrongpw", TEST_LDAP_CONF));
+ public void loginWithEmailAndWrongPasswordFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser@example.com",
+ "wrongpw", TEST_LDAP_CONF));
}
@Test
- public void loginWithUsernameAndWrongPasswordFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser", "wrongpw", TEST_LDAP_CONF));
+ public void loginWithUsernameAndWrongPasswordFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("testuser", "wrongpw", TEST_LDAP_CONF));
}
@Test
- public void loginOfNotRegisteredUserFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RNOTREG, LdapAuth3.login("not_registered_user", "topsecret", TEST_LDAP_CONF));
+ public void loginOfNotRegisteredUserFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RNOTREG, LdapAuth3.login("not_registered_user",
+ "topsecret", TEST_LDAP_CONF));
}
@Test
- public void blockedUserIsRefused() throws LDAPException {
- assertEquals(LDAP_AUTH_RLOCKED, LdapAuth3.login("nameOfBlockedUser", "topsecret", TEST_LDAP_CONF));
+ public void blockedUserIsRefused () throws LDAPException {
+ assertEquals(LDAP_AUTH_RLOCKED, LdapAuth3.login("nameOfBlockedUser",
+ "topsecret", TEST_LDAP_CONF));
}
@Test
- public void loginWithUsernameOverSSLWorks() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", "password", TEST_LDAPS_CONF));
+ public void loginWithUsernameOverSSLWorks () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", "password", TEST_LDAPS_CONF));
}
@Test
- public void loginOnTrustedServerWorks() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
+ public void loginOnTrustedServerWorks () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
}
@Test
- public void loginOnTrustedServerWithWrongPassswordFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser", "topsecrets", TEST_LDAPS_TS_CONF));
+ public void loginOnTrustedServerWithWrongPassswordFails ()
+ throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("testuser", "topsecrets", TEST_LDAPS_TS_CONF));
}
@Test
- public void passwordWithAsteriskWorks() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("test", "top*ecret", TEST_LDAPS_CONF));
+ public void passwordWithAsteriskWorks () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("test", "top*ecret", TEST_LDAPS_CONF));
}
@Test
- public void passwordWithGlobOperatorFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser", "passw*", TEST_LDAPS_TS_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
+ public void passwordWithGlobOperatorFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("testuser", "passw*", TEST_LDAPS_TS_CONF));
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
}
@Test
- public void passwordWithExistenceOperatorFails() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("testuser", "*", TEST_LDAPS_TS_CONF));
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
+ public void passwordWithExistenceOperatorFails () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("testuser", "*", TEST_LDAPS_TS_CONF));
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("testuser", "password", TEST_LDAPS_TS_CONF));
}
@Test
- public void gettingMailAttributeForUid() throws LDAPException {
- assertEquals(LdapAuth3.getEmail("testuser", TEST_LDAP_CONF), "testuser@example.com");
- assertEquals(LdapAuth3.getEmail("testuser2", TEST_LDAPS_CONF), "peter@example.org");
+ public void gettingMailAttributeForUid () throws LDAPException {
+ assertEquals(LdapAuth3.getEmail("testuser", TEST_LDAP_CONF),
+ "testuser@example.com");
+ assertEquals(LdapAuth3.getEmail("testuser2", TEST_LDAPS_CONF),
+ "peter@example.org");
assertEquals(null, LdapAuth3.getEmail("non-exsting", TEST_LDAPS_CONF));
}
@Test
- public void gettingUsernameForEmail() throws LDAPException {
- assertEquals(LdapAuth3.getUsername("testuser@example.com", TEST_LDAP_CONF), "idsTestUser");
- assertEquals(LdapAuth3.getUsername("peter@example.org", TEST_LDAPS_CONF), "testuser2");
- assertEquals(null, LdapAuth3.getUsername("non-exsting", TEST_LDAPS_CONF));
- assertEquals(LdapAuth3.getUsername("testUser2", TEST_LDAPS_CONF), "testuser2");
+ public void gettingUsernameForEmail () throws LDAPException {
+ assertEquals(
+ LdapAuth3.getUsername("testuser@example.com", TEST_LDAP_CONF),
+ "idsTestUser");
+ assertEquals(
+ LdapAuth3.getUsername("peter@example.org", TEST_LDAPS_CONF),
+ "testuser2");
+ assertEquals(null,
+ LdapAuth3.getUsername("non-exsting", TEST_LDAPS_CONF));
+ assertEquals(LdapAuth3.getUsername("testUser2", TEST_LDAPS_CONF),
+ "testuser2");
// login with uid, get idsC2Profile username
- assertEquals(LdapAuth3.getUsername("testUser", TEST_LDAPS_CONF), "idsTestUser");
+ assertEquals(LdapAuth3.getUsername("testUser", TEST_LDAPS_CONF),
+ "idsTestUser");
}
@Test
- public void gettingMailAttributeForNotRegisteredUserWorks() throws LDAPException {
- assertEquals(LdapAuth3.getEmail("not_registered_user", TEST_LDAP_CONF), "not_registered_user@example.com");
+ public void gettingMailAttributeForNotRegisteredUserWorks ()
+ throws LDAPException {
+ assertEquals(LdapAuth3.getEmail("not_registered_user", TEST_LDAP_CONF),
+ "not_registered_user@example.com");
}
@Test
- public void gettingMailAttributeForBlockedUserWorks() throws LDAPException {
- assertEquals(LdapAuth3.getEmail("nameOfBlockedUser", TEST_LDAP_CONF), "nameOfBlockedUser@example.com");
+ public void gettingMailAttributeForBlockedUserWorks ()
+ throws LDAPException {
+ assertEquals(LdapAuth3.getEmail("nameOfBlockedUser", TEST_LDAP_CONF),
+ "nameOfBlockedUser@example.com");
}
@Test
- public void canLoadLdapConfig() {
+ public void canLoadLdapConfig () {
LDAPConfig ldapConfig = new LDAPConfig(TEST_LDAPS_CONF);
assertEquals(3269, ldapConfig.port);
assertEquals(ldapConfig.host, "localhost");
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
index fd59d79..c45cc37 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
@@ -56,38 +56,43 @@
private String redirectUri = "https://client.com/redirect";
@BeforeAll
- static void startTestLDAPServer() throws LDAPException, GeneralSecurityException {
+ static void startTestLDAPServer ()
+ throws LDAPException, GeneralSecurityException {
LdapAuth3Test.startDirectoryServer();
}
@AfterAll
- static void stopTestLDAPServer() {
+ static void stopTestLDAPServer () {
LdapAuth3Test.shutDownDirectoryServer();
}
@BeforeEach
- public void setLDAPAuthentication() {
+ public void setLDAPAuthentication () {
config.setOAuth2passwordAuthentication(AuthenticationMethod.LDAP);
}
@AfterEach
- public void resetAuthenticationMethod() {
+ public void resetAuthenticationMethod () {
config.setOAuth2passwordAuthentication(AuthenticationMethod.TEST);
}
@Test
- public void testRequestTokenPasswordUnknownUser() throws KustvaktException {
- Response response = requestTokenWithPassword(superClientId, clientSecret, "unknown", "password");
+ public void testRequestTokenPasswordUnknownUser ()
+ throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId,
+ clientSecret, "unknown", "password");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2023, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "LDAP Authentication failed due to unknown user or password!");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "LDAP Authentication failed due to unknown user or password!");
}
@Test
- public void testMapEmailToUsername() throws KustvaktException {
- Response response = requestTokenWithPassword(superClientId, clientSecret, testUserEmail, "password");
+ public void testMapEmailToUsername () throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId,
+ clientSecret, testUserEmail, "password");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String accessToken = node.at("/access_token").asText();
@@ -102,29 +107,39 @@
String clientSecret = node.at("/client_secret").asText();
testRequestTokenWithAuthorization(clientId, clientSecret, accessToken);
}
-
+
private void testRegisterPublicClient (String accessToken)
throws KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("LDAP test client");
json.setType(OAuth2ClientType.PUBLIC);
- json.setDescription("Test registering a public client with LDAP authentication");
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
+ json.setDescription(
+ "Test registering a public client with LDAP authentication");
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("register").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .post(Entity.json(json));
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String clientId = node.at("/client_id").asText();
OAuth2Client client = clientDao.retrieveClientById(clientId);
assertEquals(testUsername, client.getRegisteredBy());
}
-
+
private JsonNode testRegisterConfidentialClient (String accessToken)
throws KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("LDAP test client");
json.setType(OAuth2ClientType.CONFIDENTIAL);
json.setRedirectURI(redirectUri);
- json.setDescription("Test registering a confidential client with LDAP authentication");
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
+ json.setDescription(
+ "Test registering a confidential client with LDAP authentication");
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("register").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .post(Entity.json(json));
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String clientId = node.at("/client_id").asText();
@@ -133,14 +148,23 @@
return node;
}
- private void testRequestTokenWithAuthorization(String clientId, String clientSecret, String accessToken) throws KustvaktException {
+ private void testRequestTokenWithAuthorization (String clientId,
+ String clientSecret, String accessToken) throws KustvaktException {
String authHeader = "Bearer " + accessToken;
- Response response = target().path(API_VERSION).path("oauth2").path("authorize").queryParam("response_type", "code").queryParam("client_id", clientId).queryParam("client_secret", clientSecret).queryParam("scope", "search match_info").request().header(Attributes.AUTHORIZATION, authHeader).get();
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("authorize").queryParam("response_type", "code")
+ .queryParam("client_id", clientId)
+ .queryParam("client_secret", clientSecret)
+ .queryParam("scope", "search match_info").request()
+ .header(Attributes.AUTHORIZATION, authHeader).get();
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
+ response.getStatus());
URI redirectUri = response.getLocation();
- MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder
+ .fromUri(redirectUri).build().getQueryParams();
String code = params.getFirst("code");
- response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String at = node.at("/access_token").asText();
AccessToken accessTokenObj = accessDao.retrieveAccessToken(at);
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
index a3694f0..9ffe776 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
@@ -17,14 +17,16 @@
private RandomCodeGenerator random;
@Test
- public void testRandomGenerator() throws NoSuchAlgorithmException, KustvaktException {
+ public void testRandomGenerator ()
+ throws NoSuchAlgorithmException, KustvaktException {
String value = random.createRandomCode();
assertEquals(22, value.length());
// System.out.println(value);
}
@Disabled
- public void testRandomGeneratorPerformance() throws NoSuchAlgorithmException, KustvaktException {
+ public void testRandomGeneratorPerformance ()
+ throws NoSuchAlgorithmException, KustvaktException {
long min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
String code;
while (true) {
@@ -39,7 +41,8 @@
min = duration;
else if (duration > max)
max = duration;
- System.out.println("d : " + duration + " min :" + min + ", max: " + max);
+ System.out.println(
+ "d : " + duration + " min :" + min + ", max: " + max);
}
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java b/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
index 8d3d275..7b7db2f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
@@ -27,7 +27,8 @@
private QueryDao dao;
@Test
- public void testNamedVCLoader() throws IOException, QueryException, KustvaktException {
+ public void testNamedVCLoader ()
+ throws IOException, QueryException, KustvaktException {
String vcId = "named-vc1";
vcLoader.loadVCToCache(vcId, "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains(vcId));
diff --git a/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java b/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
index 5beb40b..819f7a3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
@@ -3,7 +3,6 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.JsonNode;
@@ -18,15 +17,15 @@
@Autowired
private SearchService searchService;
-
+
@Test
public void testClearCache () {
for (int i = 1; i < 10; i++) {
searchService.getTotalResultCache().storeInCache(i, "10");
}
-
+
searchService.getTotalResultCache().clearCache();
-
+
assertEquals(0, searchService.getTotalResultCache()
.getAllCacheElements().size());
}
@@ -34,48 +33,77 @@
@Test
public void testSearchWithPaging () throws KustvaktException {
searchService.getTotalResultCache().clearCache();
-
+
assertEquals(0, searchService.getTotalResultCache()
.getAllCacheElements().size());
-
+
Response response = target().path(API_VERSION).path("search")
.queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
.queryParam("page", "1").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertTrue(node.at("/meta/totalResults").isNumber(), "totalResults should be a number");
+ assertTrue(node.at("/meta/totalResults").isNumber(),
+ "totalResults should be a number");
int totalResults = node.at("/meta/totalResults").asInt();
- assertEquals(1, searchService.getTotalResultCache().getAllCacheElements().size());
- response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "2").request().get();
+ assertEquals(1, searchService.getTotalResultCache()
+ .getAllCacheElements().size());
+ response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("page", "2").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertTrue(node.at("/meta/totalResults").isNumber(), "totalResults should be a number");
+ assertTrue(node.at("/meta/totalResults").isNumber(),
+ "totalResults should be a number");
assertEquals(totalResults, node.at("/meta/totalResults").asInt());
- assertEquals(1, searchService.getTotalResultCache().getAllCacheElements().size());
+ assertEquals(1, searchService.getTotalResultCache()
+ .getAllCacheElements().size());
assertTrue(node.at("/meta/cutOff").isMissingNode());
testSearchWithCutOff();
}
@Test
- public void testSearchWithCutOffTrue() throws KustvaktException {
- int cacheSize = searchService.getTotalResultCache().getAllCacheElements().size();
- Response response = target().path(API_VERSION).path("search").queryParam("q", "ich").queryParam("ql", "poliqarp").queryParam("page", "2").queryParam("cutoff", "true").request().get();
+ public void testSearchWithCutOffTrue () throws KustvaktException {
+ int cacheSize = searchService.getTotalResultCache()
+ .getAllCacheElements().size();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "ich").queryParam("ql", "poliqarp")
+ .queryParam("page", "2").queryParam("cutoff", "true").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- String query = "{\"meta\":{\"startPage\":2,\"tokens\":false,\"cutOff\":" + "true,\"snippets\":true,\"timeout\":10000},\"query\":{\"@type\":" + "\"koral:token\",\"wrap\":{\"@type\":\"koral:term\",\"match\":" + "\"match:eq\",\"layer\":\"orth\",\"key\":\"ich\",\"foundry\":" + "\"opennlp\",\"rewrites\":[{\"@type\":\"koral:rewrite\",\"src\":" + "\"Kustvakt\",\"operation\":\"operation:injection\",\"scope\":" + "\"foundry\"}]}},\"@context\":\"http://korap.ids-mannheim.de/ns" + "/koral/0.3/context.jsonld\",\"collection\":{\"@type\":\"koral:" + "doc\",\"match\":\"match:eq\",\"type\":\"type:regex\",\"value\":" + "\"CC-BY.*\",\"key\":\"availability\",\"rewrites\":[{\"@type\":" + "\"koral:rewrite\",\"src\":\"Kustvakt\",\"operation\":\"operation:" + "insertion\",\"scope\":\"availability(FREE)\"}]}}";
+ String query = "{\"meta\":{\"startPage\":2,\"tokens\":false,\"cutOff\":"
+ + "true,\"snippets\":true,\"timeout\":10000},\"query\":{\"@type\":"
+ + "\"koral:token\",\"wrap\":{\"@type\":\"koral:term\",\"match\":"
+ + "\"match:eq\",\"layer\":\"orth\",\"key\":\"ich\",\"foundry\":"
+ + "\"opennlp\",\"rewrites\":[{\"@type\":\"koral:rewrite\",\"src\":"
+ + "\"Kustvakt\",\"operation\":\"operation:injection\",\"scope\":"
+ + "\"foundry\"}]}},\"@context\":\"http://korap.ids-mannheim.de/ns"
+ + "/koral/0.3/context.jsonld\",\"collection\":{\"@type\":\"koral:"
+ + "doc\",\"match\":\"match:eq\",\"type\":\"type:regex\",\"value\":"
+ + "\"CC-BY.*\",\"key\":\"availability\",\"rewrites\":[{\"@type\":"
+ + "\"koral:rewrite\",\"src\":\"Kustvakt\",\"operation\":\"operation:"
+ + "insertion\",\"scope\":\"availability(FREE)\"}]}}";
int cacheKey = searchService.createTotalResultCacheKey(query);
- assertEquals(null, searchService.getTotalResultCache().getCacheValue(cacheKey));
- assertEquals(cacheSize, searchService.getTotalResultCache().getAllCacheElements().size());
+ assertEquals(null,
+ searchService.getTotalResultCache().getCacheValue(cacheKey));
+ assertEquals(cacheSize, searchService.getTotalResultCache()
+ .getAllCacheElements().size());
}
- private void testSearchWithCutOff() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "3").queryParam("cutoff", "false").request().get();
+ private void testSearchWithCutOff () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("page", "3").queryParam("cutoff", "false").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/meta/cutOff").isMissingNode());
- response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "4").queryParam("cutoff", "true").request().get();
+ response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("page", "4").queryParam("cutoff", "true").request()
+ .get();
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
assertTrue(node.at("/meta/cutOff").asBoolean());
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java b/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
index 98fa24b..80b00a5 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
@@ -25,16 +25,21 @@
@Autowired
protected GenericApplicationContext applicationContext;
- public static String[] classPackages = new String[]{"de.ids_mannheim.korap.core.web", "de.ids_mannheim.korap.web.filter", "de.ids_mannheim.korap.web.utils", "de.ids_mannheim.korap.test", "com.fasterxml.jackson.jaxrs.json"};
+ public static String[] classPackages = new String[] {
+ "de.ids_mannheim.korap.core.web",
+ "de.ids_mannheim.korap.web.filter",
+ "de.ids_mannheim.korap.web.utils", "de.ids_mannheim.korap.test",
+ "com.fasterxml.jackson.jaxrs.json" };
@Override
- protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
+ protected TestContainerFactory getTestContainerFactory ()
+ throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@BeforeEach
@Override
- public void setUp() throws Exception {
+ public void setUp () throws Exception {
GenericWebApplicationContext genericContext = new GenericWebApplicationContext();
genericContext.setParent(this.applicationContext);
genericContext.setClassLoader(this.applicationContext.getClassLoader());
@@ -43,7 +48,11 @@
}
@Override
- protected DeploymentContext configureDeployment() {
- return ServletDeploymentContext.forServlet(new ServletContainer(new ResourceConfig().packages(classPackages))).addListener(StaticContextLoaderListener.class).contextParam("adminToken", "secret").build();
+ protected DeploymentContext configureDeployment () {
+ return ServletDeploymentContext
+ .forServlet(new ServletContainer(
+ new ResourceConfig().packages(classPackages)))
+ .addListener(StaticContextLoaderListener.class)
+ .contextParam("adminToken", "secret").build();
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java b/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
index 1fca983..a1baccb 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
@@ -28,16 +28,19 @@
@Autowired
protected GenericApplicationContext applicationContext;
- public static String[] classPackages = new String[]{"de.ids_mannheim.korap.web", "de.ids_mannheim.korap.core.web", "de.ids_mannheim.korap.test", "com.fasterxml.jackson.jaxrs.json"};
+ public static String[] classPackages = new String[] {
+ "de.ids_mannheim.korap.web", "de.ids_mannheim.korap.core.web",
+ "de.ids_mannheim.korap.test", "com.fasterxml.jackson.jaxrs.json" };
@Override
- protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
+ protected TestContainerFactory getTestContainerFactory ()
+ throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@BeforeEach
@Override
- public void setUp() throws Exception {
+ public void setUp () throws Exception {
GenericWebApplicationContext genericContext = new GenericWebApplicationContext();
genericContext.setParent(this.applicationContext);
genericContext.setClassLoader(this.applicationContext.getClassLoader());
@@ -46,7 +49,11 @@
}
@Override
- protected DeploymentContext configureDeployment() {
- return ServletDeploymentContext.forServlet(new ServletContainer(new ResourceConfig().packages(classPackages))).addListener(StaticContextLoaderListener.class).contextParam("adminToken", "secret").build();
+ protected DeploymentContext configureDeployment () {
+ return ServletDeploymentContext
+ .forServlet(new ServletContainer(
+ new ResourceConfig().packages(classPackages)))
+ .addListener(StaticContextLoaderListener.class)
+ .contextParam("adminToken", "secret").build();
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/StaticContextLoaderListener.java b/full/src/test/java/de/ids_mannheim/korap/config/StaticContextLoaderListener.java
index d4cf8d9..018bd6e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/StaticContextLoaderListener.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/StaticContextLoaderListener.java
@@ -1,6 +1,5 @@
package de.ids_mannheim.korap.config;
-
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
@@ -23,14 +22,14 @@
super(applicationContext);
}
- @Override
- public void contextInitialized(ServletContextEvent event) {
+ @Override
+ public void contextInitialized (ServletContextEvent event) {
contextClassLoader = Thread.currentThread().getContextClassLoader();
super.contextInitialized(event);
- }
+ }
- @Override
- public void contextDestroyed(ServletContextEvent event) {
+ @Override
+ public void contextDestroyed (ServletContextEvent event) {
// Perform the destruction with the same contextual ClassLoader that was present
// during initialization.
// This a workaround for a bug in org.glassfish.grizzly.servlet.WebappContext
@@ -43,5 +42,5 @@
super.contextDestroyed(event);
Thread.currentThread().setContextClassLoader(loader);
- }
+ }
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/TestVariables.java b/full/src/test/java/de/ids_mannheim/korap/config/TestVariables.java
index 1e157a5..e4658ce 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/TestVariables.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/TestVariables.java
@@ -9,67 +9,44 @@
public static final String RESULT = "{\n"
+ "\t\"@context\": \"http://korap.ids-mannheim.de/ns/KoralQuery/v0.3/context.jsonld\",\n"
- + "\t\"meta\": {\n"
- + "\t\t\"count\": 25,\n"
- + "\t\t\"startIndex\": 0,\n"
- + "\t\t\"timeout\": 120000,\n"
- + "\t\t\"context\": {\n"
- + "\t\t\t\"left\": [\"token\", 6],\n"
- + "\t\t\t\"right\": [\"token\", 6]\n"
- + "\t\t},\n"
+ + "\t\"meta\": {\n" + "\t\t\"count\": 25,\n"
+ + "\t\t\"startIndex\": 0,\n" + "\t\t\"timeout\": 120000,\n"
+ + "\t\t\"context\": {\n" + "\t\t\t\"left\": [\"token\", 6],\n"
+ + "\t\t\t\"right\": [\"token\", 6]\n" + "\t\t},\n"
+ "\t\t\"fields\": [\"pubDate\", \"subTitle\", \"author\", \"pubPlace\", \"title\", \"textSigle\", \"UID\", \"ID\", \"layerInfos\", \"corpusSigle\", \"docSigle\", \"corpusID\", \"textClass\"],\n"
+ "\t\t\"version\": \"0.55.5\",\n"
+ "\t\t\"benchmark\": \"0.117436617 s\",\n"
+ "\t\t\"totalResults\": 31,\n"
+ "\t\t\"serialQuery\": \"tokens:s:das\",\n"
- + "\t\t\"itemsPerPage\": 25\n"
- + "\t},\n"
- + "\t\"query\": {\n"
- + "\t\t\"@type\": \"koral:token\",\n"
- + "\t\t\"wrap\": {\n"
- + "\t\t\t\"@type\": \"koral:term\",\n"
- + "\t\t\t\"key\": \"das\",\n"
+ + "\t\t\"itemsPerPage\": 25\n" + "\t},\n" + "\t\"query\": {\n"
+ + "\t\t\"@type\": \"koral:token\",\n" + "\t\t\"wrap\": {\n"
+ + "\t\t\t\"@type\": \"koral:term\",\n" + "\t\t\t\"key\": \"das\",\n"
+ "\t\t\t\"layer\": \"orth\",\n"
+ "\t\t\t\"match\": \"match:eq\",\n"
- + "\t\t\t\"foundry\": \"opennlp\",\n"
- + "\t\t\t\"rewrites\": [{\n"
+ + "\t\t\t\"foundry\": \"opennlp\",\n" + "\t\t\t\"rewrites\": [{\n"
+ "\t\t\t\t\"@type\": \"koral:rewrite\",\n"
+ "\t\t\t\t\"src\": \"Kustvakt\",\n"
+ "\t\t\t\t\"operation\": \"operation:injection\",\n"
- + "\t\t\t\t\"scope\": \"foundry\"\n"
- + "\t\t\t}]\n"
- + "\t\t},\n"
- + "\t\t\"idn\": \"das_0\",\n"
- + "\t\t\"rewrites\": [{\n"
+ + "\t\t\t\t\"scope\": \"foundry\"\n" + "\t\t\t}]\n" + "\t\t},\n"
+ + "\t\t\"idn\": \"das_0\",\n" + "\t\t\"rewrites\": [{\n"
+ "\t\t\t\"@type\": \"koral:rewrite\",\n"
+ "\t\t\t\"src\": \"Kustvakt\",\n"
+ "\t\t\t\"operation\": \"operation:injection\",\n"
- + "\t\t\t\"scope\": \"idn\"\n"
- + "\t\t}]\n"
- + "\t},\n"
- + "\t\"collection\": {\n"
- + "\t\t\"@type\": \"koral:docGroup\",\n"
+ + "\t\t\t\"scope\": \"idn\"\n" + "\t\t}]\n" + "\t},\n"
+ + "\t\"collection\": {\n" + "\t\t\"@type\": \"koral:docGroup\",\n"
+ "\t\t\"operation\": \"operation:or\",\n"
- + "\t\t\"operands\": [{\n"
- + "\t\t\t\"@type\": \"koral:doc\",\n"
+ + "\t\t\"operands\": [{\n" + "\t\t\t\"@type\": \"koral:doc\",\n"
+ "\t\t\t\"key\": \"corpusSigle\",\n"
- + "\t\t\t\"value\": \"GOE\",\n"
- + "\t\t\t\"match\": \"match:eq\"\n"
- + "\t\t}, {\n"
- + "\t\t\t\"@type\": \"koral:doc\",\n"
+ + "\t\t\t\"value\": \"GOE\",\n" + "\t\t\t\"match\": \"match:eq\"\n"
+ + "\t\t}, {\n" + "\t\t\t\"@type\": \"koral:doc\",\n"
+ "\t\t\t\"key\": \"corpusSigle\",\n"
- + "\t\t\t\"value\": \"WPD\",\n"
- + "\t\t\t\"match\": \"match:eq\"\n"
- + "\t\t}],\n"
- + "\t\t\"rewrites\": [{\n"
+ + "\t\t\t\"value\": \"WPD\",\n" + "\t\t\t\"match\": \"match:eq\"\n"
+ + "\t\t}],\n" + "\t\t\"rewrites\": [{\n"
+ "\t\t\t\"@type\": \"koral:rewrite\",\n"
+ "\t\t\t\"src\": \"Kustvakt\",\n"
+ "\t\t\t\"operation\": \"operation:insertion\",\n"
- + "\t\t\t\"scope\": \"corpusSigle\"\n"
- + "\t\t}]\n"
- + "\t},\n"
- + "\t\"matches\": [{\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\t\"scope\": \"corpusSigle\"\n" + "\t\t}]\n" + "\t},\n"
+ + "\t\"matches\": [{\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00004\",\n"
@@ -78,14 +55,11 @@
+ "\t\t\"title\": \"A (Logik)\",\n"
+ "\t\t\"author\": \"Zenogantner; ElRaki; 1\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>z.B. mit dem Wort Barbara" bezeichnet, </span><mark>das</mark><span class=\\\"context-right\\\"> dreimal den Buchstaben a enthält, aber<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00004-p195-196\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"kultur musik freizeit-unterhaltung reisen\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.02439\",\n"
@@ -94,14 +68,11 @@
+ "\t\t\"title\": \"Aegukka\",\n"
+ "\t\t\"author\": \"ThorstenS; 2\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>wörtlich "Das Lied der Liebe für </span><mark>das</mark><span class=\\\"context-right\\\"> Land", oder "Das patriotische Lied". Es<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.02439-p22-23\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"kultur musik freizeit-unterhaltung reisen\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.02439\",\n"
@@ -110,14 +81,11 @@
+ "\t\t\"title\": \"Aegukka\",\n"
+ "\t\t\"author\": \"ThorstenS; 2\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Besatzungszeit von 1910 bis 1945 wurde </span><mark>das</mark><span class=\\\"context-right\\\"> Lied verboten. Im Ausland lebende Koreaner<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.02439-p74-75\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"kultur musik freizeit-unterhaltung reisen\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.02439\",\n"
@@ -126,348 +94,262 @@
+ "\t\t\"title\": \"Aegukka\",\n"
+ "\t\t\"author\": \"ThorstenS; 2\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>3. Deutsche Übersetzung 1. Strophe Bis </span><mark>das</mark><span class=\\\"context-right\\\"> Meer des Ostens ausdörrt und der<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.02439-p298-299\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Ausnahme von Fremdwörtern und Namen ist </span><mark>das</mark><span class=\\\"context-right\\\"> A der einzige Buchstabe im Deutschen<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p41-42\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>flache Stellung niedergedrückt wird. Stellt man </span><mark>das</mark><span class=\\\"context-right\\\"> Verhältnis der drei Hauptvokale a, i<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p107-108\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>kommt i als der hellste an </span><mark>das</mark><span class=\\\"context-right\\\"> obere, u als der dumpfeste an<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p127-128\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>obere, u als der dumpfeste an </span><mark>das</mark><span class=\\\"context-right\\\"> untere Ende, a als der mittlere<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p134-135\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>im 9. Jahrhundert v. Chr. war </span><mark>das</mark><span class=\\\"context-right\\\"> Schriftzeichen bereits stark stilisiert, die Hörner<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p271-272\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>im Alphabet inne. Als die Griechen </span><mark>das</mark><span class=\\\"context-right\\\"> Phönizische Alphabet übernamen, drehten sie das<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p313-314\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>das Phönizische Alphabet übernamen, drehten sie </span><mark>das</mark><span class=\\\"context-right\\\"> Zeichen um 90 Grad und machten<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p319-320\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>um 90 Grad und machten daraus </span><mark>das</mark><span class=\\\"context-right\\\"> Alpha. Da das Griechische reich an<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p327-328\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>und machten daraus das Alpha. Da </span><mark>das</mark><span class=\\\"context-right\\\"> Griechische reich an Vokalen war, verwendeten<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p330-331\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>reich an Vokalen war, verwendeten sie </span><mark>das</mark><span class=\\\"context-right\\\"> Zeichen für den Lautwert a. Die<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p338-339\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>den Lautwert a. Die Etrusker übernahmen </span><mark>das</mark><span class=\\\"context-right\\\"> frühgriechische Alpha und ließen es größtenteils<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p347-348\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>von rechts nach links) versahen sie </span><mark>das</mark><span class=\\\"context-right\\\"> Zeichen mit einem Abschwung nach links<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p365-366\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Abschwung nach links. Als die Römer </span><mark>das</mark><span class=\\\"context-right\\\"> lateinische Alphabet schufen, verwendeten sie das<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p375-376\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>das lateinische Alphabet schufen, verwendeten sie </span><mark>das</mark><span class=\\\"context-right\\\"> A aus dem etruskischen Alphabet, der<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p381-382\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>in der Biologie steht A für </span><mark>das</mark><span class=\\\"context-right\\\"> Nukleosid Adenosin steht A die Base<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p404-405\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Wert 10, siehe auch Hexadezimalsystem. steht </span><mark>das</mark><span class=\\\"context-right\\\"> Symbol ∀ (ein auf den Kopf gestelltes<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p526-527\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>für die Vorsilbe Atto ist A </span><mark>das</mark><span class=\\\"context-right\\\"> Einheitensymbol der elektrischen Stromstärke Ampere in<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p624-625\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Anordnung (Rechtswesen), Agent (Börse), Aufzeichung (Rechtsw.), </span><mark>das</mark><span class=\\\"context-right\\\"> Flächenmaß Acre und Ausgabe A ist<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p757-758\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Band). in Redewendungen für den Anfang (</span><mark>das</mark><span class=\\\"context-right\\\"> A und O, von A bis<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p777-778\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>Z). a ist die Abkürzung für </span><mark>das</mark><span class=\\\"context-right\\\"> Flächenmaß Ar in der Kaufmannssprache bedeutet<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p790-791\",\n"
- + "\t\t\"UID\": 0,\n"
- + "\t\t\"pubDate\": \"2005-03-28\"\n"
- + "\t}, {\n"
- + "\t\t\"field\": \"tokens\",\n"
+ + "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ + "\t}, {\n" + "\t\t\"field\": \"tokens\",\n"
+ "\t\t\"textClass\": \"freizeit-unterhaltung reisen wissenschaft populaerwissenschaft\",\n"
+ "\t\t\"pubPlace\": \"URL:http://de.wikipedia.org\",\n"
+ "\t\t\"textSigle\": \"WPD_AAA.00001\",\n"
+ "\t\t\"docSigle\": \"WPD_AAA\",\n"
- + "\t\t\"corpusSigle\": \"WPD\",\n"
- + "\t\t\"title\": \"A\",\n"
+ + "\t\t\"corpusSigle\": \"WPD\",\n" + "\t\t\"title\": \"A\",\n"
+ "\t\t\"author\": \"Ruru; Jens.Ol; Aglarech; u.a.\",\n"
+ "\t\t\"layerInfos\": \"base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/s=spans mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans\",\n"
- + "\t\t\"startMore\": true,\n"
- + "\t\t\"endMore\": true,\n"
+ + "\t\t\"startMore\": true,\n" + "\t\t\"endMore\": true,\n"
+ "\t\t\"snippet\": \"<span class=\\\"context-left\\\"><span class=\\\"more\\\"></span>ad zu) ‚[das Stück] zu...‘ für </span><mark>das</mark><span class=\\\"context-right\\\"> Französische à „nach“, z. B. in<span class=\\\"more\\\"></span></span>\",\n"
+ "\t\t\"matchID\": \"match-WPD_AAA.00001-p805-806\",\n"
+ "\t\t\"UID\": 0,\n" + "\t\t\"pubDate\": \"2005-03-28\"\n"
+ "\t}]\n" + "}";
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
index 59ca413..13b2c91 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
@@ -27,13 +27,14 @@
private PrivilegeDao privilegeDao;
@Test
- public void retrievePredefinedRole() {
- Role r = roleDao.retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
+ public void retrievePredefinedRole () {
+ Role r = roleDao
+ .retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
assertEquals(1, r.getId());
}
@Test
- public void createDeleteRole() {
+ public void createDeleteRole () {
String roleName = "vc editor";
List<PrivilegeType> privileges = new ArrayList<PrivilegeType>();
privileges.add(PrivilegeType.READ);
@@ -46,7 +47,7 @@
}
@Test
- public void updateRole() {
+ public void updateRole () {
Role role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
roleDao.editRoleName(role.getId(), "USER_GROUP_MEMBER role");
role = roleDao.retrieveRoleById(role.getId());
@@ -57,7 +58,7 @@
}
@Test
- public void addDeletePrivilegeOfExistingRole() {
+ public void addDeletePrivilegeOfExistingRole () {
Role role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
List<Privilege> privileges = role.getPrivileges();
assertEquals(1, role.getPrivileges().size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
index dd5fcf5..1ee65bf 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
@@ -47,11 +47,12 @@
private FullConfiguration config;
@Test
- public void createDeleteNewUserGroup() throws KustvaktException {
+ public void createDeleteNewUserGroup () throws KustvaktException {
String groupName = "test group";
String createdBy = "test class";
// create group
- int groupId = userGroupDao.createGroup(groupName, null, createdBy, UserGroupStatus.ACTIVE);
+ int groupId = userGroupDao.createGroup(groupName, null, createdBy,
+ UserGroupStatus.ACTIVE);
// retrieve group
UserGroup group = userGroupDao.retrieveGroupById(groupId, true);
assertEquals(groupName, group.getName());
@@ -71,39 +72,47 @@
ArrayList<Role> roleList = new ArrayList<>(2);
roleList.addAll(roles);
Collections.sort(roleList);
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.getId(), roleList.get(0).getId());
- assertEquals(PredefinedRole.VC_ACCESS_ADMIN.getId(), roleList.get(1).getId());
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.getId(),
+ roleList.get(0).getId());
+ assertEquals(PredefinedRole.VC_ACCESS_ADMIN.getId(),
+ roleList.get(1).getId());
// retrieve VC by group
List<QueryDO> vc = virtualCorpusDao.retrieveQueryByGroup(groupId);
assertEquals(0, vc.size());
// soft delete group
- userGroupDao.deleteGroup(groupId, createdBy, config.isSoftDeleteGroup());
+ userGroupDao.deleteGroup(groupId, createdBy,
+ config.isSoftDeleteGroup());
group = userGroupDao.retrieveGroupById(groupId);
assertEquals(UserGroupStatus.DELETED, group.getStatus());
// hard delete
userGroupDao.deleteGroup(groupId, createdBy, false);
- KustvaktException exception = assertThrows(KustvaktException.class, () -> {
- userGroupDao.retrieveGroupById(groupId);
- });
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, exception.getStatusCode().intValue());
+ KustvaktException exception = assertThrows(KustvaktException.class,
+ () -> {
+ userGroupDao.retrieveGroupById(groupId);
+ });
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ exception.getStatusCode().intValue());
}
@Test
- public void retrieveGroupWithMembers() throws KustvaktException {
+ public void retrieveGroupWithMembers () throws KustvaktException {
// dory group
- List<UserGroupMember> members = userGroupDao.retrieveGroupById(2, true).getMembers();
+ List<UserGroupMember> members = userGroupDao.retrieveGroupById(2, true)
+ .getMembers();
assertEquals(4, members.size());
UserGroupMember m = members.get(1);
Set<Role> roles = m.getRoles();
assertEquals(2, roles.size());
List<Role> sortedRoles = new ArrayList<>(roles);
Collections.sort(sortedRoles);
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), sortedRoles.get(0).getName());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), sortedRoles.get(1).getName());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
+ sortedRoles.get(0).getName());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
+ sortedRoles.get(1).getName());
}
@Test
- public void retrieveGroupByUserId() throws KustvaktException {
+ public void retrieveGroupByUserId () throws KustvaktException {
List<UserGroup> group = userGroupDao.retrieveGroupByUserId("dory");
assertEquals(2, group.size());
group = userGroupDao.retrieveGroupByUserId("pearl");
@@ -111,15 +120,18 @@
}
@Test
- public void addVCToGroup() throws KustvaktException {
+ public void addVCToGroup () throws KustvaktException {
// dory group
int groupId = 2;
UserGroup group = userGroupDao.retrieveGroupById(groupId);
String createdBy = "dory";
String name = "dory new vc";
- int id = virtualCorpusDao.createQuery(name, ResourceType.PROJECT, QueryType.VIRTUAL_CORPUS, CorpusAccess.PUB, "corpusSigle=WPD15", "", "", "", false, createdBy, null, null);
+ int id = virtualCorpusDao.createQuery(name, ResourceType.PROJECT,
+ QueryType.VIRTUAL_CORPUS, CorpusAccess.PUB, "corpusSigle=WPD15",
+ "", "", "", false, createdBy, null, null);
QueryDO virtualCorpus = virtualCorpusDao.retrieveQueryById(id);
- userGroupDao.addQueryToGroup(virtualCorpus, createdBy, QueryAccessStatus.ACTIVE, group);
+ userGroupDao.addQueryToGroup(virtualCorpus, createdBy,
+ QueryAccessStatus.ACTIVE, group);
List<QueryDO> vc = virtualCorpusDao.retrieveQueryByGroup(groupId);
assertEquals(2, vc.size());
assertEquals(name, vc.get(1).getName());
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
index 93e3b78..e3fdc87 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
@@ -27,19 +27,21 @@
private RoleDao roleDao;
@Test
- public void testRetrieveMemberByRole() throws KustvaktException {
+ public void testRetrieveMemberByRole () throws KustvaktException {
// dory group
- List<UserGroupMember> vcaAdmins = dao.retrieveMemberByRole(2, PredefinedRole.VC_ACCESS_ADMIN.getId());
+ List<UserGroupMember> vcaAdmins = dao.retrieveMemberByRole(2,
+ PredefinedRole.VC_ACCESS_ADMIN.getId());
// System.out.println(vcaAdmins);
assertEquals(1, vcaAdmins.size());
assertEquals(vcaAdmins.get(0).getUserId(), "dory");
}
@Test
- public void testAddSameMemberRole() throws KustvaktException {
+ public void testAddSameMemberRole () throws KustvaktException {
UserGroupMember member = dao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
- Role adminRole = roleDao.retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
+ Role adminRole = roleDao
+ .retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
roles.add(adminRole);
member.setRoles(roles);
dao.updateMember(member);
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
index 6be38cf..72f1e0f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
@@ -23,7 +23,7 @@
private QueryAccessDao dao;
@Test
- public void getAccessByVC() throws KustvaktException {
+ public void getAccessByVC () throws KustvaktException {
List<QueryAccess> vcaList = dao.retrieveActiveAccessByQuery(2);
QueryAccess access = vcaList.get(0);
assertEquals(QueryAccessStatus.ACTIVE, access.getStatus());
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
index 95af5dc..cfd226b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
@@ -25,8 +25,9 @@
private QueryDao dao;
@Test
- public void testListVCByType() throws KustvaktException {
- List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.PUBLISHED, null, QueryType.VIRTUAL_CORPUS);
+ public void testListVCByType () throws KustvaktException {
+ List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.PUBLISHED,
+ null, QueryType.VIRTUAL_CORPUS);
assertEquals(1, vcList.size());
QueryDO vc = vcList.get(0);
assertEquals(4, vc.getId());
@@ -35,40 +36,48 @@
}
@Test
- public void testSystemVC() throws KustvaktException {
+ public void testSystemVC () throws KustvaktException {
// insert vc
- int id = dao.createQuery("system-vc", ResourceType.SYSTEM, QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE, "corpusSigle=GOE", "definition", "description", "experimental", false, "test class", null, null);
+ int id = dao.createQuery("system-vc", ResourceType.SYSTEM,
+ QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE,
+ "corpusSigle=GOE", "definition", "description", "experimental",
+ false, "test class", null, null);
// select vc
- List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
+ List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.SYSTEM,
+ null, QueryType.VIRTUAL_CORPUS);
assertEquals(2, vcList.size());
QueryDO vc = dao.retrieveQueryById(id);
// delete vc
dao.deleteQuery(vc);
// check if vc has been deleted
- KustvaktException exception = assertThrows(KustvaktException.class, () -> {
- dao.retrieveQueryById(id);
- });
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, exception.getStatusCode().intValue());
+ KustvaktException exception = assertThrows(KustvaktException.class,
+ () -> {
+ dao.retrieveQueryById(id);
+ });
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ exception.getStatusCode().intValue());
}
@Test
public void testNonUniqueVC () throws KustvaktException {
-
- PersistenceException exception = assertThrows(PersistenceException.class, ()->{
- dao.createQuery("system-vc", ResourceType.SYSTEM,
- QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE,
- "corpusSigle=GOE", "definition", "description", "experimental",
- false, "system", null, null);
- });
-
+
+ PersistenceException exception = assertThrows(
+ PersistenceException.class, () -> {
+ dao.createQuery("system-vc", ResourceType.SYSTEM,
+ QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE,
+ "corpusSigle=GOE", "definition", "description",
+ "experimental", false, "system", null, null);
+ });
+
assertEquals(exception.getMessage(),
"Converting `org.hibernate.exception.GenericJDBCException` "
- + "to JPA `PersistenceException` : could not execute statement");
+ + "to JPA `PersistenceException` : could not execute statement");
}
@Test
- public void retrieveSystemVC() throws KustvaktException {
- List<QueryDO> vc = dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
+ public void retrieveSystemVC () throws KustvaktException {
+ List<QueryDO> vc = dao.retrieveQueryByType(ResourceType.SYSTEM, null,
+ QueryType.VIRTUAL_CORPUS);
assertEquals(1, vc.size());
}
@@ -78,8 +87,9 @@
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserDory() throws KustvaktException {
- List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("dory", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserDory () throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("dory",
+ QueryType.VIRTUAL_CORPUS);
// System.out.println(virtualCorpora);
assertEquals(4, virtualCorpora.size());
// ordered by id
@@ -97,8 +107,9 @@
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserNemo() throws KustvaktException {
- List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("nemo", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserNemo () throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("nemo",
+ QueryType.VIRTUAL_CORPUS);
assertEquals(3, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
assertEquals(i.next().getName(), "group-vc");
@@ -113,8 +124,9 @@
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserMarlin() throws KustvaktException {
- List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("marlin", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserMarlin () throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("marlin",
+ QueryType.VIRTUAL_CORPUS);
assertEquals(3, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
assertEquals(i.next().getName(), "system-vc");
@@ -129,8 +141,9 @@
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserPearl() throws KustvaktException {
- List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("pearl", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserPearl () throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("pearl",
+ QueryType.VIRTUAL_CORPUS);
assertEquals(2, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
assertEquals(i.next().getName(), "system-vc");
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
index a679a12..ce1abb3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
@@ -8,7 +8,7 @@
public class BCryptTest {
@Test
- public void testSalt() {
+ public void testSalt () {
String salt = BCrypt.gensalt(8);
// System.out.println(salt);
String plain = "secret";
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
index 980d749..0935f6c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
@@ -17,7 +17,7 @@
public class CollectionQueryBuilderTest {
@Test
- public void testsimpleAdd() throws KustvaktException {
+ public void testsimpleAdd () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD");
JsonNode node = JsonUtils.readTree(b.toJSON());
@@ -27,41 +27,48 @@
}
@Test
- public void testSimpleConjunction() throws KustvaktException {
+ public void testSimpleConjunction () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD & textClass=freizeit");
JsonNode node = JsonUtils.readTree(b.toJSON());
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/operands/0/key").asText(), "corpusSigle");
- assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "corpusSigle");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "textClass");
}
@Test
- public void testSimpleDisjunction() throws KustvaktException {
+ public void testSimpleDisjunction () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD | textClass=freizeit");
JsonNode node = JsonUtils.readTree(b.toJSON());
assertNotNull(node);
assert node.at("/collection/operation").asText().equals("operation:or");
- assert node.at("/collection/operands/0/key").asText().equals("corpusSigle");
- assert node.at("/collection/operands/1/key").asText().equals("textClass");
+ assert node.at("/collection/operands/0/key").asText()
+ .equals("corpusSigle");
+ assert node.at("/collection/operands/1/key").asText()
+ .equals("textClass");
}
@Test
- public void testComplexSubQuery() throws KustvaktException {
+ public void testComplexSubQuery () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(corpusSigle=WPD) | (textClass=freizeit & corpusSigle=BRZ13)");
JsonNode node = JsonUtils.readTree(b.toJSON());
assertNotNull(node);
assert node.at("/collection/operation").asText().equals("operation:or");
- assert node.at("/collection/operands/0/key").asText().equals("corpusSigle");
- assert node.at("/collection/operands/1/@type").asText().equals("koral:docGroup");
+ assert node.at("/collection/operands/0/key").asText()
+ .equals("corpusSigle");
+ assert node.at("/collection/operands/1/@type").asText()
+ .equals("koral:docGroup");
}
@Test
- public void testAddResourceQueryAfter() throws KustvaktException {
+ public void testAddResourceQueryAfter () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(textClass=politik & title=\"random title\") | textClass=wissenschaft");
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
@@ -69,19 +76,26 @@
c.with("corpusSigle=WPD");
JsonNode node = JsonUtils.readTree(c.toJSON());
assertNotNull(node);
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
assertEquals(2, node.at("/collection/operands/0/operands").size());
- assertEquals(2, node.at("/collection/operands/0/operands/0/operands").size());
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/operands/0/operation").asText(), "operation:or");
- assertEquals(node.at("/collection/operands/0/operands/0/operation").asText(), "operation:and");
+ assertEquals(2,
+ node.at("/collection/operands/0/operands/0/operands").size());
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/operands/0/operation").asText(),
+ "operation:or");
+ assertEquals(
+ node.at("/collection/operands/0/operands/0/operation").asText(),
+ "operation:and");
assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
}
@Test
- public void testAddComplexResourceQueryAfter() throws KustvaktException {
+ public void testAddComplexResourceQueryAfter () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(title=\"random title\") | (textClass=wissenschaft)");
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
@@ -89,16 +103,26 @@
c.with("(corpusSigle=BRZ13 | corpusSigle=AZPS)");
JsonNode node = JsonUtils.readTree(c.toJSON());
assertNotNull(node);
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "BRZ13");
- assertEquals(node.at("/collection/operands/1/operands/1/value").asText(), "AZPS");
- assertEquals(node.at("/collection/operands/0/operands/0/value").asText(), "random title");
- assertEquals(node.at("/collection/operands/0/operands/1/value").asText(), "wissenschaft");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:docGroup");
+ assertEquals(
+ node.at("/collection/operands/1/operands/0/value").asText(),
+ "BRZ13");
+ assertEquals(
+ node.at("/collection/operands/1/operands/1/value").asText(),
+ "AZPS");
+ assertEquals(
+ node.at("/collection/operands/0/operands/0/value").asText(),
+ "random title");
+ assertEquals(
+ node.at("/collection/operands/0/operands/1/value").asText(),
+ "wissenschaft");
}
@Test
- public void testBuildQuery() throws KustvaktException {
+ public void testBuildQuery () throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
@@ -111,12 +135,17 @@
assertNotNull(res);
assertEquals(res.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(res.at("/collection/operation").asText(), "operation:and");
- assertEquals(res.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(res.at("/collection/operands/1/value").asText(), "freizeit");
- assertEquals(res.at("/collection/operands/1/key").asText(), "textClass");
- assertEquals(res.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(res.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(res.at("/collection/operands/1/value").asText(),
+ "freizeit");
+ assertEquals(res.at("/collection/operands/1/key").asText(),
+ "textClass");
+ assertEquals(res.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
assertEquals(res.at("/collection/operands/0/value").asText(), "WPD");
- assertEquals(res.at("/collection/operands/0/key").asText(), "corpusSigle");
+ assertEquals(res.at("/collection/operands/0/key").asText(),
+ "corpusSigle");
// check also that query is still there
assertEquals(res.at("/query/@type").asText(), "koral:token");
assertEquals(res.at("/query/wrap/@type").asText(), "koral:term");
@@ -125,7 +154,7 @@
}
@Test
- public void testBaseQueryBuild() throws KustvaktException {
+ public void testBaseQueryBuild () throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(corpusSigle=ADF) | (textClass=freizeit & corpusSigle=WPD)");
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
@@ -134,14 +163,16 @@
JsonNode base = (JsonNode) c.rebaseCollection();
assertNotNull(base);
assertEquals(base.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(base.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(base.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
assertEquals(base.at("/collection/operands/1/value").asText(), "BRZ13");
- assertEquals(base.at("/collection/operands/0/@type").asText(), "koral:docGroup");
+ assertEquals(base.at("/collection/operands/0/@type").asText(),
+ "koral:docGroup");
assertEquals(base.at("/collection/operands/0/operands").size(), 2);
}
@Test
- public void testNodeMergeWithBase() throws KustvaktException {
+ public void testNodeMergeWithBase () throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
@@ -155,12 +186,13 @@
node = b.mergeWith(node);
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
assertEquals(2, node.at("/collection/operands").size());
}
@Test
- public void testNodeMergeWithoutBase() throws KustvaktException {
+ public void testNodeMergeWithoutBase () throws KustvaktException {
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
@@ -178,7 +210,8 @@
}
@Test
- public void testNodeMergeWithoutBaseWrongOperator() throws KustvaktException {
+ public void testNodeMergeWithoutBaseWrongOperator ()
+ throws KustvaktException {
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
@@ -197,11 +230,10 @@
}
@Test
- public void testStoredCollectionBaseQueryBuild() {
- }
+ public void testStoredCollectionBaseQueryBuild () {}
@Test
- public void testAddOROperator() throws KustvaktException {
+ public void testAddOROperator () throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
@@ -218,7 +250,7 @@
}
@Test
- public void testAddANDOperator() throws KustvaktException {
+ public void testAddANDOperator () throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
@@ -230,12 +262,13 @@
JsonNode node = (JsonNode) test.rebaseCollection();
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
assertEquals(2, node.at("/collection/operands/1/operands").size());
}
@Test
- public void testAddDefaultOperator() throws KustvaktException {
+ public void testAddDefaultOperator () throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
@@ -247,12 +280,13 @@
JsonNode node = (JsonNode) test.rebaseCollection();
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
assertEquals(2, node.at("/collection/operands/1/operands").size());
}
@Test
- public void testBaseCollectionNull() throws KustvaktException {
+ public void testBaseCollectionNull () throws KustvaktException {
// base is missing collection segment
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
@@ -260,18 +294,24 @@
total.setBaseQuery(s.toJSON());
KoralCollectionQueryBuilder builder = new KoralCollectionQueryBuilder();
builder.with("textClass=politik & corpusSigle=WPD");
- JsonNode node = total.and().mergeWith((JsonNode) builder.rebaseCollection());
+ JsonNode node = total.and()
+ .mergeWith((JsonNode) builder.rebaseCollection());
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
- assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "corpusSigle");
}
@Test
- public void testMergeCollectionNull() throws KustvaktException {
+ public void testMergeCollectionNull () throws KustvaktException {
// merge json is missing collection segment
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
@@ -279,7 +319,8 @@
KoralCollectionQueryBuilder total = new KoralCollectionQueryBuilder();
total.setBaseQuery(s.toJSON());
KoralCollectionQueryBuilder builder = new KoralCollectionQueryBuilder();
- JsonNode node = total.and().mergeWith((JsonNode) builder.rebaseCollection());
+ JsonNode node = total.and()
+ .mergeWith((JsonNode) builder.rebaseCollection());
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "textClass");
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
index 7fa7e33..f683230 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
@@ -26,19 +26,19 @@
KustvaktConfiguration config;
@Test
- public void testConfigLoader() {
+ public void testConfigLoader () {
InputStream stream = ConfigLoader.loadConfigStream("kustvakt.conf");
assertNotNull(stream);
}
@Test
- public void testPropertyLoader() throws IOException {
+ public void testPropertyLoader () throws IOException {
Properties p = ConfigLoader.loadProperties("kustvakt.conf");
assertNotNull(p);
}
@Test
- public void testServiceInfo() {
+ public void testServiceInfo () {
String version = ServiceInfo.getInfo().getVersion();
String name = ServiceInfo.getInfo().getName();
assertNotEquals("UNKNOWN", version, "wrong version");
@@ -46,8 +46,10 @@
}
@Test
- public void testProperties() {
- assertEquals("opennlp", config.getDefault_orthography(), "token layer does not match");
- assertEquals(TimeUtils.convertTimeToSeconds("1D"), config.getLongTokenTTL(), "token expiration does not match");
+ public void testProperties () {
+ assertEquals("opennlp", config.getDefault_orthography(),
+ "token layer does not match");
+ assertEquals(TimeUtils.convertTimeToSeconds("1D"),
+ config.getLongTokenTTL(), "token expiration does not match");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
index 7e974f3..eb9051b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
@@ -16,7 +16,7 @@
// 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() {
+ public void addToNode () {
ObjectNode node = JsonUtils.createObjectNode();
KoralNode knode = KoralNode.wrapNode(node);
knode.put("value_1", "setting_1");
@@ -24,7 +24,7 @@
}
@Test
- public void removeFromNode() {
+ public void removeFromNode () {
ObjectNode node = JsonUtils.createObjectNode();
node.put("value_1", "setting_1");
KoralNode knode = KoralNode.wrapNode(node);
@@ -33,16 +33,16 @@
}
@Test
- public void replaceObject() {
+ public void replaceObject () {
ObjectNode node = JsonUtils.createObjectNode();
node.put("value_1", "setting_1");
KoralNode knode = KoralNode.wrapNode(node);
knode.replace("value_1", "settings_2", null);
- assertEquals(knode.rawNode().toString(), "{\"value_1\":\"settings_2\"}");
+ assertEquals(knode.rawNode().toString(),
+ "{\"value_1\":\"settings_2\"}");
}
// todo: 21.10.15 --> if a node is injected, that node must contain a "rewrites" reference?!
@Test
- public void addNodeToKoral() {
- }
+ public void addNodeToKoral () {}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
index a7b5c01..9591a0e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
@@ -29,12 +29,12 @@
KustvaktConfiguration config;
@PostConstruct
- public void setup() throws Exception {
+ public void setup () throws Exception {
index = config.getIndexDir();
}
@Test
- public void testQuery() throws KustvaktException {
+ public void testQuery () throws KustvaktException {
String qstring = "creationDate since 1786 & creationDate until 1788";
// qstring = "creationDate since 1765 & creationDate until 1768";
// qstring = "textType = Aphorismus";
@@ -47,7 +47,7 @@
}
@Test
- public void testCollQuery() throws IOException, KustvaktException {
+ public void testCollQuery () throws IOException, KustvaktException {
String qstring = "creationDate since 1800 & creationDate until 1820";
CollectionQueryProcessor processor = new CollectionQueryProcessor();
processor.process(qstring);
@@ -59,7 +59,7 @@
}
@Test
- public void testCollQuery2() throws IOException {
+ 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());
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
index 35e995e..4d59790 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
@@ -14,23 +14,23 @@
@SuppressWarnings("unchecked")
@Test
- public void testConvertToMap() {
+ public void testConvertToMap () {
MultivaluedMap<String, String> mm = new MultivaluedHashMap<String, String>();
- mm.put("k1", Arrays.asList(new String[]{"a", "b", "c"}));
- mm.put("k2", Arrays.asList(new String[]{"d", "e", "f"}));
+ mm.put("k1", Arrays.asList(new String[] { "a", "b", "c" }));
+ mm.put("k2", Arrays.asList(new String[] { "d", "e", "f" }));
Map<String, String> map = MapUtils.toMap(mm);
assertEquals(map.get("k1"), "a b c");
assertEquals(map.get("k2"), "d e f");
}
@Test
- public void testConvertNullMap() {
+ public void testConvertNullMap () {
Map<String, String> map = MapUtils.toMap(null);
assertEquals(0, map.size());
}
@Test
- public void testConvertEmptyMap() {
+ public void testConvertEmptyMap () {
MultivaluedMap<String, String> mm = new MultivaluedHashMap<String, String>();
Map<String, String> map = MapUtils.toMap(mm);
assertEquals(0, map.size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
index c6328c3..7eda84d 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
@@ -8,15 +8,15 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
-
/**
* Created by hanl on 17.04.16.
*/
public class MetaQueryBuilderTest {
@Test
- public void testSpanContext() {
- MetaQueryBuilder m = QueryBuilderUtil.defaultMetaBuilder(0, 1, 5, "sentence", false);
+ public void testSpanContext () {
+ MetaQueryBuilder m = QueryBuilderUtil.defaultMetaBuilder(0, 1, 5,
+ "sentence", false);
Map<?, ?> map = m.raw();
assertEquals(map.get("context"), "sentence");
assertEquals(1, map.get("startPage"));
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
index 518ae39..634530b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
@@ -10,7 +10,7 @@
public class RegexTest {
@Test
- public void testQuote() {
+ public void testQuote () {
String s = "ah[\"-\"]";
Matcher m = AnnotationParser.quotePattern.matcher(s);
if (m.find()) {
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
index 4d82706..ad92c36 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
@@ -9,10 +9,8 @@
public class ScopesTest {
@Test
- public void testScopes() {
- }
+ public void testScopes () {}
@Test
- public void testOpenIDScopes() {
- }
+ public void testOpenIDScopes () {}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
index 7471e12..dd4ca5b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
@@ -11,7 +11,7 @@
public class SerializationTest {
@Test
- public void testSettingsObject() {
+ public void testSettingsObject () {
// String t = "poliqarp_test";
// UserSettings s = new UserSettings();
// Map map = s.toObjectMap();
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
index 657ba0b..f7dfb3a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
@@ -16,7 +16,7 @@
public class StringUtilsTest {
@Test
- public void testTextIToDoc() {
+ public void testTextIToDoc () {
String textSigle = "WPD_AAA.02439";
String docSigle = "WPD_AAA";
assertEquals(docSigle, StringUtils.getDocSigle(textSigle));
@@ -24,13 +24,14 @@
}
@Test
- public void testBasicHttpSplit() throws KustvaktException {
+ public void testBasicHttpSplit () throws KustvaktException {
String s2 = new String(Base64.encodeBase64("test:testPass".getBytes()));
String[] f2 = TransferEncoding.decodeBase64(s2);
assertEquals(f2[0], "test");
assertEquals(f2[1], "testPass");
HttpAuthorizationHandler handler = new HttpAuthorizationHandler();
- String s1 = "basic " + new String(Base64.encodeBase64("test:testPass".getBytes()));
+ String s1 = "basic "
+ + new String(Base64.encodeBase64("test:testPass".getBytes()));
AuthorizationData f1 = handler.parseAuthorizationHeaderValue(s1);
assertEquals(s2, f1.getToken());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/TestNullableSqls.java b/full/src/test/java/de/ids_mannheim/korap/misc/TestNullableSqls.java
index 86a2a79..8fcb1d0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/TestNullableSqls.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/TestNullableSqls.java
@@ -1,4 +1,5 @@
package de.ids_mannheim.korap.misc;
+
/**
* @author hanl
* @date 30/01/2016
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
index ae8e39b..e205ce3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
@@ -24,72 +24,89 @@
public KustvaktConfiguration config;
@Test
- public void testCollectionNodeRemoveCorpusIdNoErrors() throws KustvaktException {
+ public void testCollectionNodeRemoveCorpusIdNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("textClass=politik & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(1, node.at("/collection/operands").size());
}
@Test
- public void testCollectionNodeDeletionNotification() {
- }
+ public void testCollectionNodeDeletionNotification () {}
@Test
- public void testCollectionNodeRemoveAllCorpusIdNoErrors() throws KustvaktException {
+ public void testCollectionNodeRemoveAllCorpusIdNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("corpusSigle=BRZ13 & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(0, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testCollectionNodeRemoveGroupedCorpusIdNoErrors() throws KustvaktException {
+ public void testCollectionNodeRemoveGroupedCorpusIdNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(corpusSigle=BRZ13 & textClass=Wissenschaft) & corpusSigle=WPD");
+ s.setCollection(
+ "(corpusSigle=BRZ13 & textClass=Wissenschaft) & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/0/operands/0/key").asText(), "textClass");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/operands/0/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
// fixme: will probably fail when one doc groups are being refactored
@Test
- public void testCollectionCleanEmptyDocGroupNoErrors() throws KustvaktException {
+ public void testCollectionCleanEmptyDocGroupNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft & textClass=Sport");
+ s.setCollection(
+ "(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft & textClass=Sport");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
- assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testCollectionCleanMoveOneDocFromGroupUpNoErrors() throws KustvaktException {
+ public void testCollectionCleanMoveOneDocFromGroupUpNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
@@ -97,123 +114,164 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ13 & textClass=wissenschaft)");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "textClass");
assertEquals(node.at("/collection/value").asText(), "wissenschaft");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testCollectionCleanEmptyGroupAndMoveOneFromGroupUpNoErrors() throws KustvaktException {
+ public void testCollectionCleanEmptyGroupAndMoveOneFromGroupUpNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft");
+ s.setCollection(
+ "(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "textClass");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testCollectionRemoveAndMoveOneFromGroupUpNoErrors() throws KustvaktException {
+ public void testCollectionRemoveAndMoveOneFromGroupUpNoErrors ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(docID=random & textClass=Wissenschaft) & corpusSigle=WPD");
+ s.setCollection(
+ "(docID=random & textClass=Wissenschaft) & corpusSigle=WPD");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testPublicCollectionRewriteEmptyAdd() throws KustvaktException {
+ public void testPublicCollectionRewriteEmptyAdd ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/key").asText(), "availability");
assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
// todo:
}
@Test
- public void testPublicCollectionRewriteNonEmptyAdd() throws KustvaktException {
+ public void testPublicCollectionRewriteNonEmptyAdd ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(docSigle=WPD_AAA & textClass=wissenschaft)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/operands/0/key").asText(), "docSigle");
- assertEquals(node.at("/collection/operands/1/operands/1/key").asText(), "textClass");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/key").asText(),
+ "docSigle");
+ assertEquals(node.at("/collection/operands/1/operands/1/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
}
@Test
- public void testRemoveCorpusFromDifferentGroups() throws KustvaktException {
+ public void testRemoveCorpusFromDifferentGroups ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
+ s.setCollection(
+ "(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:docGroup");
assertEquals(1, node.at("/collection/operands/0/operands").size());
assertEquals(1, node.at("/collection/operands/1/operands").size());
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testRemoveOneCorpusAndMoveDocFromTwoGroups() throws KustvaktException {
+ public void testRemoveOneCorpusAndMoveDocFromTwoGroups ()
+ throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
// todo: use this collection query also to test clean up filter! after reduction of corpusSigle (wiss | freizeit)!
handler.add(CollectionCleanRewrite.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
- s.setCollection("(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
+ s.setCollection(
+ "(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org,
+ User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
- assertEquals(node.at("/collection/operands/0/value").asText(), "wissenschaft");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
- assertEquals(node.at("/collection/operands/1/value").asText(), "freizeit");
- assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "wissenschaft");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/operands/1/value").asText(),
+ "freizeit");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
index 65d3752..51e7fc5 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
@@ -44,50 +44,67 @@
private LayerMapper m;
@Test
- public void testSearchRewriteFoundryWithUserSetting() throws KustvaktException {
+ public void testSearchRewriteFoundryWithUserSetting ()
+ throws KustvaktException {
// create user setting
String json = "{\"pos-foundry\":\"opennlp\"}";
String username = "foundryRewriteTest";
String pathUsername = "~" + username;
- Response response = target().path(API_VERSION).path(pathUsername).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path(pathUsername)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
// search
- response = target().path(API_VERSION).path("search").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).accept(MediaType.APPLICATION_JSON).get();
+ response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp")
+ .request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .accept(MediaType.APPLICATION_JSON).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
- assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(),
+ "foundry");
}
@Test
- public void testRewritePosFoundryWithUserSetting() throws KustvaktException {
+ public void testRewritePosFoundryWithUserSetting ()
+ throws KustvaktException {
// EM: see
// full/src/main/resources/db/insert/V3.6__insert_default_settings.sql
String username = "bubbles";
QuerySerializer s = new QuerySerializer();
s.setQuery("[pos=ADJA]", "poliqarp");
- String result = handler.processQuery(s.toJSON(), new KorAPUser(username));
+ String result = handler.processQuery(s.toJSON(),
+ new KorAPUser(username));
JsonNode node = JsonUtils.readTree(result);
assertEquals(node.at("/query/wrap/foundry").asText(), "corenlp");
- assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(),
+ "foundry");
}
@Test
- public void testRewriteLemmaFoundryWithUserSetting() throws KustvaktException {
+ public void testRewriteLemmaFoundryWithUserSetting ()
+ throws KustvaktException {
String username = "bubbles";
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
- String result = handler.processQuery(s.toJSON(), new KorAPUser(username));
+ String result = handler.processQuery(s.toJSON(),
+ new KorAPUser(username));
JsonNode node = JsonUtils.readTree(result);
// EM: only for testing, in fact, opennlp lemma does not
// exist!
assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
- assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(),
+ "foundry");
}
@Test
- public void testDefaultLayerMapperThrowsNoException() {
+ public void testDefaultLayerMapperThrowsNoException () {
assertEquals(config.getDefault_lemma(), m.findFoundry("lemma"));
assertEquals(config.getDefault_pos(), m.findFoundry("pos"));
assertEquals(config.getDefault_orthography(), m.findFoundry("surface"));
@@ -96,35 +113,42 @@
}
@Test
- public void testDefaultFoundryInjectLemmaThrowsNoError() throws KustvaktException {
+ public void testDefaultFoundryInjectLemmaThrowsNoError ()
+ throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
assertFalse(node.at("/query/wrap/foundry").isMissingNode());
- assertEquals(config.getDefault_lemma(), node.at("/query/wrap/foundry").asText());
+ assertEquals(config.getDefault_lemma(),
+ node.at("/query/wrap/foundry").asText());
assertEquals(node.at("/query/wrap/layer").asText(), "lemma");
assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
- assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testDefaultFoundryInjectPOSNoErrors() throws KustvaktException {
+ public void testDefaultFoundryInjectPOSNoErrors ()
+ throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[pos=ADJA]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
assertFalse(node.at("/query/wrap/foundry").isMissingNode());
- assertEquals(config.getDefault_pos(), node.at("/query/wrap/foundry").asText());
+ assertEquals(config.getDefault_pos(),
+ node.at("/query/wrap/foundry").asText());
assertEquals(node.at("/query/wrap/layer").asText(), "pos");
assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
- assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(),
+ "koral:rewrite");
}
@Test
- public void testFoundryInjectJoinedQueryNoErrors() throws KustvaktException {
+ public void testFoundryInjectJoinedQueryNoErrors ()
+ throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=laufe/i & base!=Lauf]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
@@ -138,7 +162,8 @@
}
@Test
- public void testFoundryInjectGroupedQueryNoErrors() throws KustvaktException {
+ public void testFoundryInjectGroupedQueryNoErrors ()
+ throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | tt/pos=VVFIN)]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
@@ -152,7 +177,7 @@
}
@Test
- public void testFoundryBaseRewrite() throws KustvaktException {
+ public void testFoundryBaseRewrite () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=laufen]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
index b0fc1ea..ef33982 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
@@ -26,7 +26,7 @@
private KustvaktConfiguration config;
@Test
- public void insertTokenId() throws KustvaktException {
+ public void insertTokenId () throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(IdWriter.class));
String query = "[surface=Wort]";
@@ -39,7 +39,7 @@
}
@Test
- public void testIdWriterTest() throws KustvaktException {
+ public void testIdWriterTest () throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(IdWriter.class));
QuerySerializer s = new QuerySerializer();
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
index 8862def..524dad5 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
@@ -18,28 +18,42 @@
public class QueryRewriteTest extends SpringJerseyTest {
@Test
- public void testRewriteRefNotFound() throws KustvaktException, Exception {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#examplequery} Baum").request().get();
+ public void testRewriteRefNotFound () throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "{q}").queryParam("ql", "poliqarp")
+ .resolveTemplate("q", "[orth=der]{#examplequery} Baum")
+ .request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/errors/0/1").asText(), "Query system/examplequery is not found.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Query system/examplequery is not found.");
}
@Test
- public void testRewriteSystemQuery() throws KustvaktException, Exception {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#system-q} Baum").request().get();
+ public void testRewriteSystemQuery () throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "{q}").queryParam("ql", "poliqarp")
+ .resolveTemplate("q", "[orth=der]{#system-q} Baum").request()
+ .get();
String ent = response.readEntity(String.class);
// System.out.println(ent);
JsonNode node = JsonUtils.readTree(ent);
}
@Test
- public void testRewriteRefRewrite() throws KustvaktException, Exception {
+ public void testRewriteRefRewrite () throws KustvaktException, Exception {
// Added in the database migration sql for tests
- Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#dory/dory-q} Baum").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "{q}").queryParam("ql", "poliqarp")
+ .resolveTemplate("q", "[orth=der]{#dory/dory-q} Baum").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/query/operands/1/@type").asText(), "koral:token");
- assertEquals(node.at("/query/operands/1/rewrites/0/scope").asText(), "@type(koral:queryRef)");
+ assertEquals(node.at("/query/operands/1/@type").asText(),
+ "koral:token");
+ assertEquals(node.at("/query/operands/1/rewrites/0/scope").asText(),
+ "@type(koral:queryRef)");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
index 6642514..77767a0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
@@ -21,9 +21,11 @@
public RewriteHandler ha;
@Test
- public void testPostRewriteNothingToDo() throws KustvaktException {
- assertEquals(true, ha.add(CollectionRewrite.class), "Handler could not be added to rewrite handler instance!");
+ public void testPostRewriteNothingToDo () throws KustvaktException {
+ assertEquals(true, ha.add(CollectionRewrite.class),
+ "Handler could not be added to rewrite handler instance!");
String v = ha.processResult(TestVariables.RESULT, null);
- assertEquals(JsonUtils.readTree(TestVariables.RESULT), JsonUtils.readTree(v), "results do not match");
+ assertEquals(JsonUtils.readTree(TestVariables.RESULT),
+ JsonUtils.readTree(v), "results do not match");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
index 60b934c..35df9d3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
@@ -79,7 +79,7 @@
private KustvaktConfiguration config;
@Test
- public void testRewriteTaskAdd() {
+ public void testRewriteTaskAdd () {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(FoundryInject.class));
assertTrue(handler.add(CollectionCleanRewrite.class));
@@ -88,11 +88,12 @@
// throws exception cause of missing configuration
@Test
- public void testRewriteConfigThrowsException() {
+ public void testRewriteConfigThrowsException () {
assertThrows(RuntimeException.class, () -> {
RewriteHandler handler = new RewriteHandler();
QuerySerializer s = new QuerySerializer();
- s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
+ s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]",
+ "poliqarp");
assertTrue(handler.add(FoundryInject.class));
handler.processQuery(s.toJSON(), null);
});
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
index 170ffd0..f0ea66c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
@@ -36,10 +36,13 @@
private QueryDao dao;
@Test
- public void testRefCachedVC() throws KustvaktException, IOException, QueryException {
+ public void testRefCachedVC ()
+ throws KustvaktException, IOException, QueryException {
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains("named-vc1"));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo named-vc1").request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo named-vc1").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
@@ -54,8 +57,12 @@
assertFalse(VirtualCorpusCache.contains("named-vc1"));
}
- private void testRefCachedVCWithUsername() throws KustvaktException, IOException, QueryException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/named-vc1\"").request().get();
+ private void testRefCachedVCWithUsername ()
+ throws KustvaktException, IOException, QueryException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"system/named-vc1\"").request()
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
@@ -67,8 +74,11 @@
}
@Test
- public void testRewriteFreeAndSystemVCRef() throws KustvaktException, Exception {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system-vc\"").request().get();
+ public void testRewriteFreeAndSystemVCRef ()
+ throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"system-vc\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
@@ -85,8 +95,13 @@
}
@Test
- public void testRewritePubAndSystemVCRef() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/system-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("user", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testRewritePubAndSystemVCRef () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"system/system-vc\"").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("user", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
@@ -100,8 +115,14 @@
}
@Test
- public void testRewriteWithDoryVCRef() throws KustvaktException, IOException, QueryException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Fisch").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
+ public void testRewriteWithDoryVCRef ()
+ throws KustvaktException, IOException, QueryException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Fisch").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"dory/dory-vc\"").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
diff --git a/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java b/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
index 0119a21..fcc655f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
@@ -28,12 +28,15 @@
* this instance:<em>kustvakt-icc.conf</em>.
*
* <p>
- * To run a Kustvakt jar with ICC setup, the following files are needed:
+ * To run a Kustvakt jar with ICC setup, the following files are
+ * needed:
* </p>
* <ul>
* <li>a Spring configuration file</li>
- * <li>a Kustvakt configuration file that must be placed at the jar folder</li>
- * <li>a JDBC properties file that must be placed at the jar folder</li>
+ * <li>a Kustvakt configuration file that must be placed at the jar
+ * folder</li>
+ * <li>a JDBC properties file that must be placed at the jar
+ * folder</li>
* </ul>
* <p>
* Example:
@@ -67,12 +70,14 @@
* </code>
* </pre>
*
- * <p>For production, the init-method of Initializator should be changed to init.</p>
+ * <p>For production, the init-method of Initializator should be
+ * changed to init.</p>
*
* <pre>
* <code>
- * <bean id="initializator" class="de.ids_mannheim.de.init.Initializator"
- * init-method="init"></bean>
+ * <bean id="initializator"
+ * class="de.ids_mannheim.de.init.Initializator"
+ * init-method="init"></bean>
* </code>
* </pre>
*
@@ -129,22 +134,28 @@
public String basicAuth;
- public ICCTest() throws KustvaktException {
- basicAuth = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("user", "password");
+ public ICCTest () throws KustvaktException {
+ basicAuth = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("user", "password");
}
@Test
- public void searchWithoutLogin() throws KustvaktException {
- Response r = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").request().get();
+ public void searchWithoutLogin () throws KustvaktException {
+ Response r = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), r.getStatus());
String entity = r.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void searchWithLogin() throws KustvaktException {
- Response r = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, basicAuth).get();
+ public void searchWithLogin () throws KustvaktException {
+ Response r = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .request().header(Attributes.AUTHORIZATION, basicAuth).get();
assertEquals(Status.OK.getStatusCode(), r.getStatus());
String entity = r.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -152,17 +163,23 @@
}
@Test
- public void matchInfoWithoutLogin() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("WDD17").path("982").path("72848").path("p2815-2816").queryParam("foundry", "*").request().get();
+ public void matchInfoWithoutLogin () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("WDD17").path("982").path("72848").path("p2815-2816")
+ .queryParam("foundry", "*").request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void matchInfoWithLogin() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("WDD17").path("982").path("72848").path("p2815-2816").queryParam("foundry", "*").request().header(Attributes.AUTHORIZATION, basicAuth).get();
+ public void matchInfoWithLogin () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("WDD17").path("982").path("72848").path("p2815-2816")
+ .queryParam("foundry", "*").request()
+ .header(Attributes.AUTHORIZATION, basicAuth).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java b/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
index 79f640f..98b35cf 100644
--- a/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
@@ -18,71 +18,90 @@
import static de.ids_mannheim.korap.authentication.LdapAuth3.LDAP_AUTH_RUNKNOWN;
import static org.junit.jupiter.api.Assertions.assertEquals;
-
public class EmbeddedLdapServerTest {
public static final String TEST_EMBEDDED_LDAP_CONF = "src/test/resources/test-embedded-ldap.conf";
@AfterAll
- static void shutdownEmbeddedLdapServer() {
+ static void shutdownEmbeddedLdapServer () {
EmbeddedLdapServer.stop();
}
@Test
- public void embeddedServerStartsAutomaticallyAndUsersCanLogin() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user", "password", TEST_EMBEDDED_LDAP_CONF));
+ public void embeddedServerStartsAutomaticallyAndUsersCanLogin ()
+ throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("user", "password", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void usersWithClearPasswordCanLogin() throws LDAPException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user1", "password1", TEST_EMBEDDED_LDAP_CONF));
+ public void usersWithClearPasswordCanLogin () throws LDAPException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("user1", "password1", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void usersWithSHA1PasswordCanLogin() throws LDAPException, NoSuchAlgorithmException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user3", "password3", TEST_EMBEDDED_LDAP_CONF));
+ public void usersWithSHA1PasswordCanLogin ()
+ throws LDAPException, NoSuchAlgorithmException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("user3", "password3", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void usersWithSHA256PasswordCanLogin() throws LDAPException, NoSuchAlgorithmException, InvalidKeySpecException {
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user4", "password4", TEST_EMBEDDED_LDAP_CONF));
+ public void usersWithSHA256PasswordCanLogin () throws LDAPException,
+ NoSuchAlgorithmException, InvalidKeySpecException {
+ assertEquals(LDAP_AUTH_ROK,
+ LdapAuth3.login("user4", "password4", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void asteriskPasswordsFail() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("user1", "*", TEST_EMBEDDED_LDAP_CONF));
+ public void asteriskPasswordsFail () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("user1", "*", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void loginWithPreencodedPBKDF2Password() throws LDAPException, NoSuchAlgorithmException, InvalidKeySpecException {
+ public void loginWithPreencodedPBKDF2Password () throws LDAPException,
+ NoSuchAlgorithmException, InvalidKeySpecException {
byte[] salt = new byte[32];
- KeySpec spec = new PBEKeySpec("password5".toCharArray(), salt, 65536, 256);
- SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2withHmacSHA256");
+ KeySpec spec = new PBEKeySpec("password5".toCharArray(), salt, 65536,
+ 256);
+ SecretKeyFactory f = SecretKeyFactory
+ .getInstance("PBKDF2withHmacSHA256");
byte[] hash = f.generateSecret(spec).getEncoded();
- final String pbkdf2sha256Password = "{PBKDF2-SHA256}" + Base64.encode(hash);
+ final String pbkdf2sha256Password = "{PBKDF2-SHA256}"
+ + Base64.encode(hash);
// System.out.println(pbkdf2sha256Password);
- assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user5", pbkdf2sha256Password, TEST_EMBEDDED_LDAP_CONF));
+ assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user5",
+ pbkdf2sha256Password, TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void loginWithUnencodedPBKDF2PasswordFails() throws LDAPException, NoSuchAlgorithmException, InvalidKeySpecException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("user5", "password5", TEST_EMBEDDED_LDAP_CONF));
+ public void loginWithUnencodedPBKDF2PasswordFails () throws LDAPException,
+ NoSuchAlgorithmException, InvalidKeySpecException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("user5", "password5", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void unauthorizedUsersAreNotAllowed() throws LDAPException {
- assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("yuser", "password", TEST_EMBEDDED_LDAP_CONF));
+ public void unauthorizedUsersAreNotAllowed () throws LDAPException {
+ assertEquals(LDAP_AUTH_RUNKNOWN,
+ LdapAuth3.login("yuser", "password", TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void gettingMailForUser() throws LDAPException, UnknownHostException, GeneralSecurityException {
+ public void gettingMailForUser () throws LDAPException,
+ UnknownHostException, GeneralSecurityException {
EmbeddedLdapServer.startIfNotRunning(TEST_EMBEDDED_LDAP_CONF);
- assertEquals(LdapAuth3.getEmail("user2", TEST_EMBEDDED_LDAP_CONF), "user2@example.com");
+ assertEquals(LdapAuth3.getEmail("user2", TEST_EMBEDDED_LDAP_CONF),
+ "user2@example.com");
}
@Test
- public void gettingMailForNAUTHUserIsNull() throws LDAPException, UnknownHostException, GeneralSecurityException {
+ public void gettingMailForNAUTHUserIsNull () throws LDAPException,
+ UnknownHostException, GeneralSecurityException {
EmbeddedLdapServer.startIfNotRunning(TEST_EMBEDDED_LDAP_CONF);
- assertEquals(null, LdapAuth3.getEmail("user1000", TEST_EMBEDDED_LDAP_CONF));
+ assertEquals(null,
+ LdapAuth3.getEmail("user1000", TEST_EMBEDDED_LDAP_CONF));
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
index 60a661f..8799ad7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
@@ -33,7 +33,7 @@
private UserGroupService groupService;
@Test
- public void testCreateNonUniqueVC() throws KustvaktException {
+ public void testCreateNonUniqueVC () throws KustvaktException {
// EM: message differs depending on the database used
// for testing. The message below is from sqlite.
// thrown.expectMessage("A UNIQUE constraint failed "
@@ -43,11 +43,12 @@
vc.setCorpusQuery("corpusSigle=GOE");
vc.setType(ResourceType.PRIVATE);
vc.setQueryType(QueryType.VIRTUAL_CORPUS);
- assertThrows(KustvaktException.class, () -> vcService.storeQuery(vc, "dory-vc", "dory", "dory"));
+ assertThrows(KustvaktException.class,
+ () -> vcService.storeQuery(vc, "dory-vc", "dory", "dory"));
}
@Test
- public void createDeletePublishVC() throws KustvaktException {
+ public void createDeletePublishVC () throws KustvaktException {
String vcName = "new-published-vc";
QueryJson vc = new QueryJson();
vc.setCorpusQuery("corpusSigle=GOE");
@@ -55,7 +56,8 @@
vc.setQueryType(QueryType.VIRTUAL_CORPUS);
String username = "VirtualCorpusServiceTest";
vcService.storeQuery(vc, vcName, username, username);
- List<QueryAccessDto> accesses = vcService.listQueryAccessByUsername("admin");
+ List<QueryAccessDto> accesses = vcService
+ .listQueryAccessByUsername("admin");
int size = accesses.size();
QueryAccessDto dto = accesses.get(accesses.size() - 1);
assertEquals(vcName, dto.getQueryName());
@@ -66,21 +68,25 @@
UserGroup group = groupService.retrieveUserGroupById(groupId);
assertEquals(UserGroupStatus.HIDDEN, group.getStatus());
// delete vc
- vcService.deleteQueryByName(username, vcName, username, QueryType.VIRTUAL_CORPUS);
+ vcService.deleteQueryByName(username, vcName, username,
+ QueryType.VIRTUAL_CORPUS);
// check hidden access
accesses = vcService.listQueryAccessByUsername("admin");
assertEquals(size - 1, accesses.size());
// check hidden group
- KustvaktException e = assertThrows(KustvaktException.class, () -> groupService.retrieveUserGroupById(groupId));
- assertEquals("Group with id " + groupId + " is not found", e.getMessage());
+ KustvaktException e = assertThrows(KustvaktException.class,
+ () -> groupService.retrieveUserGroupById(groupId));
+ assertEquals("Group with id " + groupId + " is not found",
+ e.getMessage());
}
@Test
- public void testEditPublishVC() throws KustvaktException {
+ public void testEditPublishVC () throws KustvaktException {
String username = "dory";
int vcId = 2;
String vcName = "group-vc";
- QueryDO existingVC = vcService.searchQueryByName(username, vcName, username, QueryType.VIRTUAL_CORPUS);
+ QueryDO existingVC = vcService.searchQueryByName(username, vcName,
+ username, QueryType.VIRTUAL_CORPUS);
QueryJson vcJson = new QueryJson();
vcJson.setType(ResourceType.PUBLISHED);
vcService.editQuery(existingVC, vcJson, vcName, username);
@@ -89,7 +95,8 @@
assertEquals(vcName, vcDto.getName());
assertEquals(ResourceType.PUBLISHED.displayName(), vcDto.getType());
// check access
- List<QueryAccessDto> accesses = vcService.listQueryAccessByUsername("admin");
+ List<QueryAccessDto> accesses = vcService
+ .listQueryAccessByUsername("admin");
int size = accesses.size();
QueryAccessDto dto = accesses.get(accesses.size() - 1);
assertEquals(vcName, dto.getQueryName());
@@ -110,7 +117,9 @@
// check access
accesses = vcService.listQueryAccessByUsername("admin");
assertEquals(size - 1, accesses.size());
- KustvaktException e = assertThrows(KustvaktException.class, () -> groupService.retrieveUserGroupById(groupId));
- assertEquals("Group with id " + groupId + " is not found", e.getMessage());
+ KustvaktException e = assertThrows(KustvaktException.class,
+ () -> groupService.retrieveUserGroupById(groupId));
+ assertEquals("Group with id " + groupId + " is not found",
+ e.getMessage());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java b/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
index 513020e..5584fb7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
@@ -20,7 +20,7 @@
public class DataFactoryTest {
@Test
- public void testDataFactoryAdd() throws KustvaktException {
+ public void testDataFactoryAdd () throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
@@ -36,7 +36,7 @@
}
@Test
- public void testDataFactoryGet() throws KustvaktException {
+ public void testDataFactoryGet () throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
@@ -63,7 +63,7 @@
}
@Test
- public void testDataFactoryMerge() throws KustvaktException {
+ public void testDataFactoryMerge () throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
@@ -85,7 +85,7 @@
}
@Test
- public void testDataFactoryKeys() throws KustvaktException {
+ public void testDataFactoryKeys () throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
@@ -98,7 +98,7 @@
@Test
@Disabled
- public void testDataFactoryRemove() throws KustvaktException {
+ public void testDataFactoryRemove () throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
@@ -136,7 +136,7 @@
}
@Test
- public void testDataFactoryEmbeddedProperty() throws KustvaktException {
+ public void testDataFactoryEmbeddedProperty () throws KustvaktException {
String data = "{}";
JsonNode node = JsonUtils.readTree(data);
DataFactory factory = DataFactory.getFactory();
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
index 75f3e6b..0e99a7f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
@@ -27,7 +27,7 @@
// EM: added
@Test
- public void testReadEmptyMap() throws KustvaktException {
+ public void testReadEmptyMap () throws KustvaktException {
Userdata userData = new UserSettingProcessor();
userData.read(new HashMap<>(), false);
String jsonSettings = userData.serialize();
@@ -35,7 +35,7 @@
}
@Test
- public void testReadNullMap() throws KustvaktException {
+ public void testReadNullMap () throws KustvaktException {
Userdata userData = new UserSettingProcessor();
userData.read(null, false);
String jsonSettings = userData.serialize();
@@ -53,10 +53,10 @@
//
// At the moment, validation is not needed for default settings.
@Test
- public void testValidateMap() throws IOException, KustvaktException {
+ public void testValidateMap () throws IOException, KustvaktException {
Map<String, Object> map = new HashMap<>();
- map.put("k1", Arrays.asList(new String[]{"a", "b", "c"}));
- map.put("k2", Arrays.asList(new Integer[]{1, 2, 3}));
+ map.put("k1", Arrays.asList(new String[] { "a", "b", "c" }));
+ map.put("k2", Arrays.asList(new Integer[] { 1, 2, 3 }));
Userdata data = new UserSettingProcessor();
data.read(map, false);
data.validate(new ApacheValidator());
@@ -64,7 +64,7 @@
// EM: below are tests from MH
@Test
- public void testDataValidation() {
+ public void testDataValidation () {
Userdata data = new UserDetails(1);
data.setField(Attributes.COUNTRY, "Germany");
String[] req = data.requiredFields();
@@ -75,7 +75,7 @@
}
@Test
- public void testSettingsValidation() {
+ public void testSettingsValidation () {
Userdata data = new UserSettingProcessor();
data.setField(Attributes.FILE_FORMAT_FOR_EXPORT, "export");
String[] req = data.requiredFields();
@@ -86,7 +86,7 @@
}
@Test
- public void testUserdataRequiredFields() throws KustvaktException {
+ public void testUserdataRequiredFields () throws KustvaktException {
UserDetails details = new UserDetails(-1);
Map<String, Object> m = new HashMap<>();
m.put(Attributes.FIRSTNAME, "first");
@@ -100,7 +100,7 @@
}
@Test
- public void testUserdataDefaultFields() throws KustvaktException {
+ public void testUserdataDefaultFields () throws KustvaktException {
UserSettingProcessor settings = new UserSettingProcessor();
Map<String, Object> m = new HashMap<>();
m.put(Attributes.DEFAULT_FOUNDRY_RELATION, "rel_1");
@@ -113,15 +113,17 @@
settings.read(m, true);
assertNotEquals(m.size(), settings.size());
assertEquals(settings.defaultFields().length, settings.size());
- assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_RELATION), "rel_1");
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_RELATION),
+ "rel_1");
assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_POS), "pos_1");
assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_LEMMA), "lemma_1");
- assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT), "const_1");
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT),
+ "const_1");
assertEquals(10, settings.get(Attributes.PAGE_LENGTH));
}
@Test
- public void testUserDataRequiredFieldsException() {
+ public void testUserDataRequiredFieldsException () {
assertThrows(KustvaktException.class, () -> {
UserDetails details = new UserDetails(-1);
Map<String, Object> m = new HashMap<>();
@@ -137,7 +139,7 @@
}
@Test
- public void testUserDataPointerFunction() throws KustvaktException {
+ public void testUserDataPointerFunction () throws KustvaktException {
UserDetails details = new UserDetails(-1);
Map<String, Object> m = new HashMap<>();
m.put(Attributes.FIRSTNAME, "first");
@@ -154,7 +156,7 @@
}
@Test
- public void testUserDataUpdate() {
+ public void testUserDataUpdate () {
UserDetails details = new UserDetails(-1);
details.setField(Attributes.FIRSTNAME, "first");
details.setField(Attributes.LASTNAME, "last");
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java b/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
index e06fe0d..9e138fa 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
@@ -18,16 +18,20 @@
public class ApiVersionTest extends SpringJerseyTest {
@Test
- public void testSearchWithoutVersion() throws KustvaktException {
- Response response = target().path("api").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWithoutVersion () throws KustvaktException {
+ Response response = target().path("api").path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
assertEquals("/api/" + API_VERSION + "/search", location.getPath());
}
@Test
- public void testSearchWrongVersion() throws KustvaktException {
- Response response = target().path("api").path("v0.2").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWrongVersion () throws KustvaktException {
+ Response response = target().path("api").path("v0.2").path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
assertEquals("/api/" + API_VERSION + "/search", location.getPath());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
index a936e6b..e8c8eef 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
@@ -29,10 +29,12 @@
@Autowired
private OAuth2ClientDao clientDao;
- private String path = KustvaktConfiguration.DATA_FOLDER + "/" + OAuth2InitClientService.TEST_OUTPUT_FILENAME;
+ private String path = KustvaktConfiguration.DATA_FOLDER + "/"
+ + OAuth2InitClientService.TEST_OUTPUT_FILENAME;
@Test
- public void testCreatingInitialSuperClient() throws IOException, KustvaktException {
+ public void testCreatingInitialSuperClient ()
+ throws IOException, KustvaktException {
assertTrue(config.createInitialSuperClient());
File f = new File(path);
assertTrue(f.exists());
@@ -45,8 +47,10 @@
removeSuperClientFile();
}
- private void testLogin(String superClientId, String superClientSecret) throws KustvaktException {
- Response response = requestTokenWithPassword(superClientId, superClientSecret, "username", "password");
+ private void testLogin (String superClientId, String superClientSecret)
+ throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId,
+ superClientSecret, "username", "password");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertTrue(!node.at("/access_token").isMissingNode());
@@ -56,7 +60,7 @@
assertEquals(node.at("/token_type").asText(), "Bearer");
}
- private void removeSuperClientFile() {
+ private void removeSuperClientFile () {
File f = new File(path);
if (f.exists()) {
f.delete();
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
index 571c15c..4730f2c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
@@ -18,29 +18,30 @@
public class JettyServerTest {
static int selectedPort = 0;
-
+
@BeforeAll
- static void testServerStarts() throws Exception {
-
-
+ static void testServerStarts () throws Exception {
+
for (int port = 1000; port <= 2000; port++) {
try (ServerSocket ignored = new ServerSocket(port)) {
selectedPort = port;
break;
- } catch (IOException ignored) {
+ }
+ catch (IOException ignored) {
// Port is already in use, try the next one
}
}
-
+
Server server = new Server(selectedPort);
- ShutdownHandler shutdownHandler = new ShutdownHandler("secret");
+ ShutdownHandler shutdownHandler = new ShutdownHandler("secret");
server.setHandler(shutdownHandler);
server.start();
}
-
+
@Test
- public void testShutdown() throws IOException {
- URL url = new URL("http://localhost:"+selectedPort+"/shutdown?token=secret");
+ public void testShutdown () throws IOException {
+ URL url = new URL(
+ "http://localhost:" + selectedPort + "/shutdown?token=secret");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
assertEquals(200, connection.getResponseCode());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java b/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
index c4476c2..2034592 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
@@ -30,31 +30,33 @@
SearchKrill krill = null;
@PostConstruct
- private void createKrill() {
+ private void createKrill () {
krill = new SearchKrill(config.getIndexDir());
assertNotNull(krill);
}
@Test
- public void testIndex() throws KustvaktException {
+ public void testIndex () throws KustvaktException {
KrillIndex index = krill.getIndex();
assertNotNull(index);
}
@Test
- public void testDocSize() {
+ public void testDocSize () {
assertNotEquals(0, krill.getIndex().numberOf("documents"));
}
@Test
- public void testMatchInfo() throws KustvaktException {
- String matchinfo = krill.getMatch("WPD/AAA.00002/p169-197", config.getFreeLicensePattern());
+ public void testMatchInfo () throws KustvaktException {
+ String matchinfo = krill.getMatch("WPD/AAA.00002/p169-197",
+ config.getFreeLicensePattern());
JsonNode node = JsonUtils.readTree(matchinfo);
- assertEquals(node.at("/errors/0/1").asText(), "Invalid match identifier");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Invalid match identifier");
}
@Test
- public void testSearch() throws KustvaktException {
+ public void testSearch () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
String result = krill.search(s.toJSON());
@@ -64,7 +66,7 @@
}
@Test
- public void testTimeOut() throws KustvaktException {
+ public void testTimeOut () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
// s.setQuery("node ->malt/d[func=/.*/] node", "annis");
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
index c7bc757..2c359a0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
@@ -20,11 +20,16 @@
public class AdminLoadVCTest extends SpringJerseyTest {
@Test
- public void testLoadCacheVC() throws KustvaktException, InterruptedException {
+ public void testLoadCacheVC ()
+ throws KustvaktException, InterruptedException {
assertFalse(VirtualCorpusCache.contains("named-vc1"));
Form f = new Form();
f.param("token", "secret");
- Response response = target().path(API_VERSION).path("admin").path("vc").path("load-cache").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin").path("vc")
+ .path("load-cache").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
Thread.sleep(100);
assertTrue(VirtualCorpusCache.contains("named-vc1"));
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
index 9626114..e6737bb 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
@@ -19,8 +19,9 @@
public class AnnotationControllerTest extends SpringJerseyTest {
@Test
- public void testAnnotationLayers() throws KustvaktException {
- Response response = target().path(API_VERSION).path("annotation").path("layers").request().get();
+ public void testAnnotationLayers () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("annotation")
+ .path("layers").request().get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
assertEquals(31, n.size());
@@ -33,9 +34,10 @@
}
@Test
- public void testAnnotationFoundry() throws KustvaktException {
+ public void testAnnotationFoundry () throws KustvaktException {
String json = "{\"codes\":[\"opennlp/*\"], \"language\":\"en\"}";
- Response response = target().path(API_VERSION).path("annotation").path("description").request().post(Entity.json(json));
+ Response response = target().path(API_VERSION).path("annotation")
+ .path("description").request().post(Entity.json(json));
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
n = n.get(0);
@@ -53,9 +55,10 @@
}
@Test
- public void testAnnotationValues() throws KustvaktException {
+ public void testAnnotationValues () throws KustvaktException {
String json = "{\"codes\":[\"mate/m\"], \"language\":\"en\"}";
- Response response = target().path(API_VERSION).path("annotation").path("description").request().post(Entity.json(json));
+ Response response = target().path(API_VERSION).path("annotation")
+ .path("description").request().post(Entity.json(json));
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
n = n.get(0);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
index ca4c915..42d7a68 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
@@ -19,125 +19,193 @@
public class AvailabilityTest extends SpringJerseyTest {
- private void checkAndFree(String json) throws KustvaktException {
+ private void checkAndFree (String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
- assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
}
- private void checkAndPublic(String json) throws KustvaktException {
+ private void checkAndPublic (String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/operands/0/operands/0/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/0/operands/0/type").asText(), "type:regex");
- assertEquals(node.at("/collection/operands/0/operands/0/key").asText(), "availability");
- assertEquals(node.at("/collection/operands/0/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/0/operands/1/operands/0/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/0/operands/1/operands/0/value").asText(), "ACA.*");
- assertEquals(node.at("/collection/operands/0/operands/1/operands/1/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/0/operands/1/operands/1/value").asText(), "QAO-NC");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(
+ node.at("/collection/operands/0/operands/0/match").asText(),
+ "match:eq");
+ assertEquals(node.at("/collection/operands/0/operands/0/type").asText(),
+ "type:regex");
+ assertEquals(node.at("/collection/operands/0/operands/0/key").asText(),
+ "availability");
+ assertEquals(
+ node.at("/collection/operands/0/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(
+ node.at("/collection/operands/0/operands/1/operands/0/match")
+ .asText(),
+ "match:eq");
+ assertEquals(
+ node.at("/collection/operands/0/operands/1/operands/0/value")
+ .asText(),
+ "ACA.*");
+ assertEquals(
+ node.at("/collection/operands/0/operands/1/operands/1/match")
+ .asText(),
+ "match:eq");
+ assertEquals(
+ node.at("/collection/operands/0/operands/1/operands/1/value")
+ .asText(),
+ "QAO-NC");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(PUB)");
}
- private void checkAndPublicWithACA(String json) throws KustvaktException {
+ private void checkAndPublicWithACA (String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
- assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/1/type").asText(), "type:regex");
- assertEquals(node.at("/collection/operands/1/key").asText(), "availability");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(PUB)");
+ assertEquals(node.at("/collection/operands/1/match").asText(),
+ "match:eq");
+ assertEquals(node.at("/collection/operands/1/type").asText(),
+ "type:regex");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "availability");
assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
node = node.at("/collection/operands/0");
assertEquals(node.at("/operands/0/match").asText(), "match:eq");
assertEquals(node.at("/operands/0/type").asText(), "type:regex");
assertEquals(node.at("/operands/0/key").asText(), "availability");
assertEquals(node.at("/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/operands/1/operands/0/match").asText(), "match:eq");
- assertEquals(node.at("/operands/1/operands/0/type").asText(), "type:regex");
- assertEquals(node.at("/operands/1/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/operands/1/operands/0/match").asText(),
+ "match:eq");
+ assertEquals(node.at("/operands/1/operands/0/type").asText(),
+ "type:regex");
+ assertEquals(node.at("/operands/1/operands/0/key").asText(),
+ "availability");
assertEquals(node.at("/operands/1/operands/0/value").asText(), "ACA.*");
}
- private void checkAndAllWithACA(String json) throws KustvaktException {
+ private void checkAndAllWithACA (String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
- assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/1/type").asText(), "type:regex");
- assertEquals(node.at("/collection/operands/1/key").asText(), "availability");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
+ assertEquals(node.at("/collection/operands/1/match").asText(),
+ "match:eq");
+ assertEquals(node.at("/collection/operands/1/type").asText(),
+ "type:regex");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "availability");
assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
node = node.at("/collection/operands/0");
assertEquals(node.at("/operands/0/match").asText(), "match:eq");
assertEquals(node.at("/operands/0/type").asText(), "type:regex");
assertEquals(node.at("/operands/0/key").asText(), "availability");
assertEquals(node.at("/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/operands/1/operands/1/operands/0/match").asText(), "match:eq");
- assertEquals(node.at("/operands/1/operands/1/operands/0/value").asText(), "QAO-NC");
- assertEquals(node.at("/operands/1/operands/1/operands/1/match").asText(), "match:eq");
- assertEquals(node.at("/operands/1/operands/1/operands/1/value").asText(), "QAO.*");
+ assertEquals(
+ node.at("/operands/1/operands/1/operands/0/match").asText(),
+ "match:eq");
+ assertEquals(
+ node.at("/operands/1/operands/1/operands/0/value").asText(),
+ "QAO-NC");
+ assertEquals(
+ node.at("/operands/1/operands/1/operands/1/match").asText(),
+ "match:eq");
+ assertEquals(
+ node.at("/operands/1/operands/1/operands/1/value").asText(),
+ "QAO.*");
}
- private Response searchQuery(String collectionQuery) {
- return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", collectionQuery).request().get();
+ private Response searchQuery (String collectionQuery) {
+ return target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("cq", collectionQuery).request().get();
}
- private Response searchQueryWithIP(String collectionQuery, String ip) throws ProcessingException, KustvaktException {
- return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", collectionQuery).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, ip).get();
+ private Response searchQueryWithIP (String collectionQuery, String ip)
+ throws ProcessingException, KustvaktException {
+ return target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("cq", collectionQuery).request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, ip).get();
}
@Test
- public void testAvailabilityFreeAuthorized() throws KustvaktException {
+ public void testAvailabilityFreeAuthorized () throws KustvaktException {
Response response = searchQuery("availability = CC-BY-SA");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexFreeAuthorized() throws KustvaktException {
+ public void testAvailabilityRegexFreeAuthorized ()
+ throws KustvaktException {
Response response = searchQuery("availability = /.*BY.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityFreeUnauthorized() throws KustvaktException {
+ public void testAvailabilityFreeUnauthorized () throws KustvaktException {
Response response = searchQuery("availability = ACA-NC");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexFreeUnauthorized() throws KustvaktException {
+ public void testAvailabilityRegexFreeUnauthorized ()
+ throws KustvaktException {
Response response = searchQuery("availability = /ACA.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexNoRewrite() throws KustvaktException {
- Response response = searchQuery("availability = /CC-BY.*/ & availability = /ACA.*/");
+ public void testAvailabilityRegexNoRewrite () throws KustvaktException {
+ Response response = searchQuery(
+ "availability = /CC-BY.*/ & availability = /ACA.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String json = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(json);
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
- assertEquals(node.at("/collection/operands/0/match").asText(), "match:eq");
- assertEquals(node.at("/collection/operands/0/type").asText(), "type:regex");
- assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
+ assertEquals(node.at("/collection/operands/0/match").asText(),
+ "match:eq");
+ assertEquals(node.at("/collection/operands/0/type").asText(),
+ "type:regex");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/match").asText(),
+ "match:eq");
assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
}
@Test
- public void testAvailabilityRegexFreeUnauthorized3() throws KustvaktException {
+ public void testAvailabilityRegexFreeUnauthorized3 ()
+ throws KustvaktException {
Response response = searchQuery("availability = /.*NC.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// System.out.println(response.readEntity(String.class));
@@ -145,113 +213,141 @@
}
@Test
- public void testNegationAvailabilityFreeUnauthorized() throws KustvaktException {
+ public void testNegationAvailabilityFreeUnauthorized ()
+ throws KustvaktException {
Response response = searchQuery("availability != /CC-BY.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityFreeUnauthorized2() throws KustvaktException {
+ public void testNegationAvailabilityFreeUnauthorized2 ()
+ throws KustvaktException {
Response response = searchQuery("availability != /.*BY.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityWithOperationOrUnauthorized() throws KustvaktException {
- Response response = searchQuery("availability = /CC-BY.*/ | availability != /CC-BY.*/");
+ public void testNegationAvailabilityWithOperationOrUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQuery(
+ "availability = /CC-BY.*/ | availability != /CC-BY.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testComplexNegationAvailabilityFreeUnauthorized() throws KustvaktException {
- Response response = searchQuery("textClass=politik & availability != /CC-BY.*/");
+ public void testComplexNegationAvailabilityFreeUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQuery(
+ "textClass=politik & availability != /CC-BY.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testComplexAvailabilityFreeUnauthorized() throws KustvaktException {
- Response response = searchQuery("textClass=politik & availability=ACA-NC");
+ public void testComplexAvailabilityFreeUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQuery(
+ "textClass=politik & availability=ACA-NC");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testComplexAvailabilityFreeUnauthorized3() throws KustvaktException {
- Response response = searchQuery("textClass=politik & availability=/.*NC.*/");
+ public void testComplexAvailabilityFreeUnauthorized3 ()
+ throws KustvaktException {
+ Response response = searchQuery(
+ "textClass=politik & availability=/.*NC.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityPublicAuthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability=ACA-NC", "149.27.0.32");
+ public void testAvailabilityPublicAuthorized () throws KustvaktException {
+ Response response = searchQueryWithIP("availability=ACA-NC",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testAvailabilityPublicUnauthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability=QAO-NC-LOC:ids", "149.27.0.32");
+ public void testAvailabilityPublicUnauthorized () throws KustvaktException {
+ Response response = searchQueryWithIP("availability=QAO-NC-LOC:ids",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexPublicAuthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability= /ACA.*/", "149.27.0.32");
+ public void testAvailabilityRegexPublicAuthorized ()
+ throws KustvaktException {
+ Response response = searchQueryWithIP("availability= /ACA.*/",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublicWithACA(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityPublicUnauthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability != ACA-NC", "149.27.0.32");
+ public void testNegationAvailabilityPublicUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQueryWithIP("availability != ACA-NC",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityRegexPublicUnauthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability != /ACA.*/", "149.27.0.32");
+ public void testNegationAvailabilityRegexPublicUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQueryWithIP("availability != /ACA.*/",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testComplexAvailabilityPublicUnauthorized() throws KustvaktException {
- Response response = searchQueryWithIP("textClass=politik & availability=QAO-NC-LOC:ids", "149.27.0.32");
+ public void testComplexAvailabilityPublicUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQueryWithIP(
+ "textClass=politik & availability=QAO-NC-LOC:ids",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testNegationComplexAvailabilityPublicUnauthorized() throws KustvaktException {
- Response response = searchQueryWithIP("textClass=politik & availability!=QAO-NC-LOC:ids", "149.27.0.32");
+ public void testNegationComplexAvailabilityPublicUnauthorized ()
+ throws KustvaktException {
+ Response response = searchQueryWithIP(
+ "textClass=politik & availability!=QAO-NC-LOC:ids",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexAllAuthorized() throws KustvaktException {
- Response response = searchQueryWithIP("availability= /ACA.*/", "10.27.0.32");
+ public void testAvailabilityRegexAllAuthorized () throws KustvaktException {
+ Response response = searchQueryWithIP("availability= /ACA.*/",
+ "10.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndAllWithACA(response.readEntity(String.class));
}
@Test
- public void testAvailabilityOr() throws KustvaktException {
- Response response = searchQuery("availability=/CC-BY.*/ | availability=/ACA.*/");
+ public void testAvailabilityOr () throws KustvaktException {
+ Response response = searchQuery(
+ "availability=/CC-BY.*/ | availability=/ACA.*/");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testRedundancyOrPub() throws KustvaktException {
- Response response = searchQueryWithIP("availability=/CC-BY.*/ | availability=/ACA.*/ | availability=/QAO-NC/", "149.27.0.32");
+ public void testRedundancyOrPub () throws KustvaktException {
+ Response response = searchQueryWithIP(
+ "availability=/CC-BY.*/ | availability=/ACA.*/ | availability=/QAO-NC/",
+ "149.27.0.32");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String json = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(json);
@@ -260,21 +356,22 @@
}
@Test
- public void testAvailabilityOrCorpusSigle() throws KustvaktException {
- Response response = searchQuery("availability=/CC-BY.*/ | corpusSigle=GOE");
+ public void testAvailabilityOrCorpusSigle () throws KustvaktException {
+ Response response = searchQuery(
+ "availability=/CC-BY.*/ | corpusSigle=GOE");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testOrWithoutAvailability() throws KustvaktException {
+ public void testOrWithoutAvailability () throws KustvaktException {
Response response = searchQuery("corpusSigle=GOE | textClass=politik");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testWithoutAvailability() throws KustvaktException {
+ public void testWithoutAvailability () throws KustvaktException {
Response response = searchQuery("corpusSigle=GOE");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
index e8a5d79..cf74436 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
@@ -15,13 +15,16 @@
public class FreeResourceControllerTest extends SpringJerseyTest {
@Test
- public void testResource() throws KustvaktException {
- Response response = target().path(API_VERSION).path("resource").request().get();
+ public void testResource () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("resource")
+ .request().get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity).get(0);
assertEquals(n.at("/resourceId").asText(), "WPD17");
- assertEquals(n.at("/titles/de").asText(), "Deutsche Wikipedia Artikel 2017");
- assertEquals(n.at("/titles/en").asText(), "German Wikipedia Articles 2017");
+ assertEquals(n.at("/titles/de").asText(),
+ "Deutsche Wikipedia Artikel 2017");
+ assertEquals(n.at("/titles/en").asText(),
+ "German Wikipedia Articles 2017");
assertEquals(1, n.at("/languages").size());
assertEquals(6, n.at("/layers").size());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
index ef70ac5..3b9dfbc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
@@ -37,8 +37,10 @@
private SearchKrill searchKrill;
@Test
- public void testCloseIndex() throws IOException, KustvaktException, URISyntaxException, InterruptedException {
- URI uri = IndexControllerTest.class.getClassLoader().getResource("vc/named-vc1.jsonld").toURI();
+ public void testCloseIndex () throws IOException, KustvaktException,
+ URISyntaxException, InterruptedException {
+ URI uri = IndexControllerTest.class.getClassLoader()
+ .getResource("vc/named-vc1.jsonld").toURI();
Path toLink = Paths.get(uri);
Path symLink = Paths.get("vc/named-vc1.jsonld");
Path vcPath = Paths.get("vc");
@@ -53,15 +55,22 @@
assertEquals(true, searchKrill.getIndex().isReaderOpen());
Form form = new Form();
form.param("token", "secret");
- Response response = target().path(API_VERSION).path("index").path("close").request().post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("index")
+ .path("close").request().post(Entity.form(form));
assertEquals(HttpStatus.SC_OK, response.getStatus());
assertEquals(false, searchKrill.getIndex().isReaderOpen());
// Cleaning database and cache
Thread.sleep(200);
- response = target().path(API_VERSION).path("vc").path("~system").path("named-vc1").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).delete();
- response = target().path(API_VERSION).path("vc").path("~system").path("named-vc1").request().get();
+ response = target().path(API_VERSION).path("vc").path("~system")
+ .path("named-vc1").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .delete();
+ response = target().path(API_VERSION).path("vc").path("~system")
+ .path("named-vc1").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
index fd12bdb..ab60ba3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
@@ -25,15 +25,20 @@
private SearchKrill krill;
@Test
- public void testInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("info").request().get();
+ public void testInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("info").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(config.getCurrentVersion(), node.at("/latest_api_version").asText());
- assertEquals(config.getSupportedVersions().size(), node.at("/supported_api_versions").size());
- assertEquals(ServiceInfo.getInfo().getVersion(), node.at("/kustvakt_version").asText());
- assertEquals(krill.getIndex().getVersion(), node.at("/krill_version").asText());
+ assertEquals(config.getCurrentVersion(),
+ node.at("/latest_api_version").asText());
+ assertEquals(config.getSupportedVersions().size(),
+ node.at("/supported_api_versions").size());
+ assertEquals(ServiceInfo.getInfo().getVersion(),
+ node.at("/kustvakt_version").asText());
+ assertEquals(krill.getIndex().getVersion(),
+ node.at("/krill_version").asText());
QuerySerializer s = new QuerySerializer();
assertEquals(s.getVersion(), node.at("/koral_version").asText());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
index 09a72be..ec282c9 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
@@ -20,55 +20,94 @@
public class MatchInfoControllerTest extends SpringJerseyTest {
@Test
- public void testGetMatchInfoPublicCorpus() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").path("p36-100").path("matchInfo").queryParam("foundry", "*").request().get();
+ public void testGetMatchInfoPublicCorpus () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGA").path("01784").path("p36-100")
+ .path("matchInfo").queryParam("foundry", "*").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
- assertEquals(node.at("/author").asText(), "Goethe, Johann Wolfgang von");
- assertTrue(node.at("/snippet").asText().startsWith("<span class=\"context-left\"></span>" + "<span class=\"match\">"));
+ assertEquals(node.at("/author").asText(),
+ "Goethe, Johann Wolfgang von");
+ assertTrue(node.at("/snippet").asText()
+ .startsWith("<span class=\"context-left\"></span>"
+ + "<span class=\"match\">"));
}
@Test
- public void testGetMatchInfoNotAllowed() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").path("p36875-36876").path("matchInfo").queryParam("foundry", "*").request().get();
+ public void testGetMatchInfoNotAllowed () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGI").path("04846").path("p36875-36876")
+ .path("matchInfo").queryParam("foundry", "*").request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Retrieving resource with ID " + "match-GOE/AGI/04846-p36875-36876 is not allowed.", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Retrieving resource with ID "
+ + "match-GOE/AGI/04846-p36875-36876 is not allowed.",
+ node.at("/errors/0/1").asText());
assertTrue(node.at("/snippet").isMissingNode());
}
@Test
- public void testGetMatchInfoWithAuthentication() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").path("p36875-36876").path("matchInfo").queryParam("foundry", "*").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ public void testGetMatchInfoWithAuthentication () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGI").path("04846").path("p36875-36876")
+ .path("matchInfo").queryParam("foundry", "*").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertEquals(node.at("/textSigle").asText(), "GOE/AGI/04846");
- assertEquals(node.at("/title").asText(), "Zweiter römischer Aufenthalt");
- assertEquals(node.at("/subTitle").asText(), "vom Juni 1787 bis April 1788");
- assertEquals(node.at("/author").asText(), "Goethe, Johann Wolfgang von");
- assertTrue(node.at("/snippet").asText().startsWith("<span class=\"context-left\"></span>" + "<span class=\"match\">"));
+ assertEquals(node.at("/title").asText(),
+ "Zweiter römischer Aufenthalt");
+ assertEquals(node.at("/subTitle").asText(),
+ "vom Juni 1787 bis April 1788");
+ assertEquals(node.at("/author").asText(),
+ "Goethe, Johann Wolfgang von");
+ assertTrue(node.at("/snippet").asText()
+ .startsWith("<span class=\"context-left\"></span>"
+ + "<span class=\"match\">"));
assertEquals(node.at("/availability").asText(), "QAO-NC-LOC:ids");
}
@Test
- public void testAvailabilityAll() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").path("p75-76").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
+ public void testAvailabilityAll () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGD").path("00000").path("p75-76").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testAvailabilityAllUnauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").path("p75-76").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
+ public void testAvailabilityAllUnauthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGD").path("00000").path("p75-76").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Retrieving resource with ID " + "match-GOE/AGD/00000-p75-76 is not allowed.", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Retrieving resource with ID "
+ + "match-GOE/AGD/00000-p75-76 is not allowed.",
+ node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
index 147d893..dcc63d7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
@@ -20,8 +20,10 @@
public class MetadataControllerTest extends SpringJerseyTest {
@Test
- public void testRetrieveMetadataWithField() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").queryParam("fields", "author").request().get();
+ public void testRetrieveMetadataWithField () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGA").path("01784")
+ .queryParam("fields", "author").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -29,8 +31,11 @@
}
@Test
- public void testRetrieveMetadataWithMultipleFields() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").queryParam("fields", "author,title").request().get();
+ public void testRetrieveMetadataWithMultipleFields ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGA").path("01784")
+ .queryParam("fields", "author,title").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -39,8 +44,9 @@
}
@Test
- public void testFreeMetadata() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").request().get();
+ public void testFreeMetadata () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGA").path("01784").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -50,34 +56,62 @@
// EM: currently all metadata are allowed
@Test
@Disabled
- public void testMetadataUnauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").request().get();
+ public void testMetadataUnauthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGI").path("04846").request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Retrieving resource with ID " + "GOE/AGI/04846 is not allowed.", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Retrieving resource with ID "
+ + "GOE/AGI/04846 is not allowed.",
+ node.at("/errors/0/1").asText());
}
@Test
- public void testMetadataWithAuthentication() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ public void testMetadataWithAuthentication () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGI").path("04846").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testMetadataAvailabilityAll() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("00000").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
+ public void testMetadataAvailabilityAll () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGI").path("00000").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
// EM: currently all metadata are allowed
@Test
@Disabled
- public void testMetadataAvailabilityAllUnauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
+ public void testMetadataAvailabilityAllUnauthorized ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").path("AGD").path("00000").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Retrieving resource with ID " + "GOE/AGD/00000 is not allowed.", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Retrieving resource with ID "
+ + "GOE/AGD/00000 is not allowed.",
+ node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
index 26a121f..775afd8 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
@@ -17,8 +17,12 @@
public class MultipleCorpusQueryTest extends SpringJerseyTest {
@Test
- public void testSearchGet() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "das").queryParam("ql", "poliqarp").queryParam("cq", "pubPlace=München").queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request().get();
+ public void testSearchGet () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "das").queryParam("ql", "poliqarp")
+ .queryParam("cq", "pubPlace=München")
+ .queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -35,8 +39,11 @@
}
@Test
- public void testStatisticsWithMultipleCq() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung").queryParam("cq", "corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithMultipleCq ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung")
+ .queryParam("cq", "corpusSigle=GOE").request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -48,8 +55,12 @@
}
@Test
- public void testStatisticsWithMultipleCorpusQuery() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie").queryParam("corpusQuery", "corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithMultipleCorpusQuery ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "textType=Autobiographie")
+ .queryParam("corpusQuery", "corpusSigle=GOE").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -58,6 +69,7 @@
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "Parameter corpusQuery is deprecated in favor of cq.");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
index 315728a..6b5627d 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
@@ -31,43 +31,56 @@
private String clientAuthHeader;
- public OAuth2AccessTokenTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
- clientAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(confidentialClientId, clientSecret);
+ public OAuth2AccessTokenTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
+ clientAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(confidentialClientId,
+ clientSecret);
}
@Test
- public void testScopeWithSuperClient() throws KustvaktException {
- Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
+ public void testScopeWithSuperClient () throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId,
+ clientSecret);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(node.at("/scope").asText(), "all");
String accessToken = node.at("/access_token").asText();
// test list user group
- response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(2, node.size());
}
@Test
- public void testCustomScope() throws KustvaktException {
- Response response = requestAuthorizationCode("code", confidentialClientId, "", OAuth2Scope.VC_INFO.toString(), "", userAuthHeader);
+ public void testCustomScope () throws KustvaktException {
+ Response response = requestAuthorizationCode("code",
+ confidentialClientId, "", OAuth2Scope.VC_INFO.toString(), "",
+ userAuthHeader);
String code = parseAuthorizationCode(response);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String token = node.at("/access_token").asText();
- assertTrue(node.at("/scope").asText().contains(OAuth2Scope.VC_INFO.toString()));
+ assertTrue(node.at("/scope").asText()
+ .contains(OAuth2Scope.VC_INFO.toString()));
// test list vc using the token
- response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + token).get();
+ response = target().path(API_VERSION).path("vc").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + token).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(4, node.size());
}
@Test
- public void testDefaultScope() throws KustvaktException, IOException {
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ public void testDefaultScope () throws KustvaktException, IOException {
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
@@ -76,52 +89,76 @@
testSearchWithOAuth2Token(accessToken);
}
- private void testScopeNotAuthorized(String accessToken) throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ private void testScopeNotAuthorized (String accessToken)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Scope vc_info is not authorized");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Scope vc_info is not authorized");
}
- private void testScopeNotAuthorize2(String accessToken) throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ private void testScopeNotAuthorize2 (String accessToken)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access")
+ .request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .get();
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Scope vc_access_info is not authorized");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Scope vc_access_info is not authorized");
}
@Test
- public void testSearchWithUnknownToken() throws KustvaktException, IOException {
- Response response = searchWithAccessToken("ljsa8tKNRSczJhk20öhq92zG8z350");
+ public void testSearchWithUnknownToken ()
+ throws KustvaktException, IOException {
+ Response response = searchWithAccessToken(
+ "ljsa8tKNRSczJhk20öhq92zG8z350");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is invalid");
}
@Test
- public void testRevokeAccessTokenConfidentialClient() throws KustvaktException {
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
+ public void testRevokeAccessTokenConfidentialClient ()
+ throws KustvaktException {
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
+ confidentialClientId, code, clientAuthHeader);
String accessToken = node.at("/access_token").asText();
Form form = new Form();
form.param("token", accessToken);
form.param("client_id", confidentialClientId);
form.param("client_secret", "secret");
- Response response = target().path(API_VERSION).path("oauth2").path("revoke").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("revoke").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
testSearchWithRevokedAccessToken(accessToken);
}
@Test
- public void testRevokeAccessTokenPublicClientViaSuperClient() throws KustvaktException {
+ public void testRevokeAccessTokenPublicClientViaSuperClient ()
+ throws KustvaktException {
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, "", code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
testRevokeTokenViaSuperClient(accessToken, userAuthHeader);
@@ -129,9 +166,12 @@
}
@Test
- public void testAccessTokenAfterRequestRefreshToken() throws KustvaktException, IOException {
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
+ public void testAccessTokenAfterRequestRefreshToken ()
+ throws KustvaktException, IOException {
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
+ confidentialClientId, code, clientAuthHeader);
String accessToken = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
Form form = new Form();
@@ -139,7 +179,12 @@
form.param("client_id", confidentialClientId);
form.param("client_secret", "secret");
form.param("refresh_token", refreshToken);
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(entity);
@@ -149,27 +194,38 @@
}
@Test
- public void testRequestAuthorizationWithBearerTokenUnauthorized() throws KustvaktException {
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
+ public void testRequestAuthorizationWithBearerTokenUnauthorized ()
+ throws KustvaktException {
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
+ confidentialClientId, code, clientAuthHeader);
String userAuthToken = node.at("/access_token").asText();
- Response response = requestAuthorizationCode("code", confidentialClientId, "", "search", "", "Bearer " + userAuthToken);
+ Response response = requestAuthorizationCode("code",
+ confidentialClientId, "", "search", "",
+ "Bearer " + userAuthToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Scope authorize is not authorized");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Scope authorize is not authorized");
}
@Test
- public void testRequestAuthorizationWithBearerToken() throws KustvaktException {
- Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
+ public void testRequestAuthorizationWithBearerToken ()
+ throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId,
+ clientSecret);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
String userAuthToken = node.at("/access_token").asText();
assertNotNull(userAuthToken);
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
- String code = requestAuthorizationCode(superClientId, "Bearer " + userAuthToken);
+ String code = requestAuthorizationCode(superClientId,
+ "Bearer " + userAuthToken);
assertNotNull(code);
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
index 2a143cb..fabc267 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
@@ -40,47 +40,65 @@
@Autowired
private AccessTokenDao accessDao;
- public OAuth2AdminControllerTest() throws KustvaktException {
- adminAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "password");
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2AdminControllerTest () throws KustvaktException {
+ adminAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "password");
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
}
- private Response updateClientPrivilege(String username, Form form) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("admin").path("oauth2").path("client").path("privilege").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ private Response updateClientPrivilege (String username, Form form)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin")
+ .path("oauth2").path("client").path("privilege").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
return response;
}
- private Response updateClientPrivilegeWithAdminToken(String clientId) throws ProcessingException, KustvaktException {
+ private Response updateClientPrivilegeWithAdminToken (String clientId)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
form.param("super", Boolean.toString(false));
// adminToken
form.param("token", "secret");
- Response response = target().path(API_VERSION).path("admin").path("oauth2").path("client").path("privilege").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("oauth2").path("client").path("privilege").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
return response;
}
- private void testUpdateClientPriviledgeUnauthorized(Form form) throws ProcessingException, KustvaktException {
+ private void testUpdateClientPriviledgeUnauthorized (Form form)
+ throws ProcessingException, KustvaktException {
Response response = updateClientPrivilege(username, form);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
@Order(1)
- public void testCleanExpiredTokensUsingAdminToken() throws KustvaktException {
+ public void testCleanExpiredTokensUsingAdminToken ()
+ throws KustvaktException {
createExpiredAccessToken();
-
- int refreshTokensBefore =
- refreshDao.retrieveInvalidRefreshTokens().size();
+
+ int refreshTokensBefore = refreshDao.retrieveInvalidRefreshTokens()
+ .size();
assertTrue(refreshTokensBefore > 0);
int accessTokensBefore = accessDao.retrieveInvalidAccessTokens().size();
assertTrue(accessTokensBefore > 0);
Form form = new Form();
form.param("token", "secret");
- target().path(API_VERSION).path("admin").path("oauth2").path("token").path("clean").request().post(Entity.form(form));
+ target().path(API_VERSION).path("admin").path("oauth2").path("token")
+ .path("clean").request().post(Entity.form(form));
assertEquals(0, refreshDao.retrieveInvalidRefreshTokens().size());
assertEquals(0, accessDao.retrieveInvalidAccessTokens().size());
}
@@ -91,28 +109,33 @@
int accessTokensBefore = accessDao.retrieveInvalidAccessTokens().size();
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
String accessToken = node.at("/access_token").asText();
testRevokeToken(accessToken, publicClientId, null, ACCESS_TOKEN_TYPE);
int accessTokensAfter = accessDao.retrieveInvalidAccessTokens().size();
assertEquals(accessTokensAfter, accessTokensBefore + 1);
- target().path(API_VERSION).path("admin").path("oauth2").path("token").path("clean").request().header(Attributes.AUTHORIZATION, adminAuthHeader).post(null);
+ target().path(API_VERSION).path("admin").path("oauth2").path("token")
+ .path("clean").request()
+ .header(Attributes.AUTHORIZATION, adminAuthHeader).post(null);
assertEquals(0, accessDao.retrieveInvalidAccessTokens().size());
}
@Test
- public void testUpdateClientPrivilege() throws KustvaktException {
+ public void testUpdateClientPrivilege () throws KustvaktException {
// register a client
Response response = registerConfidentialClient(username);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
// request an access token
- String clientAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(clientId, clientSecret);
+ String clientAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(clientId, clientSecret);
String code = requestAuthorizationCode(clientId, userAuthHeader);
- node = requestTokenWithAuthorizationCodeAndHeader(clientId, code, clientAuthHeader);
+ node = requestTokenWithAuthorizationCodeAndHeader(clientId, code,
+ clientAuthHeader);
String accessToken = node.at("/access_token").asText();
// update client priviledge to super client
Form form = new Form();
@@ -129,29 +152,37 @@
}
// old access tokens retain their scopes
- private void testAccessTokenAfterUpgradingClient(String clientId, String accessToken) throws KustvaktException {
+ private void testAccessTokenAfterUpgradingClient (String clientId,
+ String accessToken) throws KustvaktException {
JsonNode node = retrieveClientInfo(clientId, "admin");
assertTrue(node.at("/super").asBoolean());
// list vc
- Response response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ Response response = target().path(API_VERSION).path("vc").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Scope vc_info is not authorized");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Scope vc_info is not authorized");
// search
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testAccessTokenAfterDegradingSuperClient(String clientId, String accessToken) throws KustvaktException {
+ private void testAccessTokenAfterDegradingSuperClient (String clientId,
+ String accessToken) throws KustvaktException {
JsonNode node = retrieveClientInfo(clientId, username);
assertTrue(node.at("/isSuper").isMissingNode());
Response response = searchWithAccessToken(accessToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is invalid");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
index a2e7090..8372acc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
@@ -28,31 +28,41 @@
public String userAuthHeader;
- public OAuth2AuthorizationPostTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2AuthorizationPostTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
}
- private Response requestAuthorizationCode(Form form, String authHeader) throws KustvaktException {
- return target().path(API_VERSION).path("oauth2").path("authorize").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ private Response requestAuthorizationCode (Form form, String authHeader)
+ throws KustvaktException {
+ return target().path(API_VERSION).path("oauth2").path("authorize")
+ .request().header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
}
@Test
- public void testAuthorizeConfidentialClient() throws KustvaktException {
+ public void testAuthorizeConfidentialClient () throws KustvaktException {
Form form = new Form();
form.param("response_type", "code");
form.param("client_id", confidentialClientId);
form.param("state", "thisIsMyState");
form.param("scope", "search");
Response response = requestAuthorizationCode(form, userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
+ response.getStatus());
URI redirectUri = response.getLocation();
- MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder
+ .fromUri(redirectUri).build().getQueryParams();
assertNotNull(params.getFirst("code"));
assertEquals(params.getFirst("state"), "thisIsMyState");
}
@Test
- public void testRequestTokenAuthorizationConfidential() throws KustvaktException {
+ public void testRequestTokenAuthorizationConfidential ()
+ throws KustvaktException {
Form authForm = new Form();
authForm.param("response_type", "code");
authForm.param("client_id", confidentialClientId);
@@ -60,11 +70,10 @@
Response response = requestAuthorizationCode(authForm, userAuthHeader);
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- UriComponent.decodeQuery(redirectUri, true);
+ MultivaluedMap<String, String> params = UriComponent
+ .decodeQuery(redirectUri, true);
String code = params.get("code").get(0);
-
response = requestTokenWithAuthorizationCodeAndForm(
confidentialClientId, clientSecret, code);
String entity = response.readEntity(String.class);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationTest.java
index a91b119..27903e7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationTest.java
@@ -19,14 +19,14 @@
import jakarta.ws.rs.core.Response.Status;
public class OAuth2AuthorizationTest extends OAuth2TestBase {
-
+
private String userAuthHeader;
public OAuth2AuthorizationTest () throws KustvaktException {
userAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue("dory", "password");
}
-
+
@Test
public void testAuthorizeUnauthenticated () throws KustvaktException {
@@ -40,18 +40,19 @@
assertEquals("Unauthorized operation for user: guest",
node.at("/errors/0/1").asText());
}
+
@Test
public void testAuthorizeConfidentialClient () throws KustvaktException {
// with registered redirect URI
- Response response =
- requestAuthorizationCode("code", confidentialClientId, "",
- "match_info search client_info", state, userAuthHeader);
+ Response response = requestAuthorizationCode("code",
+ confidentialClientId, "", "match_info search client_info",
+ state, userAuthHeader);
assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
response.getStatus());
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- getQueryParamsFromURI(redirectUri);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(
+ redirectUri);
assertNotNull(params.getFirst("code"));
assertEquals(state, params.getFirst("state"));
}
@@ -65,10 +66,9 @@
@Test
public void testAuthorizeWithRedirectUri () throws KustvaktException {
- Response response =
- requestAuthorizationCode("code", publicClientId2,
- "https://public.com/redirect", "search match_info",
- "", userAuthHeader);
+ Response response = requestAuthorizationCode("code", publicClientId2,
+ "https://public.com/redirect", "search match_info", "",
+ userAuthHeader);
assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
response.getStatus());
@@ -93,8 +93,7 @@
assertEquals(redirectUri.getPath(), "/confidential/redirect");
String[] queryParts = redirectUri.getQuery().split("&");
- assertEquals("error_description=scope+is+required",
- queryParts[1]);
+ assertEquals("error_description=scope+is+required", queryParts[1]);
assertEquals("error=invalid_scope", queryParts[0]);
}
@@ -111,44 +110,43 @@
@Test
public void testAuthorizeMissingRedirectUri () throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- publicClientId2, "", "search", state, userAuthHeader);
+ Response response = requestAuthorizationCode("code", publicClientId2,
+ "", "search", state, userAuthHeader);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals("Missing parameter: redirect URI",
node.at("/error_description").asText());
assertEquals(state, node.at("/state").asText());
}
@Test
- public void testAuthorizeMissingResponseType() throws KustvaktException {
- Response response = requestAuthorizationCode("",
- confidentialClientId, "", "search", "", userAuthHeader);
+ public void testAuthorizeMissingResponseType () throws KustvaktException {
+ Response response = requestAuthorizationCode("", confidentialClientId,
+ "", "search", "", userAuthHeader);
assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
response.getStatus());
- assertEquals("https://third.party.com/confidential/redirect?"
- + "error=invalid_request_uri&"
- + "error_description=Missing+response_type+parameter"
- , response.getLocation().toString());
+ assertEquals(
+ "https://third.party.com/confidential/redirect?"
+ + "error=invalid_request_uri&"
+ + "error_description=Missing+response_type+parameter",
+ response.getLocation().toString());
}
-
+
@Test
- public void testAuthorizeMissingResponseTypeWithoutClientId () throws KustvaktException {
- Response response = requestAuthorizationCode("",
- "", "", "search", "", userAuthHeader);
-
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testAuthorizeMissingResponseTypeWithoutClientId ()
+ throws KustvaktException {
+ Response response = requestAuthorizationCode("", "", "", "search", "",
+ userAuthHeader);
+
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals("Missing parameter: client_id",
node.at("/error_description").asText());
}
@@ -170,9 +168,9 @@
String redirectUri = "https://different.uri/redirect";
Response response = requestAuthorizationCode("code",
confidentialClientId, redirectUri, "", state, userAuthHeader);
-
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
+
+ testInvalidRedirectUri(response.readEntity(String.class),
+ response.getHeaderString("Content-Type"), true,
response.getStatus());
}
@@ -185,8 +183,8 @@
response.getStatus());
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- getQueryParamsFromURI(redirectUri);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(
+ redirectUri);
assertNotNull(params.getFirst("code"));
assertEquals(state, params.getFirst("state"));
}
@@ -194,11 +192,11 @@
@Test
public void testAuthorizeWithRedirectUriFragment ()
throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- publicClientId2, "http://public.com/index.html#redirect", "search",
- state, userAuthHeader);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
+ Response response = requestAuthorizationCode("code", publicClientId2,
+ "http://public.com/index.html#redirect", "search", state,
+ userAuthHeader);
+ testInvalidRedirectUri(response.readEntity(String.class),
+ response.getHeaderString("Content-Type"), true,
response.getStatus());
}
@@ -206,10 +204,10 @@
public void testAuthorizeInvalidRedirectUri () throws KustvaktException {
// host not allowed by Apache URI Validator
String redirectUri = "https://public.uri/redirect";
- Response response = requestAuthorizationCode("code",
- publicClientId2, redirectUri, "", state, userAuthHeader);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
+ Response response = requestAuthorizationCode("code", publicClientId2,
+ redirectUri, "", state, userAuthHeader);
+ testInvalidRedirectUri(response.readEntity(String.class),
+ response.getHeaderString("Content-Type"), true,
response.getStatus());
}
@@ -224,8 +222,7 @@
assertEquals("https://third.party.com/confidential/redirect?"
+ "error=unsupported_response_type"
+ "&error_description=Unsupported+response+type.+Only+code+is+supported."
- + "&state=thisIsMyState" ,
- response.getLocation().toString());
+ + "&state=thisIsMyState", response.getLocation().toString());
// with redirect URI, and no registered redirect URI
response = requestAuthorizationCode("string", publicClientId2,
@@ -237,8 +234,7 @@
assertEquals("https://public.client.com/redirect?"
+ "error=unsupported_response_type"
+ "&error_description=Unsupported+response+type.+Only+code+is+supported."
- + "&state=thisIsMyState",
- response.getLocation().toString());
+ + "&state=thisIsMyState", response.getLocation().toString());
// with different redirect URI
String redirectUri = "https://different.uri/redirect";
@@ -247,8 +243,7 @@
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals("Invalid redirect URI",
node.at("/error_description").asText());
assertEquals(state, node.at("/state").asText());
@@ -260,8 +255,7 @@
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals("Missing parameter: redirect URI",
node.at("/error_description").asText());
assertEquals(state, node.at("/state").asText());
@@ -277,8 +271,8 @@
assertEquals(
"https://third.party.com/confidential/redirect?"
- + "error=invalid_scope&error_description=Invalid+"
- +"scope&state=thisIsMyState",
+ + "error=invalid_scope&error_description=Invalid+"
+ + "scope&state=thisIsMyState",
response.getLocation().toString());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
index 25127d5..5f24cd6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
@@ -43,11 +43,13 @@
private String userAuthHeader;
- public OAuth2ClientControllerTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2ClientControllerTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
}
- private OAuth2ClientJson createOAuth2ClientJson(String name, OAuth2ClientType type, String description) {
+ private OAuth2ClientJson createOAuth2ClientJson (String name,
+ OAuth2ClientType type, String description) {
OAuth2ClientJson client = new OAuth2ClientJson();
if (name != null) {
client.setName(name);
@@ -60,19 +62,22 @@
}
@Test
- public void testRetrieveClientInfo() throws KustvaktException {
+ public void testRetrieveClientInfo () throws KustvaktException {
// public client
JsonNode clientInfo = retrieveClientInfo(publicClientId, "system");
assertEquals(publicClientId, clientInfo.at("/client_id").asText());
- assertEquals(clientInfo.at("/client_name").asText(), "public client plugin with redirect uri");
+ assertEquals(clientInfo.at("/client_name").asText(),
+ "public client plugin with redirect uri");
assertNotNull(clientInfo.at("/client_description"));
assertNotNull(clientInfo.at("/client_url"));
assertEquals(clientInfo.at("/client_type").asText(), "PUBLIC");
assertEquals(clientInfo.at("/registered_by").asText(), "system");
// confidential client
clientInfo = retrieveClientInfo(confidentialClientId, "system");
- assertEquals(confidentialClientId, clientInfo.at("/client_id").asText());
- assertEquals(clientInfo.at("/client_name").asText(), "non super confidential client");
+ assertEquals(confidentialClientId,
+ clientInfo.at("/client_id").asText());
+ assertEquals(clientInfo.at("/client_name").asText(),
+ "non super confidential client");
assertNotNull(clientInfo.at("/client_url"));
assertNotNull(clientInfo.at("/redirect_uri"));
assertEquals(false, clientInfo.at("/super").asBoolean());
@@ -80,7 +85,8 @@
// super client
clientInfo = retrieveClientInfo(superClientId, "system");
assertEquals(superClientId, clientInfo.at("/client_id").asText());
- assertEquals(clientInfo.at("/client_name").asText(), "super confidential client");
+ assertEquals(clientInfo.at("/client_name").asText(),
+ "super confidential client");
assertNotNull(clientInfo.at("/client_url"));
assertNotNull(clientInfo.at("/redirect_uri"));
assertEquals(clientInfo.at("/client_type").asText(), "CONFIDENTIAL");
@@ -88,7 +94,7 @@
}
@Test
- public void testRegisterConfidentialClient() throws KustvaktException {
+ public void testRegisterConfidentialClient () throws KustvaktException {
Response response = registerConfidentialClient(username);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -105,68 +111,88 @@
}
@Test
- public void testRegisterClientNameTooShort() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R", OAuth2ClientType.PUBLIC, null);
+ public void testRegisterClientNameTooShort ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R",
+ OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "client_name must contain at least 3 characters");
+ assertEquals(node.at("/error_description").asText(),
+ "client_name must contain at least 3 characters");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientEmptyName() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("", OAuth2ClientType.PUBLIC, null);
+ public void testRegisterClientEmptyName ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("",
+ OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "client_name must contain at least 3 characters");
+ assertEquals(node.at("/error_description").asText(),
+ "client_name must contain at least 3 characters");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingName() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson(null, OAuth2ClientType.PUBLIC, null);
+ public void testRegisterClientMissingName ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(null,
+ OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "client_name is null");
+ assertEquals(node.at("/error_description").asText(),
+ "client_name is null");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingDescription() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", OAuth2ClientType.PUBLIC, null);
+ public void testRegisterClientMissingDescription ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client",
+ OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "client_description is null");
+ assertEquals(node.at("/error_description").asText(),
+ "client_description is null");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingType() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", null, null);
+ public void testRegisterClientMissingType ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", null,
+ null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "client_type is null");
+ assertEquals(node.at("/error_description").asText(),
+ "client_type is null");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientInvalidRedirectURI() throws ProcessingException, KustvaktException {
+ public void testRegisterClientInvalidRedirectURI ()
+ throws ProcessingException, KustvaktException {
// invalid hostname
String redirectUri = "https://test.public.client/redirect";
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2PublicClient", OAuth2ClientType.PUBLIC,
+ "A public test client.");
clientJson.setRedirectURI(redirectUri);
Response response = registerClient(username, clientJson);
- testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), false, response.getStatus());
+ testInvalidRedirectUri(response.readEntity(String.class),
+ response.getHeaderString("Content-Type"), false,
+ response.getStatus());
// localhost is not allowed
// redirectUri = "http://localhost:1410";
// clientJson.setRedirectURI(redirectUri);
@@ -177,12 +203,17 @@
redirectUri = "https://public.client.com/redirect.html#bar";
clientJson.setRedirectURI(redirectUri);
response = registerClient(username, clientJson);
- testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), false, response.getStatus());
+ testInvalidRedirectUri(response.readEntity(String.class),
+ response.getHeaderString("Content-Type"), false,
+ response.getStatus());
}
@Test
- public void testRegisterPublicClientWithRefreshTokenExpiry() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
+ public void testRegisterPublicClientWithRefreshTokenExpiry ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2PublicClient", OAuth2ClientType.PUBLIC,
+ "A public test client.");
clientJson.setRefreshTokenExpiry(31535000);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
@@ -191,9 +222,12 @@
}
@Test
- public void testRegisterConfidentialClientWithRefreshTokenExpiry() throws ProcessingException, KustvaktException {
+ public void testRegisterConfidentialClientWithRefreshTokenExpiry ()
+ throws ProcessingException, KustvaktException {
int expiry = 31535000;
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL, "A confidential client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL,
+ "A confidential client.");
clientJson.setRefreshTokenExpiry(expiry);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
@@ -204,21 +238,28 @@
}
@Test
- public void testRegisterConfidentialClientWithInvalidRefreshTokenExpiry() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL, "A confidential client.");
+ public void testRegisterConfidentialClientWithInvalidRefreshTokenExpiry ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL,
+ "A confidential client.");
clientJson.setRefreshTokenExpiry(31537000);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(node.at("/error_description").asText(), "Maximum refresh token expiry is 31536000 seconds (1 year)");
+ assertEquals(node.at("/error_description").asText(),
+ "Maximum refresh token expiry is 31536000 seconds (1 year)");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientInvalidURL() throws ProcessingException, KustvaktException {
+ public void testRegisterClientInvalidURL ()
+ throws ProcessingException, KustvaktException {
// invalid hostname
String url = "https://test.public.client";
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2PublicClient", OAuth2ClientType.PUBLIC,
+ "A public test client.");
clientJson.setUrl(url);
Response response = registerClient(username, clientJson);
testInvalidUrl(response.readEntity(String.class), response.getStatus());
@@ -229,7 +270,8 @@
testInvalidUrl(response.readEntity(String.class), response.getStatus());
}
- private void testInvalidUrl(String entity, int status) throws KustvaktException {
+ private void testInvalidUrl (String entity, int status)
+ throws KustvaktException {
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals(node.at("/error_description").asText(), "Invalid URL");
@@ -237,9 +279,12 @@
}
@Test
- public void testRegisterPublicClient() throws ProcessingException, KustvaktException {
+ public void testRegisterPublicClient ()
+ throws ProcessingException, KustvaktException {
String redirectUri = "https://public.client.com/redirect";
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2PublicClient", OAuth2ClientType.PUBLIC,
+ "A public test client.");
// http and fragment are allowed
clientJson.setUrl("http://public.client.com/index.html#bar");
clientJson.setRedirectURI(redirectUri);
@@ -255,27 +300,46 @@
testAccessTokenAfterDeregistration(clientId, null, "");
}
- private void testRegisterClientUnauthorizedScope(String clientId) throws ProcessingException, KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ private void testRegisterClientUnauthorizedScope (String clientId)
+ throws ProcessingException, KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
String code = requestAuthorizationCode(clientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(node.at("/scope").asText(), "match_info search");
String accessToken = node.at("/access_token").asText();
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", OAuth2ClientType.PUBLIC, null);
- response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(clientJson));
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client",
+ OAuth2ClientType.PUBLIC, null);
+ response = target().path(API_VERSION).path("oauth2").path("client")
+ .path("register").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .post(Entity.json(clientJson));
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Scope register_client is not authorized");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Scope register_client is not authorized");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientUsingPlainJson() throws ProcessingException, KustvaktException, IOException {
- InputStream is = getClass().getClassLoader().getResourceAsStream("json/oauth2_public_client.json");
+ public void testRegisterClientUsingPlainJson ()
+ throws ProcessingException, KustvaktException, IOException {
+ InputStream is = getClass().getClassLoader()
+ .getResourceAsStream("json/oauth2_public_client.json");
String json = IOUtils.toString(is, Charset.defaultCharset());
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("register").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username,
+ "password"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .post(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
@@ -287,8 +351,11 @@
}
@Test
- public void testRegisterDesktopApp() throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2DesktopClient", OAuth2ClientType.PUBLIC, "This is a desktop test client.");
+ public void testRegisterDesktopApp ()
+ throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2DesktopClient", OAuth2ClientType.PUBLIC,
+ "This is a desktop test client.");
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -302,9 +369,12 @@
}
@Test
- public void testRegisterMultipleDesktopApps() throws ProcessingException, KustvaktException {
+ public void testRegisterMultipleDesktopApps ()
+ throws ProcessingException, KustvaktException {
// First client
- OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2DesktopClient1", OAuth2ClientType.PUBLIC, "A desktop test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(
+ "OAuth2DesktopClient1", OAuth2ClientType.PUBLIC,
+ "A desktop test client.");
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -313,7 +383,8 @@
assertNotNull(clientId1);
assertTrue(node.at("/client_secret").isMissingNode());
// Second client
- clientJson = createOAuth2ClientJson("OAuth2DesktopClient2", OAuth2ClientType.PUBLIC, "Another desktop test client.");
+ clientJson = createOAuth2ClientJson("OAuth2DesktopClient2",
+ OAuth2ClientType.PUBLIC, "Another desktop test client.");
response = registerClient(username, clientJson);
entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -322,66 +393,106 @@
assertNotNull(clientId2);
assertTrue(node.at("/client_secret").isMissingNode());
testResetPublicClientSecret(clientId1);
- testAccessTokenAfterDeregistration(clientId1, null, "https://OAuth2DesktopClient1.com");
+ testAccessTokenAfterDeregistration(clientId1, null,
+ "https://OAuth2DesktopClient1.com");
testResetPublicClientSecret(clientId2);
- testAccessTokenAfterDeregistration(clientId2, null, "https://OAuth2DesktopClient2.com");
+ testAccessTokenAfterDeregistration(clientId2, null,
+ "https://OAuth2DesktopClient2.com");
}
- private void testAccessTokenAfterDeregistration(String clientId, String clientSecret, String redirectUri) throws KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
- String code = requestAuthorizationCode(clientId, redirectUri, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, redirectUri);
+ private void testAccessTokenAfterDeregistration (String clientId,
+ String clientSecret, String redirectUri) throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
+ String code = requestAuthorizationCode(clientId, redirectUri,
+ userAuthHeader);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code, redirectUri);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
code = requestAuthorizationCode(clientId, redirectUri, userAuthHeader);
testDeregisterPublicClient(clientId, username);
- response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, redirectUri);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code, redirectUri);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuth2Error.INVALID_CLIENT.toString(), node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_CLIENT.toString(),
+ node.at("/error").asText());
response = searchWithAccessToken(accessToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is invalid");
}
- private void testDeregisterPublicClientMissingUserAuthentication(String clientId) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").path(clientId).request().delete();
+ private void testDeregisterPublicClientMissingUserAuthentication (
+ String clientId) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("deregister").path(clientId).request()
+ .delete();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
- private void testDeregisterPublicClientMissingId() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
- assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
+ private void testDeregisterPublicClientMissingId ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("deregister").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
+ assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(),
+ response.getStatus());
}
- private void testDeregisterPublicClient(String clientId, String username) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").path(clientId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private void testDeregisterPublicClient (String clientId, String username)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("deregister").path(clientId).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testResetPublicClientSecret(String clientId) throws ProcessingException, KustvaktException {
+ private void testResetPublicClientSecret (String clientId)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("reset").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("reset").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Operation is not allowed for public clients");
+ assertEquals(node.at("/error_description").asText(),
+ "Operation is not allowed for public clients");
}
- private String testResetConfidentialClientSecret(String clientId, String clientSecret) throws ProcessingException, KustvaktException {
+ private String testResetConfidentialClientSecret (String clientId,
+ String clientSecret) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("reset").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("reset").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
@@ -391,10 +502,16 @@
return newClientSecret;
}
- private void requestAuthorizedClientList(String userAuthHeader) throws KustvaktException {
+ private void requestAuthorizedClientList (String userAuthHeader)
+ throws KustvaktException {
Form form = getSuperClientForm();
form.param("authorized_only", "true");
- Response response = target().path(API_VERSION).path("oauth2").path("client").path("list").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("client").path("list").request()
+ .header(Attributes.AUTHORIZATION, userAuthHeader)
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
// System.out.println(entity);
@@ -402,21 +519,24 @@
assertEquals(2, node.size());
assertEquals(confidentialClientId, node.at("/0/client_id").asText());
assertEquals(publicClientId, node.at("/1/client_id").asText());
- assertEquals(node.at("/0/client_name").asText(), "non super confidential client");
+ assertEquals(node.at("/0/client_name").asText(),
+ "non super confidential client");
assertEquals(node.at("/0/client_type").asText(), "CONFIDENTIAL");
assertFalse(node.at("/0/client_url").isMissingNode());
assertFalse(node.at("/0/client_description").isMissingNode());
}
@Test
- public void testListPublicClient() throws KustvaktException {
+ public void testListPublicClient () throws KustvaktException {
String clientName = "OAuth2DoryClient";
- OAuth2ClientJson json = createOAuth2ClientJson(clientName, OAuth2ClientType.PUBLIC, "Dory's client.");
+ OAuth2ClientJson json = createOAuth2ClientJson(clientName,
+ OAuth2ClientType.PUBLIC, "Dory's client.");
registerClient("dory", json);
JsonNode node = listUserRegisteredClients("dory");
assertEquals(1, node.size());
assertEquals(clientName, node.at("/0/client_name").asText());
- assertEquals(OAuth2ClientType.PUBLIC.name(), node.at("/0/client_type").asText());
+ assertEquals(OAuth2ClientType.PUBLIC.name(),
+ node.at("/0/client_type").asText());
assertTrue(node.at("/0/permitted").asBoolean());
assertFalse(node.at("/0/registration_date").isMissingNode());
assertTrue(node.at("/refresh_token_expiry").isMissingNode());
@@ -424,38 +544,46 @@
testDeregisterPublicClient(clientId, "dory");
}
- private void testListConfidentialClient(String username, String clientId) throws ProcessingException, KustvaktException {
+ private void testListConfidentialClient (String username, String clientId)
+ throws ProcessingException, KustvaktException {
JsonNode node = listUserRegisteredClients(username);
assertEquals(1, node.size());
assertEquals(clientId, node.at("/0/client_id").asText());
assertEquals(node.at("/0/client_name").asText(), "OAuth2ClientTest");
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), node.at("/0/client_type").asText());
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
+ node.at("/0/client_type").asText());
assertNotNull(node.at("/0/client_description"));
assertEquals(clientURL, node.at("/0/client_url").asText());
- assertEquals(clientRedirectUri, node.at("/0/client_redirect_uri").asText());
+ assertEquals(clientRedirectUri,
+ node.at("/0/client_redirect_uri").asText());
assertNotNull(node.at("/0/registration_date"));
- assertEquals(defaultRefreshTokenExpiry, node.at("/0/refresh_token_expiry").asInt());
+ assertEquals(defaultRefreshTokenExpiry,
+ node.at("/0/refresh_token_expiry").asInt());
assertTrue(node.at("/0/permitted").asBoolean());
assertTrue(node.at("/0/source").isMissingNode());
}
@Test
- public void testListUserClients() throws KustvaktException {
+ public void testListUserClients () throws KustvaktException {
String username = "pearl";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, password);
// super client
- Response response = requestTokenWithPassword(superClientId, clientSecret, username, password);
+ Response response = requestTokenWithPassword(superClientId,
+ clientSecret, username, password);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// client 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "",
+ code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
// client 2
code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
String refreshToken = node.at("/refresh_token").asText();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
@@ -463,64 +591,88 @@
testListAuthorizedClientWithMultipleAccessTokens(userAuthHeader);
testListWithClientsFromAnotherUser(userAuthHeader);
// revoke client 1
- testRevokeAllTokenViaSuperClient(publicClientId, userAuthHeader, accessToken);
+ testRevokeAllTokenViaSuperClient(publicClientId, userAuthHeader,
+ accessToken);
// revoke client 2
node = JsonUtils.readTree(response.readEntity(String.class));
accessToken = node.at("/access_token").asText();
refreshToken = node.at("/refresh_token").asText();
- testRevokeAllTokenViaSuperClient(confidentialClientId, userAuthHeader, accessToken);
- testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
+ testRevokeAllTokenViaSuperClient(confidentialClientId, userAuthHeader,
+ accessToken);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId,
+ clientSecret, refreshToken);
}
- private void testListAuthorizedClientWithMultipleRefreshTokens(String userAuthHeader) throws KustvaktException {
+ private void testListAuthorizedClientWithMultipleRefreshTokens (
+ String userAuthHeader) throws KustvaktException {
// client 2
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
}
- private void testListAuthorizedClientWithMultipleAccessTokens(String userAuthHeader) throws KustvaktException {
+ private void testListAuthorizedClientWithMultipleAccessTokens (
+ String userAuthHeader) throws KustvaktException {
// client 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
}
- private void testListWithClientsFromAnotherUser(String userAuthHeader) throws KustvaktException {
- String aaaAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("aaa", "pwd");
+ private void testListWithClientsFromAnotherUser (String userAuthHeader)
+ throws KustvaktException {
+ String aaaAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("aaa", "pwd");
// client 1
String code = requestAuthorizationCode(publicClientId, aaaAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, "", code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken1 = node.at("/access_token").asText();
// client 2
code = requestAuthorizationCode(confidentialClientId, aaaAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken2 = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
requestAuthorizedClientList(aaaAuthHeader);
requestAuthorizedClientList(userAuthHeader);
- testRevokeAllTokenViaSuperClient(publicClientId, aaaAuthHeader, accessToken1);
- testRevokeAllTokenViaSuperClient(confidentialClientId, aaaAuthHeader, accessToken2);
- testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
+ testRevokeAllTokenViaSuperClient(publicClientId, aaaAuthHeader,
+ accessToken1);
+ testRevokeAllTokenViaSuperClient(confidentialClientId, aaaAuthHeader,
+ accessToken2);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId,
+ clientSecret, refreshToken);
}
- private void testRevokeAllTokenViaSuperClient(String clientId, String userAuthHeader, String accessToken) throws KustvaktException {
+ private void testRevokeAllTokenViaSuperClient (String clientId,
+ String userAuthHeader, String accessToken)
+ throws KustvaktException {
// check token before revoking
Response response = searchWithAccessToken(accessToken);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertTrue(node.at("/matches").size() > 0);
Form form = getSuperClientForm();
form.param("client_id", clientId);
- response = target().path(API_VERSION).path("oauth2").path("revoke").path("super").path("all").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ response = target().path(API_VERSION).path("oauth2").path("revoke")
+ .path("super").path("all").request()
+ .header(Attributes.AUTHORIZATION, userAuthHeader)
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals(response.readEntity(String.class), "SUCCESS");
response = searchWithAccessToken(accessToken);
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is invalid");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
index af00355..ab2eb27 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
@@ -40,29 +40,35 @@
public String userAuthHeader;
- public OAuth2ControllerTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2ControllerTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "password");
}
@Test
public void testRequestTokenAuthorizationPublic ()
throws KustvaktException {
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
String accessToken = node.at("/access_token").asText();
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertEquals(31536000, node.at("/expires_in").asInt());
testRevokeToken(accessToken, publicClientId, null, ACCESS_TOKEN_TYPE);
assertTrue(node.at("/refresh_token").isMissingNode());
}
@Test
- public void testRequestTokenAuthorizationConfidential() throws KustvaktException {
+ public void testRequestTokenAuthorizationConfidential ()
+ throws KustvaktException {
String scope = "search";
- Response response = requestAuthorizationCode("code", confidentialClientId, "", scope, state, userAuthHeader);
- MultivaluedMap<String, String> params = getQueryParamsFromURI(response.getLocation());
+ Response response = requestAuthorizationCode("code",
+ confidentialClientId, "", scope, state, userAuthHeader);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(
+ response.getLocation());
String code = params.get("code").get(0);
response = requestTokenWithAuthorizationCodeAndForm(
@@ -71,7 +77,8 @@
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
testRequestTokenWithUsedAuthorization(code);
String refreshToken = node.at("/refresh_token").asText();
@@ -79,21 +86,27 @@
testRequestRefreshTokenInvalidScope(confidentialClientId, refreshToken);
testRequestRefreshTokenInvalidClient(refreshToken);
testRequestRefreshTokenInvalidRefreshToken(confidentialClientId);
- testRequestRefreshToken(confidentialClientId, clientSecret, refreshToken);
+ testRequestRefreshToken(confidentialClientId, clientSecret,
+ refreshToken);
}
- private void testRequestTokenWithUsedAuthorization(String code) throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ private void testRequestTokenWithUsedAuthorization (String code)
+ throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Invalid authorization");
+ assertEquals(node.at("/error_description").asText(),
+ "Invalid authorization");
}
@Test
- public void testRequestTokenInvalidAuthorizationCode() throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, "blahblah");
+ public void testRequestTokenInvalidAuthorizationCode ()
+ throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, "blahblah");
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
@@ -101,10 +114,13 @@
}
@Test
- public void testRequestTokenAuthorizationReplyAttack() throws KustvaktException {
+ public void testRequestTokenAuthorizationReplyAttack ()
+ throws KustvaktException {
String redirect_uri = "https://third.party.com/confidential/redirect";
String scope = "search";
- Response response = requestAuthorizationCode("code", confidentialClientId, redirect_uri, scope, state, userAuthHeader);
+ Response response = requestAuthorizationCode("code",
+ confidentialClientId, redirect_uri, scope, state,
+ userAuthHeader);
String code = parseAuthorizationCode(response);
testRequestTokenAuthorizationInvalidClient(code);
testRequestTokenAuthorizationMissingRedirectUri(code);
@@ -112,22 +128,28 @@
testRequestTokenAuthorizationRevoked(code, redirect_uri);
}
- private void testRequestTokenAuthorizationInvalidClient(String code) throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, "wrong_secret", code);
+ private void testRequestTokenAuthorizationInvalidClient (String code)
+ throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, "wrong_secret", code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_CLIENT, node.at("/error").asText());
}
- private void testRequestTokenAuthorizationMissingRedirectUri(String code) throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, "secret", code);
+ private void testRequestTokenAuthorizationMissingRedirectUri (String code)
+ throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, "secret", code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Missing redirect URI");
+ assertEquals(node.at("/error_description").asText(),
+ "Missing redirect URI");
}
- private void testRequestTokenAuthorizationInvalidRedirectUri(String code) throws KustvaktException {
+ private void testRequestTokenAuthorizationInvalidRedirectUri (String code)
+ throws KustvaktException {
Form tokenForm = new Form();
tokenForm.param("grant_type", "authorization_code");
tokenForm.param("client_id", confidentialClientId);
@@ -140,7 +162,8 @@
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
}
- private void testRequestTokenAuthorizationRevoked(String code, String uri) throws KustvaktException {
+ private void testRequestTokenAuthorizationRevoked (String code, String uri)
+ throws KustvaktException {
Form tokenForm = new Form();
tokenForm.param("grant_type", "authorization_code");
tokenForm.param("client_id", confidentialClientId);
@@ -151,21 +174,26 @@
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Invalid authorization");
+ assertEquals(node.at("/error_description").asText(),
+ "Invalid authorization");
}
@Test
- public void testRequestTokenPasswordGrantConfidentialSuper() throws KustvaktException {
- Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
+ public void testRequestTokenPasswordGrantConfidentialSuper ()
+ throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId,
+ clientSecret);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
assertEquals(node.at("/scope").asText(), "all");
String refresh = node.at("/refresh_token").asText();
- RefreshToken refreshToken = refreshTokenDao.retrieveRefreshToken(refresh);
+ RefreshToken refreshToken = refreshTokenDao
+ .retrieveRefreshToken(refresh);
Set<AccessScope> scopes = refreshToken.getScopes();
assertEquals(1, scopes.size());
assertEquals(scopes.toString(), "[all]");
@@ -173,7 +201,8 @@
}
@Test
- public void testRequestTokenPasswordGrantWithScope() throws KustvaktException {
+ public void testRequestTokenPasswordGrantWithScope ()
+ throws KustvaktException {
String scope = "match_info search";
Form form = new Form();
form.param("grant_type", "password");
@@ -187,47 +216,65 @@
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
assertEquals(scope, node.at("/scope").asText());
String refreshToken = node.at("/refresh_token").asText();
- testRequestRefreshTokenWithUnauthorizedScope(superClientId, clientSecret, refreshToken, "all");
- testRequestRefreshTokenWithScope(superClientId, clientSecret, refreshToken, "search");
+ testRequestRefreshTokenWithUnauthorizedScope(superClientId,
+ clientSecret, refreshToken, "all");
+ testRequestRefreshTokenWithScope(superClientId, clientSecret,
+ refreshToken, "search");
}
@Test
- public void testRequestTokenPasswordGrantConfidentialNonSuper() throws KustvaktException {
- Response response = requestTokenWithDoryPassword(confidentialClientId, clientSecret);
+ public void testRequestTokenPasswordGrantConfidentialNonSuper ()
+ throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(confidentialClientId,
+ clientSecret);
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Password grant is not allowed for third party clients");
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
+ node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(),
+ "Password grant is not allowed for third party clients");
}
@Test
- public void testRequestTokenPasswordGrantPublic() throws KustvaktException {
+ public void testRequestTokenPasswordGrantPublic ()
+ throws KustvaktException {
Response response = requestTokenWithDoryPassword(publicClientId, "");
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Password grant is not allowed for third party clients");
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
+ node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(),
+ "Password grant is not allowed for third party clients");
}
@Test
- public void testRequestTokenPasswordGrantAuthorizationHeader() throws KustvaktException {
+ public void testRequestTokenPasswordGrantAuthorizationHeader ()
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", superClientId);
form.param("username", "dory");
form.param("password", "password");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.AUTHORIZATION, "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.AUTHORIZATION,
+ "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
@@ -238,74 +285,81 @@
* @throws KustvaktException
*/
@Test
- public void testRequestTokenPasswordGrantDifferentClientIds() throws KustvaktException {
+ public void testRequestTokenPasswordGrantDifferentClientIds ()
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", "9aHsGW6QflV13ixNpez");
form.param("username", "dory");
form.param("password", "password");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.AUTHORIZATION, "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.AUTHORIZATION,
+ "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
@Test
public void testRequestTokenPasswordGrantMissingClientSecret ()
throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(confidentialClientId, "");
+ Response response = requestTokenWithDoryPassword(confidentialClientId,
+ "");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertNotNull(node.at("/error_description").asText());
}
-
+
@Test
public void testRequestTokenPasswordGrantEmptyClientSecret ()
throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(confidentialClientId, "");
+ Response response = requestTokenWithDoryPassword(confidentialClientId,
+ "");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals(node.at("/error_description").asText(), "Missing parameter: client_secret");
+ assertEquals(node.at("/error_description").asText(),
+ "Missing parameter: client_secret");
}
@Test
- public void testRequestTokenPasswordGrantMissingClientId() throws KustvaktException {
+ public void testRequestTokenPasswordGrantMissingClientId ()
+ throws KustvaktException {
Response response = requestTokenWithDoryPassword(null, clientSecret);
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertNotNull(node.at("/error_description").asText());
}
-
+
@Test
public void testRequestTokenPasswordGrantEmptyClientId ()
throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword("", clientSecret);
+ Response response = requestTokenWithDoryPassword("", clientSecret);
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertNotNull(node.at("/error_description").asText());
}
@Test
- public void testRequestTokenClientCredentialsGrant() throws KustvaktException {
+ public void testRequestTokenClientCredentialsGrant ()
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", confidentialClientId);
@@ -317,7 +371,8 @@
// length?
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
@@ -326,7 +381,8 @@
* clients.
*/
@Test
- public void testRequestTokenClientCredentialsGrantPublic() throws KustvaktException {
+ public void testRequestTokenClientCredentialsGrantPublic ()
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", publicClientId);
@@ -335,13 +391,13 @@
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertNotNull(node.at("/error_description").asText());
}
@Test
- public void testRequestTokenClientCredentialsGrantReducedScope() throws KustvaktException {
+ public void testRequestTokenClientCredentialsGrantReducedScope ()
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", confidentialClientId);
@@ -354,13 +410,14 @@
// length?
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
assertEquals(node.at("/scope").asText(), "client_info");
}
@Test
- public void testRequestTokenMissingGrantType() throws KustvaktException {
+ public void testRequestTokenMissingGrantType () throws KustvaktException {
Form form = new Form();
Response response = requestToken(form);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
@@ -370,109 +427,155 @@
}
@Test
- public void testRequestTokenUnsupportedGrant() throws KustvaktException {
+ public void testRequestTokenUnsupportedGrant () throws KustvaktException {
Form form = new Form();
form.param("grant_type", "blahblah");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.get("error_description").asText());
- assertEquals(OAuth2Error.INVALID_REQUEST,
- node.get("error").asText());
+ assertEquals(OAuth2Error.INVALID_REQUEST, node.get("error").asText());
}
- private void testRequestRefreshTokenInvalidScope(String clientId, String refreshToken) throws KustvaktException {
+ private void testRequestRefreshTokenInvalidScope (String clientId,
+ String refreshToken) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
form.param("scope", "search serialize_query");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_SCOPE, node.at("/error").asText());
}
- private void testRequestRefreshToken(String clientId, String clientSecret, String refreshToken) throws KustvaktException {
+ private void testRequestRefreshToken (String clientId, String clientSecret,
+ String refreshToken) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
String newRefreshToken = node.at("/refresh_token").asText();
assertNotNull(newRefreshToken);
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
assertTrue(!newRefreshToken.equals(refreshToken));
- testRequestTokenWithRevokedRefreshToken(clientId, clientSecret, refreshToken);
- testRevokeToken(newRefreshToken, clientId, clientSecret, REFRESH_TOKEN_TYPE);
- testRequestTokenWithRevokedRefreshToken(clientId, clientSecret, newRefreshToken);
+ testRequestTokenWithRevokedRefreshToken(clientId, clientSecret,
+ refreshToken);
+ testRevokeToken(newRefreshToken, clientId, clientSecret,
+ REFRESH_TOKEN_TYPE);
+ testRequestTokenWithRevokedRefreshToken(clientId, clientSecret,
+ newRefreshToken);
}
- private void testRequestRefreshTokenWithUnauthorizedScope(String clientId, String clientSecret, String refreshToken, String scope) throws KustvaktException {
+ private void testRequestRefreshTokenWithUnauthorizedScope (String clientId,
+ String clientSecret, String refreshToken, String scope)
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
form.param("scope", scope);
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_SCOPE, node.at("/error").asText());
}
- private void testRequestRefreshTokenWithScope(String clientId, String clientSecret, String refreshToken, String scope) throws KustvaktException {
+ private void testRequestRefreshTokenWithScope (String clientId,
+ String clientSecret, String refreshToken, String scope)
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
form.param("scope", scope);
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
String newRefreshToken = node.at("/refresh_token").asText();
assertNotNull(newRefreshToken);
- assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(),
+ node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
assertTrue(!newRefreshToken.equals(refreshToken));
assertEquals(scope, node.at("/scope").asText());
}
- private void testRequestRefreshTokenInvalidClient(String refreshToken) throws KustvaktException {
+ private void testRequestRefreshTokenInvalidClient (String refreshToken)
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", "iBr3LsTCxOj7D2o0A5m");
form.param("refresh_token", refreshToken);
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_CLIENT, node.at("/error").asText());
}
- private void testRequestRefreshTokenInvalidRefreshToken(String clientId) throws KustvaktException {
+ private void testRequestRefreshTokenInvalidRefreshToken (String clientId)
+ throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", "Lia8s8w8tJeZSBlaQDrYV8ion3l");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
}
- private JsonNode requestTokenList(String userAuthHeader, String tokenType, String clientId) throws KustvaktException {
+ private JsonNode requestTokenList (String userAuthHeader, String tokenType,
+ String clientId) throws KustvaktException {
Form form = new Form();
form.param("super_client_id", superClientId);
form.param("super_client_secret", clientSecret);
@@ -480,33 +583,46 @@
if (clientId != null && !clientId.isEmpty()) {
form.param("client_id", clientId);
}
- Response response = target().path(API_VERSION).path("oauth2").path("token").path("list").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").path("list").request()
+ .header(Attributes.AUTHORIZATION, userAuthHeader)
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private JsonNode requestTokenList(String userAuthHeader, String tokenType) throws KustvaktException {
+ private JsonNode requestTokenList (String userAuthHeader, String tokenType)
+ throws KustvaktException {
return requestTokenList(userAuthHeader, tokenType, null);
}
@Test
- public void testListRefreshTokenConfidentialClient() throws KustvaktException {
+ public void testListRefreshTokenConfidentialClient ()
+ throws KustvaktException {
String username = "gurgle";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, password);
// super client
- Response response = requestTokenWithPassword(superClientId, clientSecret, username, password);
+ Response response = requestTokenWithPassword(superClientId,
+ clientSecret, username, password);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String refreshToken1 = node.at("/refresh_token").asText();
// client 1
- String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ String code = requestAuthorizationCode(confidentialClientId,
+ userAuthHeader);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// client 2
- code = requestAuthorizationCode(confidentialClientId2, clientRedirectUri, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId2, clientSecret, code, clientRedirectUri);
+ code = requestAuthorizationCode(confidentialClientId2,
+ clientRedirectUri, userAuthHeader);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId2, clientSecret, code, clientRedirectUri);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// list
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
@@ -515,31 +631,39 @@
assertEquals(confidentialClientId2, node.at("/1/client_id").asText());
// client 1
code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// another user
- String darlaAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("darla", "pwd");
+ String darlaAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("darla", "pwd");
// test listing clients
node = requestTokenList(darlaAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
// client 1
code = requestAuthorizationCode(confidentialClientId, darlaAuthHeader);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(
+ confidentialClientId, clientSecret, code);
node = JsonUtils.readTree(response.readEntity(String.class));
String refreshToken5 = node.at("/refresh_token").asText();
// list all refresh tokens
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(3, node.size());
// list refresh tokens from client 1
- node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE, confidentialClientId);
+ node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE,
+ confidentialClientId);
assertEquals(2, node.size());
- testRevokeToken(refreshToken1, superClientId, clientSecret, REFRESH_TOKEN_TYPE);
- testRevokeToken(node.at("/0/token").asText(), confidentialClientId, clientSecret, REFRESH_TOKEN_TYPE);
- testRevokeToken(node.at("/1/token").asText(), confidentialClientId2, clientSecret, REFRESH_TOKEN_TYPE);
+ testRevokeToken(refreshToken1, superClientId, clientSecret,
+ REFRESH_TOKEN_TYPE);
+ testRevokeToken(node.at("/0/token").asText(), confidentialClientId,
+ clientSecret, REFRESH_TOKEN_TYPE);
+ testRevokeToken(node.at("/1/token").asText(), confidentialClientId2,
+ clientSecret, REFRESH_TOKEN_TYPE);
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(1, node.size());
- testRevokeTokenViaSuperClient(node.at("/0/token").asText(), userAuthHeader);
+ testRevokeTokenViaSuperClient(node.at("/0/token").asText(),
+ userAuthHeader);
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
// try revoking a token belonging to another user
@@ -553,19 +677,22 @@
}
@Test
- public void testListTokenPublicClient() throws KustvaktException {
+ public void testListTokenPublicClient () throws KustvaktException {
String username = "nemo";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, password);
// access token 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(
+ publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken1 = node.at("/access_token").asText();
// access token 2
code = requestAuthorizationCode(publicClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
+ response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "",
+ code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken2 = node.at("/access_token").asText();
@@ -593,9 +720,11 @@
assertEquals(0, node.size());
}
- private void testRefreshTokenExpiry(String refreshToken) throws KustvaktException {
+ private void testRefreshTokenExpiry (String refreshToken)
+ throws KustvaktException {
RefreshToken token = refreshTokenDao.retrieveRefreshToken(refreshToken);
- ZonedDateTime expiry = token.getCreatedDate().plusSeconds(config.getRefreshTokenLongExpiry());
+ ZonedDateTime expiry = token.getCreatedDate()
+ .plusSeconds(config.getRefreshTokenLongExpiry());
assertTrue(expiry.equals(token.getExpiryDate()));
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
index 62b96f7..90597e2 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
@@ -45,9 +45,10 @@
@Autowired
private InstalledPluginDao pluginDao;
-
+
@Test
- public void testRegisterPlugin() throws ProcessingException, KustvaktException {
+ public void testRegisterPlugin ()
+ throws ProcessingException, KustvaktException {
JsonNode source = JsonUtils.readTree("{ \"plugin\" : \"source\"}");
int refreshTokenExpiry = TimeUtils.convertTimeToSeconds("90D");
String clientName = "Plugin";
@@ -71,12 +72,13 @@
// permitted only
node = listPlugins(true);
assertEquals(2, node.size());
- testListUserRegisteredPlugins(username, clientId, clientName, refreshTokenExpiry);
+ testListUserRegisteredPlugins(username, clientId, clientName,
+ refreshTokenExpiry);
deregisterClient(username, clientId);
}
@Test
- public void testRegisterPublicPlugin() throws KustvaktException {
+ public void testRegisterPublicPlugin () throws KustvaktException {
JsonNode source = JsonUtils.readTree("{ \"plugin\" : \"source\"}");
String clientName = "Public Plugin";
OAuth2ClientJson json = new OAuth2ClientJson();
@@ -96,40 +98,50 @@
// deregisterClient(username, clientId);
}
- private void testRetrievePluginInfo(String clientId, int refreshTokenExpiry) throws ProcessingException, KustvaktException {
+ private void testRetrievePluginInfo (String clientId,
+ int refreshTokenExpiry)
+ throws ProcessingException, KustvaktException {
JsonNode clientInfo = retrieveClientInfo(clientId, username);
assertEquals(clientId, clientInfo.at("/client_id").asText());
assertEquals(clientInfo.at("/client_name").asText(), "Plugin");
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), clientInfo.at("/client_type").asText());
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
+ clientInfo.at("/client_type").asText());
assertNotNull(clientInfo.at("/client_description").asText());
assertNotNull(clientInfo.at("/source").asText());
assertFalse(clientInfo.at("/permitted").asBoolean());
assertEquals(username, clientInfo.at("/registered_by").asText());
assertNotNull(clientInfo.at("/registration_date"));
- assertEquals(refreshTokenExpiry, clientInfo.at("/refresh_token_expiry").asInt());
+ assertEquals(refreshTokenExpiry,
+ clientInfo.at("/refresh_token_expiry").asInt());
}
- private void testListUserRegisteredPlugins(String username, String clientId, String clientName, int refreshTokenExpiry) throws ProcessingException, KustvaktException {
+ private void testListUserRegisteredPlugins (String username,
+ String clientId, String clientName, int refreshTokenExpiry)
+ throws ProcessingException, KustvaktException {
JsonNode node = listUserRegisteredClients(username);
assertEquals(1, node.size());
assertEquals(clientId, node.at("/0/client_id").asText());
assertEquals(clientName, node.at("/0/client_name").asText());
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), node.at("/0/client_type").asText());
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
+ node.at("/0/client_type").asText());
assertFalse(node.at("/0/permitted").asBoolean());
assertFalse(node.at("/0/registration_date").isMissingNode());
assertFalse(node.at("/0/source").isMissingNode());
- assertEquals(refreshTokenExpiry, node.at("/0/refresh_token_expiry").asInt());
+ assertEquals(refreshTokenExpiry,
+ node.at("/0/refresh_token_expiry").asInt());
}
@Test
- public void testListPluginsUnauthorizedPublic() throws ProcessingException, KustvaktException {
+ public void testListPluginsUnauthorizedPublic ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", publicClientId);
testListPluginsClientUnauthorized(form);
}
@Test
- public void testListPluginsUnauthorizedConfidential() throws ProcessingException, KustvaktException {
+ public void testListPluginsUnauthorizedConfidential ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId2);
form.param("super_client_secret", clientSecret);
@@ -137,10 +149,16 @@
}
@Test
- public void testListPluginsMissingClientSecret() throws ProcessingException, KustvaktException {
+ public void testListPluginsMissingClientSecret ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId);
- Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("plugins").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
@@ -148,31 +166,45 @@
assertFalse(node.at("/error_description").isMissingNode());
}
- private void testListPluginsClientUnauthorized(Form form) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ private void testListPluginsClientUnauthorized (Form form)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("plugins").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
+ node.at("/error").asText());
assertFalse(node.at("/error_description").isMissingNode());
}
@Test
- public void testListPluginsUserUnauthorized() throws ProcessingException, KustvaktException {
+ public void testListPluginsUserUnauthorized ()
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
- Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, "Bearer blahblah").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("plugins").request()
+ .header(Attributes.AUTHORIZATION, "Bearer blahblah")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testListPluginsConcurrent() throws InterruptedException {
+ public void testListPluginsConcurrent () throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<Void>> futures = new ArrayList<>();
for (int i = 0; i < 3; i++) {
- futures.add(executorService.submit(new PluginListCallable("Thread " + (i + 1))));
+ futures.add(executorService
+ .submit(new PluginListCallable("Thread " + (i + 1))));
}
executorService.shutdown();
executorService.awaitTermination(2, TimeUnit.SECONDS);
@@ -181,7 +213,8 @@
// This will re-throw any exceptions
future.get();
// that occurred in threads
- } catch (ExecutionException e) {
+ }
+ catch (ExecutionException e) {
fail("Test failed: " + e.getCause().getMessage());
}
}
@@ -191,20 +224,29 @@
private final String name;
- public PluginListCallable(String name) {
+ public PluginListCallable (String name) {
this.name = name;
}
@Override
- public Void call() {
+ public Void call () {
Form form = getSuperClientForm();
try {
- Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("plugins")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
- } catch (KustvaktException e) {
+ }
+ catch (KustvaktException e) {
e.printStackTrace();
throw new RuntimeException(name, e);
}
@@ -213,7 +255,8 @@
}
@Test
- public void testListAllPlugins() throws ProcessingException, KustvaktException {
+ public void testListAllPlugins ()
+ throws ProcessingException, KustvaktException {
JsonNode node = listPlugins(false);
assertEquals(2, node.size());
assertFalse(node.at("/0/client_id").isMissingNode());
@@ -227,18 +270,26 @@
// assertTrue(node.at("/1/refresh_token_expiry").isMissingNode());
}
- private JsonNode listPlugins(boolean permitted_only) throws ProcessingException, KustvaktException {
+ private JsonNode listPlugins (boolean permitted_only)
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
if (permitted_only) {
form.param("permitted_only", Boolean.toString(permitted_only));
}
- Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("plugins").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private void testInstallConfidentialPlugin(String superClientId, String clientId, String username) throws ProcessingException, KustvaktException {
+ private void testInstallConfidentialPlugin (String superClientId,
+ String clientId, String username)
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
Response response = installPlugin(form);
@@ -255,7 +306,8 @@
}
@Test
- public void testInstallPublicPlugin() throws ProcessingException, KustvaktException {
+ public void testInstallPublicPlugin ()
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", publicClientId2);
Response response = installPlugin(form);
@@ -276,71 +328,84 @@
assertTrue(node.isEmpty());
}
- private void testInstallPluginRedundant(Form form) throws ProcessingException, KustvaktException {
+ private void testInstallPluginRedundant (Form form)
+ throws ProcessingException, KustvaktException {
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.PLUGIN_HAS_BEEN_INSTALLED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.PLUGIN_HAS_BEEN_INSTALLED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
- private void testInstallPluginNotPermitted(String clientId) throws ProcessingException, KustvaktException {
+ private void testInstallPluginNotPermitted (String clientId)
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.PLUGIN_NOT_PERMITTED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.PLUGIN_NOT_PERMITTED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingClientId() throws ProcessingException, KustvaktException {
+ public void testInstallPluginMissingClientId ()
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginInvalidClientId() throws ProcessingException, KustvaktException {
+ public void testInstallPluginInvalidClientId ()
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", "unknown");
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "Unknown client: unknown");
+ assertEquals(node.at("/error_description").asText(),
+ "Unknown client: unknown");
assertEquals(node.at("/error").asText(), "invalid_client");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingSuperClientSecret() throws ProcessingException, KustvaktException {
+ public void testInstallPluginMissingSuperClientSecret ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", superClientId);
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "Missing parameter: super_client_secret");
+ assertEquals(node.at("/error_description").asText(),
+ "Missing parameter: super_client_secret");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingSuperClientId() throws ProcessingException, KustvaktException {
+ public void testInstallPluginMissingSuperClientId ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/error_description").asText(), "Missing parameter: super_client_id");
+ assertEquals(node.at("/error_description").asText(),
+ "Missing parameter: super_client_id");
assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginUnauthorizedClient() throws ProcessingException, KustvaktException {
+ public void testInstallPluginUnauthorizedClient ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId);
form.param("super_client_secret", clientSecret);
@@ -351,18 +416,34 @@
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
- private Response installPlugin(Form form) throws ProcessingException, KustvaktException {
- return target().path(API_VERSION).path("plugins").path("install").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ private Response installPlugin (Form form)
+ throws ProcessingException, KustvaktException {
+ return target().path(API_VERSION).path("plugins").path("install")
+ .request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
}
- private Response uninstallPlugin(String clientId, String username) throws ProcessingException, KustvaktException {
+ private Response uninstallPlugin (String clientId, String username)
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
- return target().path(API_VERSION).path("plugins").path("uninstall").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ return target().path(API_VERSION).path("plugins").path("uninstall")
+ .request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
}
- private void testRetrieveInstalledPlugin(String superClientId, String clientId, String installedBy) throws KustvaktException {
- InstalledPlugin plugin = pluginDao.retrieveInstalledPlugin(superClientId, clientId, installedBy);
+ private void testRetrieveInstalledPlugin (String superClientId,
+ String clientId, String installedBy) throws KustvaktException {
+ InstalledPlugin plugin = pluginDao
+ .retrieveInstalledPlugin(superClientId, clientId, installedBy);
assertEquals(clientId, plugin.getClient().getId());
assertEquals(superClientId, plugin.getSuperClient().getId());
assertEquals(installedBy, plugin.getInstalledBy());
@@ -371,20 +452,24 @@
}
@Test
- public void testListUserInstalledPlugins() throws ProcessingException, KustvaktException, IOException {
- testInstallConfidentialPlugin(superClientId, confidentialClientId, username);
+ public void testListUserInstalledPlugins ()
+ throws ProcessingException, KustvaktException, IOException {
+ testInstallConfidentialPlugin(superClientId, confidentialClientId,
+ username);
JsonNode node = testRequestAccessToken(confidentialClientId);
String accessToken = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
testSearchWithOAuth2Token(accessToken);
- testInstallConfidentialPlugin(superClientId, confidentialClientId2, username);
+ testInstallConfidentialPlugin(superClientId, confidentialClientId2,
+ username);
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(2, node.size());
Response response = uninstallPlugin(confidentialClientId, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(1, node.size());
- testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId,
+ clientSecret, refreshToken);
testSearchWithRevokedAccessToken(accessToken);
response = uninstallPlugin(confidentialClientId2, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -394,8 +479,10 @@
testUninstallNotInstalledPlugin();
}
- private void testReinstallUninstalledPlugin() throws ProcessingException, KustvaktException {
- testInstallConfidentialPlugin(superClientId, confidentialClientId2, username);
+ private void testReinstallUninstalledPlugin ()
+ throws ProcessingException, KustvaktException {
+ testInstallConfidentialPlugin(superClientId, confidentialClientId2,
+ username);
JsonNode node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(1, node.size());
Response response = uninstallPlugin(confidentialClientId2, username);
@@ -404,24 +491,36 @@
assertEquals(0, node.size());
}
- private JsonNode testRequestAccessToken(String clientId) throws KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
+ private JsonNode testRequestAccessToken (String clientId)
+ throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "password");
String code = requestAuthorizationCode(clientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
return node;
}
- private void testUninstallNotInstalledPlugin() throws ProcessingException, KustvaktException {
+ private void testUninstallNotInstalledPlugin ()
+ throws ProcessingException, KustvaktException {
Response response = uninstallPlugin(confidentialClientId2, username);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
- private JsonNode retrieveUserInstalledPlugin(Form form) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("plugins").path("installed").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ private JsonNode retrieveUserInstalledPlugin (Form form)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("plugins")
+ .path("installed").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
index 30bb832..d0eab61 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
@@ -26,11 +26,12 @@
private String userAuthHeader;
- public OAuth2RClientTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("R-user", "password");
+ public OAuth2RClientTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("R-user", "password");
}
- public OAuth2ClientJson createOAuth2RClient() {
+ public OAuth2ClientJson createOAuth2RClient () {
OAuth2ClientJson client = new OAuth2ClientJson();
client.setName("R client");
client.setType(OAuth2ClientType.PUBLIC);
@@ -40,7 +41,8 @@
}
@Test
- public void testRClientWithLocalhost() throws ProcessingException, KustvaktException, IOException {
+ public void testRClientWithLocalhost ()
+ throws ProcessingException, KustvaktException, IOException {
// Register client
OAuth2ClientJson clientJson = createOAuth2RClient();
Response response = registerClient(username, clientJson);
@@ -50,7 +52,8 @@
// send authorization
String code = testAuthorize(clientId);
// send token request
- response = requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, null,
+ code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
@@ -62,14 +65,17 @@
testSearchWithRevokedAccessToken(accessToken);
}
- private String testAuthorize(String clientId) throws KustvaktException {
- Response response = requestAuthorizationCode("code", clientId, "", "search", "", userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ private String testAuthorize (String clientId) throws KustvaktException {
+ Response response = requestAuthorizationCode("code", clientId, "",
+ "search", "", userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
+ response.getStatus());
URI redirectUri = response.getLocation();
assertEquals(redirectUri.getScheme(), "http");
assertEquals(redirectUri.getHost(), "localhost");
assertEquals(1410, redirectUri.getPort());
- MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder
+ .fromUri(redirectUri).build().getQueryParams();
String code = params.getFirst("code");
assertNotNull(code);
return code;
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
index 0b94e02..b27fd0f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
@@ -80,8 +80,9 @@
public static String ACCESS_TOKEN_TYPE = "access_token";
public static String REFRESH_TOKEN_TYPE = "refresh_token";
- protected int defaultRefreshTokenExpiry = TimeUtils.convertTimeToSeconds("365D");
-
+ protected int defaultRefreshTokenExpiry = TimeUtils
+ .convertTimeToSeconds("365D");
+
protected String clientURL = "http://example.client.com";
protected String clientRedirectUri = "https://example.client.com/redirect";
@@ -97,7 +98,7 @@
}
protected String parseAuthorizationCode (Response response) {
-
+
assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
response.getStatus());
@@ -106,7 +107,7 @@
.fromUri(redirectUri).build().getQueryParams();
return params.getFirst("code");
}
-
+
protected Response requestAuthorizationCode (String responseType,
String clientId, String redirectUri, String scope, String state,
String authHeader) throws KustvaktException {
@@ -114,7 +115,7 @@
ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, false);
Client client = ClientBuilder.newClient(clientConfig);
-
+
WebTarget request = client.target(getBaseUri()).path(API_VERSION)
.path("oauth2").path("authorize");
@@ -133,9 +134,10 @@
if (!state.isEmpty()) {
request = request.queryParam("state", state);
}
-
- Builder builder = request.request().header(Attributes.AUTHORIZATION, authHeader);
-
+
+ Builder builder = request.request().header(Attributes.AUTHORIZATION,
+ authHeader);
+
return builder.get();
}
@@ -166,14 +168,12 @@
return params.getFirst("code");
}
- protected Response requestToken (Form form)
- throws KustvaktException {
- return target().path(API_VERSION).path("oauth2").path("token")
- .request()
+ protected Response requestToken (Form form) throws KustvaktException {
+ return target().path(API_VERSION).path("oauth2").path("token").request()
.header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ .post(Entity.form(form));
}
// client credentials as form params
@@ -187,8 +187,7 @@
form.param("client_secret", clientSecret);
form.param("code", code);
- return target().path(API_VERSION).path("oauth2").path("token")
- .request()
+ return target().path(API_VERSION).path("oauth2").path("token").request()
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.post(Entity.form(form));
@@ -207,8 +206,7 @@
form.param("redirect_uri", redirectUri);
}
- return target().path(API_VERSION).path("oauth2").path("token")
- .request()
+ return target().path(API_VERSION).path("oauth2").path("token").request()
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.post(Entity.form(form));
@@ -224,15 +222,14 @@
form.param("code", code);
Response response = target().path(API_VERSION).path("oauth2")
- .path("token")
- .request()
+ .path("token").request()
.header(Attributes.AUTHORIZATION, authHeader)
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
+
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
@@ -249,7 +246,7 @@
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", clientId);
- if (clientSecret !=null && !clientSecret.isEmpty()) {
+ if (clientSecret != null && !clientSecret.isEmpty()) {
form.param("client_secret", clientSecret);
}
form.param("username", username);
@@ -269,27 +266,25 @@
form.param("client_secret", clientSecret);
}
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.INVALID_GRANT.getCode(), node.at("/error").asText());
+ assertEquals(OAuth2Error.INVALID_GRANT.getCode(),
+ node.at("/error").asText());
assertEquals("Refresh token has been revoked",
node.at("/error_description").asText());
}
- protected Response registerClient (String username,
- OAuth2ClientJson json) throws
- ProcessingException, KustvaktException {
+ protected Response registerClient (String username, OAuth2ClientJson json)
+ throws ProcessingException, KustvaktException {
return target().path(API_VERSION).path("oauth2").path("client")
- .path("register")
- .request()
+ .path("register").request()
.header(Attributes.AUTHORIZATION,
HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username,
@@ -313,11 +308,11 @@
}
protected void testConfidentialClientInfo (String clientId, String username)
- throws ProcessingException,
- KustvaktException {
+ throws ProcessingException, KustvaktException {
JsonNode clientInfo = retrieveClientInfo(clientId, username);
assertEquals(clientId, clientInfo.at("/client_id").asText());
- assertEquals("OAuth2ClientTest", clientInfo.at("/client_name").asText());
+ assertEquals("OAuth2ClientTest",
+ clientInfo.at("/client_name").asText());
assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
clientInfo.at("/client_type").asText());
assertEquals(username, clientInfo.at("/registered_by").asText());
@@ -334,13 +329,11 @@
}
- protected void deregisterClient (String username,
- String clientId) throws
- ProcessingException, KustvaktException {
+ protected void deregisterClient (String username, String clientId)
+ throws ProcessingException, KustvaktException {
Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("deregister").path(clientId)
- .request()
+ .path("client").path("deregister").path(clientId).request()
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.delete();
@@ -349,17 +342,15 @@
}
protected JsonNode retrieveClientInfo (String clientId, String username)
- throws ProcessingException,
- KustvaktException {
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", superClientId);
form.param("super_client_secret", clientSecret);
-
+
Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path(clientId)
- .request()
-// .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
-// .createBasicAuthorizationHeaderValue(username, "pass"))
+ .path("client").path(clientId).request()
+ // .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ // .createBasicAuthorizationHeaderValue(username, "pass"))
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.post(Entity.form(form));
@@ -375,27 +366,24 @@
.queryParam("q", "Wasser").queryParam("ql", "poliqarp")
.request()
.header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
}
-
+
protected void testSearchWithOAuth2Token (String accessToken)
throws KustvaktException, IOException {
Response response = searchWithAccessToken(accessToken);
String entity = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertEquals(25, node.at("/matches").size());
}
-
+
protected void testSearchWithRevokedAccessToken (String accessToken)
throws KustvaktException {
Response response = searchWithAccessToken(accessToken);
String entity = response.readEntity(String.class);
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
@@ -404,7 +392,6 @@
node.at("/errors/0/1").asText());
}
-
protected void testRevokeTokenViaSuperClient (String token,
String userAuthHeader) {
Form form = new Form();
@@ -413,8 +400,7 @@
form.param("super_client_secret", clientSecret);
Response response = target().path(API_VERSION).path("oauth2")
- .path("revoke").path("super")
- .request()
+ .path("revoke").path("super").request()
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.header(Attributes.AUTHORIZATION, userAuthHeader)
@@ -434,24 +420,21 @@
form.param("client_secret", clientSecret);
}
- Response response =
- target().path(API_VERSION).path("oauth2").path("revoke")
- .request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("revoke").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals("SUCCESS", response.readEntity(String.class));
}
protected JsonNode listUserRegisteredClients (String username)
- throws ProcessingException,
- KustvaktException {
+ throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("list")
- .request()
+ .path("client").path("list").request()
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pwd"))
.header(HttpHeaders.CONTENT_TYPE,
@@ -463,7 +446,7 @@
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
-
+
protected void testInvalidRedirectUri (String entity, String contentType,
boolean includeState, int status) throws KustvaktException {
JsonNode node = JsonUtils.readTree(entity);
@@ -478,18 +461,18 @@
assertEquals("application/json;charset=utf-8", contentType);
assertEquals(Status.BAD_REQUEST.getStatusCode(), status);
}
-
+
protected String createExpiredAccessToken () throws KustvaktException {
String authToken = codeGenerator.createRandomCode();
-
+
// create new access token
OAuth2Client client = clientDao.retrieveClientById(publicClientId);
- ZonedDateTime now =
- ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+ ZonedDateTime now = ZonedDateTime
+ .now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
Set<AccessScope> scopes = new HashSet<>();
scopes.add(new AccessScope(OAuth2Scope.EDIT_VC));
-
+
AccessToken accessToken = new AccessToken();
accessToken.setCreatedDate(now.minusSeconds(5));
accessToken.setExpiryDate(now.minusSeconds(3));
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
index 89e2cb5..57dc847 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
@@ -28,8 +28,14 @@
private String system = "system";
- private void testRetrieveQueryByName(String qName, String query, String queryCreator, String username, ResourceType resourceType, CorpusAccess access) throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").path("~" + queryCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
+ private void testRetrieveQueryByName (String qName, String query,
+ String queryCreator, String username, ResourceType resourceType,
+ CorpusAccess access) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + queryCreator).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -42,173 +48,283 @@
assertEquals(access.name(), node.at("/requiredAccess").asText());
}
- private void testUpdateQuery(String qName, String qCreator, String username, ResourceType type) throws ProcessingException, KustvaktException {
- String json = "{\"query\": \"Sonne\"" + ",\"queryLanguage\": \"poliqarp\"}";
- Response response = target().path(API_VERSION).path("query").path("~" + qCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ private void testUpdateQuery (String qName, String qCreator,
+ String username, ResourceType type)
+ throws ProcessingException, KustvaktException {
+ String json = "{\"query\": \"Sonne\""
+ + ",\"queryLanguage\": \"poliqarp\"}";
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + qCreator).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "Sonne", qCreator, username, type, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Sonne", qCreator, username, type,
+ CorpusAccess.PUB);
}
@Test
- public void testCreatePrivateQuery() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"der\"}";
+ public void testCreatePrivateQuery () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"der\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "der", testUser, testUser, ResourceType.PRIVATE, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "der", testUser, testUser,
+ ResourceType.PRIVATE, CorpusAccess.PUB);
testUpdateQuery(qName, testUser, testUser, ResourceType.PRIVATE);
testDeleteQueryByName(qName, testUser, testUser);
}
@Test
- public void testCreatePublishQuery() throws KustvaktException {
- String json = "{\"type\": \"PUBLISHED\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Regen\"}";
+ public void testCreatePublishQuery () throws KustvaktException {
+ String json = "{\"type\": \"PUBLISHED\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Regen\"}";
String qName = "publish_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "Regen", testUser, testUser, ResourceType.PUBLISHED, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Regen", testUser, testUser,
+ ResourceType.PUBLISHED, CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
// check if hidden group has been created
}
@Test
- public void testCreateUserQueryByAdmin() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
+ public void testCreateUserQueryByAdmin () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\""
+ + ",\"query\": \"Sommer\"}";
String qName = "marlin-query";
- Response response = target().path(API_VERSION).path("query").path("~marlin").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(adminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~marlin").path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(adminUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "Sommer", "marlin", adminUser, ResourceType.PRIVATE, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Sommer", "marlin", adminUser,
+ ResourceType.PRIVATE, CorpusAccess.PUB);
testUpdateQuery(qName, "marlin", adminUser, ResourceType.PRIVATE);
testDeleteQueryByName(qName, "marlin", adminUser);
}
@Test
- public void testCreateSystemQuery() throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
+ public void testCreateSystemQuery () throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\""
+ + ",\"query\": \"Sommer\"}";
String qName = "system-query";
- Response response = target().path(API_VERSION).path("query").path("~system").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(adminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~system").path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(adminUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "Sommer", system, adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Sommer", system, adminUser,
+ ResourceType.SYSTEM, CorpusAccess.PUB);
testUpdateQuery(qName, system, adminUser, ResourceType.SYSTEM);
testDeleteSystemQueryUnauthorized(qName);
testDeleteQueryByName(qName, system, adminUser);
}
@Test
- public void testCreateSystemQueryUnauthorized() throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path("system-query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateSystemQueryUnauthorized () throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\""
+ + ",\"query\": \"Sommer\"}";
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path("system-query").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser,
+ node.at("/errors/0/1").asText());
}
@Test
- public void testCreateQueryMissingQueryType() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sohn\"}";
+ public void testCreateQueryMissingQueryType () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sohn\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveQueryByName(qName, "Sohn", testUser, testUser, ResourceType.PRIVATE, CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Sohn", testUser, testUser,
+ ResourceType.PRIVATE, CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
}
@Test
- public void testCreateQueryMissingQueryLanguage() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"query\": \"Sohn\"}";
+ public void testCreateQueryMissingQueryLanguage ()
+ throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\""
+ + ",\"query\": \"Sohn\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "queryLanguage is null");
assertEquals(node.at("/errors/0/2").asText(), "queryLanguage");
}
@Test
- public void testCreateQueryMissingQuery() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"}";
+ public void testCreateQueryMissingQuery () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\""
+ + ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "query is null");
assertEquals(node.at("/errors/0/2").asText(), "query");
}
@Test
- public void testCreateQueryMissingResourceType() throws KustvaktException {
- String json = "{\"query\": \"Wind\"" + ",\"queryLanguage\": \"poliqarp\"}";
+ public void testCreateQueryMissingResourceType () throws KustvaktException {
+ String json = "{\"query\": \"Wind\""
+ + ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + testUser).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "type is null");
assertEquals(node.at("/errors/0/2").asText(), "type");
}
- private void testDeleteQueryByName(String qName, String qCreator, String username) throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").path("~" + qCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private void testDeleteQueryByName (String qName, String qCreator,
+ String username) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .path("~" + qCreator).path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testDeleteQueryUnauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").path("~dory").path("dory-q").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).delete();
+ public void testDeleteQueryUnauthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .path("~dory").path("dory-q").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .delete();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser,
+ node.at("/errors/0/1").asText());
}
- private void testDeleteSystemQueryUnauthorized(String qName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").path("~system").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).delete();
+ private void testDeleteSystemQueryUnauthorized (String qName)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .path("~system").path(qName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .delete();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser,
+ node.at("/errors/0/1").asText());
}
@Test
- public void testDeleteNonExistingQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").path("~dory").path("non-existing-query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).delete();
+ public void testDeleteNonExistingQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .path("~dory").path("non-existing-query").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Query dory/non-existing-query is not found.");
- assertEquals(node.at("/errors/0/2").asText(), "dory/non-existing-query");
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Query dory/non-existing-query is not found.");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "dory/non-existing-query");
}
@Test
- public void testListAvailableQueryForDory() throws ProcessingException, KustvaktException {
+ public void testListAvailableQueryForDory ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testListAvailableQuery("dory");
assertEquals(2, node.size());
}
@Test
- public void testListAvailableQueryForPearl() throws ProcessingException, KustvaktException {
+ public void testListAvailableQueryForPearl ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testListAvailableQuery("pearl");
assertEquals(1, node.size());
assertEquals(node.at("/0/name").asText(), "system-q");
- assertEquals(ResourceType.SYSTEM.displayName(), node.at("/0/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(),
+ node.at("/0/type").asText());
assertEquals(node.at("/0/description").asText(), "\"system\" query");
assertEquals(node.at("/0/query").asText(), "[]");
- assertEquals(CorpusAccess.FREE.name(), node.at("/0/requiredAccess").asText());
+ assertEquals(CorpusAccess.FREE.name(),
+ node.at("/0/requiredAccess").asText());
// assertEquals("koral:token", node.at("/0/koralQuery/@type").asText());
}
- private JsonNode testListAvailableQuery(String username) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ private JsonNode testListAvailableQuery (String username)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("query").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
// System.out.println(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
index e709d1b..27f3567 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
@@ -28,10 +28,10 @@
.queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
.queryParam("cq", "referTo \"dory/dory-q\"")
.get();
-
+
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
}
-*/
+ */
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
index b1d8add..5c70f57 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
@@ -25,8 +25,12 @@
public class QuerySerializationControllerTest extends SpringJerseyTest {
@Test
- public void testQuerySerializationFilteredPublic() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/WPD13/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ public void testQuerySerializationFilteredPublic ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/WPD13/query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -36,28 +40,46 @@
}
@Test
- public void testQuerySerializationUnexistingResource() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/ZUW19/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ public void testQuerySerializationUnexistingResource ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/ZUW19/query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
+ .request().method("GET");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [ZUW19]]");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[Cannot found public Corpus with ids: [ZUW19]]");
}
@Test
- public void testQuerySerializationWithNonPublicCorpus() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/BRZ10/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ public void testQuerySerializationWithNonPublicCorpus ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/BRZ10/query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
+ .request().method("GET");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [BRZ10]]");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[Cannot found public Corpus with ids: [BRZ10]]");
}
@Test
- public void testQuerySerializationWithAuthentication() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/BRZ10/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).method("GET");
+ public void testQuerySerializationWithAuthentication ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/BRZ10/query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -68,9 +90,21 @@
}
@Test
- public void testQuerySerializationWithNewCollection() throws KustvaktException {
+ public void testQuerySerializationWithNewCollection ()
+ throws KustvaktException {
// Add Virtual Collection
- Response response = target().path(API_VERSION).path("virtualcollection").queryParam("filter", "false").queryParam("query", "creationDate since 1775 & corpusSigle=GOE").queryParam("name", "Weimarer Werke").queryParam("description", "Goethe-Werke in Weimar (seit 1775)").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(""));
+ Response response = target().path(API_VERSION).path("virtualcollection")
+ .queryParam("filter", "false")
+ .queryParam("query",
+ "creationDate since 1775 & corpusSigle=GOE")
+ .queryParam("name", "Weimarer Werke")
+ .queryParam("description", "Goethe-Werke in Weimar (seit 1775)")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .post(Entity.json(""));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -78,7 +112,12 @@
assertTrue(node.isObject());
assertEquals(node.path("name").asText(), "Weimarer Werke");
// Get virtual collections
- response = target().path(API_VERSION).path("collection").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ response = target().path(API_VERSION).path("collection").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
ent = response.readEntity(String.class);
node = JsonUtils.readTree(ent);
@@ -93,42 +132,70 @@
assertNotNull(id);
assertFalse(id.isEmpty());
// query serialization service
- response = target().path(API_VERSION).path("collection").path(id).path("query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).method("GET");
+ response = target().path(API_VERSION).path("collection").path(id)
+ .path("query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
ent = response.readEntity(String.class);
node = JsonUtils.readTree(ent);
assertNotNull(node);
// System.out.println("NODE " + ent);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/key").asText(), "creationDate");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "creationDate");
assertEquals(node.at("/collection/operands/0/value").asText(), "1775");
- assertEquals(node.at("/collection/operands/0/type").asText(), "type:date");
- assertEquals(node.at("/collection/operands/0/match").asText(), "match:geq");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/0/type").asText(),
+ "type:date");
+ assertEquals(node.at("/collection/operands/0/match").asText(),
+ "match:geq");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "corpusSigle");
assertEquals(node.at("/collection/operands/1/value").asText(), "GOE");
- assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/1/match").asText(),
+ "match:eq");
}
@Test
- public void testQuerySerializationOfVirtualCollection() throws KustvaktException {
- Response response = target().path(API_VERSION).path("collection/GOE-VC/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ public void testQuerySerializationOfVirtualCollection ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("collection/GOE-VC/query").queryParam("q", "[orth=der]")
+ .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/0/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/0/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "corpusSigle");
assertEquals(node.at("/collection/operands/0/value").asText(), "GOE");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
- assertEquals(node.at("/collection/operands/1/key").asText(), "creationDate");
- assertEquals(node.at("/collection/operands/1/value").asText(), "1810-01-01");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "creationDate");
+ assertEquals(node.at("/collection/operands/1/value").asText(),
+ "1810-01-01");
}
@Test
- public void testMetaQuerySerialization() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").queryParam("context", "sentence").queryParam("count", "20").queryParam("page", "5").queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().method("GET");
+ public void testMetaQuerySerialization () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .queryParam("context", "sentence").queryParam("count", "20")
+ .queryParam("page", "5").queryParam("cutoff", "true")
+ .queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp")
+ .request().method("GET");
assertEquals(response.getStatus(), Status.OK.getStatusCode());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -143,8 +210,13 @@
}
@Test
- public void testMetaQuerySerializationWithOffset() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").queryParam("context", "sentence").queryParam("count", "20").queryParam("page", "5").queryParam("offset", "2").queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().method("GET");
+ public void testMetaQuerySerializationWithOffset ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .queryParam("context", "sentence").queryParam("count", "20")
+ .queryParam("page", "5").queryParam("offset", "2")
+ .queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]")
+ .queryParam("ql", "poliqarp").request().method("GET");
assertEquals(response.getStatus(), Status.OK.getStatusCode());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
index 8f30d17..d2d4fed 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
@@ -20,14 +20,15 @@
/**
* @author hanl, margaretha
* @lastUpdate 19/04/2017
- * EM: FIX ME: Database restructure
+ * EM: FIX ME: Database restructure
*/
@Disabled
public class ResourceInfoControllerTest extends SpringJerseyTest {
@Test
- public void testGetPublicVirtualCollectionInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("collection").request().get();
+ public void testGetPublicVirtualCollectionInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -36,8 +37,15 @@
}
@Test
- public void testGetVirtualCollectionInfoWithAuthentication() throws KustvaktException {
- Response response = target().path(API_VERSION).path("collection").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ public void testGetVirtualCollectionInfoWithAuthentication ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertNotNull(node);
@@ -46,32 +54,38 @@
}
@Test
- public void testGetVirtualCollectionInfoById() throws KustvaktException {
- Response response = target().path(API_VERSION).path("collection").path("GOE-VC").request().get();
+ public void testGetVirtualCollectionInfoById () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection")
+ .path("GOE-VC").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(node.path("name").asText(), "Goethe Virtual Collection");
- assertEquals(node.path("description").asText(), "Goethe works from 1810");
+ assertEquals(node.path("description").asText(),
+ "Goethe works from 1810");
}
@Test
- public void testGetVirtualCollectionInfoByIdUnauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("collection").path("WPD15-VC").request().get();
+ public void testGetVirtualCollectionInfoByIdUnauthorized ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection")
+ .path("WPD15-VC").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public VirtualCollection with ids: [WPD15-VC]]");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[Cannot found public VirtualCollection with ids: [WPD15-VC]]");
}
@Test
- public void testGetPublicCorporaInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").request().get();
+ public void testGetPublicCorporaInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -81,8 +95,9 @@
}
@Test
- public void testGetCorpusInfoById() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("WPD13").request().get();
+ public void testGetCorpusInfoById () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("WPD13").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
// System.out.println(ent);
@@ -93,8 +108,9 @@
}
@Test
- public void testGetCorpusInfoById2() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("GOE").request().get();
+ public void testGetCorpusInfoById2 () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("GOE").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -104,8 +120,9 @@
}
@Test
- public void testGetPublicFoundriesInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("foundry").request().get();
+ public void testGetPublicFoundriesInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("foundry").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -115,8 +132,9 @@
}
@Test
- public void testGetFoundryInfoById() throws KustvaktException {
- Response response = target().path(API_VERSION).path("foundry").path("tt").request().get();
+ public void testGetFoundryInfoById () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("foundry")
+ .path("tt").request().get();
String ent = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
@@ -125,15 +143,17 @@
}
@Test
- public void testGetUnexistingCorpusInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("ZUW19").request().get();
+ public void testGetUnexistingCorpusInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("ZUW19").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [ZUW19]]");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[Cannot found public Corpus with ids: [ZUW19]]");
}
// EM: queries for an unauthorized corpus get the same responses /
@@ -141,14 +161,16 @@
// asking for an unexisting corpus info. Does it need a specific
// exception instead?
@Test
- public void testGetUnauthorizedCorpusInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus").path("BRZ10").request().get();
+ public void testGetUnauthorizedCorpusInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus")
+ .path("BRZ10").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [BRZ10]]");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[Cannot found public Corpus with ids: [BRZ10]]");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
index f683f01..9e932fc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
@@ -35,15 +35,19 @@
@Autowired
private KustvaktConfiguration config;
- private JsonNode requestSearchWithFields(String fields) throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", fields).queryParam("context", "sentence").queryParam("count", "13").request().get();
+ private JsonNode requestSearchWithFields (String fields)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("fields", fields).queryParam("context", "sentence")
+ .queryParam("count", "13").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
return node;
}
- private String createJsonQuery() {
+ private String createJsonQuery () {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
s.setCollection("corpusSigle=GOE");
@@ -52,17 +56,20 @@
}
@Test
- public void testApiWelcomeMessage() {
+ public void testApiWelcomeMessage () {
Response response = target().path(API_VERSION).path("").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
String message = response.readEntity(String.class);
assertEquals(message, config.getApiWelcomeMessage());
}
@Test
- public void testSearchShowTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("show-tokens", true).request().get();
+ public void testSearchShowTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("show-tokens", true).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -71,8 +78,11 @@
}
@Test
- public void testSearchDisableSnippet() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("show-snippet", false).queryParam("show-tokens", true).request().get();
+ public void testSearchDisableSnippet () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("show-snippet", false)
+ .queryParam("show-tokens", true).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -81,7 +91,7 @@
}
@Test
- public void testSearchWithField() throws KustvaktException {
+ public void testSearchWithField () throws KustvaktException {
JsonNode node = requestSearchWithFields("author");
assertNotEquals(0, node.at("/matches").size());
assertEquals(node.at("/meta/fields").toString(), "[\"author\"]");
@@ -89,15 +99,18 @@
}
@Test
- public void testSearchWithMultipleFields() throws KustvaktException {
+ public void testSearchWithMultipleFields () throws KustvaktException {
JsonNode node = requestSearchWithFields("author, title");
assertNotEquals(0, node.at("/matches").size());
- assertEquals(node.at("/meta/fields").toString(), "[\"author\",\"title\"]");
+ assertEquals(node.at("/meta/fields").toString(),
+ "[\"author\",\"title\"]");
}
@Test
- public void testSearchQueryPublicCorpora() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchQueryPublicCorpora () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -105,13 +118,19 @@
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "availability");
assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchQueryFailure() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").queryParam("count", "13").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchQueryFailure () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der").queryParam("ql", "poliqarp")
+ .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
+ .queryParam("count", "13").request()
+ .accept(MediaType.APPLICATION_JSON).get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -124,8 +143,12 @@
}
@Test
- public void testSearchQueryWithMeta() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=Bachelor]").queryParam("ql", "poliqarp").queryParam("cutoff", "true").queryParam("count", "5").queryParam("page", "1").queryParam("context", "40-t,30-t").request().get();
+ public void testSearchQueryWithMeta () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=Bachelor]").queryParam("ql", "poliqarp")
+ .queryParam("cutoff", "true").queryParam("count", "5")
+ .queryParam("page", "1").queryParam("context", "40-t,30-t")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -137,14 +160,19 @@
assertEquals(40, node.at("/meta/context/left/1").asInt());
assertEquals(30, node.at("/meta/context/right/1").asInt());
assertEquals(-1, node.at("/meta/totalResults").asInt());
- for (String path : new String[]{"/meta/count", "/meta/startIndex", "/meta/context/left/1", "/meta/context/right/1", "/meta/totalResults", "/meta/itemsPerPage"}) {
+ for (String path : new String[] { "/meta/count", "/meta/startIndex",
+ "/meta/context/left/1", "/meta/context/right/1",
+ "/meta/totalResults", "/meta/itemsPerPage" }) {
assertTrue(node.at(path).isNumber(), path + " should be a number");
}
}
@Test
- public void testSearchQueryFreeExtern() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testSearchQueryFreeExtern () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -153,13 +181,18 @@
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "availability");
assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchQueryFreeIntern() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ public void testSearchQueryFreeIntern () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request().header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -168,13 +201,22 @@
assertEquals(node.at("/collection/@type").asText(), "koral:doc");
assertEquals(node.at("/collection/key").asText(), "availability");
assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchQueryExternAuthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testSearchQueryExternAuthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -182,17 +224,31 @@
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "ACA.*");
- assertEquals(node.at("/collection/operands/1/operands/1/value").asText(), "QAO-NC");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(
+ node.at("/collection/operands/1/operands/0/value").asText(),
+ "ACA.*");
+ assertEquals(
+ node.at("/collection/operands/1/operands/1/value").asText(),
+ "QAO-NC");
assertEquals(node.at("/collection/operation").asText(), "operation:or");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(PUB)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchQueryInternAuthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ public void testSearchQueryInternAuthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -200,74 +256,121 @@
assertNotEquals(0, node.path("matches").size());
// System.out.println(node);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "ACA.*");
- assertEquals(node.at("/collection/operands/1/operands/1/operands/0/value").asText(), "QAO-NC");
- assertEquals(node.at("/collection/operands/1/operands/1/operands/1/value").asText(), "QAO.*");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(
+ node.at("/collection/operands/1/operands/0/value").asText(),
+ "ACA.*");
+ assertEquals(
+ node.at("/collection/operands/1/operands/1/operands/0/value")
+ .asText(),
+ "QAO-NC");
+ assertEquals(
+ node.at("/collection/operands/1/operands/1/operands/1/value")
+ .asText(),
+ "QAO.*");
assertEquals(node.at("/collection/operation").asText(), "operation:or");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchWithCorpusQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "corpusTitle=gingko").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWithCorpusQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "corpusTitle=gingko").request()
+ .accept(MediaType.APPLICATION_JSON).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/value").asText(), "gingko");
- assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/value").asText(),
+ "gingko");
+ assertEquals(node.at("/collection/operands/1/match").asText(),
+ "match:eq");
assertTrue(node.at("/collection/operands/1/type").isMissingNode());
}
@Test
- public void testSearchQueryWithCollectionQueryAuthorizedWithoutIP() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", "textClass=politik & corpusSigle=BRZ10").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ public void testSearchQueryWithCollectionQueryAuthorizedWithoutIP ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "textClass=politik & corpusSigle=BRZ10")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertNotNull(node);
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
// EM: double AND operations
- assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/operands/0/key").asText(), "textClass");
- assertEquals(node.at("/collection/operands/1/operands/1/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/0/key").asText(),
+ "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/key").asText(),
+ "textClass");
+ assertEquals(node.at("/collection/operands/1/operands/1/key").asText(),
+ "corpusSigle");
}
@Test
@Disabled
- public void testSearchQueryAuthorizedWithoutIP() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ public void testSearchQueryAuthorizedWithoutIP () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
assertEquals(node.at("/collection/operation").asText(), "operation:or");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(PUB)");
}
@Test
- public void testSearchWithInvalidPage() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "0").request().get();
+ public void testSearchWithInvalidPage () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("page", "0").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "page must start from 1");
}
@Test
- public void testSearchSentenceMeta() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "sentence").request().get();
+ public void testSearchSentenceMeta () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("context", "sentence").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -279,10 +382,11 @@
// EM: The API is disabled
@Disabled
@Test
- public void testSearchSimpleCQL() throws KustvaktException {
+ public void testSearchSimpleCQL () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("(der) or (das)", "CQL");
- Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ Response response = target().path(API_VERSION).path("search").request()
+ .post(Entity.json(s.toJSON()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -294,39 +398,55 @@
// EM: The API is disabled
@Test
@Disabled
- public void testSearchRawQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").request().post(Entity.json(createJsonQuery()));
+ public void testSearchRawQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request()
+ .post(Entity.json(createJsonQuery()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
}
// EM: The API is disabled
@Test
@Disabled
- public void testSearchPostAll() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").request().header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(createJsonQuery()));
+ public void testSearchPostAll () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32")
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .post(Entity.json(createJsonQuery()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
}
// EM: The API is disabled
@Test
@Disabled
- public void testSearchPostPublic() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(createJsonQuery()));
+ public void testSearchPostPublic () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("kustvakt",
+ "kustvakt2015"))
+ .post(Entity.json(createJsonQuery()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(PUB)");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
index 1938b51..ef42760 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
@@ -43,26 +43,41 @@
private String endpointURL = "http://localhost:" + port + "/searchEndpoint";
- public SearchNetworkEndpointTest() throws IOException {
- searchResult = IOUtils.toString(ClassLoader.getSystemResourceAsStream("network-output/search-result.jsonld"), StandardCharsets.UTF_8);
+ public SearchNetworkEndpointTest () throws IOException {
+ searchResult = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "network-output/search-result.jsonld"),
+ StandardCharsets.UTF_8);
}
@BeforeEach
- public void startMockServer() {
+ public void startMockServer () {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
@AfterEach
- public void stopMockServer() {
+ public void stopMockServer () {
mockServer.stop();
}
@Test
- public void testSearchNetwork() throws IOException, KustvaktException, URISyntaxException {
+ public void testSearchNetwork ()
+ throws IOException, KustvaktException, URISyntaxException {
config.setNetworkEndpointURL(endpointURL);
- mockClient.reset().when(request().withMethod("POST").withPath("/searchEndpoint").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(searchResult).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/searchEndpoint")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(searchResult).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -70,22 +85,29 @@
}
@Test
- public void testSearchWithUnknownURL() throws IOException, KustvaktException {
+ public void testSearchWithUnknownURL ()
+ throws IOException, KustvaktException {
config.setNetworkEndpointURL("http://localhost:1040/search");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testSearchWithUnknownHost() throws KustvaktException {
+ public void testSearchWithUnknownHost () throws KustvaktException {
config.setNetworkEndpointURL("http://search.com");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
index 9591933..03a019e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
@@ -45,29 +45,43 @@
private String glemmUri = "http://localhost:" + port + "/glemm";
- public SearchPipeTest() throws URISyntaxException, IOException {
- pipeJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/test-pipes.jsonld"), StandardCharsets.UTF_8);
- pipeWithParamJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/with-param.jsonld"), StandardCharsets.UTF_8);
+ public SearchPipeTest () throws URISyntaxException, IOException {
+ pipeJson = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "pipe-output/test-pipes.jsonld"),
+ StandardCharsets.UTF_8);
+ pipeWithParamJson = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "pipe-output/with-param.jsonld"),
+ StandardCharsets.UTF_8);
}
@BeforeEach
- public void startMockServer() {
+ public void startMockServer () {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
@AfterEach
- public void stopMockServer() {
+ public void stopMockServer () {
mockServer.stop();
}
@Test
- public void testMockServer() throws IOException {
- mockClient.reset().when(request().withMethod("POST").withPath("/test").withHeader(new Header("Content-Type", "application/json; charset=utf-8"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody("{test}").withStatusCode(200));
+ public void testMockServer () throws IOException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/test")
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody("{test}").withStatusCode(200));
URL url = new URL("http://localhost:" + port + "/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ connection.setRequestProperty("Content-Type",
+ "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
String json = "{\"name\" : \"dory\"}";
@@ -76,21 +90,36 @@
os.write(input, 0, input.length);
}
assertEquals(200, connection.getResponseCode());
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(connection.getInputStream(), "utf-8"));
assertEquals(br.readLine(), "{test}");
}
@Test
- public void testSearchWithPipes() throws IOException, KustvaktException, URISyntaxException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ public void testSearchWithPipes ()
+ throws IOException, KustvaktException, URISyntaxException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
assertEquals(1, node.at("/collection/rewrites").size());
- assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(),
+ "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(FREE)");
node = node.at("/query/wrap/rewrites");
assertEquals(2, node.size());
assertEquals(node.at("/0/src").asText(), "Glemm");
@@ -102,20 +131,44 @@
}
@Test
- public void testSearchWithUrlEncodedPipes() throws IOException, KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ public void testSearchWithUrlEncodedPipes ()
+ throws IOException, KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
glemmUri = URLEncoder.encode(glemmUri, "utf-8");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri).request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithMultiplePipes() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withQueryStringParameter("param").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeWithParamJson).withStatusCode(200));
+ public void testSearchWithMultiplePipes () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withQueryStringParameter("param").withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeWithParamJson).withStatusCode(200));
String glemmUri2 = glemmUri + "?param=blah";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + "," + glemmUri2).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri + "," + glemmUri2).request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -123,9 +176,13 @@
}
@Test
- public void testSearchWithUnknownURL() throws IOException, KustvaktException {
- String url = target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url).request().get();
+ public void testSearchWithUnknownURL ()
+ throws IOException, KustvaktException {
+ String url = target().getUri().toString() + API_VERSION
+ + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", url).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -134,8 +191,10 @@
}
@Test
- public void testSearchWithUnknownHost() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://glemm").request().get();
+ public void testSearchWithUnknownHost () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", "http://glemm").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -144,21 +203,30 @@
}
@Test
- public void testSearchUnsupportedMediaType() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/non-json-pipe")).respond(response().withStatusCode(415));
+ public void testSearchUnsupportedMediaType () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/non-json-pipe"))
+ .respond(response().withStatusCode(415));
String pipeUri = "http://localhost:" + port + "/non-json-pipe";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/3").asText(), "415 Unsupported Media Type");
+ assertEquals(node.at("/warnings/0/3").asText(),
+ "415 Unsupported Media Type");
}
@Test
- public void testSearchWithMultiplePipeWarnings() throws KustvaktException {
- String url = target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url + "," + "http://glemm").request().get();
+ public void testSearchWithMultiplePipeWarnings () throws KustvaktException {
+ String url = target().getUri().toString() + API_VERSION
+ + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", url + "," + "http://glemm").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -172,37 +240,73 @@
}
@Test
- public void testSearchWithInvalidJsonResponse() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/invalid-response").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("{blah:}").withStatusCode(200).withHeaders(new Header("Content-Type", "application/json; charset=utf-8")));
+ public void testSearchWithInvalidJsonResponse () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/invalid-response")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response().withBody("{blah:}").withStatusCode(200)
+ .withHeaders(new Header("Content-Type",
+ "application/json; charset=utf-8")));
String pipeUri = "http://localhost:" + port + "/invalid-response";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithPlainTextResponse() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/plain-text").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("blah").withStatusCode(200));
+ public void testSearchWithPlainTextResponse () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/plain-text")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response().withBody("blah").withStatusCode(200));
String pipeUri = "http://localhost:" + port + "/plain-text";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithMultipleAndUnknownPipes() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://unknown" + "," + glemmUri).request().get();
+ public void testSearchWithMultipleAndUnknownPipes ()
+ throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", "http://unknown" + "," + glemmUri)
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
assertTrue(node.at("/warnings").isMissingNode());
- response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + ",http://unknown").request().get();
+ response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri + ",http://unknown").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
index 1d1db61..aeec05e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
@@ -22,53 +22,73 @@
public class SearchPublicMetadataTest extends SpringJerseyTest {
@Test
- public void testSearchPublicMetadata() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadata () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
@Test
- public void testSearchPublicMetadataExtern() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testSearchPublicMetadataExtern () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("access-rewrite-disabled", "true").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
@Test
- public void testSearchPublicMetadataWithCustomFields() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithCustomFields ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author,title")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
- assertEquals(node.at("/matches/0/author").asText(), "Goethe, Johann Wolfgang von");
- assertEquals(node.at("/matches/0/title").asText(), "Italienische Reise");
+ assertEquals(node.at("/matches/0/author").asText(),
+ "Goethe, Johann Wolfgang von");
+ assertEquals(node.at("/matches/0/title").asText(),
+ "Italienische Reise");
// assertEquals(3, node.at("/matches/0").size());
}
@Test
- public void testSearchPublicMetadataWithNonPublicField() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title,snippet").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithNonPublicField ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author,title,snippet")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "The requested non public fields are ignored");
+ assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED,
+ node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "The requested non public fields are ignored");
assertEquals(node.at("/warnings/0/2").asText(), "snippet");
}
// EM: The API is disabled
@Disabled
@Test
- public void testSearchPostPublicMetadata() throws KustvaktException {
+ public void testSearchPostPublicMetadata () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
s.setCollection("corpusSigle=GOE");
@@ -76,39 +96,55 @@
MetaQueryBuilder meta = new MetaQueryBuilder();
meta.addEntry("snippets", "true");
s.setMeta(meta);
- Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ Response response = target().path(API_VERSION).path("search").request()
+ .post(Entity.json(s.toJSON()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(),
+ "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
@Test
- public void testSearchPublicMetadataWithSystemVC() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("cq", "referTo system-vc").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithSystemVC ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo system-vc")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
node = node.at("/collection/operands/1");
assertEquals(node.at("/@type").asText(), "koral:doc");
assertEquals(node.at("/value").asText(), "GOE");
assertEquals(node.at("/match").asText(), "match:eq");
assertEquals(node.at("/key").asText(), "corpusSigle");
- assertEquals(node.at("/rewrites/0/operation").asText(), "operation:deletion");
- assertEquals(node.at("/rewrites/0/scope").asText(), "@type(koral:docGroupRef)");
- assertEquals(node.at("/rewrites/1/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/rewrites/0/operation").asText(),
+ "operation:deletion");
+ assertEquals(node.at("/rewrites/0/scope").asText(),
+ "@type(koral:docGroupRef)");
+ assertEquals(node.at("/rewrites/1/operation").asText(),
+ "operation:deletion");
assertEquals(node.at("/rewrites/1/scope").asText(), "ref(system-vc)");
- assertEquals(node.at("/rewrites/2/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/rewrites/2/operation").asText(),
+ "operation:insertion");
}
@Test
- public void testSearchPublicMetadataWithPrivateVC() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithPrivateVC ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"dory/dory-vc\"")
+ .queryParam("access-rewrite-disabled", "true").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/2").asText(), "guest");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
index c0e9fa7..e115f90 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
@@ -18,8 +18,12 @@
public class SearchTokenSnippetTest extends SpringJerseyTest {
@Test
- public void testSearchWithTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchWithTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("show-tokens", "true")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -31,8 +35,12 @@
}
@Test
- public void testSearchWithoutTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "false").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchWithoutTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("show-tokens", "false")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -42,8 +50,13 @@
}
@Test
- public void testSearchPublicMetadataWithTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchPublicMetadataWithTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("access-rewrite-disabled", "true")
+ .queryParam("show-tokens", "true")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
index 8bcb604..ecdad64 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
@@ -25,11 +25,14 @@
public class StatisticsControllerTest extends SpringJerseyTest {
@Test
- public void testGetStatisticsNoResource() throws IOException, KustvaktException {
+ public void testGetStatisticsNoResource ()
+ throws IOException, KustvaktException {
String corpusQuery = "corpusSigle=WPD15";
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", corpusQuery).request().get();
assert Status.OK.getStatusCode() == response.getStatus();
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.get("documents").asInt(), 0);
@@ -37,8 +40,10 @@
}
@Test
- public void testStatisticsWithCq() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithCq () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -50,8 +55,12 @@
}
@Test
- public void testStatisticsWithCqAndCorpusQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithCqAndCorpusQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
+ .queryParam("corpusQuery",
+ "textType=Autobiographie & corpusSigle=GOE")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -63,21 +72,27 @@
}
@Test
- public void testGetStatisticsWithcorpusQuery1() throws IOException, KustvaktException {
+ public void testGetStatisticsWithcorpusQuery1 ()
+ throws IOException, KustvaktException {
String corpusQuery = "corpusSigle=GOE";
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", corpusQuery).request().get();
assert Status.OK.getStatusCode() == response.getStatus();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.get("documents").asInt(), 11);
assertEquals(node.get("tokens").asInt(), 665842);
assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "Parameter corpusQuery is deprecated in favor of cq.");
}
@Test
- public void testGetStatisticsWithcorpusQuery2() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate since 1810").request().get();
+ public void testGetStatisticsWithcorpusQuery2 ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "creationDate since 1810").request()
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assert Status.OK.getStatusCode() == response.getStatus();
@@ -88,30 +103,41 @@
}
@Test
- public void testGetStatisticsWithWrongcorpusQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate geq 1810").request().get();
+ public void testGetStatisticsWithWrongcorpusQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "creationDate geq 1810").request()
+ .get();
assert Status.BAD_REQUEST.getStatusCode() == response.getStatus();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/errors/0/0").asInt(), 302);
- assertEquals(node.at("/errors/0/1").asText(), "Could not parse query >>> (creationDate geq 1810) <<<.");
- assertEquals(node.at("/errors/0/2").asText(), "(creationDate geq 1810)");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Could not parse query >>> (creationDate geq 1810) <<<.");
+ assertEquals(node.at("/errors/0/2").asText(),
+ "(creationDate geq 1810)");
}
@Test
- public void testGetStatisticsWithWrongcorpusQuery2() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate >= 1810").request().get();
+ public void testGetStatisticsWithWrongcorpusQuery2 ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "creationDate >= 1810").request()
+ .get();
String ent = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/errors/0/0").asInt(), 305);
- assertEquals(node.at("/errors/0/1").asText(), "Operator >= is not acceptable.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Operator >= is not acceptable.");
assertEquals(node.at("/errors/0/2").asText(), ">=");
}
@Test
- public void testGetStatisticsWithoutcorpusQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().get();
+ public void testGetStatisticsWithoutcorpusQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -122,9 +148,17 @@
}
@Test
- public void testGetStatisticsWithKoralQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : {\"@type\": " + "\"koral:doc\", \"key\": \"availability\", \"match\": " + "\"match:eq\", \"type\": \"type:regex\", \"value\": " + "\"CC-BY.*\"} }"));
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ public void testGetStatisticsWithKoralQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{ \"collection\" : {\"@type\": "
+ + "\"koral:doc\", \"key\": \"availability\", \"match\": "
+ + "\"match:eq\", \"type\": \"type:regex\", \"value\": "
+ + "\"CC-BY.*\"} }"));
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -135,28 +169,42 @@
}
@Test
- public void testGetStatisticsWithEmptyCollection() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{}"));
+ public void testGetStatisticsWithEmptyCollection ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{}"));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/errors/0/0").asInt(), de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
- assertEquals(node.at("/errors/0/1").asText(), "Collection is not found");
+ assertEquals(node.at("/errors/0/0").asInt(),
+ de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Collection is not found");
}
@Test
- public void testGetStatisticsWithIncorrectJson() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : }"));
+ public void testGetStatisticsWithIncorrectJson ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{ \"collection\" : }"));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Failed deserializing json object: { \"collection\" : }");
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Failed deserializing json object: { \"collection\" : }");
}
@Test
- public void testGetStatisticsWithoutKoralQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().post(Entity.json(""));
+ public void testGetStatisticsWithoutKoralQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request().post(Entity.json(""));
String ent = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
index 7cc5e6f..1d130b6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
@@ -32,14 +32,19 @@
@Disabled
@Test
- public void requestToken() throws KustvaktException, InterruptedException, IOException {
+ public void requestToken ()
+ throws KustvaktException, InterruptedException, IOException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
form.param("client_secret", "secret");
form.param("username", "dory");
form.param("password", "password");
- Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("token").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
String token = node.at("/access_token").asText();
@@ -53,17 +58,23 @@
// because sqlite needs a trigger after INSERT to
// oauth_access_token to store created_date. Before INSERT trigger
// does not work.
- private void testSearchWithExpiredToken(String token) throws KustvaktException, IOException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, "Bearer " + token).get();
+ private void testSearchWithExpiredToken (String token)
+ throws KustvaktException, IOException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
+ .request().header(Attributes.AUTHORIZATION, "Bearer " + token)
+ .get();
String ent = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertEquals(StatusCodes.EXPIRED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is expired");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is expired");
}
// cannot be tested dynamically
- private void testRequestAuthorizationCodeAuthenticationTooOld(String token) throws KustvaktException {
+ private void testRequestAuthorizationCodeAuthenticationTooOld (String token)
+ throws KustvaktException {
Form form = new Form();
form.param("response_type", "code");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
@@ -72,19 +83,22 @@
form.param("scope", "search");
form.param("max_age", "1");
- Response response =
- target().path(API_VERSION).path("oauth2").path("authorize")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + token)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2")
+ .path("authorize").request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + token)
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ ContentType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(form));
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.USER_REAUTHENTICATION_REQUIRED, node.at("/errors/0/0").asInt());
- assertEquals("User reauthentication is required because the authentication " + "time is too old according to max_age", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.USER_REAUTHENTICATION_REQUIRED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "User reauthentication is required because the authentication "
+ + "time is too old according to max_age",
+ node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
index 4ecbe46..27c8512 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
@@ -25,11 +25,12 @@
private String userAuthHeader;
- public UserControllerTest() throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
+ public UserControllerTest () throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "password");
}
- private OAuth2ClientJson createOAuth2Client() {
+ private OAuth2ClientJson createOAuth2Client () {
OAuth2ClientJson client = new OAuth2ClientJson();
client.setName("OWID client");
client.setType(OAuth2ClientType.PUBLIC);
@@ -38,7 +39,8 @@
return client;
}
- private String registerClient() throws ProcessingException, KustvaktException {
+ private String registerClient ()
+ throws ProcessingException, KustvaktException {
OAuth2ClientJson clientJson = createOAuth2Client();
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
@@ -46,10 +48,13 @@
return clientId;
}
- private String requestOAuth2AccessToken(String clientId) throws KustvaktException {
- Response response = requestAuthorizationCode("code", clientId, "", "user_info", "", userAuthHeader);
+ private String requestOAuth2AccessToken (String clientId)
+ throws KustvaktException {
+ Response response = requestAuthorizationCode("code", clientId, "",
+ "user_info", "", userAuthHeader);
String code = parseAuthorizationCode(response);
- response = requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, null,
+ code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -58,10 +63,13 @@
}
@Test
- public void getUsername() throws ProcessingException, KustvaktException {
+ public void getUsername () throws ProcessingException, KustvaktException {
String clientId = registerClient();
String accessToken = requestOAuth2AccessToken(clientId);
- Response response = target().path(API_VERSION).path("user").path("info").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ Response response = target().path(API_VERSION).path("user").path("info")
+ .request()
+ .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
index 99cf31a..aa6a4c6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
@@ -32,8 +32,12 @@
private String testUser = "group-admin";
- private JsonNode listGroup(String username) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ private JsonNode listGroup (String username)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -41,11 +45,15 @@
}
@Test
- public void testListUserGroupsUsingAdminToken() throws KustvaktException {
+ public void testListUserGroupsUsingAdminToken () throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
f.param("token", "secret");
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -75,22 +83,38 @@
// assertEquals(3, node.size());
// }
@Test
- public void testListUserGroupsUnauthorized() throws KustvaktException {
+ public void testListUserGroupsUnauthorized () throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testListUserGroupsWithStatus() throws KustvaktException {
+ public void testListUserGroupsWithStatus () throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
f.param("status", "ACTIVE");
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").queryParam("username", "dory").queryParam("status", "ACTIVE").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").queryParam("username", "dory")
+ .queryParam("status", "ACTIVE").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
// System.out.println(entity);
@@ -100,16 +124,31 @@
// same as list user-groups of the admin
@Test
- public void testListWithoutUsername() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testListWithoutUsername ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
assertEquals(entity, "[]");
}
@Test
- public void testListByStatusAll() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(null);
+ public void testListByStatusAll ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(null);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -123,10 +162,21 @@
}
@Test
- public void testListByStatusHidden() throws ProcessingException, KustvaktException {
+ public void testListByStatusHidden ()
+ throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("status", "HIDDEN");
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").queryParam("status", "HIDDEN").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").queryParam("status", "HIDDEN")
+ .request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -135,9 +185,17 @@
}
@Test
- public void testUserGroupAdmin() throws ProcessingException, KustvaktException {
+ public void testUserGroupAdmin ()
+ throws ProcessingException, KustvaktException {
String groupName = "admin-test-group";
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(new Form()));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser,
+ "password"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .put(Entity.form(new Form()));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
// list user group
JsonNode node = listGroup(testUser);
@@ -150,22 +208,38 @@
testDeleteGroup(groupName);
}
- private void testMemberRole(String memberUsername, String groupName) throws ProcessingException, KustvaktException {
+ private void testMemberRole (String memberUsername, String groupName)
+ throws ProcessingException, KustvaktException {
// accept invitation
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(memberUsername, "pass")).post(Entity.form(new Form()));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ memberUsername, "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
testAddMemberRoles(groupName, memberUsername);
testDeleteMemberRoles(groupName, memberUsername);
}
- private void testAddMemberRoles(String groupName, String memberUsername) throws ProcessingException, KustvaktException {
+ private void testAddMemberRoles (String groupName, String memberUsername)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", memberUsername);
// USER_GROUP_ADMIN
form.param("roleId", "1");
// USER_GROUP_MEMBER
form.param("roleId", "2");
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("role").path("add").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("role").path("add").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "password"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = retrieveGroup(groupName).at("/members");
JsonNode member;
@@ -173,18 +247,27 @@
member = node.get(i);
if (member.at("/userId").asText().equals(memberUsername)) {
assertEquals(3, member.at("/roles").size());
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(), member.at("/roles/0").asText());
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(),
+ member.at("/roles/0").asText());
break;
}
}
}
- private void testDeleteMemberRoles(String groupName, String memberUsername) throws ProcessingException, KustvaktException {
+ private void testDeleteMemberRoles (String groupName, String memberUsername)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", memberUsername);
// USER_GROUP_ADMIN
form.param("roleId", "1");
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("role").path("delete").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("role").path("delete").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "password"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = retrieveGroup(groupName).at("/members");
JsonNode member;
@@ -197,46 +280,77 @@
}
}
- private JsonNode retrieveGroup(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
+ private JsonNode retrieveGroup (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testDeleteGroup(String groupName) throws ProcessingException, KustvaktException {
+ private void testDeleteGroup (String groupName)
+ throws ProcessingException, KustvaktException {
// delete group
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// check group
JsonNode node = listGroup(testUser);
assertEquals(0, node.size());
}
- private void testDeleteMember(String groupName) throws ProcessingException, KustvaktException {
+ private void testDeleteMember (String groupName)
+ throws ProcessingException, KustvaktException {
// delete marlin from group
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~marlin").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("~marlin").request()
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// check group member
JsonNode node = listGroup(testUser);
node = node.get(0);
assertEquals(3, node.get("members").size());
assertEquals(node.at("/members/1/userId").asText(), "nemo");
- assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ node.at("/members/1/status").asText());
}
- private void testInviteMember(String groupName) throws ProcessingException, KustvaktException {
+ private void testInviteMember (String groupName)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "marlin,nemo,darla");
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION,
+ HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(
+ sysAdminUser, "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// list group
JsonNode node = listGroup(testUser);
node = node.get(0);
assertEquals(4, node.get("members").size());
assertEquals(node.at("/members/3/userId").asText(), "darla");
- assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
index 52e3bb3..5495c85 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
@@ -40,22 +40,33 @@
private String admin = "admin";
- private JsonNode retrieveUserGroups(String username) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ private JsonNode retrieveUserGroups (String username)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
return JsonUtils.readTree(entity);
}
- private void deleteGroupByName(String groupName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ private void deleteGroupByName (String groupName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
// dory is a group admin in dory-group
@Test
- public void testListDoryGroups() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testListDoryGroups () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -69,8 +80,11 @@
// nemo is a group member in dory-group
@Test
- public void testListNemoGroups() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testListNemoGroups () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("nemo", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// System.out.println(entity);
@@ -84,8 +98,11 @@
// marlin has 2 groups
@Test
- public void testListMarlinGroups() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testListMarlinGroups () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
@@ -93,17 +110,21 @@
}
@Test
- public void testListGroupGuest() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testListGroupGuest () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: guest");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: guest");
}
@Test
- public void testCreateGroupEmptyDescription() throws ProcessingException, KustvaktException {
+ public void testCreateGroupEmptyDescription ()
+ throws ProcessingException, KustvaktException {
String groupName = "empty_group";
Response response = testCreateUserGroup(groupName, "");
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
@@ -111,50 +132,68 @@
}
@Test
- public void testCreateGroupMissingDescription() throws ProcessingException, KustvaktException {
+ public void testCreateGroupMissingDescription ()
+ throws ProcessingException, KustvaktException {
String groupName = "missing-desc-group";
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
deleteGroupByName(groupName);
}
- private Response testCreateUserGroup(String groupName, String description) throws ProcessingException, KustvaktException {
+ private Response testCreateUserGroup (String groupName, String description)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("description", description);
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .put(Entity.form(form));
return response;
}
- private Response testCreateGroupWithoutDescription(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(new Form()));
+ private Response testCreateGroupWithoutDescription (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .put(Entity.form(new Form()));
return response;
}
@Test
- public void testCreateGroupInvalidName() throws ProcessingException, KustvaktException {
+ public void testCreateGroupInvalidName ()
+ throws ProcessingException, KustvaktException {
String groupName = "invalid-group-name$";
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
// assertEquals("User-group name must only contains letters, numbers, "
// + "underscores, hypens and spaces", node.at("/errors/0/1").asText());
assertEquals(node.at("/errors/0/2").asText(), "invalid-group-name$");
}
@Test
- public void testCreateGroupNameTooShort() throws ProcessingException, KustvaktException {
+ public void testCreateGroupNameTooShort ()
+ throws ProcessingException, KustvaktException {
String groupName = "a";
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "groupName must contain at least 3 characters");
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "groupName must contain at least 3 characters");
assertEquals(node.at("/errors/0/2").asText(), "groupName");
}
@Test
- public void testUserGroup() throws ProcessingException, KustvaktException {
+ public void testUserGroup () throws ProcessingException, KustvaktException {
String groupName = "new-user-group";
String description = "This is new-user-group.";
Response response = testCreateUserGroup(groupName, description);
@@ -171,9 +210,12 @@
assertEquals(username, node.get("owner").asText());
assertEquals(1, node.get("members").size());
assertEquals(username, node.at("/members/0/userId").asText());
- assertEquals(GroupMemberStatus.ACTIVE.name(), node.at("/members/0/status").asText());
- assertEquals(PredefinedRole.VC_ACCESS_ADMIN.name(), node.at("/members/0/roles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(), node.at("/members/0/roles/0").asText());
+ assertEquals(GroupMemberStatus.ACTIVE.name(),
+ node.at("/members/0/status").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_ADMIN.name(),
+ node.at("/members/0/roles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(),
+ node.at("/members/0/roles/0").asText());
testUpdateUserGroup(groupName);
testInviteMember(groupName);
testDeleteMemberUnauthorized(groupName);
@@ -183,7 +225,8 @@
testUnsubscribeToDeletedGroup(groupName);
}
- private void testUpdateUserGroup(String groupName) throws ProcessingException, KustvaktException {
+ private void testUpdateUserGroup (String groupName)
+ throws ProcessingException, KustvaktException {
String description = "Description is updated.";
Response response = testCreateUserGroup(groupName, description);
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
@@ -192,32 +235,52 @@
assertEquals(description, node.get(0).get("description").asText());
}
- private void testDeleteMember(String groupName) throws ProcessingException, KustvaktException {
+ private void testDeleteMember (String groupName)
+ throws ProcessingException, KustvaktException {
// delete darla from group
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~darla").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("~darla").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
// check group member
- response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
node = node.get(0);
assertEquals(1, node.get("members").size());
}
- private void testDeleteMemberUnauthorized(String groupName) throws ProcessingException, KustvaktException {
+ private void testDeleteMemberUnauthorized (String groupName)
+ throws ProcessingException, KustvaktException {
// nemo is a group member
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~darla").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("~darla").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("nemo", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: nemo");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: nemo");
}
// EM: same as cancel invitation
- private void testDeletePendingMember() throws ProcessingException, KustvaktException {
+ private void testDeletePendingMember ()
+ throws ProcessingException, KustvaktException {
// dory delete pearl
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("~pearl").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("~pearl").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// check member
JsonNode node = retrieveUserGroups("pearl");
@@ -225,20 +288,32 @@
}
@Test
- public void testDeleteDeletedMember() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("~pearl").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ public void testDeleteDeletedMember ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("~pearl").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "pearl has already been deleted from the group dory-group");
assertEquals(node.at("/errors/0/2").asText(), "[pearl, dory-group]");
}
- private void testDeleteGroup(String groupName) throws ProcessingException, KustvaktException {
+ private void testDeleteGroup (String groupName)
+ throws ProcessingException, KustvaktException {
// delete group
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
Form f = new Form();
f.param("username", username);
@@ -246,7 +321,13 @@
// EM: this is so complicated because the group retrieval are not allowed
// for delete groups
// check group
- response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ response = target().path(API_VERSION).path("admin").path("group")
+ .path("list").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -254,136 +335,214 @@
JsonNode group = node.get(j);
// check group members
for (int i = 0; i < group.at("/0/members").size(); i++) {
- assertEquals(GroupMemberStatus.DELETED.name(), group.at("/0/members/" + i + "/status").asText());
+ assertEquals(GroupMemberStatus.DELETED.name(),
+ group.at("/0/members/" + i + "/status").asText());
}
}
}
@Test
- public void testDeleteGroupUnauthorized() throws ProcessingException, KustvaktException {
+ public void testDeleteGroupUnauthorized ()
+ throws ProcessingException, KustvaktException {
// dory is a group admin in marlin-group
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: dory");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: dory");
}
@Test
- public void testDeleteDeletedGroup() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@deleted-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ public void testDeleteDeletedGroup ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@deleted-group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group deleted-group has been deleted.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group deleted-group has been deleted.");
assertEquals(node.at("/errors/0/2").asText(), "deleted-group");
}
@Test
- public void testDeleteGroupOwner() throws ProcessingException, KustvaktException {
+ public void testDeleteGroupOwner ()
+ throws ProcessingException, KustvaktException {
// delete marlin from marlin-group
// dory is a group admin in marlin-group
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("~marlin").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").path("~marlin").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Operation 'delete group owner'is not allowed.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Operation 'delete group owner'is not allowed.");
}
- private void testInviteMember(String groupName) throws ProcessingException, KustvaktException {
+ private void testInviteMember (String groupName)
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "darla");
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// list group
- response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
node = node.get(0);
assertEquals(2, node.get("members").size());
assertEquals(node.at("/members/1/userId").asText(), "darla");
- assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
- private void testInviteDeletedMember() throws ProcessingException, KustvaktException {
+ private void testInviteDeletedMember ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "marlin");
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// check member
JsonNode node = retrieveUserGroups("marlin");
assertEquals(2, node.size());
JsonNode group = node.get(1);
- assertEquals(GroupMemberStatus.PENDING.name(), group.at("/userMemberStatus").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ group.at("/userMemberStatus").asText());
}
@Test
- public void testInviteDeletedMember2() throws ProcessingException, KustvaktException {
+ public void testInviteDeletedMember2 ()
+ throws ProcessingException, KustvaktException {
// pearl has status deleted in dory-group
Form form = new Form();
form.param("members", "pearl");
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// check member
JsonNode node = retrieveUserGroups("pearl");
assertEquals(1, node.size());
JsonNode group = node.get(0);
- assertEquals(GroupMemberStatus.PENDING.name(), group.at("/userMemberStatus").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ group.at("/userMemberStatus").asText());
testDeletePendingMember();
}
@Test
- public void testInvitePendingMember() throws ProcessingException, KustvaktException {
+ public void testInvitePendingMember ()
+ throws ProcessingException, KustvaktException {
// marlin has status PENDING in dory-group
Form form = new Form();
form.param("members", "marlin");
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(form));
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_EXISTS, node.at("/errors/0/0").asInt());
- assertEquals("Username marlin with status PENDING exists in the user-group " + "dory-group", node.at("/errors/0/1").asText());
- assertEquals(node.at("/errors/0/2").asText(), "[marlin, PENDING, dory-group]");
+ assertEquals(StatusCodes.GROUP_MEMBER_EXISTS,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Username marlin with status PENDING exists in the user-group "
+ + "dory-group",
+ node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[marlin, PENDING, dory-group]");
}
@Test
- public void testInviteActiveMember() throws ProcessingException, KustvaktException {
+ public void testInviteActiveMember ()
+ throws ProcessingException, KustvaktException {
// nemo has status active in dory-group
Form form = new Form();
form.param("members", "nemo");
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.GROUP_MEMBER_EXISTS, node.at("/errors/0/0").asInt());
- assertEquals("Username nemo with status ACTIVE exists in the user-group " + "dory-group", node.at("/errors/0/1").asText());
- assertEquals(node.at("/errors/0/2").asText(), "[nemo, ACTIVE, dory-group]");
+ assertEquals(StatusCodes.GROUP_MEMBER_EXISTS,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "Username nemo with status ACTIVE exists in the user-group "
+ + "dory-group",
+ node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/2").asText(),
+ "[nemo, ACTIVE, dory-group]");
}
@Test
- public void testInviteMemberToDeletedGroup() throws ProcessingException, KustvaktException {
+ public void testInviteMemberToDeletedGroup ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "nemo");
- Response response = target().path(API_VERSION).path("group").path("@deleted-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@deleted-group").path("invite").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group deleted-group has been deleted.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group deleted-group has been deleted.");
assertEquals(node.at("/errors/0/2").asText(), "deleted-group");
}
// marlin has GroupMemberStatus.PENDING in dory-group
@Test
- public void testSubscribePendingMember() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(new Form()));
+ public void testSubscribePendingMember () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// retrieve marlin group
JsonNode node = retrieveUserGroups("marlin");
@@ -395,9 +554,12 @@
assertEquals(group.at("/owner").asText(), "dory");
// group members are not allowed to see other members
assertEquals(0, group.at("/members").size());
- assertEquals(GroupMemberStatus.ACTIVE.name(), group.at("/userMemberStatus").asText());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), group.at("/userRoles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), group.at("/userRoles/0").asText());
+ assertEquals(GroupMemberStatus.ACTIVE.name(),
+ group.at("/userMemberStatus").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
+ group.at("/userRoles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
+ group.at("/userRoles/0").asText());
// unsubscribe marlin from dory-group
testUnsubscribeActiveMember("dory-group");
checkGroupMemberRole("dory-group", "marlin");
@@ -408,60 +570,104 @@
// pearl has GroupMemberStatus.DELETED in dory-group
@Test
- public void testSubscribeDeletedMember() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).post(Entity.form(new Form()));
+ public void testSubscribeDeletedMember () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("pearl", "pass"))
+ .post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "pearl has already been deleted from the group dory-group");
}
@Test
- public void testSubscribeMissingGroupName() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).post(Entity.form(new Form()));
+ public void testSubscribeMissingGroupName () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("bruce", "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
- public void testSubscribeNonExistentMember() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).post(Entity.form(new Form()));
+ public void testSubscribeNonExistentMember () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("bruce", "pass"))
+ .post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "bruce is not found in the group");
+ assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "bruce is not found in the group");
}
@Test
- public void testSubscribeToNonExistentGroup() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@non-existent").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).post(Entity.form(new Form()));
+ public void testSubscribeToNonExistentGroup () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@non-existent").path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("pearl", "pass"))
+ .post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group non-existent is not found");
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group non-existent is not found");
}
- private void testSubscribeToDeletedGroup(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).post(Entity.form(new Form()));
+ private void testSubscribeToDeletedGroup (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("subscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("nemo", "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group new-user-group has been deleted.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group new-user-group has been deleted.");
}
- private void testUnsubscribeActiveMember(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
+ private void testUnsubscribeActiveMember (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = retrieveUserGroups("marlin");
assertEquals(1, node.size());
}
- private void checkGroupMemberRole(String groupName, String deletedMemberName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).post(null);
+ private void checkGroupMemberRole (String groupName,
+ String deletedMemberName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .post(null);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity).at("/members");
@@ -476,23 +682,37 @@
}
@Test
- public void testUnsubscribeDeletedMember() throws ProcessingException, KustvaktException {
+ public void testUnsubscribeDeletedMember ()
+ throws ProcessingException, KustvaktException {
// pearl unsubscribes from dory-group
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("pearl", "pass"))
+ .delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "pearl has already been deleted from the group dory-group");
assertEquals(node.at("/errors/0/2").asText(), "[pearl, dory-group]");
}
@Test
- public void testUnsubscribePendingMember() throws ProcessingException, KustvaktException {
+ public void testUnsubscribePendingMember ()
+ throws ProcessingException, KustvaktException {
JsonNode node = retrieveUserGroups("marlin");
assertEquals(2, node.size());
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = retrieveUserGroups("marlin");
assertEquals(1, node.size());
@@ -502,46 +722,77 @@
}
@Test
- public void testUnsubscribeMissingGroupName() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
+ public void testUnsubscribeMissingGroupName () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
- public void testUnsubscribeNonExistentMember() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).delete();
+ public void testUnsubscribeNonExistentMember () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@dory-group").path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("bruce", "pass"))
+ .delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "bruce is not found in the group");
+ assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "bruce is not found in the group");
}
@Test
- public void testUnsubscribeToNonExistentGroup() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@tralala-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).delete();
+ public void testUnsubscribeToNonExistentGroup () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@tralala-group").path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("pearl", "pass"))
+ .delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group tralala-group is not found");
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group tralala-group is not found");
}
- private void testUnsubscribeToDeletedGroup(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).delete();
+ private void testUnsubscribeToDeletedGroup (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("unsubscribe").request()
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("nemo", "pass"))
+ .delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Group new-user-group has been deleted.");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Group new-user-group has been deleted.");
}
@Test
- public void testAddSameMemberRole() throws ProcessingException, KustvaktException {
+ public void testAddSameMemberRole ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("add").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").path("role").path("add").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
@@ -549,11 +800,16 @@
}
@Test
- public void testDeleteAddMemberRole() throws ProcessingException, KustvaktException {
+ public void testDeleteAddMemberRole ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("delete").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").path("role").path("delete").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
@@ -562,10 +818,15 @@
}
@Test
- public void testEditMemberRoleEmpty() throws ProcessingException, KustvaktException {
+ public void testEditMemberRoleEmpty ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("edit").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").path("role").path("edit").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
@@ -573,12 +834,17 @@
testEditMemberRole();
}
- private void testEditMemberRole() throws ProcessingException, KustvaktException {
+ private void testEditMemberRole ()
+ throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
form.param("roleId", "3");
- Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("edit").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@marlin-group").path("role").path("edit").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
index 7f7078e..176e31b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
@@ -30,18 +30,29 @@
private String username2 = "UserSetting.Test2";
- public Response sendPutRequest(String username, Map<String, Object> map) throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(map));
+ public Response sendPutRequest (String username, Map<String, Object> map)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .put(Entity.json(map));
return response;
}
@Test
- public void testCreateSettingWithJson() throws KustvaktException {
- String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":[\"author\", \"title\"," + "\"textSigle\", \"availability\"],\"resultPerPage\":25}";
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(json));
+ public void testCreateSettingWithJson () throws KustvaktException {
+ String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":[\"author\", \"title\","
+ + "\"textSigle\", \"availability\"],\"resultPerPage\":25}";
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
int numOfResult = 25;
- String metadata = "[\"author\",\"title\",\"textSigle\"," + "\"availability\"]";
+ String metadata = "[\"author\",\"title\",\"textSigle\","
+ + "\"availability\"]";
testRetrieveSettings(username, "opennlp", numOfResult, metadata, true);
testDeleteKeyNotExist(username);
testDeleteKey(username, numOfResult, metadata, true);
@@ -49,102 +60,151 @@
}
@Test
- public void testCreateSettingWithMap() throws KustvaktException {
+ public void testCreateSettingWithMap () throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("pos-foundry", "opennlp");
map.put("resultPerPage", 25);
map.put("metadata", "author title textSigle availability");
Response response = sendPutRequest(username2, map);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- testRetrieveSettings(username2, "opennlp", 25, "author title textSigle availability", false);
+ testRetrieveSettings(username2, "opennlp", 25,
+ "author title textSigle availability", false);
testUpdateSetting(username2);
testputRequestInvalidKey();
}
@Test
- public void testputRequestInvalidKey() throws KustvaktException {
+ public void testputRequestInvalidKey () throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("key/", "invalidKey");
Response response = sendPutRequest(username2, map);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/2").asText(), "key/");
}
@Test
- public void testPutDifferentUsername() throws KustvaktException {
- String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title " + "textSigle availability\",\"resultPerPage\":25}";
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).put(Entity.json(json));
+ public void testPutDifferentUsername () throws KustvaktException {
+ String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title "
+ + "textSigle availability\",\"resultPerPage\":25}";
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username2, "pass"))
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testGetDifferentUsername() throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).get();
+ public void testGetDifferentUsername () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username2, "pass"))
+ .get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testGetSettingNotExist() throws KustvaktException {
+ public void testGetSettingNotExist () throws KustvaktException {
String username = "tralala";
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .get();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals("No default setting for username: " + username + " is found", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(
+ "No default setting for username: " + username + " is found",
+ node.at("/errors/0/1").asText());
assertEquals(username, node.at("/errors/0/2").asText());
}
@Test
- public void testDeleteSettingNotExist() throws KustvaktException {
+ public void testDeleteSettingNotExist () throws KustvaktException {
String username = "tralala";
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testDeleteKeyDifferentUsername() throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").path("pos-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).delete();
+ public void testDeleteKeyDifferentUsername () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").path("pos-foundry").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username2, "pass"))
+ .delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
}
- private void testDeleteSetting(String username) throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private void testDeleteSetting (String username) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
assertEquals(username, node.at("/errors/0/2").asText());
}
// EM: deleting a non-existing key does not throw an error,
// because
// the purpose of the request has been achieved.
- private void testDeleteKeyNotExist(String username) throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").path("lemma-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private void testDeleteKeyNotExist (String username)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").path("lemma-foundry").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testDeleteKey(String username, int numOfResult, String metadata, boolean isMetadataArray) throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").path("pos-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private void testDeleteKey (String username, int numOfResult,
+ String metadata, boolean isMetadataArray) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").path("pos-foundry").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- testRetrieveSettings(username, null, numOfResult, metadata, isMetadataArray);
+ testRetrieveSettings(username, null, numOfResult, metadata,
+ isMetadataArray);
}
- private void testUpdateSetting(String username) throws KustvaktException {
+ private void testUpdateSetting (String username) throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("pos-foundry", "malt");
map.put("resultPerPage", 15);
@@ -154,19 +214,27 @@
testRetrieveSettings(username, "malt", 15, "author title", false);
}
- private void testRetrieveSettings(String username, String posFoundry, int numOfResult, String metadata, boolean isMetadataArray) throws KustvaktException {
- Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ private void testRetrieveSettings (String username, String posFoundry,
+ int numOfResult, String metadata, boolean isMetadataArray)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username)
+ .path("setting").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
if (posFoundry == null) {
assertTrue(node.at("/pos-foundry").isMissingNode());
- } else {
+ }
+ else {
assertEquals(posFoundry, node.at("/pos-foundry").asText());
}
assertEquals(numOfResult, node.at("/resultPerPage").asInt());
if (isMetadataArray) {
assertEquals(metadata, node.at("/metadata").toString());
- } else {
+ }
+ else {
assertEquals(metadata, node.at("/metadata").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
index 382535d..346b71d 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
@@ -45,15 +45,18 @@
* @throws KustvaktException
*/
@Test
- public void testRefVcNotPrecached() throws KustvaktException {
+ public void testRefVcNotPrecached () throws KustvaktException {
JsonNode node = testSearchWithRef_VC1();
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Virtual corpus system/named-vc1 is not found.");
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Virtual corpus system/named-vc1 is not found.");
assertEquals(node.at("/errors/0/2").asText(), "system/named-vc1");
}
@Test
- public void testRefVcPrecached() throws KustvaktException, IOException, QueryException {
+ public void testRefVcPrecached ()
+ throws KustvaktException, IOException, QueryException {
int numOfMatches = testSearchWithoutRef_VC1();
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains("named-vc1"));
@@ -77,8 +80,12 @@
assertNull(vc);
}
- private int testSearchWithoutRef_VC1() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "textSigle=\"GOE/AGF/00000\" | textSigle=\"GOE/AGA/01784\"").request().get();
+ private int testSearchWithoutRef_VC1 () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq",
+ "textSigle=\"GOE/AGF/00000\" | textSigle=\"GOE/AGA/01784\"")
+ .request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
int size = node.at("/matches").size();
@@ -86,8 +93,12 @@
return size;
}
- private int testSearchWithoutRef_VC2() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "textSigle!=\"GOE/AGI/04846\" & textSigle!=\"GOE/AGA/01784\"").request().get();
+ private int testSearchWithoutRef_VC2 () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq",
+ "textSigle!=\"GOE/AGI/04846\" & textSigle!=\"GOE/AGA/01784\"")
+ .request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
int size = node.at("/matches").size();
@@ -95,22 +106,28 @@
return size;
}
- private JsonNode testSearchWithRef_VC1() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/named-vc1\"").request().get();
+ private JsonNode testSearchWithRef_VC1 () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"system/named-vc1\"").request()
+ .get();
String ent = response.readEntity(String.class);
return JsonUtils.readTree(ent);
}
- private JsonNode testSearchWithRef_VC2() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo named-vc2").request().get();
+ private JsonNode testSearchWithRef_VC2 () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo named-vc2").request().get();
String ent = response.readEntity(String.class);
return JsonUtils.readTree(ent);
}
@Test
- public void testStatisticsWithRef() throws KustvaktException {
+ public void testStatisticsWithRef () throws KustvaktException {
String corpusQuery = "availability = /CC-BY.*/ & referTo named-vc1";
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", corpusQuery).request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(2, node.at("/documents").asInt());
@@ -119,33 +136,45 @@
}
@Test
- public void testRefVcNotExist() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"username/vc1\"").request().get();
+ public void testRefVcNotExist () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"username/vc1\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/2").asText(), "username/vc1");
}
@Test
- public void testRefNotAuthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").request().get();
+ public void testRefNotAuthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"dory/dory-vc\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/2").asText(), "guest");
}
@Test
- public void testSearchWithRefPublishedVcGuest() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"marlin/published-vc\"").request().get();
+ public void testSearchWithRefPublishedVcGuest () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"marlin/published-vc\"").request()
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
- assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
- assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/@type").asText(),
+ "koral:doc");
assertEquals(node.at("/collection/operands/1/value").asText(), "GOE");
- assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/1/key").asText(),
+ "corpusSigle");
node = node.at("/collection/operands/1/rewrites");
assertEquals(3, node.size());
assertEquals(node.at("/0/operation").asText(), "operation:deletion");
@@ -156,15 +185,26 @@
}
@Test
- public void testSearchWithRefPublishedVc() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"marlin/published-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("squirt", "pass")).get();
+ public void testSearchWithRefPublishedVc () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"marlin/published-vc\"").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("squirt", "pass"))
+ .get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
Form f = new Form();
f.param("status", "HIDDEN");
// check dory in the hidden group of the vc
- response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ response = target().path(API_VERSION).path("admin").path("group")
+ .path("list").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
index beb1308..a1594fc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
@@ -21,10 +21,12 @@
private String testUser = "VirtualCorpusAccessTest";
@Test
- public void testlistAccessByNonVCAAdmin() throws KustvaktException {
+ public void testlistAccessByNonVCAAdmin () throws KustvaktException {
JsonNode node = listAccessByGroup("nemo", "dory-group");
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: nemo");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: nemo");
}
// @Test
@@ -48,8 +50,12 @@
// assertEquals("vcId", node.at("/errors/0/1").asText());
// }
@Test
- public void testlistAccessByGroup() throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access").queryParam("groupName", "dory-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
+ public void testlistAccessByGroup () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access")
+ .queryParam("groupName", "dory-group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
@@ -61,11 +67,14 @@
}
@Test
- public void testDeleteSharedVC() throws KustvaktException {
- String json = "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testDeleteSharedVC () throws KustvaktException {
+ String json = "{\"type\": \"PROJECT\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new_project_vc";
String username = "dory";
- String authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass");
+ String authHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass");
createVC(authHeader, username, vcName, json);
String groupName = "dory-group";
testShareVCByCreator(username, vcName, groupName);
@@ -78,7 +87,8 @@
}
@Test
- public void testCreateDeleteAccess() throws ProcessingException, KustvaktException {
+ public void testCreateDeleteAccess ()
+ throws ProcessingException, KustvaktException {
String vcName = "marlin-vc";
String groupName = "marlin-group";
// check the vc type
@@ -116,30 +126,40 @@
String json = "{\"type\": \"" + ResourceType.PRIVATE + "\"}";
editVC("marlin", "marlin", vcName, json);
node = retrieveVCInfo("marlin", "marlin", vcName);
- assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.PRIVATE.displayName(),
+ node.at("/type").asText());
}
- private void testShareVC_nonUniqueAccess(String vcCreator, String vcName, String groupName) throws ProcessingException, KustvaktException {
+ private void testShareVC_nonUniqueAccess (String vcCreator, String vcName,
+ String groupName) throws ProcessingException, KustvaktException {
Response response = testShareVCByCreator(vcCreator, vcName, groupName);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus());
- assertEquals(StatusCodes.DB_INSERT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DB_INSERT_FAILED,
+ node.at("/errors/0/0").asInt());
// EM: message differs depending on the database used
// for testing. The message below is from sqlite.
// assertTrue(node.at("/errors/0/1").asText()
// .startsWith("[SQLITE_CONSTRAINT_UNIQUE]"));
}
- private Response testDeleteAccess(String username, String accessId) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access").path(accessId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ private Response testDeleteAccess (String username, String accessId)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access")
+ .path(accessId).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .delete();
return response;
}
@Test
- public void testDeleteNonExistingAccess() throws ProcessingException, KustvaktException {
+ public void testDeleteNonExistingAccess ()
+ throws ProcessingException, KustvaktException {
Response response = testDeleteAccess("dory", "100");
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
index 225a331..a3b7e12 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
@@ -16,7 +16,7 @@
private String username = "VirtualCorpusClientTest";
@Test
- public void testVC_withClient() throws KustvaktException {
+ public void testVC_withClient () throws KustvaktException {
// create client
Response response = registerConfidentialClient(username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -24,20 +24,27 @@
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
// obtain authorization
- String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
- response = requestAuthorizationCode("code", clientId, clientRedirectUri, "create_vc vc_info delete_vc edit_vc", "myState", userAuthHeader);
+ String userAuthHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "password");
+ response = requestAuthorizationCode("code", clientId, clientRedirectUri,
+ "create_vc vc_info delete_vc edit_vc", "myState",
+ userAuthHeader);
String code = parseAuthorizationCode(response);
- response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, clientRedirectUri);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId,
+ clientSecret, code, clientRedirectUri);
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
String accessTokenHeader = "Bearer " + accessToken;
// create VC 1
String vcName = "vc-client1";
- String vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ String vcJson = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
createVC(accessTokenHeader, username, vcName, vcJson);
// create VC 2
vcName = "vc-client2";
- vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate until 1820\"}";
+ vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate until 1820\"}";
createVC(accessTokenHeader, username, vcName, vcJson);
// edit VC
String description = "vc created from client";
@@ -58,7 +65,8 @@
deregisterClient(username, clientId);
testSearchWithRevokedAccessToken(accessToken);
// obtain authorization from another client
- response = requestTokenWithPassword(superClientId, this.clientSecret, username, "pass");
+ response = requestTokenWithPassword(superClientId, this.clientSecret,
+ username, "pass");
node = JsonUtils.readTree(response.readEntity(String.class));
accessToken = node.at("/access_token").asText();
// checking vc should still be available after client deregistration
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
index e93582f..90f9d4a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
@@ -28,48 +28,82 @@
private String testUser = "VirtualCorpusControllerAdminTest";
- private JsonNode testAdminListVC(String username) throws ProcessingException, KustvaktException {
+ private JsonNode testAdminListVC (String username)
+ throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("createdBy", username);
- Response response = target().path(API_VERSION).path("admin").path("vc").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin").path("vc")
+ .path("list").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private JsonNode testAdminListVC_UsingAdminToken(String username, ResourceType type) throws ProcessingException, KustvaktException {
+ private JsonNode testAdminListVC_UsingAdminToken (String username,
+ ResourceType type) throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("createdBy", username);
f.param("type", type.toString());
f.param("token", "secret");
- Response response = target().path(API_VERSION).path("admin").path("vc").path("list").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin").path("vc")
+ .path("list").request()
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
@Test
- public void testCreateSystemVC() throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~system").path("new-system-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateSystemVC () throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~system").path("new-system-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
- JsonNode node = testAdminListVC_UsingAdminToken("system", ResourceType.SYSTEM);
+ JsonNode node = testAdminListVC_UsingAdminToken("system",
+ ResourceType.SYSTEM);
assertEquals(2, node.size());
testDeleteSystemVC(admin, "new-system-vc");
}
- private void testDeleteSystemVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~system").path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
+ private void testDeleteSystemVC (String vcCreator, String vcName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~system").path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- JsonNode node = testAdminListVC_UsingAdminToken("system", ResourceType.SYSTEM);
+ JsonNode node = testAdminListVC_UsingAdminToken("system",
+ ResourceType.SYSTEM);
assertEquals(1, node.size());
}
@Test
- public void testCreatePrivateVC() throws ProcessingException, KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testCreatePrivateVC ()
+ throws ProcessingException, KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new-vc";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
JsonNode node = testAdminListVC(testUser);
assertEquals(1, node.size());
@@ -77,16 +111,27 @@
testDeletePrivateVC(testUser, vcName);
}
- private void testEditPrivateVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
+ private void testEditPrivateVC (String vcCreator, String vcName)
+ throws ProcessingException, KustvaktException {
String json = "{\"description\": \"edited vc\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + vcCreator).path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
JsonNode node = testAdminListVC(testUser);
assertEquals(node.at("/0/description").asText(), "edited vc");
}
- private void testDeletePrivateVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
+ private void testDeletePrivateVC (String vcCreator, String vcName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + vcCreator).path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = testAdminListVC(vcCreator);
assertEquals(0, node.size());
@@ -116,8 +161,13 @@
//
// return node.at("/accessId").asText();
// }
- private JsonNode testlistAccessByGroup(String groupName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access").queryParam("groupName", groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
+ private JsonNode testlistAccessByGroup (String groupName)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access")
+ .queryParam("groupName", groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
@@ -125,35 +175,49 @@
}
@Test
- public void testVCSharing() throws ProcessingException, KustvaktException {
+ public void testVCSharing () throws ProcessingException, KustvaktException {
String vcCreator = "marlin";
String vcName = "marlin-vc";
String groupName = "marlin-group";
- JsonNode node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
+ JsonNode node2 = testAdminListVC_UsingAdminToken(vcCreator,
+ ResourceType.PROJECT);
assertEquals(0, node2.size());
testCreateVCAccess(vcCreator, vcName, groupName);
JsonNode node = testlistAccessByGroup(groupName);
String accessId = node.at("/accessId").asText();
testDeleteVCAccess(accessId);
- node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
+ node2 = testAdminListVC_UsingAdminToken(vcCreator,
+ ResourceType.PROJECT);
assertEquals(1, node2.size());
String json = "{\"type\": \"" + ResourceType.PRIVATE + "\"}";
editVC(admin, vcCreator, vcName, json);
node = retrieveVCInfo(admin, vcCreator, vcName);
- assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
- node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
+ assertEquals(ResourceType.PRIVATE.displayName(),
+ node.at("/type").asText());
+ node2 = testAdminListVC_UsingAdminToken(vcCreator,
+ ResourceType.PROJECT);
assertEquals(0, node2.size());
}
- private void testCreateVCAccess(String vcCreator, String vcName, String groupName) throws ProcessingException, KustvaktException {
+ private void testCreateVCAccess (String vcCreator, String vcName,
+ String groupName) throws ProcessingException, KustvaktException {
Response response;
// share VC
- response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).path("share").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).post(Entity.form(new Form()));
+ response = target().path(API_VERSION).path("vc").path("~" + vcCreator)
+ .path(vcName).path("share").path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testDeleteVCAccess(String accessId) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access").path(accessId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
+ private void testDeleteVCAccess (String accessId)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access")
+ .path(accessId).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
index fe45cec..a9ff786 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
@@ -34,13 +34,16 @@
private String authHeader;
- public VirtualCorpusControllerTest() throws KustvaktException {
- authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass");
+ public VirtualCorpusControllerTest () throws KustvaktException {
+ authHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass");
}
@Test
- public void testCreatePrivateVC() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testCreatePrivateVC () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
createVC(authHeader, testUser, "new_vc", json);
// list user VC
JsonNode node = listVC(testUser);
@@ -54,8 +57,10 @@
}
@Test
- public void testCreatePublishedVC() throws KustvaktException {
- String json = "{\"type\": \"PUBLISHED\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testCreatePublishedVC () throws KustvaktException {
+ String json = "{\"type\": \"PUBLISHED\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new-published-vc";
createVC(authHeader, testUser, vcName, json);
// test list owner vc
@@ -76,44 +81,64 @@
deleteVC(vcName, testUser, testUser);
// EM: check if the hidden groups are deleted as well
node = testCheckHiddenGroup(groupName);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
- assertEquals("Group " + groupName + " is not found", node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
+ assertEquals("Group " + groupName + " is not found",
+ node.at("/errors/0/1").asText());
}
- private JsonNode testCheckHiddenGroup(String groupName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
+ private JsonNode testCheckHiddenGroup (String groupName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
@Test
- public void testCreateVCWithInvalidToken() throws IOException, KustvaktException {
- String json = "{\"type\": \"PRIVATE\"," + "\"corpusQuery\": \"corpusSigle=GOE\"}";
- InputStream is = getClass().getClassLoader().getResourceAsStream("test-invalid-signature.token");
+ public void testCreateVCWithInvalidToken ()
+ throws IOException, KustvaktException {
+ String json = "{\"type\": \"PRIVATE\","
+ + "\"corpusQuery\": \"corpusSigle=GOE\"}";
+ InputStream is = getClass().getClassLoader()
+ .getResourceAsStream("test-invalid-signature.token");
String authToken;
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
+ try (BufferedReader reader = new BufferedReader(
+ new InputStreamReader(is))) {
authToken = reader.readLine();
}
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, AuthenticationScheme.BEARER.displayName() + " " + authToken).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION,
+ AuthenticationScheme.BEARER.displayName() + " "
+ + authToken)
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is invalid");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateVCWithExpiredToken() throws IOException, KustvaktException {
+ public void testCreateVCWithExpiredToken ()
+ throws IOException, KustvaktException {
String json = "{\"type\": \"PRIVATE\","
+ "\"corpusQuery\": \"corpusSigle=GOE\"}";
//String authToken = "fia0123ikBWn931470H8s5gRqx7Moc4p";
String authToken = createExpiredAccessToken();
-
+
Response response = target().path(API_VERSION).path("vc")
- .path("~marlin").path("new_vc")
- .request()
+ .path("~marlin").path("new_vc").request()
.header(Attributes.AUTHORIZATION,
AuthenticationScheme.BEARER.displayName() + " "
+ authToken)
@@ -121,130 +146,201 @@
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(Entity.json(json));
-
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.EXPIRED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Access token is expired");
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Access token is expired");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateSystemVC() throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"pubDate since 1820\"}";
+ public void testCreateSystemVC () throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"pubDate since 1820\"}";
String vcName = "new_system_vc";
- Response response = target().path(API_VERSION).path("vc").path("~system").path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~system").path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
JsonNode node = listSystemVC("pearl");
assertEquals(2, node.size());
- assertEquals(ResourceType.SYSTEM.displayName(), node.at("/0/type").asText());
- assertEquals(ResourceType.SYSTEM.displayName(), node.at("/1/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(),
+ node.at("/0/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(),
+ node.at("/1/type").asText());
deleteVC(vcName, "system", "admin");
node = listSystemVC("pearl");
assertEquals(1, node.size());
}
@Test
- public void testCreateSystemVC_unauthorized() throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateSystemVC_unauthorized () throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
testResponseUnauthorized(response, testUser);
}
@Test
- public void testCreateVC_invalidName() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new $vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_invalidName () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new $vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testCreateVC_nameTooShort() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("ne").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_nameTooShort () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("ne").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "queryName must contain at least 3 characters");
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "queryName must contain at least 3 characters");
}
@Test
- public void testCreateVC_unauthorized() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"," + "\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_unauthorized () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\","
+ + "\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: guest");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: guest");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateVC_withoutCorpusQuery() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_withoutCorpusQuery () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "corpusQuery is null");
assertEquals(node.at("/errors/0/2").asText(), "corpusQuery");
}
@Test
- public void testCreateVC_withoutEntity() throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(""));
+ public void testCreateVC_withoutEntity () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(""));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "request entity is null");
assertEquals(node.at("/errors/0/2").asText(), "request entity");
}
@Test
- public void testCreateVC_withoutType() throws KustvaktException {
- String json = "{\"corpusQuery\": " + "\"creationDate since 1820\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_withoutType () throws KustvaktException {
+ String json = "{\"corpusQuery\": " + "\"creationDate since 1820\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "type is null");
assertEquals(node.at("/errors/0/2").asText(), "type");
}
@Test
- public void testCreateVC_withWrongType() throws KustvaktException {
- String json = "{\"type\": \"PRIVAT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ public void testCreateVC_withWrongType () throws KustvaktException {
+ String json = "{\"type\": \"PRIVAT\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertTrue(node.at("/errors/0/1").asText().startsWith("Cannot deserialize value of type `de.ids_mannheim.korap.constant." + "ResourceType` from String \"PRIVAT\""));
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertTrue(node.at("/errors/0/1").asText().startsWith(
+ "Cannot deserialize value of type `de.ids_mannheim.korap.constant."
+ + "ResourceType` from String \"PRIVAT\""));
}
@Test
- public void testMaxNumberOfVC() throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testMaxNumberOfVC () throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
for (int i = 1; i < 6; i++) {
createVC(authHeader, testUser, "new_vc_" + i, json);
}
- Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc_6").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~" + testUser).path("new_vc_6").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
- assertEquals("Cannot create virtual corpus. The maximum number of " + "virtual corpus has been reached.", node.at("/errors/0/1").asText());
+ assertEquals(
+ "Cannot create virtual corpus. The maximum number of "
+ + "virtual corpus has been reached.",
+ node.at("/errors/0/1").asText());
// list user VC
node = listVC(testUser);
// including 1 system-vc
@@ -260,13 +356,15 @@
}
@Test
- public void testDeleteVC_unauthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, authHeader).delete();
+ public void testDeleteVC_unauthorized () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("dory-vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader).delete();
testResponseUnauthorized(response, testUser);
}
@Test
- public void testEditVC() throws KustvaktException {
+ public void testEditVC () throws KustvaktException {
// 1st edit
String json = "{\"description\": \"edited vc\"}";
editVC("dory", "dory", "dory-vc", json);
@@ -282,20 +380,28 @@
}
@Test
- public void testEditVCName() throws KustvaktException {
+ public void testEditVCName () throws KustvaktException {
String json = "{\"name\": \"new-name\"}";
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("dory-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testEditCorpusQuery() throws ProcessingException, KustvaktException {
+ public void testEditCorpusQuery ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testRetrieveKoralQuery("dory", "dory-vc");
assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operation").asText(),
+ "operation:and");
assertEquals(2, node.at("/collection/operands").size());
String json = "{\"corpusQuery\": \"corpusSigle=WPD17\"}";
editVC("dory", "dory", "dory-vc", json);
@@ -305,8 +411,14 @@
assertEquals(node.at("/collection/value").asText(), "WPD17");
}
- private JsonNode testRetrieveKoralQuery(String username, String vcName) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("koralQuery").path("~" + username).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
+ private JsonNode testRetrieveKoralQuery (String username, String vcName)
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .path("koralQuery").path("~" + username).path(vcName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -314,30 +426,39 @@
}
@Test
- public void testEditVC_notOwner() throws KustvaktException {
+ public void testEditVC_notOwner () throws KustvaktException {
String json = "{\"description\": \"edited vc\"}";
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("dory-vc").request()
+ .header(Attributes.AUTHORIZATION, authHeader)
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .put(Entity.json(json));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser,
+ node.at("/errors/0/1").asText());
checkWWWAuthenticateHeader(response);
}
@Test
- public void testPublishProjectVC() throws KustvaktException {
+ public void testPublishProjectVC () throws KustvaktException {
String vcName = "group-vc";
// check the vc type
JsonNode node = retrieveVCInfo("dory", "dory", vcName);
- assertEquals(ResourceType.PROJECT.displayName(), node.get("type").asText());
+ assertEquals(ResourceType.PROJECT.displayName(),
+ node.get("type").asText());
// edit vc
String json = "{\"type\": \"PUBLISHED\"}";
editVC("dory", "dory", vcName, json);
// check VC
node = testListOwnerVC("dory");
JsonNode n = node.get(1);
- assertEquals(ResourceType.PUBLISHED.displayName(), n.get("type").asText());
+ assertEquals(ResourceType.PUBLISHED.displayName(),
+ n.get("type").asText());
// check hidden VC access
node = listAccessByGroup("admin", "");
assertEquals(4, node.size());
@@ -349,7 +470,8 @@
json = "{\"type\": \"PROJECT\"}";
editVC("dory", "dory", vcName, json);
node = testListOwnerVC("dory");
- assertEquals(ResourceType.PROJECT.displayName(), node.get(1).get("type").asText());
+ assertEquals(ResourceType.PROJECT.displayName(),
+ node.get(1).get("type").asText());
// check VC access
node = listAccessByGroup("admin", "");
assertEquals(3, node.size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
index 1e06bd3..27c527d 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
@@ -32,23 +32,37 @@
@Autowired
private QueryDao dao;
- private JsonNode testRetrieveField(String username, String vcName, String field) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("field").path("~" + username).path(vcName).queryParam("fieldName", field).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
+ private JsonNode testRetrieveField (String username, String vcName,
+ String field) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("field")
+ .path("~" + username).path(vcName)
+ .queryParam("fieldName", field).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testRetrieveProhibitedField(String username, String vcName, String field) throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("field").path("~" + username).path(vcName).queryParam("fieldName", field).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
+ private void testRetrieveProhibitedField (String username, String vcName,
+ String field) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("field")
+ .path("~" + username).path(vcName)
+ .queryParam("fieldName", field).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
}
- private void deleteVcFromDB(String vcName) throws KustvaktException {
+ private void deleteVcFromDB (String vcName) throws KustvaktException {
QueryDO vc = dao.retrieveQueryByName(vcName, "system");
dao.deleteQuery(vc);
vc = dao.retrieveQueryByName(vcName, "system");
@@ -56,15 +70,18 @@
}
@Test
- public void testRetrieveFieldsNamedVC1() throws IOException, QueryException, KustvaktException {
+ public void testRetrieveFieldsNamedVC1 ()
+ throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
JsonNode n = testRetrieveField("system", "named-vc1", "textSigle");
- assertEquals(n.at("/@context").asText(), "http://korap.ids-mannheim.de/ns/KoralQuery/v0.3/context.jsonld");
+ assertEquals(n.at("/@context").asText(),
+ "http://korap.ids-mannheim.de/ns/KoralQuery/v0.3/context.jsonld");
assertEquals(n.at("/corpus/key").asText(), "textSigle");
assertEquals(2, n.at("/corpus/value").size());
n = testRetrieveField("system", "named-vc1", "author");
assertEquals(2, n.at("/corpus/value").size());
- assertEquals(n.at("/corpus/value/0").asText(), "Goethe, Johann Wolfgang von");
+ assertEquals(n.at("/corpus/value/0").asText(),
+ "Goethe, Johann Wolfgang von");
testRetrieveUnknownTokens();
testRetrieveProhibitedField("system", "named-vc1", "tokens");
testRetrieveProhibitedField("system", "named-vc1", "base");
@@ -72,14 +89,16 @@
deleteVcFromDB("named-vc1");
}
- private void testRetrieveUnknownTokens() throws ProcessingException, KustvaktException {
+ private void testRetrieveUnknownTokens ()
+ throws ProcessingException, KustvaktException {
JsonNode n = testRetrieveField("system", "named-vc1", "unknown");
assertEquals(n.at("/corpus/key").asText(), "unknown");
assertEquals(0, n.at("/corpus/value").size());
}
@Test
- public void testRetrieveTextSigleNamedVC2() throws IOException, QueryException, KustvaktException {
+ public void testRetrieveTextSigleNamedVC2 ()
+ throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc2", "/vc/named-vc2.jsonld");
JsonNode n = testRetrieveField("system", "named-vc2", "textSigle");
assertEquals(2, n.at("/corpus/value").size());
@@ -88,7 +107,8 @@
}
@Test
- public void testRetrieveTextSigleNamedVC3() throws IOException, QueryException, KustvaktException {
+ public void testRetrieveTextSigleNamedVC3 ()
+ throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc3", "/vc/named-vc3.jsonld");
JsonNode n = testRetrieveField("system", "named-vc3", "textSigle");
n = n.at("/corpus/value");
@@ -99,14 +119,23 @@
}
@Test
- public void testRetrieveFieldUnauthorized() throws KustvaktException, IOException, QueryException {
+ public void testRetrieveFieldUnauthorized ()
+ throws KustvaktException, IOException, QueryException {
vcLoader.loadVCToCache("named-vc3", "/vc/named-vc3.jsonld");
- Response response = target().path(API_VERSION).path("vc").path("field").path("~system").path("named-vc3").queryParam("fieldName", "textSigle").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
+ Response response = target().path(API_VERSION).path("vc").path("field")
+ .path("~system").path("named-vc3")
+ .queryParam("fieldName", "textSigle").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+ .get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: dory");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: dory");
VirtualCorpusCache.delete("named-vc3");
deleteVcFromDB("named-vc3");
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
index 168edbb..4d20c0f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
@@ -26,64 +26,96 @@
private String testUser = "VirtualCorpusInfoTest";
@Test
- public void testRetrieveSystemVC() throws ProcessingException, KustvaktException {
+ public void testRetrieveSystemVC ()
+ throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo(testUser, "system", "system-vc");
assertEquals(node.at("/name").asText(), "system-vc");
- assertEquals(ResourceType.SYSTEM.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(),
+ node.at("/type").asText());
// assertEquals("koral:doc", node.at("/koralQuery/collection/@type").asText());
assertTrue(node.at("/query").isMissingNode());
assertTrue(node.at("/queryLanguage").isMissingNode());
}
@Test
- public void testRetrieveSystemVCGuest() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~system").path("system-vc").request().get();
+ public void testRetrieveSystemVCGuest ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~system").path("system-vc").request().get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(node.at("/name").asText(), "system-vc");
- assertEquals(ResourceType.SYSTEM.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(),
+ node.at("/type").asText());
}
@Test
- public void testRetrieveOwnerPrivateVC() throws ProcessingException, KustvaktException {
+ public void testRetrieveOwnerPrivateVC ()
+ throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("dory", "dory", "dory-vc");
assertEquals(node.at("/name").asText(), "dory-vc");
- assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.PRIVATE.displayName(),
+ node.at("/type").asText());
}
@Test
- public void testRetrievePrivateVCUnauthorized() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).get();
+ public void testRetrievePrivateVCUnauthorized ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("dory-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .get();
testResponseUnauthorized(response, testUser);
}
@Test
- public void testRetrieveProjectVC() throws ProcessingException, KustvaktException {
+ public void testRetrieveProjectVC ()
+ throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("nemo", "dory", "group-vc");
assertEquals(node.at("/name").asText(), "group-vc");
- assertEquals(ResourceType.PROJECT.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.PROJECT.displayName(),
+ node.at("/type").asText());
}
@Test
- public void testRetrieveProjectVCUnauthorized() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).get();
+ public void testRetrieveProjectVCUnauthorized ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("group-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass"))
+ .get();
testResponseUnauthorized(response, testUser);
}
@Test
- public void testRetrieveProjectVCbyNonActiveMember() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).get();
+ public void testRetrieveProjectVCbyNonActiveMember ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("group-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("marlin", "pass"))
+ .get();
testResponseUnauthorized(response, "marlin");
}
@Test
- public void testRetrievePublishedVC() throws ProcessingException, KustvaktException {
+ public void testRetrievePublishedVC ()
+ throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("gill", "marlin", "published-vc");
assertEquals(node.at("/name").asText(), "published-vc");
- assertEquals(ResourceType.PUBLISHED.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.PUBLISHED.displayName(),
+ node.at("/type").asText());
Form f = new Form();
f.param("status", "HIDDEN");
// check gill in the hidden group of the vc
- Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
+ Response response = target().path(API_VERSION).path("admin")
+ .path("group").path("list").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .header(HttpHeaders.CONTENT_TYPE,
+ MediaType.APPLICATION_FORM_URLENCODED)
+ .post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
@@ -93,8 +125,13 @@
}
@Test
- public void testAdminRetrievePrivateVC() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
+ public void testAdminRetrievePrivateVC ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("dory-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -103,12 +140,18 @@
}
@Test
- public void testAdminRetrieveProjectVC() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
+ public void testAdminRetrieveProjectVC ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .path("group-vc").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(admin, "pass"))
+ .get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(node.at("/name").asText(), "group-vc");
- assertEquals(ResourceType.PROJECT.displayName(), node.at("/type").asText());
+ assertEquals(ResourceType.PROJECT.displayName(),
+ node.at("/type").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
index df1ac17..f1e1d17 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
@@ -19,7 +19,8 @@
public class VirtualCorpusListTest extends VirtualCorpusTestBase {
@Test
- public void testListVCNemo() throws ProcessingException, KustvaktException {
+ public void testListVCNemo ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("nemo");
assertEquals(1, node.size());
node = listSystemVC("nemo");
@@ -29,7 +30,8 @@
}
@Test
- public void testListVCPearl() throws ProcessingException, KustvaktException {
+ public void testListVCPearl ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("pearl");
assertEquals(0, node.size());
node = listVC("pearl");
@@ -37,7 +39,8 @@
}
@Test
- public void testListVCDory() throws ProcessingException, KustvaktException {
+ public void testListVCDory ()
+ throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("dory");
assertEquals(2, node.size());
node = listVC("dory");
@@ -45,29 +48,43 @@
}
@Test
- public void testListAvailableVCGuest() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").request().get();
+ public void testListAvailableVCGuest ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").request()
+ .get();
testResponseUnauthorized(response, "guest");
}
@Disabled
@Deprecated
@Test
- public void testListAvailableVCByOtherUser() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).get();
+ public void testListAvailableVCByOtherUser ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory")
+ .request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("pearl", "pass"))
+ .get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: pearl");
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Unauthorized operation for user: pearl");
checkWWWAuthenticateHeader(response);
}
@Disabled
@Deprecated
@Test
- public void testListUserVC() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").queryParam("username", "dory").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).get();
+ public void testListUserVC ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc")
+ .queryParam("username", "dory").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("admin", "pass"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
index 288c9e3..d7de5a3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
@@ -25,40 +25,60 @@
private String testUser = "VirtualCorpusSharingTest";
@Test
- public void testShareUnknownVC() throws ProcessingException, KustvaktException {
- Response response = testShareVCByCreator("marlin", "non-existing-vc", "marlin group");
+ public void testShareUnknownVC ()
+ throws ProcessingException, KustvaktException {
+ Response response = testShareVCByCreator("marlin", "non-existing-vc",
+ "marlin group");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testShareUnknownGroup() throws ProcessingException, KustvaktException {
- Response response = testShareVCByCreator("marlin", "marlin-vc", "non-existing-group");
+ public void testShareUnknownGroup ()
+ throws ProcessingException, KustvaktException {
+ Response response = testShareVCByCreator("marlin", "marlin-vc",
+ "non-existing-group");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testShareVC_notOwner() throws ProcessingException, KustvaktException {
+ public void testShareVC_notOwner ()
+ throws ProcessingException, KustvaktException {
// dory is VCA in marlin group
- Response response = target().path(API_VERSION).path("vc").path("~marlin").path("marlin-vc").path("share").path("@marlin group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(new Form()));
+ Response response = target().path(API_VERSION).path("vc")
+ .path("~marlin").path("marlin-vc").path("share")
+ .path("@marlin group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("dory", "pass"))
+ .post(Entity.form(new Form()));
testResponseUnauthorized(response, "dory");
}
@Test
- public void testShareVC_byMember() throws ProcessingException, KustvaktException {
+ public void testShareVC_byMember ()
+ throws ProcessingException, KustvaktException {
// nemo is not VCA in marlin group
- Response response = target().path(API_VERSION).path("vc").path("~nemo").path("nemo-vc").path("share").path("@marlin-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).post(Entity.form(new Form()));
+ Response response = target().path(API_VERSION).path("vc").path("~nemo")
+ .path("nemo-vc").path("share").path("@marlin-group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("nemo", "pass"))
+ .post(Entity.form(new Form()));
testResponseUnauthorized(response, "nemo");
}
@Test
- public void testCreateShareProjectVC() throws KustvaktException {
- String json = "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testCreateShareProjectVC () throws KustvaktException {
+ String json = "{\"type\": \"PROJECT\""
+ + ",\"queryType\": \"VIRTUAL_CORPUS\""
+ + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new_project_vc";
- String authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass");
+ String authHeader = HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(testUser, "pass");
createVC(authHeader, testUser, vcName, json);
// retrieve vc info
JsonNode vcInfo = retrieveVCInfo(testUser, testUser, vcName);
@@ -96,54 +116,87 @@
response = searchWithVCRef(memberName, testUser, vcName);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND,
+ node.at("/errors/0/0").asInt());
}
- private Response createUserGroup(String username, String groupName, String description) throws ProcessingException, KustvaktException {
+ private Response createUserGroup (String username, String groupName,
+ String description) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("description", description);
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .put(Entity.form(form));
return response;
}
- private JsonNode listUserGroup(String username, String groupName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
+ private JsonNode listUserGroup (String username, String groupName)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testInviteMember(String username, String groupName, String memberName) throws ProcessingException, KustvaktException {
+ private void testInviteMember (String username, String groupName,
+ String memberName) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", memberName);
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("invite").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// list group
JsonNode node = listUserGroup(username, groupName);
node = node.get(0);
assertEquals(2, node.get("members").size());
assertEquals(memberName, node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(),
+ node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
- private void subscribeToGroup(String username, String groupName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(new Form()));
+ private void subscribeToGroup (String username, String groupName)
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group")
+ .path("@" + groupName).path("subscribe").request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void checkMemberInGroup(String memberName, String testUser, String groupName) throws KustvaktException {
+ private void checkMemberInGroup (String memberName, String testUser,
+ String groupName) throws KustvaktException {
JsonNode node = listUserGroup(testUser, groupName).get(0);
assertEquals(2, node.get("members").size());
assertEquals(memberName, node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.ACTIVE.name(), node.at("/members/1/status").asText());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), node.at("/members/1/roles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), node.at("/members/1/roles/0").asText());
+ assertEquals(GroupMemberStatus.ACTIVE.name(),
+ node.at("/members/1/status").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
+ node.at("/members/1/roles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
+ node.at("/members/1/roles/0").asText());
}
- private Response searchWithVCRef(String username, String vcCreator, String vcName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"" + vcCreator + "/" + vcName + "\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
+ private Response searchWithVCRef (String username, String vcCreator,
+ String vcName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq",
+ "referTo \"" + vcCreator + "/" + vcName + "\"")
+ .request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue(username, "pass"))
+ .get();
return response;
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
index 7293e04..04538e9 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
@@ -43,7 +43,7 @@
return JsonUtils.readTree(entity);
}
- protected void createVC (String authHeader,String username, String vcName,
+ protected void createVC (String authHeader, String username, String vcName,
String vcJson) throws KustvaktException {
Response response = target().path(API_VERSION).path("vc")
.path("~" + username).path(vcName).request()
@@ -78,7 +78,7 @@
// System.out.println(entity);
return JsonUtils.readTree(entity);
}
-
+
protected JsonNode listVCWithAuthHeader (String authHeader)
throws ProcessingException, KustvaktException {
Response response = target().path(API_VERSION).path("vc").request()
@@ -88,7 +88,7 @@
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
-
+
protected JsonNode testListOwnerVC (String username)
throws ProcessingException, KustvaktException {
Response response = target().path(API_VERSION).path("vc")
@@ -146,7 +146,7 @@
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
-
+
protected void testResponseUnauthorized (Response response, String username)
throws KustvaktException {
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
@@ -158,19 +158,22 @@
node.at("/errors/0/0").asInt());
assertEquals("Unauthorized operation for user: " + username,
node.at("/errors/0/1").asText());
-
+
checkWWWAuthenticateHeader(response);
}
-
+
protected void checkWWWAuthenticateHeader (Response response) {
- Set<Entry<String, List<Object>>> headers =
- response.getHeaders().entrySet();
+ Set<Entry<String, List<Object>>> headers = response.getHeaders()
+ .entrySet();
for (Entry<String, List<Object>> header : headers) {
if (header.getKey().equals(ContainerRequest.WWW_AUTHENTICATE)) {
- assertThat(header.getValue(), not(hasItem("Api realm=\"Kustvakt\"")));
- assertThat(header.getValue(), hasItem("Bearer realm=\"Kustvakt\""));
- assertThat(header.getValue(), hasItem("Basic realm=\"Kustvakt\""));
+ assertThat(header.getValue(),
+ not(hasItem("Api realm=\"Kustvakt\"")));
+ assertThat(header.getValue(),
+ hasItem("Bearer realm=\"Kustvakt\""));
+ assertThat(header.getValue(),
+ hasItem("Basic realm=\"Kustvakt\""));
}
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
index f8b2b1d..27054fd 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
@@ -25,15 +25,21 @@
private SearchKrill krill;
@Test
- public void testInfo() throws KustvaktException {
- Response response = target().path(API_VERSION).path("info").request().get();
+ public void testInfo () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("info").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(config.getCurrentVersion(), node.at("/latest_api_version").asText());
- assertEquals(config.getSupportedVersions().size(), node.at("/supported_api_versions").size());
- assertEquals(ServiceInfo.getInfo().getVersion(), node.at("/kustvakt_version").asText());
- assertEquals(krill.getIndex().getVersion(), node.at("/krill_version").asText());
- assertEquals(ServiceInfo.getInfo().getKoralVersion(), node.at("/koral_version").asText());
+ assertEquals(config.getCurrentVersion(),
+ node.at("/latest_api_version").asText());
+ assertEquals(config.getSupportedVersions().size(),
+ node.at("/supported_api_versions").size());
+ assertEquals(ServiceInfo.getInfo().getVersion(),
+ node.at("/kustvakt_version").asText());
+ assertEquals(krill.getIndex().getVersion(),
+ node.at("/krill_version").asText());
+ assertEquals(ServiceInfo.getInfo().getKoralVersion(),
+ node.at("/koral_version").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
index c037f20..5d93355 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
@@ -18,8 +18,12 @@
public class LiteMultipleCorpusQueryTest extends LiteJerseyTest {
@Test
- public void testSearchGet() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "das").queryParam("ql", "poliqarp").queryParam("cq", "pubPlace=München").queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request().get();
+ public void testSearchGet () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "das").queryParam("ql", "poliqarp")
+ .queryParam("cq", "pubPlace=München")
+ .queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -36,8 +40,11 @@
}
@Test
- public void testStatisticsWithMultipleCq() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung").queryParam("cq", "corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithMultipleCq ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung")
+ .queryParam("cq", "corpusSigle=GOE").request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -49,8 +56,12 @@
}
@Test
- public void testStatisticsWithMultipleCorpusQuery() throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie").queryParam("corpusQuery", "corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithMultipleCorpusQuery ()
+ throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "textType=Autobiographie")
+ .queryParam("corpusQuery", "corpusSigle=GOE").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -59,6 +70,7 @@
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "Parameter corpusQuery is deprecated in favor of cq.");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
index 60b6550..610646c0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
@@ -43,8 +43,11 @@
// EM: The API is disabled
@Disabled
@Test
- public void testGetJSONQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().method("GET");
+ public void testGetJSONQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -58,13 +61,17 @@
// EM: The API is disabled
@Disabled
@Test
- public void testbuildAndPostQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").request().method("GET");
+ public void testbuildAndPostQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- response = target().path(API_VERSION).path("search").request().post(Entity.json(query));
+ response = target().path(API_VERSION).path("search").request()
+ .post(Entity.json(query));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String matches = response.readEntity(String.class);
JsonNode match_node = JsonUtils.readTree(matches);
@@ -72,17 +79,21 @@
}
@Test
- public void testApiWelcomeMessage() {
+ public void testApiWelcomeMessage () {
Response response = target().path(API_VERSION).path("").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String message = response.readEntity(String.class);
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
assertEquals(message, config.getApiWelcomeMessage());
}
@Test
- public void testQueryGet() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testQueryGet () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -94,8 +105,11 @@
}
@Test
- public void testQueryFailure() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").queryParam("count", "13").request().get();
+ public void testQueryFailure () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das").queryParam("ql", "poliqarp")
+ .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
+ .queryParam("count", "13").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -108,8 +122,11 @@
}
@Test
- public void testFoundryRewrite() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testFoundryRewrite () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -121,10 +138,11 @@
// EM: The API is disabled
@Test
@Disabled
- public void testQueryPost() throws KustvaktException {
+ public void testQueryPost () throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=das]", "poliqarp");
- Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ Response response = target().path(API_VERSION).path("search").request()
+ .post(Entity.json(s.toJSON()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -134,71 +152,105 @@
}
@Test
- public void testParameterField() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", "author,docSigle").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testParameterField () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author,docSigle")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
assertEquals(node.at("/query/wrap/layer").asText(), "orth");
assertNotEquals(0, node.at("/matches").size());
- assertEquals(node.at("/meta/fields").toString(), "[\"author\",\"docSigle\"]");
+ assertEquals(node.at("/meta/fields").toString(),
+ "[\"author\",\"docSigle\"]");
}
@Test
- public void testMatchInfoGetWithoutSpans() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "*").queryParam("spans", "false").request().get();
+ public void testMatchInfoGetWithoutSpans () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
+ .queryParam("foundry", "*").queryParam("spans", "false")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
- assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/matchID").asText(),
+ "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
}
@Test
- public void testMatchInfoGetWithoutHighlights() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "xy").queryParam("spans", "false").request().get();
+ public void testMatchInfoGetWithoutHighlights () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
+ .queryParam("foundry", "xy").queryParam("spans", "false")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals(node.at("/snippet").asText(), "<span class=\"context-left\"></span><span class=\"match\">der alte freie Weg nach Mainz war gesperrt, ich mußte über die Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark> auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span><span class=\"context-right\"></span>");
+ assertEquals(node.at("/snippet").asText(),
+ "<span class=\"context-left\"></span><span class=\"match\">der alte freie Weg nach Mainz war gesperrt, ich mußte über die Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark> auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span><span class=\"context-right\"></span>");
assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
- assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/matchID").asText(),
+ "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
}
@Test
- public void testMatchInfoWithoutExtension() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42").queryParam("foundry", "-").queryParam("spans", "false").queryParam("expand", "false").request().get();
+ public void testMatchInfoWithoutExtension () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42")
+ .queryParam("foundry", "-").queryParam("spans", "false")
+ .queryParam("expand", "false").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
- assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
- assertEquals(node.at("/snippet").asText(), "<span class=\"context-left\"><span class=\"more\"></span></span><span class=\"match\"><mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark></span><span class=\"context-right\"><span class=\"more\"></span></span>");
+ assertEquals(node.at("/matchID").asText(),
+ "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/snippet").asText(),
+ "<span class=\"context-left\"><span class=\"more\"></span></span><span class=\"match\"><mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark></span><span class=\"context-right\"><span class=\"more\"></span></span>");
assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
}
@Test
- public void testMatchInfoGetWithHighlights() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "xy").queryParam("spans", "false").queryParam("hls", "true").request().get();
+ public void testMatchInfoGetWithHighlights () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
+ .queryParam("foundry", "xy").queryParam("spans", "false")
+ .queryParam("hls", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
- assertEquals("<span class=\"context-left\"></span><span class=\"match\">" + "der alte freie Weg nach Mainz war gesperrt, ich mußte über die " + "Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; " + "<mark class=\"class-5 level-0\">der <mark class=\"class-2 level-1\">" + "Ort ist sehr zerschossen; dann</mark> über die Schiffbrücke</mark></mark> " + "auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem " + "zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span>" + "<span class=\"context-right\"></span>", node.at("/snippet").asText());
- assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(
+ "<span class=\"context-left\"></span><span class=\"match\">"
+ + "der alte freie Weg nach Mainz war gesperrt, ich mußte über die "
+ + "Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; "
+ + "<mark class=\"class-5 level-0\">der <mark class=\"class-2 level-1\">"
+ + "Ort ist sehr zerschossen; dann</mark> über die Schiffbrücke</mark></mark> "
+ + "auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem "
+ + "zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span>"
+ + "<span class=\"context-right\"></span>",
+ node.at("/snippet").asText());
+ assertEquals(node.at("/matchID").asText(),
+ "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
}
@Test
- public void testMatchInfoGet2() throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46/matchInfo").queryParam("foundry", "*").request().get();
+ public void testMatchInfoGet2 () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("corpus/GOE/AGA/01784/p36-46/matchInfo")
+ .queryParam("foundry", "*").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -210,16 +262,27 @@
// EM: The API is disabled
@Disabled
@Test
- public void testCollectionQueryParameter() throws KustvaktException {
- Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", "author, docSigle").queryParam("context", "sentence").queryParam("count", "13").queryParam("cq", "textClass=Politik & corpus=WPD").request().method("GET");
+ public void testCollectionQueryParameter () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author, docSigle")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .queryParam("cq", "textClass=Politik & corpus=WPD").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
assertEquals(node.at("/query/wrap/layer").asText(), "orth");
- assertEquals(node.at("/collection/operands/0/value").asText(), "Politik");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "Politik");
assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
- response = target().path(API_VERSION).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").request().get();
+ response = target().path(API_VERSION).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").request()
+ .get();
// String version =
// LucenePackage.get().getImplementationVersion();;
// System.out.println("VERSION "+ version);
@@ -229,22 +292,33 @@
node = JsonUtils.readTree(query);
assertNotNull(node);
assertEquals(node.at("/query/wrap/layer").asText(), "orth");
- assertEquals(node.at("/collection/operands/0/value").asText(), "Politik");
+ assertEquals(node.at("/collection/operands/0/value").asText(),
+ "Politik");
assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
}
@Test
- public void testTokenRetrieval() throws KustvaktException {
- Response response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105/").request().method("GET");
+ public void testTokenRetrieval () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("/corpus/GOE/AGA/01784/p104-105/").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String resp = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(resp);
assertTrue(node.at("/hasSnippet").asBoolean());
assertFalse(node.at("/hasTokens").asBoolean());
assertTrue(node.at("/tokens").isMissingNode());
- assertEquals("<span class=\"context-left\"><span class=\"more\"></span></span>" + "<span class=\"match\"><mark>die</mark></span>" + "<span class=\"context-right\"><span class=\"more\"></span></span>", node.at("/snippet").asText());
+ assertEquals(
+ "<span class=\"context-left\"><span class=\"more\"></span></span>"
+ + "<span class=\"match\"><mark>die</mark></span>"
+ + "<span class=\"context-right\"><span class=\"more\"></span></span>",
+ node.at("/snippet").asText());
// Tokens
- response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105").queryParam("show-snippet", "false").queryParam("show-tokens", "true").queryParam("expand", "false").request().method("GET");
+ response = target().path(API_VERSION)
+ .path("/corpus/GOE/AGA/01784/p104-105")
+ .queryParam("show-snippet", "false")
+ .queryParam("show-tokens", "true").queryParam("expand", "false")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
resp = response.readEntity(String.class);
node = JsonUtils.readTree(resp);
@@ -256,8 +330,9 @@
}
@Test
- public void testMetaFields() throws KustvaktException {
- Response response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784").request().method("GET");
+ public void testMetaFields () throws KustvaktException {
+ Response response = target().path(API_VERSION)
+ .path("/corpus/GOE/AGA/01784").request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String resp = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(resp);
@@ -276,7 +351,8 @@
break;
case "author":
assertEquals(field.at("/type").asText(), "type:text");
- assertEquals(field.at("/value").asText(), "Goethe, Johann Wolfgang von");
+ assertEquals(field.at("/value").asText(),
+ "Goethe, Johann Wolfgang von");
checkC++;
break;
case "docSigle":
@@ -286,7 +362,8 @@
break;
case "docTitle":
assertEquals(field.at("/type").asText(), "type:text");
- assertEquals(field.at("/value").asText(), "Goethe: Autobiographische Schriften II, (1817-1825, 1832)");
+ assertEquals(field.at("/value").asText(),
+ "Goethe: Autobiographische Schriften II, (1817-1825, 1832)");
checkC++;
break;
case "pubDate":
@@ -294,32 +371,37 @@
assertEquals(1982, field.at("/value").asInt());
checkC++;
break;
- }
- ;
- }
- ;
+ };
+ };
assertEquals(5, checkC);
}
@Test
- public void testSearchWithoutVersion() throws KustvaktException {
- Response response = target().path("api").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWithoutVersion () throws KustvaktException {
+ Response response = target().path("api").path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
assertEquals(location.getPath(), "/api/v1.0/search");
}
@Test
- public void testSearchWrongVersion() throws KustvaktException {
- Response response = target().path("api").path("v0.2").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWrongVersion () throws KustvaktException {
+ Response response = target().path("api").path("v0.2").path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
assertEquals(location.getPath(), "/api/v1.0/search");
}
@Test
- public void testSearchWithIP() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testSearchWithIP () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
+ .request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -327,8 +409,13 @@
}
@Test
- public void testSearchWithAuthorizationHeader() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("test", "pwd")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ public void testSearchWithAuthorizationHeader () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
+ .request()
+ .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ .createBasicAuthorizationHeaderValue("test", "pwd"))
+ .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -336,8 +423,10 @@
}
@Test
- public void testSearchPublicMetadata() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadata () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -345,45 +434,61 @@
}
@Test
- public void testSearchPublicMetadataWithCustomFields() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithCustomFields ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author,title")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/matches/0/snippet").isMissingNode());
- assertEquals(node.at("/matches/0/author").asText(), "Goethe, Johann Wolfgang von");
- assertEquals(node.at("/matches/0/title").asText(), "Italienische Reise");
+ assertEquals(node.at("/matches/0/author").asText(),
+ "Goethe, Johann Wolfgang von");
+ assertEquals(node.at("/matches/0/title").asText(),
+ "Italienische Reise");
// assertEquals(3, node.at("/matches/0").size());
}
@Test
- public void testSearchPublicMetadataWithNonPublicField() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title,snippet").queryParam("access-rewrite-disabled", "true").request().get();
+ public void testSearchPublicMetadataWithNonPublicField ()
+ throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
+ .queryParam("fields", "author,title,snippet")
+ .queryParam("access-rewrite-disabled", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "The requested non public fields are ignored");
+ assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED,
+ node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "The requested non public fields are ignored");
assertEquals(node.at("/warnings/0/2").asText(), "snippet");
}
@Test
- public void testSearchWithInvalidPage() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "0").request().get();
+ public void testSearchWithInvalidPage () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
+ .queryParam("page", "0").request().get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT,
+ node.at("/errors/0/0").asInt());
assertEquals(node.at("/errors/0/1").asText(), "page must start from 1");
}
@Test
- public void testCloseIndex() throws IOException, KustvaktException {
+ public void testCloseIndex () throws IOException, KustvaktException {
searchKrill.getStatistics(null);
assertEquals(true, searchKrill.getIndex().isReaderOpen());
Form form = new Form();
form.param("token", "secret");
- Response response = target().path(API_VERSION).path("index").path("close").request().post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("index")
+ .path("close").request().post(Entity.form(form));
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(false, searchKrill.getIndex().isReaderOpen());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
index f747934..704ae5f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
@@ -45,29 +45,43 @@
private String glemmUri = "http://localhost:" + port + "/glemm";
- public LiteSearchPipeTest() throws IOException {
- pipeJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/test-pipes.jsonld"), StandardCharsets.UTF_8);
- pipeWithParamJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/with-param.jsonld"), StandardCharsets.UTF_8);
+ public LiteSearchPipeTest () throws IOException {
+ pipeJson = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "pipe-output/test-pipes.jsonld"),
+ StandardCharsets.UTF_8);
+ pipeWithParamJson = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "pipe-output/with-param.jsonld"),
+ StandardCharsets.UTF_8);
}
@BeforeEach
- public void startMockServer() {
+ public void startMockServer () {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
@AfterEach
- public void stopMockServer() {
+ public void stopMockServer () {
mockServer.stop();
}
@Test
- public void testMockServer() throws IOException {
- mockClient.reset().when(request().withMethod("POST").withPath("/test").withHeader(new Header("Content-Type", "application/json; charset=utf-8"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody("{test}").withStatusCode(200));
+ public void testMockServer () throws IOException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/test")
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody("{test}").withStatusCode(200));
URL url = new URL("http://localhost:" + port + "/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ connection.setRequestProperty("Content-Type",
+ "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
String json = "{\"name\" : \"dory\"}";
@@ -76,14 +90,27 @@
os.write(input, 0, input.length);
}
assertEquals(200, connection.getResponseCode());
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(connection.getInputStream(), "utf-8"));
assertEquals(br.readLine(), "{test}");
}
@Test
- public void testSearchWithPipes() throws IOException, KustvaktException, URISyntaxException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ public void testSearchWithPipes ()
+ throws IOException, KustvaktException, URISyntaxException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -99,20 +126,44 @@
}
@Test
- public void testSearchWithUrlEncodedPipes() throws IOException, KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ public void testSearchWithUrlEncodedPipes ()
+ throws IOException, KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
glemmUri = URLEncoder.encode(glemmUri, "utf-8");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri).request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithMultiplePipes() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withQueryStringParameter("param").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeWithParamJson).withStatusCode(200));
+ public void testSearchWithMultiplePipes () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withQueryStringParameter("param").withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeWithParamJson).withStatusCode(200));
String glemmUri2 = glemmUri + "?param=blah";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + "," + glemmUri2).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri + "," + glemmUri2).request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -120,9 +171,13 @@
}
@Test
- public void testSearchWithUnknownURL() throws IOException, KustvaktException {
- String url = target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url).request().get();
+ public void testSearchWithUnknownURL ()
+ throws IOException, KustvaktException {
+ String url = target().getUri().toString() + API_VERSION
+ + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", url).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -131,8 +186,10 @@
}
@Test
- public void testSearchWithUnknownHost() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://glemm").request().get();
+ public void testSearchWithUnknownHost () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", "http://glemm").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -141,21 +198,30 @@
}
@Test
- public void testSearchUnsupportedMediaType() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/non-json-pipe")).respond(response().withStatusCode(415));
+ public void testSearchUnsupportedMediaType () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/non-json-pipe"))
+ .respond(response().withStatusCode(415));
String pipeUri = "http://localhost:" + port + "/non-json-pipe";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/3").asText(), "415 Unsupported Media Type");
+ assertEquals(node.at("/warnings/0/3").asText(),
+ "415 Unsupported Media Type");
}
@Test
- public void testSearchWithMultiplePipeWarnings() throws KustvaktException {
- String url = target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url + "," + "http://glemm").request().get();
+ public void testSearchWithMultiplePipeWarnings () throws KustvaktException {
+ String url = target().getUri().toString() + API_VERSION
+ + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", url + "," + "http://glemm").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -169,37 +235,73 @@
}
@Test
- public void testSearchWithInvalidJsonResponse() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/invalid-response").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("{blah:}").withStatusCode(200).withHeaders(new Header("Content-Type", "application/json; charset=utf-8")));
+ public void testSearchWithInvalidJsonResponse () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/invalid-response")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response().withBody("{blah:}").withStatusCode(200)
+ .withHeaders(new Header("Content-Type",
+ "application/json; charset=utf-8")));
String pipeUri = "http://localhost:" + port + "/invalid-response";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithPlainTextResponse() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/plain-text").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("blah").withStatusCode(200));
+ public void testSearchWithPlainTextResponse () throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/plain-text")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response().withBody("blah").withStatusCode(200));
String pipeUri = "http://localhost:" + port + "/plain-text";
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithMultipleAndUnknownPipes() throws KustvaktException {
- mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://unknown" + "," + glemmUri).request().get();
+ public void testSearchWithMultipleAndUnknownPipes ()
+ throws KustvaktException {
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/glemm")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", "http://unknown" + "," + glemmUri)
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
assertTrue(node.at("/warnings").isMissingNode());
- response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + ",http://unknown").request().get();
+ response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("pipes", glemmUri + ",http://unknown").request()
+ .get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
index 75b9920..fb78508 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
@@ -18,8 +18,12 @@
public class LiteSearchTokenSnippetTest extends LiteJerseyTest {
@Test
- public void testSearchWithTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchWithTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("show-tokens", "true")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -31,8 +35,12 @@
}
@Test
- public void testSearchWithoutTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "false").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchWithoutTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("show-tokens", "false")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
@@ -42,8 +50,13 @@
}
@Test
- public void testSearchPublicMetadataWithTokens() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ public void testSearchPublicMetadataWithTokens () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
+ .queryParam("access-rewrite-disabled", "true")
+ .queryParam("show-tokens", "true")
+ .queryParam("context", "sentence").queryParam("count", "13")
+ .request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
index 65e57c3..4314ef0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
@@ -21,10 +21,13 @@
public class LiteStatisticControllerTest extends LiteJerseyTest {
@Test
- public void testStatisticsWithCq() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithCq () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(2, node.at("/documents").asInt());
@@ -35,8 +38,12 @@
}
@Test
- public void testStatisticsWithCqAndCorpusQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithCqAndCorpusQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
+ .queryParam("corpusQuery",
+ "textType=Autobiographie & corpusSigle=GOE")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -48,8 +55,11 @@
}
@Test
- public void testStatisticsWithCorpusQuery() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ public void testStatisticsWithCorpusQuery () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery",
+ "textType=Autobiographie & corpusSigle=GOE")
+ .request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -58,12 +68,14 @@
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
- assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
+ assertEquals(node.at("/warnings/0/1").asText(),
+ "Parameter corpusQuery is deprecated in favor of cq.");
}
@Test
- public void testEmptyStatistics() throws KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "").request().method("GET");
+ public void testEmptyStatistics () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .queryParam("corpusQuery", "").request().method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
@@ -71,7 +83,8 @@
assertEquals(665842, node.at("/tokens").asInt());
assertEquals(25074, node.at("/sentences").asInt());
assertEquals(772, node.at("/paragraphs").asInt());
- response = target().path(API_VERSION).path("statistics").request().method("GET");
+ response = target().path(API_VERSION).path("statistics").request()
+ .method("GET");
assertEquals(Status.OK.getStatusCode(), response.getStatus());
query = response.readEntity(String.class);
node = JsonUtils.readTree(query);
@@ -82,11 +95,19 @@
}
@Test
- public void testGetStatisticsWithKoralQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : {\"@type\": " + "\"koral:doc\", \"key\": \"availability\", \"match\": " + "\"match:eq\", \"type\": \"type:regex\", \"value\": " + "\"CC-BY.*\"} }"));
+ public void testGetStatisticsWithKoralQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{ \"collection\" : {\"@type\": "
+ + "\"koral:doc\", \"key\": \"availability\", \"match\": "
+ + "\"match:eq\", \"type\": \"type:regex\", \"value\": "
+ + "\"CC-BY.*\"} }"));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
- assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"),
+ "Wes8Bd4h1OypPqbWF5njeQ==");
JsonNode node = JsonUtils.readTree(ent);
assertEquals(2, node.at("/documents").asInt());
assertEquals(72770, node.at("/tokens").asInt());
@@ -95,28 +116,42 @@
}
@Test
- public void testGetStatisticsWithEmptyCollection() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{}"));
+ public void testGetStatisticsWithEmptyCollection ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{}"));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/errors/0/0").asInt(), de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
- assertEquals(node.at("/errors/0/1").asText(), "Collection is not found");
+ assertEquals(node.at("/errors/0/0").asInt(),
+ de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Collection is not found");
}
@Test
- public void testGetStatisticsWithIncorrectJson() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : }"));
+ public void testGetStatisticsWithIncorrectJson ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .post(Entity.json("{ \"collection\" : }"));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals(node.at("/errors/0/1").asText(), "Failed deserializing json object: { \"collection\" : }");
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED,
+ node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(),
+ "Failed deserializing json object: { \"collection\" : }");
}
@Test
- public void testGetStatisticsWithoutKoralQuery() throws IOException, KustvaktException {
- Response response = target().path(API_VERSION).path("statistics").request().post(Entity.json(""));
+ public void testGetStatisticsWithoutKoralQuery ()
+ throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics")
+ .request().post(Entity.json(""));
String ent = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
index fa72cee..81c2430 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
@@ -42,26 +42,41 @@
private String endpointURL = "http://localhost:" + port + "/searchEndpoint";
- public SearchNetworkEndpointTest() throws IOException {
- searchResult = IOUtils.toString(ClassLoader.getSystemResourceAsStream("network-output/search-result.jsonld"), StandardCharsets.UTF_8);
+ public SearchNetworkEndpointTest () throws IOException {
+ searchResult = IOUtils.toString(
+ ClassLoader.getSystemResourceAsStream(
+ "network-output/search-result.jsonld"),
+ StandardCharsets.UTF_8);
}
@BeforeEach
- public void startMockServer() {
+ public void startMockServer () {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
@AfterEach
- public void stopMockServer() {
+ public void stopMockServer () {
mockServer.stop();
}
@Test
- public void testSearchNetwork() throws IOException, KustvaktException, URISyntaxException {
+ public void testSearchNetwork ()
+ throws IOException, KustvaktException, URISyntaxException {
config.setNetworkEndpointURL(endpointURL);
- mockClient.reset().when(request().withMethod("POST").withPath("/searchEndpoint").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(searchResult).withStatusCode(200));
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ mockClient.reset()
+ .when(request().withMethod("POST").withPath("/searchEndpoint")
+ .withHeaders(
+ new Header("Content-Type",
+ "application/json; charset=utf-8"),
+ new Header("Accept", "application/json")))
+ .respond(response()
+ .withHeader(new Header("Content-Type",
+ "application/json; charset=utf-8"))
+ .withBody(searchResult).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -69,22 +84,29 @@
}
@Test
- public void testSearchWithUnknownURL() throws IOException, KustvaktException {
+ public void testSearchWithUnknownURL ()
+ throws IOException, KustvaktException {
config.setNetworkEndpointURL("http://localhost:1040/search");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testSearchWithUnknownHost() throws KustvaktException {
+ public void testSearchWithUnknownHost () throws KustvaktException {
config.setNetworkEndpointURL("http://search.com");
- Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
+ node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
diff --git a/full/src/test/resources/test-config-icc.xml b/full/src/test/resources/test-config-icc.xml
index 9d65017..d418f05 100644
--- a/full/src/test/resources/test-config-icc.xml
+++ b/full/src/test/resources/test-config-icc.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
@@ -15,7 +18,8 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
- <context:component-scan base-package="de.ids_mannheim.korap" />
+ <context:component-scan
+ base-package="de.ids_mannheim.korap" />
<context:annotation-config />
<bean id="props"
@@ -44,17 +48,12 @@
</array>
</property>
</bean>
-
- <!--
- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
- p:cacheManager-ref='ehcache' />
- <bean id='ehcache'
- class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
- p:configLocation='classpath:ehcache.xml' p:shared='true' />
- -->
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- lazy-init="true">
+ <!-- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
+ p:cacheManager-ref='ehcache' /> <bean id='ehcache' class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
+ p:configLocation='classpath:ehcache.xml' p:shared='true' /> -->
+ <bean id="dataSource"
+ class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true">
<!-- <property name="driverClassName" value="${jdbc.driverClassName}" /> -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
@@ -86,7 +85,8 @@
</property>
</bean>
- <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
+ <bean id="c3p0DataSource"
+ class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
@@ -99,21 +99,24 @@
</bean>
<!-- to configure database for sqlite, mysql, etc. migrations -->
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
<!-- drop existing tables and create new tables -->
<property name="validateOnMigrate" value="true" />
<property name="cleanOnValidationError" value="true" />
<property name="baselineOnMigrate" value="false" />
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<property name="dataSource" ref="sqliteDataSource" />
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
-
+
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
@@ -129,7 +132,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -150,8 +154,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -161,75 +167,95 @@
<!-- Data access objects -->
<bean id="adminDao" class="de.ids_mannheim.korap.dao.AdminDaoImpl" />
- <bean id="resourceDao" class="de.ids_mannheim.korap.dao.ResourceDao" />
- <bean id="accessScopeDao" class="de.ids_mannheim.korap.oauth2.dao.AccessScopeDao" />
- <bean id="authorizationDao" class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
-
+ <bean id="resourceDao"
+ class="de.ids_mannheim.korap.dao.ResourceDao" />
+ <bean id="accessScopeDao"
+ class="de.ids_mannheim.korap.oauth2.dao.AccessScopeDao" />
+ <bean id="authorizationDao"
+ class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
+
<!-- Services -->
- <bean id="scopeService" class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
-
-
+ <bean id="scopeService"
+ class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
+
+
<!-- Controller -->
-
-
+
+
<!-- props are injected from default-config.xml -->
- <bean id="kustvakt_config" class="de.ids_mannheim.korap.config.FullConfiguration">
+ <bean id="kustvakt_config"
+ class="de.ids_mannheim.korap.config.FullConfiguration">
<constructor-arg name="properties" ref="props" />
</bean>
- <bean id="initializator" class="de.ids_mannheim.korap.init.Initializator"
+ <bean id="initializator"
+ class="de.ids_mannheim.korap.init.Initializator"
init-method="initTest">
</bean>
<!-- Krill -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
<!-- Validator -->
- <bean id="validator" class="de.ids_mannheim.korap.validator.ApacheValidator"/>
-
+ <bean id="validator"
+ class="de.ids_mannheim.korap.validator.ApacheValidator" />
+
<!-- URLValidator -->
- <bean id="redirectURIValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="redirectURIValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" index="0" />
- <constructor-arg index="1" type="long"
- value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
- T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}"/>
+ <constructor-arg index="1" type="long"
+ value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
+ T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}" />
</bean>
- <bean id="urlValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="urlValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" />
</bean>
<!-- Rewrite -->
- <bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
- <bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
- <bean id="collectionCleanRewrite" class="de.ids_mannheim.korap.rewrite.CollectionCleanRewrite"/>
- <bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
- <bean id="collectionConstraint" class="de.ids_mannheim.korap.rewrite.CollectionConstraint"/>
- <bean id="queryReferenceRewrite" class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite"/>
-
+ <bean id="foundryRewrite"
+ class="de.ids_mannheim.korap.rewrite.FoundryRewrite" />
+ <bean id="collectionRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionRewrite" />
+ <bean id="collectionCleanRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionCleanRewrite" />
+ <bean id="virtualCorpusRewrite"
+ class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite" />
+ <bean id="collectionConstraint"
+ class="de.ids_mannheim.korap.rewrite.CollectionConstraint" />
+ <bean id="queryReferenceRewrite"
+ class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite" />
+
<util:list id="rewriteTasks"
value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
- <!-- <ref bean="collectionConstraint" />
- <ref bean="collectionCleanRewrite" /> -->
+ <!-- <ref bean="collectionConstraint" /> <ref bean="collectionCleanRewrite"
+ /> -->
<ref bean="foundryRewrite" />
<!-- <ref bean="collectionRewrite" /> -->
<ref bean="virtualCorpusRewrite" />
<ref bean="queryReferenceRewrite" />
</util:list>
-
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
- <constructor-arg ref="rewriteTasks"/>
+
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+ <constructor-arg ref="rewriteTasks" />
</bean>
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- OAuth -->
- <bean id="oauth2ResponseHandler" class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
+ <bean id="oauth2ResponseHandler"
+ class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
</bean>
- <bean name="kustvakt_encryption" class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
+ <bean name="kustvakt_encryption"
+ class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
<constructor-arg ref="kustvakt_config" />
</bean>
@@ -251,7 +277,8 @@
<!-- specify type for constructor argument -->
<bean id="authenticationManager"
class="de.ids_mannheim.korap.authentication.KustvaktAuthenticationManager">
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
<constructor-arg ref="kustvakt_config" />
<!-- inject authentication providers to use -->
@@ -266,7 +293,8 @@
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
- <tx:method name="get*" read-only="true" rollback-for="KorAPException" />
+ <tx:method name="get*" read-only="true"
+ rollback-for="KorAPException" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="KorAPException" />
</tx:attributes>
@@ -287,11 +315,13 @@
</bean>
<!-- mail -->
- <bean id="authenticator" class="de.ids_mannheim.korap.service.MailAuthenticator">
+ <bean id="authenticator"
+ class="de.ids_mannheim.korap.service.MailAuthenticator">
<constructor-arg index="0" value="${mail.username}" />
<constructor-arg index="1" value="${mail.password}" />
</bean>
- <bean id="smtpSession" class="jakarta.mail.Session" factory-method="getInstance">
+ <bean id="smtpSession" class="jakarta.mail.Session"
+ factory-method="getInstance">
<constructor-arg index="0">
<props>
<prop key="mail.smtp.submitter">${mail.username}</prop>
@@ -304,10 +334,12 @@
</constructor-arg>
<constructor-arg index="1" ref="authenticator" />
</bean>
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
+ <bean id="mailSender"
+ class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session" ref="smtpSession" />
</bean>
- <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine">
+ <bean id="velocityEngine"
+ class="org.apache.velocity.app.VelocityEngine">
<constructor-arg index="0">
<props>
<prop key="resource.loader">class</prop>
diff --git a/full/src/test/resources/test-config-lite.xml b/full/src/test/resources/test-config-lite.xml
index 96ac3bf..5de7bd6 100644
--- a/full/src/test/resources/test-config-lite.xml
+++ b/full/src/test/resources/test-config-lite.xml
@@ -1,7 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
@@ -10,8 +12,9 @@
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
-
- <context:component-scan base-package="
+
+ <context:component-scan
+ base-package="
de.ids_mannheim.korap.core.service,
de.ids_mannheim.korap.core.web,
de.ids_mannheim.korap.web.filter,
@@ -44,14 +47,16 @@
</property>
</bean>
- <bean id="config" class="de.ids_mannheim.korap.config.KustvaktConfiguration">
- <constructor-arg index="0" name="properties" ref="properties" />
+ <bean id="config"
+ class="de.ids_mannheim.korap.config.KustvaktConfiguration">
+ <constructor-arg index="0" name="properties"
+ ref="properties" />
</bean>
<!-- Database -->
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- lazy-init="true">
+ <bean id="dataSource"
+ class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true">
<!-- <property name="driverClassName" value="${jdbc.driverClassName}" /> -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
@@ -66,7 +71,8 @@
<bean id="sqliteDataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
lazy-init="true">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
+ <property name="driverClassName"
+ value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
@@ -82,17 +88,20 @@
</property>
</bean>
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
- <property name="baselineOnMigrate" value="true" />
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <property name="baselineOnMigrate" value="true" />
<!-- <property name="validateOnMigrate" value="false" /> -->
<!-- <property name="cleanOnValidationError" value="true" /> -->
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<property name="dataSource" ref="dataSource" />
<property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
<bean id="entityManagerFactory"
@@ -107,7 +116,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -127,8 +137,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -141,10 +153,11 @@
</bean>
<!-- Search Engine -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
-
+
<!-- Filters -->
<!-- <bean id="APIVersionFilter" class="de.ids_mannheim.korap.web.APIVersionFilter"
@@ -154,37 +167,42 @@
class="de.ids_mannheim.korap.authentication.DummyAuthenticationManager" />
<!-- Response handler -->
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- Controllers -->
- <!-- added via component-scan
- <bean id="annotationController"
- class="de.ids_mannheim.korap.web.controller.AnnotationController" />
- <bean id="searchController" class="de.ids_mannheim.korap.web.controller.SearchController" />
- <bean id="statisticController"
- class="de.ids_mannheim.korap.web.controller.StatisticController" />
- -->
+ <!-- added via component-scan <bean id="annotationController" class="de.ids_mannheim.korap.web.controller.AnnotationController"
+ /> <bean id="searchController" class="de.ids_mannheim.korap.web.controller.SearchController"
+ /> <bean id="statisticController" class="de.ids_mannheim.korap.web.controller.StatisticController"
+ /> -->
<!-- Services -->
<bean id="scopeService"
class="de.ids_mannheim.korap.oauth2.service.DummyOAuth2ScopeServiceImpl" />
<!-- DAO -->
- <bean id="adminDao" class="de.ids_mannheim.korap.dao.DummyAdminDaoImpl" />
- <bean id="annotationDao" class="de.ids_mannheim.korap.dao.AnnotationDao" />
+ <bean id="adminDao"
+ class="de.ids_mannheim.korap.dao.DummyAdminDaoImpl" />
+ <bean id="annotationDao"
+ class="de.ids_mannheim.korap.dao.AnnotationDao" />
<!-- DTO Converter -->
- <bean id="annotationConverter" class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
+ <bean id="annotationConverter"
+ class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
<!-- Rewrite -->
- <bean id="layerMapper" class="de.ids_mannheim.korap.rewrite.LayerMapper" />
- <bean id="foundryInject" class="de.ids_mannheim.korap.rewrite.FoundryInject" />
+ <bean id="layerMapper"
+ class="de.ids_mannheim.korap.rewrite.LayerMapper" />
+ <bean id="foundryInject"
+ class="de.ids_mannheim.korap.rewrite.FoundryInject" />
- <util:list id="rewriteTasks" value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+ <util:list id="rewriteTasks"
+ value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
<ref bean="foundryInject" />
</util:list>
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
<constructor-arg ref="rewriteTasks" />
</bean>
</beans>
\ No newline at end of file
diff --git a/full/src/test/resources/test-config.xml b/full/src/test/resources/test-config.xml
index b3ae6f3..d1dd61c 100644
--- a/full/src/test/resources/test-config.xml
+++ b/full/src/test/resources/test-config.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
@@ -15,7 +18,8 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
- <context:component-scan base-package="de.ids_mannheim.korap" />
+ <context:component-scan
+ base-package="de.ids_mannheim.korap" />
<context:annotation-config />
<bean id="props"
@@ -45,15 +49,12 @@
</property>
</bean>
- <!-- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
- p:cacheManager-ref='ehcache' />
-
- <bean id='ehcache'
- class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
+ <!-- <bean id='cacheManager' class='org.springframework.cache.ehcache.EhCacheCacheManager'
+ p:cacheManager-ref='ehcache' /> <bean id='ehcache' class='org.springframework.cache.ehcache.EhCacheManagerFactoryBean'
p:configLocation='classpath:ehcache.xml' p:shared='true' /> -->
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- lazy-init="true">
+ <bean id="dataSource"
+ class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true">
<!-- <property name="driverClassName" value="${jdbc.driverClassName}" /> -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
@@ -85,7 +86,8 @@
</property>
</bean>
- <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
+ <bean id="c3p0DataSource"
+ class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
@@ -98,21 +100,24 @@
</bean>
<!-- to configure database for sqlite, mysql, etc. migrations -->
- <bean id="flywayConfig" class="org.flywaydb.core.api.configuration.ClassicConfiguration">
+ <bean id="flywayConfig"
+ class="org.flywaydb.core.api.configuration.ClassicConfiguration">
<!-- drop existing tables and create new tables -->
<property name="validateOnMigrate" value="true" />
<property name="cleanOnValidationError" value="true" />
<property name="baselineOnMigrate" value="false" />
- <property name="locations" value="#{'${jdbc.schemaPath}'.split(',')}"/>
+ <property name="locations"
+ value="#{'${jdbc.schemaPath}'.split(',')}" />
<!-- <property name="dataSource" ref="sqliteDataSource" /> -->
<property name="dataSource" ref="dataSource" />
<property name="outOfOrder" value="true" />
</bean>
-
- <bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
- <constructor-arg ref="flywayConfig"/>
+
+ <bean id="flyway" class="org.flywaydb.core.Flyway"
+ init-method="migrate">
+ <constructor-arg ref="flywayConfig" />
</bean>
-
+
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
@@ -128,7 +133,8 @@
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="databasePlatform" value="${hibernate.dialect}" />
+ <property name="databasePlatform"
+ value="${hibernate.dialect}" />
</bean>
</property>
<property name="jpaProperties">
@@ -149,8 +155,10 @@
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="entityManagerFactory" />
+ <bean id="transactionManager"
+ class="org.springframework.orm.jpa.JpaTransactionManager">
+ <property name="entityManagerFactory"
+ ref="entityManagerFactory" />
</bean>
<bean id="transactionTemplate"
@@ -160,71 +168,91 @@
<!-- Data access objects -->
<bean id="adminDao" class="de.ids_mannheim.korap.dao.AdminDaoImpl" />
- <bean id="resourceDao" class="de.ids_mannheim.korap.dao.ResourceDao" />
- <bean id="accessScopeDao" class="de.ids_mannheim.korap.oauth2.dao.AccessScopeDao" />
- <bean id="authorizationDao" class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
-
+ <bean id="resourceDao"
+ class="de.ids_mannheim.korap.dao.ResourceDao" />
+ <bean id="accessScopeDao"
+ class="de.ids_mannheim.korap.oauth2.dao.AccessScopeDao" />
+ <bean id="authorizationDao"
+ class="de.ids_mannheim.korap.oauth2.dao.CachedAuthorizationDaoImpl" />
+
<!-- Services -->
- <bean id="scopeService" class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
-
+ <bean id="scopeService"
+ class="de.ids_mannheim.korap.oauth2.service.OAuth2ScopeServiceImpl" />
+
<!-- props are injected from default-config.xml -->
- <bean id="kustvakt_config" class="de.ids_mannheim.korap.config.FullConfiguration">
+ <bean id="kustvakt_config"
+ class="de.ids_mannheim.korap.config.FullConfiguration">
<constructor-arg name="properties" ref="props" />
</bean>
- <bean id="initializator" class="de.ids_mannheim.korap.init.Initializator"
+ <bean id="initializator"
+ class="de.ids_mannheim.korap.init.Initializator"
init-method="initTest">
</bean>
<!-- Krill -->
- <bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+ <bean id="search_krill"
+ class="de.ids_mannheim.korap.web.SearchKrill">
<constructor-arg value="${krill.indexDir}" />
</bean>
<!-- Validator -->
- <bean id="validator" class="de.ids_mannheim.korap.validator.ApacheValidator"/>
-
+ <bean id="validator"
+ class="de.ids_mannheim.korap.validator.ApacheValidator" />
+
<!-- URLValidator -->
- <bean id="redirectURIValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="redirectURIValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" index="0" />
- <constructor-arg index="1" type="long"
- value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
- T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}"/>
+ <constructor-arg index="1" type="long"
+ value="#{T(org.apache.commons.validator.routines.UrlValidator).ALLOW_LOCAL_URLS +
+ T(org.apache.commons.validator.routines.UrlValidator).NO_FRAGMENTS}" />
</bean>
- <bean id="urlValidator" class="org.apache.commons.validator.routines.UrlValidator">
+ <bean id="urlValidator"
+ class="org.apache.commons.validator.routines.UrlValidator">
<constructor-arg value="http,https" />
</bean>
<!-- Rewrite -->
- <bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
- <bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
- <bean id="collectionCleanRewrite" class="de.ids_mannheim.korap.rewrite.CollectionCleanRewrite"/>
- <bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
- <bean id="collectionConstraint" class="de.ids_mannheim.korap.rewrite.CollectionConstraint"/>
- <bean id="queryReferenceRewrite" class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite"/>
-
+ <bean id="foundryRewrite"
+ class="de.ids_mannheim.korap.rewrite.FoundryRewrite" />
+ <bean id="collectionRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionRewrite" />
+ <bean id="collectionCleanRewrite"
+ class="de.ids_mannheim.korap.rewrite.CollectionCleanRewrite" />
+ <bean id="virtualCorpusRewrite"
+ class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite" />
+ <bean id="collectionConstraint"
+ class="de.ids_mannheim.korap.rewrite.CollectionConstraint" />
+ <bean id="queryReferenceRewrite"
+ class="de.ids_mannheim.korap.rewrite.QueryReferenceRewrite" />
+
<util:list id="rewriteTasks"
value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
- <!-- <ref bean="collectionConstraint" />
- <ref bean="collectionCleanRewrite" /> -->
+ <!-- <ref bean="collectionConstraint" /> <ref bean="collectionCleanRewrite"
+ /> -->
<ref bean="foundryRewrite" />
<ref bean="collectionRewrite" />
<ref bean="virtualCorpusRewrite" />
<ref bean="queryReferenceRewrite" />
</util:list>
-
- <bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
- <constructor-arg ref="rewriteTasks"/>
+
+ <bean id="rewriteHandler"
+ class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+ <constructor-arg ref="rewriteTasks" />
</bean>
- <bean id="kustvaktResponseHandler" class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
+ <bean id="kustvaktResponseHandler"
+ class="de.ids_mannheim.korap.web.KustvaktResponseHandler">
</bean>
<!-- OAuth -->
- <bean id="oauth2ResponseHandler" class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
+ <bean id="oauth2ResponseHandler"
+ class="de.ids_mannheim.korap.web.OAuth2ResponseHandler">
</bean>
- <bean name="kustvakt_encryption" class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
+ <bean name="kustvakt_encryption"
+ class="de.ids_mannheim.korap.encryption.KustvaktEncryption">
<constructor-arg ref="kustvakt_config" />
</bean>
@@ -235,9 +263,11 @@
<bean id="session_auth"
class="de.ids_mannheim.korap.authentication.SessionAuthentication">
- <constructor-arg type="de.ids_mannheim.korap.config.KustvaktConfiguration"
+ <constructor-arg
+ type="de.ids_mannheim.korap.config.KustvaktConfiguration"
ref="kustvakt_config" />
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
</bean>
@@ -255,7 +285,8 @@
<!-- specify type for constructor argument -->
<bean id="authenticationManager"
class="de.ids_mannheim.korap.authentication.KustvaktAuthenticationManager">
- <constructor-arg type="de.ids_mannheim.korap.interfaces.EncryptionIface"
+ <constructor-arg
+ type="de.ids_mannheim.korap.interfaces.EncryptionIface"
ref="kustvakt_encryption" />
<constructor-arg ref="kustvakt_config" />
<!-- inject authentication providers to use -->
@@ -270,7 +301,8 @@
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
- <tx:method name="get*" read-only="true" rollback-for="KorAPException" />
+ <tx:method name="get*" read-only="true"
+ rollback-for="KorAPException" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="KorAPException" />
</tx:attributes>
@@ -291,11 +323,13 @@
</bean>
<!-- mail -->
- <bean id="authenticator" class="de.ids_mannheim.korap.service.MailAuthenticator">
+ <bean id="authenticator"
+ class="de.ids_mannheim.korap.service.MailAuthenticator">
<constructor-arg index="0" value="${mail.username}" />
<constructor-arg index="1" value="${mail.password}" />
</bean>
- <bean id="smtpSession" class="jakarta.mail.Session" factory-method="getInstance">
+ <bean id="smtpSession" class="jakarta.mail.Session"
+ factory-method="getInstance">
<constructor-arg index="0">
<props>
<prop key="mail.smtp.submitter">${mail.username}</prop>
@@ -308,10 +342,12 @@
</constructor-arg>
<constructor-arg index="1" ref="authenticator" />
</bean>
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
+ <bean id="mailSender"
+ class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session" ref="smtpSession" />
</bean>
- <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine">
+ <bean id="velocityEngine"
+ class="org.apache.velocity.app.VelocityEngine">
<constructor-arg index="0">
<props>
<prop key="resource.loader">class</prop>
diff --git a/full/src/test/resources/test-resource-config.xml b/full/src/test/resources/test-resource-config.xml
index 28eea3e..f26182c 100644
--- a/full/src/test/resources/test-resource-config.xml
+++ b/full/src/test/resources/test-resource-config.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
@@ -15,8 +18,9 @@
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
- <import resource="classpath:test-config.xml"/>
- <bean id="initializator" class="de.ids_mannheim.korap.init.Initializator"
+ <import resource="classpath:test-config.xml" />
+ <bean id="initializator"
+ class="de.ids_mannheim.korap.init.Initializator"
init-method="initResourceTest">
</bean>