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>