diff --git a/.classpath b/.classpath index f6d9ade643..0090dfc279 100644 --- a/.classpath +++ b/.classpath @@ -1,39 +1,39 @@ - + - + - + + - + - - - + - - - + + - + + + diff --git a/pom.xml b/pom.xml index 5ab62c717a..498369ad24 100644 --- a/pom.xml +++ b/pom.xml @@ -182,7 +182,7 @@ - 17 + ${java.version} @@ -278,6 +278,23 @@ compile + + org.openrewrite.maven + rewrite-maven-plugin + 5.23.1 + + + org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_0 + + + + + org.openrewrite.recipe + rewrite-spring + 5.5.0 + + + @@ -331,7 +348,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.18 + 3.2.0 @@ -381,6 +398,10 @@ org.springframework.boot spring-boot-starter-mail + + org.springframework.boot + spring-boot-starter-oauth2-client + org.springframework.boot spring-boot-starter-cache @@ -395,38 +416,33 @@ spring-boot-devtools true + + org.springframework.boot + spring-boot-properties-migrator + runtime + org.apache.tomcat.embed tomcat-embed-jasper - javax.servlet - jstl - 1.2 - + jakarta.servlet.jsp.jstl + jakarta.servlet.jsp.jstl-api + 2.0.0 + + + org.glassfish.web + jakarta.servlet.jsp.jstl + 2.0.0 + org.springframework.security spring-security-taglibs + - org.springframework.security.oauth - spring-security-oauth2 - ${spring-security-oauth2.version} - - - org.springframework.security - spring-security-jwt - ${spring-security-jwt.version} - - - com.auth0 - jwks-rsa - ${jwks-rsa.version} - - - mysql - mysql-connector-java - 8.0.30 + com.mysql + mysql-connector-j com.zaxxer @@ -484,16 +500,16 @@ test - org.testcontainers - testcontainers - 1.20.6 - test + org.testcontainers + testcontainers + 2.0.3 + test - org.testcontainers - junit-jupiter - 1.20.6 - test + org.testcontainers + junit-jupiter + 1.21.4 + test org.easymock @@ -518,10 +534,14 @@ lombok provided + + org.glassfish.jaxb + jaxb-runtime + runtime + redis.clients jedis - 3.7.0 com.google.api-client @@ -538,6 +558,10 @@ commons-io 2.11.0 + + jakarta.mail + jakarta.mail-api + org.apache.tika tika-core @@ -556,14 +580,9 @@ UTF-8 - 5.8.16 - 2.2.5.RELEASE - 1.0.9.RELEASE - 0.3.0 1.7.4 disabled - 2.17.0 diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 6269645bc3..9b2ee26647 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -136,7 +136,7 @@ public JSONArray(JSONTokener x) throws JSONException { case ']': case ')': if (q != c) { - throw x.syntaxError("Expected a '" + new Character(q) + "'"); + throw x.syntaxError("Expected a '" + Character.valueOf(q) + "'"); } return; default: @@ -181,8 +181,8 @@ public JSONArray(Collection collection, boolean includeSuperClass) { Iterator iter = collection.iterator();; while (iter.hasNext()) { Object o = iter.next(); - if (o instanceof Map) { - this.myArrayList.add(new JSONObject((Map)o, includeSuperClass)); + if (o instanceof Map map) { + this.myArrayList.add(new JSONObject(map, includeSuperClass)); } else if (!JSONObject.isStandardProperty(o.getClass())) { this.myArrayList.add(new JSONObject(o, includeSuperClass)); } else { @@ -262,12 +262,12 @@ public Object get(int index) throws JSONException { public boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("false"))) { + (o instanceof String string && + string.equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("true"))) { + (o instanceof String string && + string.equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); @@ -285,8 +285,8 @@ public boolean getBoolean(int index) throws JSONException { public double getDouble(int index) throws JSONException { Object o = get(index); try { - return o instanceof Number ? - ((Number)o).doubleValue() : + return o instanceof Number n ? + n.doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONArray[" + index + @@ -306,8 +306,8 @@ public double getDouble(int index) throws JSONException { */ public int getInt(int index) throws JSONException { Object o = get(index); - return o instanceof Number ? - ((Number)o).intValue() : (int)getDouble(index); + return o instanceof Number n ? + n.intValue() : (int)getDouble(index); } @@ -320,8 +320,8 @@ public int getInt(int index) throws JSONException { */ public JSONArray getJSONArray(int index) throws JSONException { Object o = get(index); - if (o instanceof JSONArray) { - return (JSONArray)o; + if (o instanceof JSONArray array) { + return array; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); @@ -337,8 +337,8 @@ public JSONArray getJSONArray(int index) throws JSONException { */ public JSONObject getJSONObject(int index) throws JSONException { Object o = get(index); - if (o instanceof JSONObject) { - return (JSONObject)o; + if (o instanceof JSONObject object) { + return object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); @@ -355,8 +355,8 @@ public JSONObject getJSONObject(int index) throws JSONException { */ public long getLong(int index) throws JSONException { Object o = get(index); - return o instanceof Number ? - ((Number)o).longValue() : (long)getDouble(index); + return o instanceof Number n ? + n.longValue() : (long)getDouble(index); } @@ -525,7 +525,7 @@ public int optInt(int index, int defaultValue) { */ public JSONArray optJSONArray(int index) { Object o = opt(index); - return o instanceof JSONArray ? (JSONArray)o : null; + return o instanceof JSONArray jsona ? jsona : null; } @@ -539,7 +539,7 @@ public JSONArray optJSONArray(int index) { */ public JSONObject optJSONObject(int index) { Object o = opt(index); - return o instanceof JSONObject ? (JSONObject)o : null; + return o instanceof JSONObject jsono ? jsono : null; } @@ -632,7 +632,7 @@ public JSONArray put(Collection value) { * @return this. */ public JSONArray put(double value) throws JSONException { - Double d = new Double(value); + Double d = Double.valueOf(value); JSONObject.testValidity(d); put(d); return this; @@ -646,7 +646,7 @@ public JSONArray put(double value) throws JSONException { * @return this. */ public JSONArray put(int value) { - put(new Integer(value)); + put(Integer.valueOf(value)); return this; } @@ -658,7 +658,7 @@ public JSONArray put(int value) { * @return this. */ public JSONArray put(long value) { - put(new Long(value)); + put(Long.valueOf(value)); return this; } @@ -729,7 +729,7 @@ public JSONArray put(int index, Collection value) throws JSONException { * not finite. */ public JSONArray put(int index, double value) throws JSONException { - put(index, new Double(value)); + put(index, Double.valueOf(value)); return this; } @@ -744,7 +744,7 @@ public JSONArray put(int index, double value) throws JSONException { * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { - put(index, new Integer(value)); + put(index, Integer.valueOf(value)); return this; } @@ -759,7 +759,7 @@ public JSONArray put(int index, int value) throws JSONException { * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { - put(index, new Long(value)); + put(index, Long.valueOf(value)); return this; } @@ -942,10 +942,10 @@ public Writer write(Writer writer) throws JSONException { writer.write(','); } Object v = this.myArrayList.get(i); - if (v instanceof JSONObject) { - ((JSONObject)v).write(writer); - } else if (v instanceof JSONArray) { - ((JSONArray)v).write(writer); + if (v instanceof JSONObject object) { + object.write(writer); + } else if (v instanceof JSONArray array) { + array.write(writer); } else { writer.write(JSONObject.valueToString(v)); } diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java index 7feee448cc..45e178121a 100644 --- a/src/main/java/org/json/JSONML.java +++ b/src/main/java/org/json/JSONML.java @@ -218,8 +218,8 @@ private static Object parse(XMLTokener x, boolean arrayForm, } } else { if (ja != null) { - ja.put(token instanceof String ? - JSONObject.stringToValue((String)token) : token); + ja.put(token instanceof String s ? + JSONObject.stringToValue(s) : token); } } } @@ -321,9 +321,9 @@ public static String toString(JSONArray ja) throws JSONException { sb.append(tagName); e = ja.opt(1); - if (e instanceof JSONObject) { + if (e instanceof JSONObject object) { i = 2; - jo = (JSONObject)e; + jo = object; // Emit the attributes @@ -359,10 +359,10 @@ public static String toString(JSONArray ja) throws JSONException { if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); - } else if (e instanceof JSONObject) { - sb.append(toString((JSONObject)e)); - } else if (e instanceof JSONArray) { - sb.append(toString((JSONArray)e)); + } else if (e instanceof JSONObject object) { + sb.append(toString(object)); + } else if (e instanceof JSONArray array) { + sb.append(toString(array)); } } } while (i < length); @@ -438,10 +438,10 @@ public static String toString(JSONObject jo) throws JSONException { if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); - } else if (e instanceof JSONObject) { - sb.append(toString((JSONObject)e)); - } else if (e instanceof JSONArray) { - sb.append(toString((JSONArray)e)); + } else if (e instanceof JSONObject object) { + sb.append(toString(object)); + } else if (e instanceof JSONArray array) { + sb.append(toString(array)); } } } diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 6b7c1d4100..11ba2b51f9 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -88,1482 +88,1384 @@ of this software and associated documentation files (the "Software"), to deal */ public class JSONObject { - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null { - - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * @return NULL. - */ - protected final Object clone() { - return this; - } - - - /** - * A Null object is equal to the null value and to itself. - * @param object An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object - * or null. - */ - public boolean equals(Object object) { - return object == null || object == this; - } - - - /** - * Get the "null" string value. - * @return The string "null". - */ - public String toString() { - return "null"; - } - } - - - /** - * The map where the JSONObject's properties are kept. - */ - private Map map; - + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. + */ + private static final class Null { /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * @return NULL. */ - public static final Object NULL = new Null(); - - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - this.map = new HashMap(); + protected final Object clone() { + return this; } - /** - * Construct a JSONObject from a subset of another JSONObject. - * An array of strings is used to identify the keys that should be copied. - * Missing keys are ignored. - * @param jo A JSONObject. - * @param names An array of strings. - * @exception JSONException If a value is a non-finite number or if a name is duplicated. + * A Null object is equal to the null value and to itself. + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object + * or null. */ - public JSONObject(JSONObject jo, String[] names) throws JSONException { - this(); - for (int i = 0; i < names.length; i += 1) { - putOnce(names[i], jo.opt(names[i])); - } + public boolean equals(Object object) { + return object == null || object == this; } - - /** - * Construct a JSONObject from a JSONTokener. - * @param x A JSONTokener object containing the source string. - * @throws JSONException If there is a syntax error in the source string - * or a duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - - /* - * The key is followed by ':'. We will also tolerate '=' or '=>'. - */ - - c = x.nextClean(); - if (c == '=') { - if (x.next() != '>') { - x.back(); - } - } else if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - putOnce(key, x.nextValue()); - - /* - * Pairs are separated by ','. We will also tolerate ';'. - */ - - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - - /** - * Construct a JSONObject from a Map. - * - * @param map A map object that can be used to initialize the contents of - * the JSONObject. - */ - public JSONObject(Map map) { - this.map = (map == null) ? new HashMap() : map; - } - - - /** - * Construct a JSONObject from a Map. - * - * Note: Use this constructor when the map contains . - * - * @param map - A map with Key-Bean data. - * @param includeSuperClass - Tell whether to include the super class properties. - */ - public JSONObject(Map map, boolean includeSuperClass) { - this.map = new HashMap(); - if (map != null) { - Iterator i = map.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry e = (Map.Entry)i.next(); - if (isStandardProperty(e.getValue().getClass())) { - this.map.put(e.getKey(), e.getValue()); - } else { - this.map.put(e.getKey(), new JSONObject(e.getValue(), - includeSuperClass)); - } - } - } - } - - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with "get" or "is" followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the "get" or "is" prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is "Larry Fine", - * then the JSONObject will contain "name": "Larry Fine". - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - */ - public JSONObject(Object bean) { - this(); - populateInternalMap(bean, false); - } - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with "get" or "is" followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the "get" or "is" prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - * @param includeSuperClass If true, include the super class properties. + * Get the "null" string value. + * @return The string "null". */ - public JSONObject(Object bean, boolean includeSuperClass) { - this(); - populateInternalMap(bean, includeSuperClass); - } - - private void populateInternalMap(Object bean, boolean includeSuperClass){ - Class klass = bean.getClass(); - - /* If klass.getSuperClass is System class then force includeSuperClass to false. */ - - if (klass.getClassLoader() == null) { - includeSuperClass = false; - } - - Method[] methods = (includeSuperClass) ? - klass.getMethods() : klass.getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - key = name.substring(3); - } else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 && - Character.isUpperCase(key.charAt(0)) && - method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + - key.substring(1); - } - - Object result = method.invoke(bean, (Object[])null); - if (result == null) { - map.put(key, NULL); - } else if (result.getClass().isArray()) { - map.put(key, new JSONArray(result, includeSuperClass)); - } else if (result instanceof Collection) { // List or Set - map.put(key, new JSONArray((Collection)result, includeSuperClass)); - } else if (result instanceof Map) { - map.put(key, new JSONObject((Map)result, includeSuperClass)); - } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper - map.put(key, result); - } else { - if (result.getClass().getPackage().getName().startsWith("java") || - result.getClass().getClassLoader() == null) { - map.put(key, result.toString()); - } else { // User defined Objects - map.put(key, new JSONObject(result, includeSuperClass)); - } - } - } - } - } catch (Exception e) { - throw new RuntimeException(e); + public String toString() { + return "null"; + } + } + + /** + * The map where the JSONObject's properties are kept. + */ + private Map map; + + /** + * It is sometimes more convenient and less ambiguous to have a + * NULL object than to use Java's null value. + * JSONObject.NULL.equals(null) returns true. + * JSONObject.NULL.toString() returns "null". + */ + public static final Object NULL = new Null(); + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + this.map = new HashMap(); + } + + /** + * Construct a JSONObject from a subset of another JSONObject. + * An array of strings is used to identify the keys that should be copied. + * Missing keys are ignored. + * @param jo A JSONObject. + * @param names An array of strings. + * @exception JSONException If a value is a non-finite number or if a name is duplicated. + */ + public JSONObject(JSONObject jo, String[] names) throws JSONException { + this(); + for (int i = 0; i < names.length; i += 1) { + putOnce(names[i], jo.opt(names[i])); + } + } + + /** + * Construct a JSONObject from a JSONTokener. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string + * or a duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + + /* + * The key is followed by ':'. We will also tolerate '=' or '=>'. + */ + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + putOnce(key, x.nextValue()); + + /* + * Pairs are separated by ','. We will also tolerate ';'. + */ + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + */ + public JSONObject(Map map) { + this.map = (map == null) ? new HashMap() : map; + } + + /** + * Construct a JSONObject from a Map. + * + * Note: Use this constructor when the map contains . + * + * @param map - A map with Key-Bean data. + * @param includeSuperClass - Tell whether to include the super class properties. + */ + public JSONObject(Map map, boolean includeSuperClass) { + this.map = new HashMap(); + if (map != null) { + Iterator i = map.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry) i.next(); + if (isStandardProperty(e.getValue().getClass())) { + this.map.put(e.getKey(), e.getValue()); + } else { + this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); + } + } + } + } + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with "get" or "is" followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + * + * The key is formed by removing the "get" or "is" prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + * + * For example, if an object has a method named "getName", and + * if the result of calling object.getName() is "Larry Fine", + * then the JSONObject will contain "name": "Larry Fine". + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + */ + public JSONObject(Object bean) { + this(); + populateInternalMap(bean, false); + } + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with "get" or "is" followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + * + * The key is formed by removing the "get" or "is" prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + * @param includeSuperClass If true, include the super class properties. + */ + public JSONObject(Object bean, boolean includeSuperClass) { + this(); + populateInternalMap(bean, includeSuperClass); + } + + private void populateInternalMap(Object bean, boolean includeSuperClass) { + Class klass = bean.getClass(); + + /* If klass.getSuperClass is System class then force includeSuperClass to false. */ + + if (klass.getClassLoader() == null) { + includeSuperClass = false; + } + + Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i += 1) { + try { + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + key = name.substring(3); + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) + && method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + key.substring(1); } - } - } - - - static boolean isStandardProperty(Class clazz) { - return clazz.isPrimitive() || - clazz.isAssignableFrom(Byte.class) || - clazz.isAssignableFrom(Short.class) || - clazz.isAssignableFrom(Integer.class) || - clazz.isAssignableFrom(Long.class) || - clazz.isAssignableFrom(Float.class) || - clazz.isAssignableFrom(Double.class) || - clazz.isAssignableFrom(Character.class) || - clazz.isAssignableFrom(String.class) || - clazz.isAssignableFrom(Boolean.class); - } - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings - * from the names array, and the values will be the field values associated - * with those keys in the object. If a key is not found or not visible, - * then it will not be copied into the new JSONObject. - * @param object An object that has fields that should be used to make a - * JSONObject. - * @param names An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String names[]) { - this(); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - putOpt(name, c.getField(name).get(object)); - } catch (Exception e) { - /* forget about it */ + Object result = method.invoke(bean, (Object[]) null); + if (result == null) { + map.put(key, NULL); + } else if (result.getClass().isArray()) { + map.put(key, new JSONArray(result, includeSuperClass)); + } else if (result instanceof Collection collection) { // List or Set + map.put(key, new JSONArray(collection, includeSuperClass)); + } else if (result instanceof Map map1) { + map.put(key, new JSONObject(map1, includeSuperClass)); + } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper + map.put(key, result); + } else { + if (result.getClass().getPackage().getName().startsWith("java") + || result.getClass().getClassLoader() == null) { + map.put(key, result.toString()); + } else { // User defined Objects + map.put(key, new JSONObject(result, includeSuperClass)); + } } - } - } - - - /** - * Construct a JSONObject from a source JSON text string. - * This is the most commonly used JSONObject constructor. - * @param source A string beginning - * with { (left brace) and ending - * with } (right brace). - * @exception JSONException If there is a syntax error in the source - * string or a duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a - * JSONArray is stored under the key to hold all of the accumulated values. - * If there is already a JSONArray, then the new value is appended to it. - * In contrast, the put method replaces the previous value. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the value is an invalid number - * or if the key is null. - */ - public JSONObject accumulate(String key, Object value) - throws JSONException { - testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, value instanceof JSONArray ? - new JSONArray().put(value) : - value); - } else if (o instanceof JSONArray) { - ((JSONArray)o).put(value); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + static boolean isStandardProperty(Class clazz) { + return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) + || clazz.isAssignableFrom(Short.class) || clazz.isAssignableFrom(Integer.class) + || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(Float.class) + || clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(Character.class) + || clazz.isAssignableFrom(String.class) || clazz.isAssignableFrom(Boolean.class); + } + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings + * from the names array, and the values will be the field values associated + * with those keys in the object. If a key is not found or not visible, + * then it will not be copied into the new JSONObject. + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String names[]) { + this(); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + putOpt(name, c.getField(name).get(object)); + } catch (Exception e) { + /* forget about it */ + } + } + } + + /** + * Construct a JSONObject from a source JSON text string. + * This is the most commonly used JSONObject constructor. + * @param source A string beginning + * with { (left brace) and ending + * with } (right brace). + * @exception JSONException If there is a syntax error in the source + * string or a duplicated key. + */ + public JSONObject(String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Accumulate values under a key. It is similar to the put method except + * that if there is already an object stored under the key then a + * JSONArray is stored under the key to hold all of the accumulated values. + * If there is already a JSONArray, then the new value is appended to it. + * In contrast, the put method replaces the previous value. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is an invalid number + * or if the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException { + testValidity(value); + Object o = opt(key); + if (o == null) { + put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (o instanceof JSONArray array) { + array.put(value); + } else { + put(key, new JSONArray().put(o).put(value)); + } + return this; + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value + * associated with the key is not a JSONArray. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object o = opt(key); + if (o == null) { + put(key, new JSONArray().put(value)); + } else if (o instanceof JSONArray array) { + put(key, array.put(value)); + } else { + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); + } + return this; + } + + /** + * Produce a string from a double. The string "null" will be returned if + * the number is not finite. + * @param d A double. + * @return A String. + */ + static public String doubleToString(double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } + + // Shave off trailing zeros and decimal point, if possible. + + String s = Double.toString(d); + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { + s = s.substring(0, s.length() - 1); + } + if (s.endsWith(".")) { + s = s.substring(0, s.length() - 1); + } + } + return s; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + Object o = opt(key); + if (o == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return o; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException + * if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object o = get(key); + if (o.equals(Boolean.FALSE) + || (o instanceof String string && string.equalsIgnoreCase("false"))) { + return false; + } else if (o.equals(Boolean.TRUE) + || (o instanceof String string && string.equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); + } + + /** + * Get the double value associated with a key. + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or + * if the value is not a Number object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException { + Object o = get(key); + try { + return o instanceof Number n ? n.doubleValue() : Double.valueOf((String) o).doubleValue(); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); + } + } + + /** + * Get the int value associated with a key. If the number value is too + * large for an int, it will be clipped. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to an integer. + */ + public int getInt(String key) throws JSONException { + Object o = get(key); + return o instanceof Number n ? n.intValue() : (int) getDouble(key); + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object o = get(key); + if (o instanceof JSONArray array) { + return array; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object o = get(key); + if (o instanceof JSONObject object) { + return object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); + } + + /** + * Get the long value associated with a key. If the number value is too + * long for a long, it will be clipped. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to a long. + */ + public long getLong(String key) throws JSONException { + Object o = get(key); + return o instanceof Number n ? n.longValue() : (long) getDouble(key); + } + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(JSONObject jo) { + int length = jo.length(); + if (length == 0) { + return null; + } + Iterator i = jo.keys(); + String[] names = new String[length]; + int j = 0; + while (i.hasNext()) { + names[j] = (String) i.next(); + j += 1; + } + return names; + } + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if the key is not found. + */ + public String getString(String key) throws JSONException { + return get(key).toString(); + } + + /** + * Determine if the JSONObject contains a specific key. + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + /** + * Determine if the value associated with the key is null or if there is + * no value. + * @param key A key string. + * @return true if there is no value associated with the key or if + * the value is the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.map.keySet().iterator(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names() { + JSONArray ja = new JSONArray(); + Iterator keys = keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * @param n A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + static public String numberToString(Number n) throws JSONException { + if (n == null) { + throw new JSONException("Null pointer"); + } + testValidity(n); + + // Shave off trailing zeros and decimal point, if possible. + + String s = n.toString(); + if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { + while (s.endsWith("0")) { + s = s.substring(0, s.length() - 1); + } + if (s.endsWith(".")) { + s = s.substring(0, s.length() - 1); + } + } + return s; + } + + /** + * Get an optional value associated with a key. + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + /** + * Get an optional boolean associated with a key. + * It returns false if there is no such key, or if the value is not + * Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. + * It returns the defaultValue if there is no such key, or if it is not + * a Boolean or the String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + try { + return getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONArray which is produced from a Collection. + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Collection value) throws JSONException { + put(key, new JSONArray(value)); + return this; + } + + /** + * Get an optional double associated with a key, + * or NaN if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the + * defaultValue if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + try { + Object o = opt(key); + return o instanceof Number n ? n.doubleValue() : Double.valueOf((String) o).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional int value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + try { + return getInt(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional JSONArray associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + Object o = opt(key); + return o instanceof JSONArray jsona ? jsona : null; + } + + /** + * Get an optional JSONObject associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key) { + Object o = opt(key); + return o instanceof JSONObject jsono ? jsono : null; + } + + /** + * Get an optional long value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + try { + return getLong(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional string associated with a key. + * It returns an empty string if there is no such key. If the value is not + * a string and is not null, then it is coverted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return optString(key, ""); + } + + /** + * Get an optional string associated with a key. + * It returns the defaultValue if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + Object o = opt(key); + return o != null ? o.toString() : defaultValue; + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put(String key, double value) throws JSONException { + put(key, Double.valueOf(value)); + return this; + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + put(key, Integer.valueOf(value)); + return this; + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + put(key, Long.valueOf(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Map value) throws JSONException { + put(key, new JSONObject(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, + * then the key will be removed from the JSONObject if it is present. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number + * or if the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + remove(key); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the + * value are both non-null, and only if there is not already a member + * with that name. + * @param key + * @param value + * @return his. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the + * key and the value are both non-null. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + put(key, value); + } + return this; + } + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + t = "000" + Integer.toHexString(c); + sb.append("\\u" + t.substring(t.length() - 4)); } else { - put(key, new JSONArray().put(o).put(value)); - } - return this; - } - - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the key is null or if the current value - * associated with the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) - throws JSONException { - testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, new JSONArray().put(value)); - } else if (o instanceof JSONArray) { - put(key, ((JSONArray)o).put(value)); + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + /** + * Remove a name and its value, if present. + * @param key The name to be removed. + * @return The value that was associated with the name, + * or null if there was no value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * The keys will be sorted alphabetically. + * + * @return An iterator of the keys. + */ + public Iterator sortedKeys() { + return new TreeSet(this.map.keySet()).iterator(); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * @param s A String. + * @return A simple JSON value. + */ + static public Object stringToValue(String s) { + if (s.equals("")) { + return s; + } + if (s.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (s.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (s.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. We support the 0- and 0x- + * conventions. If a number cannot be produced, then the value will just + * be a string. Note that the 0-, 0x-, plus, and implied string + * conventions are non-standard. A JSON parser is free to accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = s.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + if (b == '0') { + if (s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { + try { + return Integer.valueOf(Integer.parseInt(s.substring(2), 16)); + } catch (Exception e) { + /* Ignore the error */ + } } else { - throw new JSONException("JSONObject[" + key + - "] is not a JSONArray."); - } - return this; - } - - - /** - * Produce a string from a double. The string "null" will be returned if - * the number is not finite. - * @param d A double. - * @return A String. - */ - static public String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - -// Shave off trailing zeros and decimal point, if possible. - - String s = Double.toString(d); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { - while (s.endsWith("0")) { - s = s.substring(0, s.length() - 1); - } - if (s.endsWith(".")) { - s = s.substring(0, s.length() - 1); - } - } - return s; - } - - - /** - * Get the value object associated with a key. - * - * @param key A key string. - * @return The object associated with the key. - * @throws JSONException if the key is not found. - */ - public Object get(String key) throws JSONException { - Object o = opt(key); - if (o == null) { - throw new JSONException("JSONObject[" + quote(key) + - "] not found."); - } - return o; - } - - - /** - * Get the boolean value associated with a key. - * - * @param key A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object o = get(key); - if (o.equals(Boolean.FALSE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("false"))) { - return false; - } else if (o.equals(Boolean.TRUE) || - (o instanceof String && - ((String)o).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a Boolean."); - } - - - /** - * Get the double value associated with a key. - * @param key A key string. - * @return The numeric value. - * @throws JSONException if the key is not found or - * if the value is not a Number object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - Object o = get(key); - try { - return o instanceof Number ? - ((Number)o).doubleValue() : - Double.valueOf((String)o).doubleValue(); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a number."); - } - } - - - /** - * Get the int value associated with a key. If the number value is too - * large for an int, it will be clipped. - * - * @param key A key string. - * @return The integer value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to an integer. - */ - public int getInt(String key) throws JSONException { - Object o = get(key); - return o instanceof Number ? - ((Number)o).intValue() : (int)getDouble(key); - } - - - /** - * Get the JSONArray value associated with a key. - * - * @param key A key string. - * @return A JSONArray which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONArray) { - return (JSONArray)o; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONArray."); - } - - - /** - * Get the JSONObject value associated with a key. - * - * @param key A key string. - * @return A JSONObject which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONObject) { - return (JSONObject)o; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONObject."); - } - - - /** - * Get the long value associated with a key. If the number value is too - * long for a long, it will be clipped. - * - * @param key A key string. - * @return The long value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to a long. - */ - public long getLong(String key) throws JSONException { - Object o = get(key); - return o instanceof Number ? - ((Number)o).longValue() : (long)getDouble(key); - } - - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator i = jo.keys(); - String[] names = new String[length]; - int j = 0; - while (i.hasNext()) { - names[j] = (String)i.next(); - j += 1; - } - return names; - } - - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - - /** - * Get the string associated with a key. - * - * @param key A key string. - * @return A string which is the value. - * @throws JSONException if the key is not found. - */ - public String getString(String key) throws JSONException { - return get(key).toString(); - } - - - /** - * Determine if the JSONObject contains a specific key. - * @param key A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - - /** - * Determine if the value associated with the key is null or if there is - * no value. - * @param key A key string. - * @return true if there is no value associated with the key or if - * the value is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(opt(key)); - } - - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.map.keySet().iterator(); - } - - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * @param n A Number - * @return A String. - * @throws JSONException If n is a non-finite number. - */ - static public String numberToString(Number n) - throws JSONException { - if (n == null) { - throw new JSONException("Null pointer"); - } - testValidity(n); - -// Shave off trailing zeros and decimal point, if possible. - - String s = n.toString(); - if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { - while (s.endsWith("0")) { - s = s.substring(0, s.length() - 1); - } - if (s.endsWith(".")) { - s = s.substring(0, s.length() - 1); - } - } - return s; - } - - - /** - * Get an optional value associated with a key. - * @param key A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - - /** - * Get an optional boolean associated with a key. - * It returns false if there is no such key, or if the value is not - * Boolean.TRUE or the String "true". - * - * @param key A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return optBoolean(key, false); - } - - - /** - * Get an optional boolean associated with a key. - * It returns the defaultValue if there is no such key, or if it is not - * a Boolean or the String "true" or "false" (case insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - try { - return getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * @param key A key string. - * @param value A Collection value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Collection value) throws JSONException { - put(key, new JSONArray(value)); - return this; - } - - - /** - * Get an optional double associated with a key, - * or NaN if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return optDouble(key, Double.NaN); - } - - - /** - * Get an optional double associated with a key, or the - * defaultValue if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - try { - Object o = opt(key); - return o instanceof Number ? ((Number)o).doubleValue() : - new Double((String)o).doubleValue(); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional int value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return optInt(key, 0); - } - - - /** - * Get an optional int value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - try { - return getInt(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional JSONArray associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONArray. - * - * @param key A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = opt(key); - return o instanceof JSONArray ? (JSONArray)o : null; - } - - - /** - * Get an optional JSONObject associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONObject. - * - * @param key A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object o = opt(key); - return o instanceof JSONObject ? (JSONObject)o : null; - } - - - /** - * Get an optional long value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return optLong(key, 0); - } - - - /** - * Get an optional long value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - try { - return getLong(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional string associated with a key. - * It returns an empty string if there is no such key. If the value is not - * a string and is not null, then it is coverted to a string. - * - * @param key A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return optString(key, ""); - } - - - /** - * Get an optional string associated with a key. - * It returns the defaultValue if there is no such key. - * - * @param key A key string. - * @param defaultValue The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object o = opt(key); - return o != null ? o.toString() : defaultValue; - } - - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key A key string. - * @param value A boolean which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a key/double pair in the JSONObject. - * - * @param key A key string. - * @param value A double which is the value. - * @return this. - * @throws JSONException If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException { - put(key, new Double(value)); - return this; - } - - - /** - * Put a key/int pair in the JSONObject. - * - * @param key A key string. - * @param value An int which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - put(key, new Integer(value)); - return this; - } - - - /** - * Put a key/long pair in the JSONObject. - * - * @param key A key string. - * @param value A long which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - put(key, new Long(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * @param key A key string. - * @param value A Map value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Map value) throws JSONException { - put(key, new JSONObject(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject. If the value is null, - * then the key will be removed from the JSONObject if it is present. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is non-finite number - * or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); + try { + return Integer.valueOf(Integer.parseInt(s, 8)); + } catch (Exception e) { + /* Ignore the error */ + } + } + } + try { + if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { + return Double.valueOf(s); } else { - remove(key); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the key and the - * value are both non-null, and only if there is not already a member - * with that name. - * @param key - * @param value - * @return his. - * @throws JSONException if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - put(key, value); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the - * key and the value are both non-null. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - put(key, value); - } - return this; - } - - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || - (c >= '\u2000' && c < '\u2100')) { - t = "000" + Integer.toHexString(c); - sb.append("\\u" + t.substring(t.length() - 4)); - } else { - sb.append(c); - } - } - } - sb.append('"'); - return sb.toString(); - } - - /** - * Remove a name and its value, if present. - * @param key The name to be removed. - * @return The value that was associated with the name, - * or null if there was no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * The keys will be sorted alphabetically. - * - * @return An iterator of the keys. - */ - public Iterator sortedKeys() { - return new TreeSet(this.map.keySet()).iterator(); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * @param s A String. - * @return A simple JSON value. - */ - static public Object stringToValue(String s) { - if (s.equals("")) { - return s; - } - if (s.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (s.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (s.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. We support the 0- and 0x- - * conventions. If a number cannot be produced, then the value will just - * be a string. Note that the 0-, 0x-, plus, and implied string - * conventions are non-standard. A JSON parser is free to accept - * non-JSON forms as long as it accepts all correct JSON forms. - */ - - char b = s.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { - if (b == '0') { - if (s.length() > 2 && - (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { - try { - return new Integer(Integer.parseInt(s.substring(2), - 16)); - } catch (Exception e) { - /* Ignore the error */ - } - } else { - try { - return new Integer(Integer.parseInt(s, 8)); - } catch (Exception e) { - /* Ignore the error */ - } - } - } - try { - if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { - return Double.valueOf(s); - } else { - Long myLong = new Long(s); - if (myLong.longValue() == myLong.intValue()) { - return new Integer(myLong.intValue()); - } else { - return myLong; - } - } - } catch (Exception f) { - /* Ignore the error */ - } - } - return s; - } - - - /** - * Throw an exception if the object is an NaN or infinite number. - * @param o The object to test. - * @throws JSONException If o is a non-finite number. - */ - static void testValidity(Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double)o).isInfinite() || ((Double)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float)o).isInfinite() || ((Float)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } - } - } - - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * @param names A JSONArray containing a list of key strings. This - * determines the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace - * is added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - */ - public String toString() { - try { - Iterator keys = keys(); - StringBuffer sb = new StringBuffer("{"); - - while (keys.hasNext()) { - if (sb.length() > 1) { - sb.append(','); - } - Object o = keys.next(); - sb.append(quote(o.toString())); - sb.append(':'); - sb.append(valueToString(this.map.get(o))); - } - sb.append('}'); - return sb.toString(); - } catch (Exception e) { - return null; - } - } - - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - return toString(indentFactor, 0); - } - - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - String toString(int indentFactor, int indent) throws JSONException { - int j; - int n = length(); - if (n == 0) { - return "{}"; - } - Iterator keys = sortedKeys(); - StringBuffer sb = new StringBuffer("{"); - int newindent = indent + indentFactor; - Object o; - if (n == 1) { - o = keys.next(); - sb.append(quote(o.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(o), indentFactor, - indent)); + Long myLong = Long.valueOf(s); + if (myLong.longValue() == myLong.intValue()) { + return Integer.valueOf(myLong.intValue()); + } else { + return myLong; + } + } + } catch (Exception f) { + /* Ignore the error */ + } + } + return s; + } + + /** + * Throw an exception if the object is an NaN or infinite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + static void testValidity(Object o) throws JSONException { + if (o != null) { + if (o instanceof Double double1) { + if (double1.isInfinite() || double1.isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float float1) { + if (float1.isInfinite() || float1.isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * Produce a JSONArray containing the values of the members of this + * JSONObject. + * @param names A JSONArray containing a list of key strings. This + * determines the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace + * is added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + */ + public String toString() { + try { + Iterator keys = keys(); + StringBuffer sb = new StringBuffer("{"); + + while (keys.hasNext()) { + if (sb.length() > 1) { + sb.append(','); + } + Object o = keys.next(); + sb.append(quote(o.toString())); + sb.append(':'); + sb.append(valueToString(this.map.get(o))); + } + sb.append('}'); + return sb.toString(); + } catch (Exception e) { + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + String toString(int indentFactor, int indent) throws JSONException { + int j; + int n = length(); + if (n == 0) { + return "{}"; + } + Iterator keys = sortedKeys(); + StringBuffer sb = new StringBuffer("{"); + int newindent = indent + indentFactor; + Object o; + if (n == 1) { + o = keys.next(); + sb.append(quote(o.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(o), indentFactor, indent)); + } else { + while (keys.hasNext()) { + o = keys.next(); + if (sb.length() > 1) { + sb.append(",\n"); } else { - while (keys.hasNext()) { - o = keys.next(); - if (sb.length() > 1) { - sb.append(",\n"); - } else { - sb.append('\n'); - } - for (j = 0; j < newindent; j += 1) { - sb.append(' '); - } - sb.append(quote(o.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(o), indentFactor, - newindent)); - } - if (sb.length() > 1) { - sb.append('\n'); - for (j = 0; j < indent; j += 1) { - sb.append(' '); - } - } - } - sb.append('}'); - return sb.toString(); - } - - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce - * the JSON text. The method is required to produce a strictly - * conforming text. If the object does not contain a toJSONString - * method (which is the most common case), then a text will be - * produced by other means. If the value is an array or Collection, - * then a JSONArray will be made from it and its toJSONString method - * will be called. If the value is a MAP, then a JSONObject will be made - * from it and its toJSONString method will be called. Otherwise, the - * value's toString method will be called, and the result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the value is or contains an invalid number. - */ - static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString)value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (o instanceof String) { - return (String)o; - } - throw new JSONException("Bad value from toJSONString: " + o); - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject || - value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection)value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); + sb.append('\n'); + } + for (j = 0; j < newindent; j += 1) { + sb.append(' '); + } + sb.append(quote(o.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(o), indentFactor, newindent)); + } + if (sb.length() > 1) { + sb.append('\n'); + for (j = 0; j < indent; j += 1) { + sb.append(' '); + } + } + } + sb.append('}'); + return sb.toString(); + } + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce + * the JSON text. The method is required to produce a strictly + * conforming text. If the object does not contain a toJSONString + * method (which is the most common case), then a text will be + * produced by other means. If the value is an array or Collection, + * then a JSONArray will be made from it and its toJSONString method + * will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the + * value's toString method will be called, and the result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString string) { + Object o; + try { + o = string.toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (o instanceof String string1) { + return string1; + } + throw new JSONException("Bad value from toJSONString: " + o); + } + if (value instanceof Number number) { + return numberToString(number); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map map1) { + return new JSONObject(map1).toString(); + } + if (value instanceof Collection collection) { + return new JSONArray(collection).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Make a prettyprinted JSON text of an object value. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + static String valueToString(Object value, int indentFactor, int indent) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + try { + if (value instanceof JSONString string) { + Object o = string.toJSONString(); + if (o instanceof String string1) { + return string1; + } + } + } catch (Exception e) { + /* forget about it */ + } + if (value instanceof Number number) { + return numberToString(number); + } + if (value instanceof Boolean) { + return value.toString(); + } + if (value instanceof JSONObject object) { + return object.toString(indentFactor, indent); + } + if (value instanceof JSONArray array) { + return array.toString(indentFactor, indent); + } + if (value instanceof Map map1) { + return new JSONObject(map1).toString(indentFactor, indent); + } + if (value instanceof Collection collection) { + return new JSONArray(collection).toString(indentFactor, indent); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(indentFactor, indent); + } + return quote(value.toString()); + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. + * For compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + try { + boolean b = false; + Iterator keys = keys(); + writer.write('{'); + + while (keys.hasNext()) { + if (b) { + writer.write(','); + } + Object k = keys.next(); + writer.write(quote(k.toString())); + writer.write(':'); + Object v = this.map.get(k); + if (v instanceof JSONObject object) { + object.write(writer); + } else if (v instanceof JSONArray array) { + array.write(writer); + } else { + writer.write(valueToString(v)); } - return quote(value.toString()); + b = true; + } + writer.write('}'); + return writer; + } catch (IOException e) { + throw new JSONException(e); } - - - /** - * Make a prettyprinted JSON text of an object value. - *

- * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - static String valueToString(Object value, int indentFactor, int indent) - throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - try { - if (value instanceof JSONString) { - Object o = ((JSONString)value).toJSONString(); - if (o instanceof String) { - return (String)o; - } - } - } catch (Exception e) { - /* forget about it */ - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean) { - return value.toString(); - } - if (value instanceof JSONObject) { - return ((JSONObject)value).toString(indentFactor, indent); - } - if (value instanceof JSONArray) { - return ((JSONArray)value).toString(indentFactor, indent); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(indentFactor, indent); - } - if (value instanceof Collection) { - return new JSONArray((Collection)value).toString(indentFactor, indent); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(indentFactor, indent); - } - return quote(value.toString()); - } - - - /** - * Write the contents of the JSONObject as JSON text to a writer. - * For compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - try { - boolean b = false; - Iterator keys = keys(); - writer.write('{'); - - while (keys.hasNext()) { - if (b) { - writer.write(','); - } - Object k = keys.next(); - writer.write(quote(k.toString())); - writer.write(':'); - Object v = this.map.get(k); - if (v instanceof JSONObject) { - ((JSONObject)v).write(writer); - } else if (v instanceof JSONArray) { - ((JSONArray)v).write(writer); - } else { - writer.write(valueToString(v)); - } - b = true; - } - writer.write('}'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } -} \ No newline at end of file + } +} diff --git a/src/main/java/org/json/JSONWriter.java b/src/main/java/org/json/JSONWriter.java index 32c2414d04..f403b851be 100644 --- a/src/main/java/org/json/JSONWriter.java +++ b/src/main/java/org/json/JSONWriter.java @@ -295,7 +295,7 @@ public JSONWriter value(boolean b) throws JSONException { * @throws JSONException If the number is not finite. */ public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); + return this.value(Double.valueOf(d)); } /** diff --git a/src/main/java/org/json/Test.java b/src/main/java/org/json/Test.java index a1b8d44919..8d7f86d9f1 100644 --- a/src/main/java/org/json/Test.java +++ b/src/main/java/org/json/Test.java @@ -204,10 +204,12 @@ public String toString() { System.out.println(""); j = new JSONObject( - "{foo: [true, false,9876543210, 0.0, 1.00000001, 1.000000000001, 1.00000000000000001," + - " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " + - " to : null, op : 'Good'," + - "ten:10} postfix comment"); + """ + {foo: [true, false,9876543210, 0.0, 1.00000001, 1.000000000001, 1.00000000000000001,\ + .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, "string"], \ + to : null, op : 'Good',\ + ten:10} postfix comment\ + """); j.put("String", "98.6"); j.put("JSONObject", new JSONObject()); j.put("JSONArray", new JSONArray()); @@ -313,25 +315,29 @@ public String toString() { System.out.println(HTTP.toString(j)); System.out.println(""); - j = XML.toJSONObject(""+"\n\n"+""+ - ""+ - "GOOGLEKEY '+search+' 0 10 true false latin1 latin1"+ - ""+ - ""); + j = XML.toJSONObject(""" + + + \ + \ + GOOGLEKEY '+search+' 0 10 true false latin1 latin1\ + \ + \ + """); System.out.println(j.toString(2)); System.out.println(XML.toString(j)); System.out.println(""); diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index 4d95be4b61..b0e89822c0 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -36,31 +36,31 @@ of this software and associated documentation files (the "Software"), to deal public class XML { /** The Character '&'. */ - public static final Character AMP = new Character('&'); + public static final Character AMP = Character.valueOf('&'); /** The Character '''. */ - public static final Character APOS = new Character('\''); + public static final Character APOS = Character.valueOf('\''); /** The Character '!'. */ - public static final Character BANG = new Character('!'); + public static final Character BANG = Character.valueOf('!'); /** The Character '='. */ - public static final Character EQ = new Character('='); + public static final Character EQ = Character.valueOf('='); /** The Character '>'. */ - public static final Character GT = new Character('>'); + public static final Character GT = Character.valueOf('>'); /** The Character '<'. */ - public static final Character LT = new Character('<'); + public static final Character LT = Character.valueOf('<'); /** The Character '?'. */ - public static final Character QUEST = new Character('?'); + public static final Character QUEST = Character.valueOf('?'); /** The Character '"'. */ - public static final Character QUOT = new Character('"'); + public static final Character QUOT = Character.valueOf('"'); /** The Character '/'. */ - public static final Character SLASH = new Character('/'); + public static final Character SLASH = Character.valueOf('/'); /** * Replace special characters with XML escapes: @@ -218,15 +218,15 @@ private static boolean parse(XMLTokener x, JSONObject context, // attribute = value - if (t instanceof String) { - s = (String)t; + if (t instanceof String string) { + s = string; t = x.nextToken(); if (t == EQ) { t = x.nextToken(); if (!(t instanceof String)) { throw x.syntaxError("Missing value"); } - o.accumulate(s, JSONObject.stringToValue((String)t)); + o.accumulate(s, JSONObject.stringToValue(string)); t = null; } else { o.accumulate(s, ""); @@ -251,8 +251,8 @@ private static boolean parse(XMLTokener x, JSONObject context, throw x.syntaxError("Unclosed tag " + n); } return false; - } else if (t instanceof String) { - s = (String)t; + } else if (t instanceof String string) { + s = string; if (s.length() > 0) { o.accumulate("content", JSONObject.stringToValue(s)); } @@ -334,7 +334,7 @@ public static String toString(Object o, String tagName) int len; String s; Object v; - if (o instanceof JSONObject) { + if (o instanceof JSONObject object) { // Emit @@ -346,7 +346,7 @@ public static String toString(Object o, String tagName) // Loop thru the keys. - jo = (JSONObject)o; + jo = object; keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); @@ -354,8 +354,8 @@ public static String toString(Object o, String tagName) if (v == null) { v = ""; } - if (v instanceof String) { - s = (String)v; + if (v instanceof String string) { + s = string; } else { s = null; } @@ -363,8 +363,8 @@ public static String toString(Object o, String tagName) // Emit content in body if (k.equals("content")) { - if (v instanceof JSONArray) { - ja = (JSONArray)v; + if (v instanceof JSONArray array) { + ja = array; len = ja.length(); for (i = 0; i < len; i += 1) { if (i > 0) { @@ -378,8 +378,8 @@ public static String toString(Object o, String tagName) // Emit an array of similar keys - } else if (v instanceof JSONArray) { - ja = (JSONArray)v; + } else if (v instanceof JSONArray array) { + ja = array; len = ja.length(); for (i = 0; i < len; i += 1) { v = ja.get(i); @@ -419,8 +419,8 @@ public static String toString(Object o, String tagName) // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an element. - } else if (o instanceof JSONArray) { - ja = (JSONArray)o; + } else if (o instanceof JSONArray array) { + ja = array; len = ja.length(); for (i = 0; i < len; ++i) { v = ja.opt(i); diff --git a/src/main/java/org/wise/WISE.java b/src/main/java/org/wise/WISE.java index 06a48a1ae1..de785ba765 100644 --- a/src/main/java/org/wise/WISE.java +++ b/src/main/java/org/wise/WISE.java @@ -86,10 +86,13 @@ public static void main(String[] args) { private static int mainMenuPrompt() { Scanner reader = new Scanner(System.in); - System.out.println("\nAvailable actions:\n" + - "[0] Reset WISE (database & curriculum) to initial state\n" + - "[1] Exit\n" + - "Enter number:"); + System.out.println(""" + + Available actions: + [0] Reset WISE (database & curriculum) to initial state + [1] Exit + Enter number:\ + """); try { return reader.nextInt(); } catch (InputMismatchException ime) { diff --git a/src/main/java/org/wise/portal/dao/achievement/HibernateAchievementDao.java b/src/main/java/org/wise/portal/dao/achievement/HibernateAchievementDao.java index cd7fdce396..ec4886776e 100644 --- a/src/main/java/org/wise/portal/dao/achievement/HibernateAchievementDao.java +++ b/src/main/java/org/wise/portal/dao/achievement/HibernateAchievementDao.java @@ -26,11 +26,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/annotation/wise5/impl/HibernateAnnotationDao.java b/src/main/java/org/wise/portal/dao/annotation/wise5/impl/HibernateAnnotationDao.java index 8f8a929578..56bee376b2 100644 --- a/src/main/java/org/wise/portal/dao/annotation/wise5/impl/HibernateAnnotationDao.java +++ b/src/main/java/org/wise/portal/dao/annotation/wise5/impl/HibernateAnnotationDao.java @@ -4,11 +4,11 @@ import java.util.List; import java.util.Set; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.annotation.wise5.AnnotationDao; diff --git a/src/main/java/org/wise/portal/dao/attendance/impl/HibernateStudentAttendanceDao.java b/src/main/java/org/wise/portal/dao/attendance/impl/HibernateStudentAttendanceDao.java index d82c7745a3..0a62744772 100644 --- a/src/main/java/org/wise/portal/dao/attendance/impl/HibernateStudentAttendanceDao.java +++ b/src/main/java/org/wise/portal/dao/attendance/impl/HibernateStudentAttendanceDao.java @@ -28,11 +28,11 @@ import java.util.Date; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclSidDao.java b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclSidDao.java index 4a1efb1bbb..ed179e05cd 100644 --- a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclSidDao.java +++ b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclSidDao.java @@ -20,10 +20,10 @@ */ package org.wise.portal.dao.authentication.impl; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.authentication.AclSidDao; diff --git a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectDao.java b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectDao.java index b2a122999c..d7eb711583 100644 --- a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectDao.java +++ b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectDao.java @@ -20,10 +20,10 @@ */ package org.wise.portal.dao.authentication.impl; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.authentication.AclTargetObjectDao; diff --git a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectIdentityDao.java b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectIdentityDao.java index be8abef90b..faae32d75e 100644 --- a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectIdentityDao.java +++ b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateAclTargetObjectIdentityDao.java @@ -23,11 +23,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.stereotype.Repository; diff --git a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateGrantedAuthorityDao.java b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateGrantedAuthorityDao.java index a1da37e8db..9b738dc8be 100644 --- a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateGrantedAuthorityDao.java +++ b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateGrantedAuthorityDao.java @@ -20,10 +20,10 @@ */ package org.wise.portal.dao.authentication.impl; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.authentication.GrantedAuthorityDao; diff --git a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateUserDetailsDao.java b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateUserDetailsDao.java index 36e3c3026b..b0a4989196 100644 --- a/src/main/java/org/wise/portal/dao/authentication/impl/HibernateUserDetailsDao.java +++ b/src/main/java/org/wise/portal/dao/authentication/impl/HibernateUserDetailsDao.java @@ -22,10 +22,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.authentication.UserDetailsDao; diff --git a/src/main/java/org/wise/portal/dao/impl/AbstractHibernateDao.java b/src/main/java/org/wise/portal/dao/impl/AbstractHibernateDao.java index 06a35de780..fcea05fbf2 100644 --- a/src/main/java/org/wise/portal/dao/impl/AbstractHibernateDao.java +++ b/src/main/java/org/wise/portal/dao/impl/AbstractHibernateDao.java @@ -26,11 +26,11 @@ import java.io.Serializable; import java.util.List; -import javax.annotation.Resource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; +import jakarta.annotation.Resource; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/org/wise/portal/dao/newsitem/impl/HibernateNewsItemDao.java b/src/main/java/org/wise/portal/dao/newsitem/impl/HibernateNewsItemDao.java index 464a31da18..a82253ff6d 100644 --- a/src/main/java/org/wise/portal/dao/newsitem/impl/HibernateNewsItemDao.java +++ b/src/main/java/org/wise/portal/dao/newsitem/impl/HibernateNewsItemDao.java @@ -25,10 +25,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/notification/impl/HibernateNotificationDao.java b/src/main/java/org/wise/portal/dao/notification/impl/HibernateNotificationDao.java index 7bccf918c5..4d26c8acd0 100644 --- a/src/main/java/org/wise/portal/dao/notification/impl/HibernateNotificationDao.java +++ b/src/main/java/org/wise/portal/dao/notification/impl/HibernateNotificationDao.java @@ -26,11 +26,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/peergroup/impl/HibernatePeerGroupDao.java b/src/main/java/org/wise/portal/dao/peergroup/impl/HibernatePeerGroupDao.java index 3a98e28c5b..f66bf55cc4 100644 --- a/src/main/java/org/wise/portal/dao/peergroup/impl/HibernatePeerGroupDao.java +++ b/src/main/java/org/wise/portal/dao/peergroup/impl/HibernatePeerGroupDao.java @@ -27,12 +27,13 @@ import java.util.List; import java.util.Set; -import javax.persistence.LockModeType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.LockModeType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; @@ -66,9 +67,8 @@ public PeerGroup getByWorkgroupAndPeerGrouping(Workgroup workgroup, PeerGrouping Root workgroupImplRoot = cq.from(WorkgroupImpl.class); List predicates = new ArrayList<>(); predicates.add(cb.equal(workgroupImplRoot.get("id"), workgroup.getId())); - predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGrouping.getId())); - predicates.add(cb.isMember(workgroupImplRoot.get("id"), - peerGroupImplRoot.> get("members"))); + predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGrouping)); + predicates.add(cb.isMember(workgroup, peerGroupImplRoot.> get("members"))); cq.select(peerGroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); query.setLockMode(LockModeType.PESSIMISTIC_WRITE); @@ -86,9 +86,9 @@ private List getListByTag(Run run, String tag) { Root peerGroupImplRoot = cq.from(PeerGroupImpl.class); Root peerGroupingImplRoot = cq.from(PeerGroupingImpl.class); List predicates = new ArrayList<>(); - predicates.add(cb.equal(peerGroupingImplRoot.get("run"), run.getId())); + predicates.add(cb.equal(peerGroupingImplRoot.get("run"), run)); predicates.add(cb.equal(peerGroupingImplRoot.get("tag"), tag)); - predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGroupingImplRoot.get("id"))); + predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGroupingImplRoot)); cq.select(peerGroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); List resultList = query.getResultList(); @@ -104,8 +104,7 @@ public List getListByWorkgroup(Workgroup workgroup) { Root workgroupImplRoot = cq.from(WorkgroupImpl.class); List predicates = new ArrayList<>(); predicates.add(cb.equal(workgroupImplRoot.get("id"), workgroup.getId())); - predicates.add(cb.isMember(workgroupImplRoot.get("id"), - peerGroupImplRoot.> get("members"))); + predicates.add(cb.isMember(workgroup, peerGroupImplRoot.> get("members"))); cq.select(peerGroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); List resultList = query.getResultList(); @@ -118,13 +117,11 @@ public List getWorkgroupsInPeerGroup(PeerGrouping peerGrouping, Group CriteriaBuilder cb = getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(WorkgroupImpl.class); Root peerGroupImplRoot = cq.from(PeerGroupImpl.class); - Root workgroupImplRoot = cq.from(WorkgroupImpl.class); + Join membersJoin = peerGroupImplRoot.join("members"); List predicates = new ArrayList<>(); - predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGrouping.getId())); - predicates.add(cb.equal(workgroupImplRoot.get("period"), period.getId())); - predicates.add(cb.isMember(workgroupImplRoot.get("id"), - peerGroupImplRoot.> get("members"))); - cq.select(workgroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); + predicates.add(cb.equal(peerGroupImplRoot.get("peerGrouping"), peerGrouping)); + predicates.add(cb.equal(membersJoin.get("period"), period)); + cq.select(membersJoin).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); List resultList = query.getResultList(); return (List) (Object) resultList; diff --git a/src/main/java/org/wise/portal/dao/peergrouping/impl/HibernatePeerGroupingDao.java b/src/main/java/org/wise/portal/dao/peergrouping/impl/HibernatePeerGroupingDao.java index f9b5f42327..6dfa45a04e 100644 --- a/src/main/java/org/wise/portal/dao/peergrouping/impl/HibernatePeerGroupingDao.java +++ b/src/main/java/org/wise/portal/dao/peergrouping/impl/HibernatePeerGroupingDao.java @@ -26,11 +26,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; @@ -57,7 +57,7 @@ public PeerGrouping getByTag(Run run, String tag) { CriteriaQuery cq = cb.createQuery(PeerGroupingImpl.class); Root peerGroupingImplRoot = cq.from(PeerGroupingImpl.class); List predicates = new ArrayList<>(); - predicates.add(cb.equal(peerGroupingImplRoot.get("run"), run.getId())); + predicates.add(cb.equal(peerGroupingImplRoot.get("run"), run)); predicates.add(cb.equal(peerGroupingImplRoot.get("tag"), tag)); cq.select(peerGroupingImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); diff --git a/src/main/java/org/wise/portal/dao/portal/impl/HibernatePortalStatisticsDao.java b/src/main/java/org/wise/portal/dao/portal/impl/HibernatePortalStatisticsDao.java index 8fe1c83aa4..e57303616d 100644 --- a/src/main/java/org/wise/portal/dao/portal/impl/HibernatePortalStatisticsDao.java +++ b/src/main/java/org/wise/portal/dao/portal/impl/HibernatePortalStatisticsDao.java @@ -25,10 +25,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/project/impl/HibernateProjectDao.java b/src/main/java/org/wise/portal/dao/project/impl/HibernateProjectDao.java index 45d2439060..b1b59c59e7 100644 --- a/src/main/java/org/wise/portal/dao/project/impl/HibernateProjectDao.java +++ b/src/main/java/org/wise/portal/dao/project/impl/HibernateProjectDao.java @@ -28,13 +28,13 @@ import java.util.List; import java.util.Set; -import javax.persistence.NoResultException; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.persistence.criteria.Subquery; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -70,10 +70,10 @@ public List getSharedProjectsWithoutRun(User user) { CriteriaQuery cq = cb.createQuery(ProjectImpl.class); Root projectRoot = cq.from(ProjectImpl.class); Root userRoot = cq.from(UserImpl.class); - Subquery runProjectIds = getRunProjectIds(cq); + Subquery runProjectIds = getRunProjectIds(cq); List predicates = new ArrayList<>(); - predicates.add(cb.equal(userRoot.get("id"), user.getId())); - predicates.add(cb.isMember(userRoot.get("id"), projectRoot.> get("sharedowners"))); + predicates.add(cb.equal(userRoot, user)); + predicates.add(cb.isMember(user, projectRoot.> get("sharedowners"))); predicates.add(cb.not(projectRoot.get("id").in(runProjectIds))); cq.select(projectRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); @@ -81,8 +81,8 @@ public List getSharedProjectsWithoutRun(User user) { return (List) (Object) projectResultList; } - private Subquery getRunProjectIds(CriteriaQuery cq) { - Subquery runsSubquery = cq.subquery(RunImpl.class); + private Subquery getRunProjectIds(CriteriaQuery cq) { + Subquery runsSubquery = cq.subquery(Long.class); Root runRoot = runsSubquery.from(RunImpl.class); runsSubquery.select(runRoot.get("project").get("id")); return runsSubquery; @@ -185,10 +185,10 @@ public List getProjectsWithoutRuns(User user) { CriteriaQuery cq = cb.createQuery(ProjectImpl.class); Root projectRoot = cq.from(ProjectImpl.class); Root userRoot = cq.from(UserImpl.class); - Subquery runProjectIds = getRunProjectIds(cq); + Subquery runProjectIds = getRunProjectIds(cq); List predicates = new ArrayList<>(); - predicates.add(cb.equal(userRoot.get("id"), user.getId())); - predicates.add(cb.equal(userRoot.get("id"), projectRoot.get("owner"))); + predicates.add(cb.equal(userRoot, user)); + predicates.add(cb.equal(userRoot, projectRoot.get("owner"))); predicates.add(cb.not(projectRoot.get("id").in(runProjectIds))); cq.select(projectRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); diff --git a/src/main/java/org/wise/portal/dao/project/impl/HibernateTagDao.java b/src/main/java/org/wise/portal/dao/project/impl/HibernateTagDao.java index 27b3592706..839bd95778 100644 --- a/src/main/java/org/wise/portal/dao/project/impl/HibernateTagDao.java +++ b/src/main/java/org/wise/portal/dao/project/impl/HibernateTagDao.java @@ -26,10 +26,10 @@ import java.util.List; import java.util.Set; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.ObjectNotFoundException; diff --git a/src/main/java/org/wise/portal/dao/run/impl/HibernateRunDao.java b/src/main/java/org/wise/portal/dao/run/impl/HibernateRunDao.java index e546ae2a37..8625b9fc95 100644 --- a/src/main/java/org/wise/portal/dao/run/impl/HibernateRunDao.java +++ b/src/main/java/org/wise/portal/dao/run/impl/HibernateRunDao.java @@ -29,11 +29,11 @@ import java.util.List; import java.util.Set; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.ObjectNotFoundException; @@ -114,7 +114,7 @@ public List getRunListByUser(User user) { Root periodGroupRoot = cq.from(PersistentGroup.class); List predicates = new ArrayList<>(); predicates.add(cb.equal(userRoot.get("id"), user.getId())); - predicates.add(cb.isMember(userRoot.get("id"), periodGroupRoot.> get("members"))); + predicates.add(cb.isMember(user, periodGroupRoot.>get("members"))); predicates.add(cb.isMember(periodGroupRoot, runRoot.> get("periods"))); cq.select(runRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); @@ -150,10 +150,7 @@ public List getRunListBySharedOwner(User owner) { CriteriaBuilder cb = getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(RunImpl.class); Root runRoot = cq.from(RunImpl.class); - Root userRoot = cq.from(UserImpl.class); - cq.select(runRoot) - .where(cb.and(cb.equal(userRoot.get("id"), owner.getId()), - cb.isMember(userRoot.get("id"), runRoot.> get("sharedowners")))) + cq.select(runRoot).where(cb.isMember(owner, runRoot.> get("sharedowners"))) .orderBy(cb.desc(runRoot.get("id"))); TypedQuery query = entityManager.createQuery(cq); List runResultList = query.getResultList(); diff --git a/src/main/java/org/wise/portal/dao/statistics/impl/HibernateVLEStatisticsDao.java b/src/main/java/org/wise/portal/dao/statistics/impl/HibernateVLEStatisticsDao.java index 8ee2807530..b18b2da278 100644 --- a/src/main/java/org/wise/portal/dao/statistics/impl/HibernateVLEStatisticsDao.java +++ b/src/main/java/org/wise/portal/dao/statistics/impl/HibernateVLEStatisticsDao.java @@ -25,10 +25,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/org/wise/portal/dao/status/impl/HibernateRunStatusDao.java b/src/main/java/org/wise/portal/dao/status/impl/HibernateRunStatusDao.java index c775bc71da..fe534a5807 100644 --- a/src/main/java/org/wise/portal/dao/status/impl/HibernateRunStatusDao.java +++ b/src/main/java/org/wise/portal/dao/status/impl/HibernateRunStatusDao.java @@ -23,10 +23,10 @@ */ package org.wise.portal.dao.status.impl; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/org/wise/portal/dao/status/impl/HibernateStudentStatusDao.java b/src/main/java/org/wise/portal/dao/status/impl/HibernateStudentStatusDao.java index c2ad58f92b..b498a82ce3 100644 --- a/src/main/java/org/wise/portal/dao/status/impl/HibernateStudentStatusDao.java +++ b/src/main/java/org/wise/portal/dao/status/impl/HibernateStudentStatusDao.java @@ -25,10 +25,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/org/wise/portal/dao/user/impl/HibernateUserDao.java b/src/main/java/org/wise/portal/dao/user/impl/HibernateUserDao.java index 6a97b31d53..bccb51371a 100644 --- a/src/main/java/org/wise/portal/dao/user/impl/HibernateUserDao.java +++ b/src/main/java/org/wise/portal/dao/user/impl/HibernateUserDao.java @@ -25,11 +25,11 @@ import java.util.Date; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Repository; diff --git a/src/main/java/org/wise/portal/dao/usertags/impl/HibernateUserTagsDao.java b/src/main/java/org/wise/portal/dao/usertags/impl/HibernateUserTagsDao.java index 5ed73e5c0d..d3a4df7f24 100644 --- a/src/main/java/org/wise/portal/dao/usertags/impl/HibernateUserTagsDao.java +++ b/src/main/java/org/wise/portal/dao/usertags/impl/HibernateUserTagsDao.java @@ -3,11 +3,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/work/impl/HibernateEventDao.java b/src/main/java/org/wise/portal/dao/work/impl/HibernateEventDao.java index 35dad70c21..a0fecf57e5 100644 --- a/src/main/java/org/wise/portal/dao/work/impl/HibernateEventDao.java +++ b/src/main/java/org/wise/portal/dao/work/impl/HibernateEventDao.java @@ -26,11 +26,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.json.JSONException; import org.json.JSONObject; diff --git a/src/main/java/org/wise/portal/dao/work/impl/HibernateNotebookItemDao.java b/src/main/java/org/wise/portal/dao/work/impl/HibernateNotebookItemDao.java index 8e90c930c3..8f1da42ff2 100644 --- a/src/main/java/org/wise/portal/dao/work/impl/HibernateNotebookItemDao.java +++ b/src/main/java/org/wise/portal/dao/work/impl/HibernateNotebookItemDao.java @@ -3,12 +3,12 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.persistence.criteria.Subquery; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentAssetDao.java b/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentAssetDao.java index 9a2278f16e..281033f992 100644 --- a/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentAssetDao.java +++ b/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentAssetDao.java @@ -26,11 +26,11 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; diff --git a/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentWorkDao.java b/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentWorkDao.java index 79e3e9ff9a..73362f0020 100644 --- a/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentWorkDao.java +++ b/src/main/java/org/wise/portal/dao/work/impl/HibernateStudentWorkDao.java @@ -27,11 +27,12 @@ import java.util.List; import java.util.Set; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Repository; diff --git a/src/main/java/org/wise/portal/dao/workgroup/impl/HibernateWorkgroupDao.java b/src/main/java/org/wise/portal/dao/workgroup/impl/HibernateWorkgroupDao.java index 495806f941..f28f415b85 100644 --- a/src/main/java/org/wise/portal/dao/workgroup/impl/HibernateWorkgroupDao.java +++ b/src/main/java/org/wise/portal/dao/workgroup/impl/HibernateWorkgroupDao.java @@ -27,11 +27,11 @@ import java.util.List; import java.util.Set; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.wise.portal.dao.impl.AbstractHibernateDao; @@ -67,10 +67,9 @@ public List getListByRunAndUser(Run run, User user) { List predicates = new ArrayList<>(); predicates.add(cb.equal(userImplRoot.get("id"), user.getId())); predicates.add(cb.equal(runImplRoot.get("id"), run.getId())); - predicates.add(cb.equal(runImplRoot.get("id"), workgroupImplRoot.get("run"))); - predicates.add(cb.equal(workgroupImplRoot.get("group"), persistentGroupRoot.get("id"))); - predicates - .add(cb.isMember(userImplRoot.get("id"), persistentGroupRoot.> get("members"))); + predicates.add(cb.equal(runImplRoot, workgroupImplRoot.get("run"))); + predicates.add(cb.equal(workgroupImplRoot.get("group"), persistentGroupRoot)); + predicates.add(cb.isMember(user, persistentGroupRoot.> get("members"))); cq.select(workgroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); List runResultList = query.getResultList(); @@ -86,9 +85,8 @@ public List getListByUser(User user) { Root userImplRoot = cq.from(UserImpl.class); List predicates = new ArrayList<>(); predicates.add(cb.equal(userImplRoot.get("id"), user.getId())); - predicates.add(cb.equal(workgroupImplRoot.get("group"), persistentGroupRoot.get("id"))); - predicates - .add(cb.isMember(userImplRoot.get("id"), persistentGroupRoot.> get("members"))); + predicates.add(cb.equal(workgroupImplRoot.get("group"), persistentGroupRoot)); + predicates.add(cb.isMember(user, persistentGroupRoot.> get("members"))); cq.select(workgroupImplRoot).where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery query = entityManager.createQuery(cq); List runResultList = query.getResultList(); diff --git a/src/main/java/org/wise/portal/domain/admin/DailyAdminJob.java b/src/main/java/org/wise/portal/domain/admin/DailyAdminJob.java index 1494296c4b..ee1a738864 100644 --- a/src/main/java/org/wise/portal/domain/admin/DailyAdminJob.java +++ b/src/main/java/org/wise/portal/domain/admin/DailyAdminJob.java @@ -33,7 +33,7 @@ import java.text.DateFormat; import java.util.*; -import javax.mail.MessagingException; +import jakarta.mail.MessagingException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -225,7 +225,7 @@ public void gatherVLEStatistics() { String username = appProperties.getProperty("spring.datasource.username"); String password = appProperties.getProperty("spring.datasource.password"); String url = appProperties.getProperty("spring.datasource.url"); - Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); + Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); Connection conn = DriverManager.getConnection(url, username, password); Statement statement = conn.createStatement(); JSONObject vleStatistics = new JSONObject(); diff --git a/src/main/java/org/wise/portal/domain/attendance/impl/StudentAttendanceImpl.java b/src/main/java/org/wise/portal/domain/attendance/impl/StudentAttendanceImpl.java index 65af6ca2c7..a16b3ecefb 100644 --- a/src/main/java/org/wise/portal/domain/attendance/impl/StudentAttendanceImpl.java +++ b/src/main/java/org/wise/portal/domain/attendance/impl/StudentAttendanceImpl.java @@ -25,13 +25,13 @@ import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import lombok.Getter; import lombok.Setter; @@ -53,7 +53,7 @@ public class StudentAttendanceImpl implements StudentAttendance { public static final String DATA_STORE_NAME = "student_attendance"; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", columnDefinition = "int") private Integer id = null; diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclEntry.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclEntry.java index afecc20056..cc76d2dad5 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclEntry.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclEntry.java @@ -22,18 +22,18 @@ import java.io.Serializable; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -52,9 +52,9 @@ * @author Cynick Young */ @Entity -@Table(name = PersistentAclEntry.DATA_STORE_NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { - PersistentAclEntry.COLUMN_NAME_TARGET_OBJECT_ID, - PersistentAclEntry.COLUMN_NAME_ACE_ORDER }) }) +@Table(name = PersistentAclEntry.DATA_STORE_NAME, uniqueConstraints = { + @UniqueConstraint(columnNames = { PersistentAclEntry.COLUMN_NAME_TARGET_OBJECT_ID, + PersistentAclEntry.COLUMN_NAME_ACE_ORDER }) }) public class PersistentAclEntry implements ImmutableAclEntry, Serializable { @Transient @@ -121,7 +121,7 @@ public class PersistentAclEntry implements ImmutableAclEntry, Serializable { private Boolean auditFailure; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id; @@ -141,10 +141,9 @@ public class PersistentAclEntry implements ImmutableAclEntry, Serializable { * @param auditSuccess * @param auditFailure */ - public PersistentAclEntry( - MutableAclTargetObjectIdentity targetObjectIdentity, - Integer aceOrder, MutableAclSid sid, Permission permission, - Boolean granting, Boolean auditSuccess, Boolean auditFailure) { + public PersistentAclEntry(MutableAclTargetObjectIdentity targetObjectIdentity, Integer aceOrder, + MutableAclSid sid, Permission permission, Boolean granting, Boolean auditSuccess, + Boolean auditFailure) { super(); this.targetObjectIdentity = targetObjectIdentity; this.aceOrder = aceOrder; @@ -173,8 +172,7 @@ public boolean isAuditSuccess() { } @SuppressWarnings("unused") - private void setTargetObjectIdentity( - MutableAclTargetObjectIdentity targetObjectIdentity) { + private void setTargetObjectIdentity(MutableAclTargetObjectIdentity targetObjectIdentity) { this.targetObjectIdentity = targetObjectIdentity; } diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclSid.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclSid.java index a5fc2f8bcf..33e9b5c7fd 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclSid.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclSid.java @@ -20,15 +20,15 @@ */ package org.wise.portal.domain.authentication.impl; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -45,9 +45,9 @@ * @see org.springframework.security.acls.model.Sid */ @Entity -@Table(name = PersistentAclSid.DATA_STORE_NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { - PersistentAclSid.COLUMN_NAME_SID, - PersistentAclSid.COLUMN_NAME_IS_PRINCIPAL }) }) +@Table(name = PersistentAclSid.DATA_STORE_NAME, uniqueConstraints = { + @UniqueConstraint(columnNames = { PersistentAclSid.COLUMN_NAME_SID, + PersistentAclSid.COLUMN_NAME_IS_PRINCIPAL }) }) public class PersistentAclSid implements MutableAclSid { @Transient @@ -63,7 +63,7 @@ public class PersistentAclSid implements MutableAclSid { public static final String COLUMN_NAME_SID = "sid"; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id; @@ -104,15 +104,13 @@ public String getPrincipal() { if (this.getIsPrincipal()) { return this.getSidName(); } - throw new UnsupportedOperationException( - "Unsupported method for this instance of Sid"); + throw new UnsupportedOperationException("Unsupported method for this instance of Sid"); } public void setPrincipal(Authentication authentication) { this.setIsPrincipal(Boolean.TRUE); if (authentication.getPrincipal() instanceof UserDetails) { - this.setSidName(((UserDetails) authentication.getPrincipal()) - .getUsername()); + this.setSidName(((UserDetails) authentication.getPrincipal()).getUsername()); } else { this.setSidName(authentication.getPrincipal().toString()); } @@ -128,8 +126,7 @@ public String getGrantedAuthority() { throw new IllegalStateException(); } if (this.getIsPrincipal()) { - throw new UnsupportedOperationException( - "Unsupported method for this instance of Sid"); + throw new UnsupportedOperationException("Unsupported method for this instance of Sid"); } else { return this.getSidName(); } @@ -139,8 +136,7 @@ public String getGrantedAuthority() { public int hashCode() { final int PRIME = 31; int result = 1; - result = PRIME * result - + ((isPrincipal == null) ? 0 : isPrincipal.hashCode()); + result = PRIME * result + ((isPrincipal == null) ? 0 : isPrincipal.hashCode()); result = PRIME * result + ((sidName == null) ? 0 : sidName.hashCode()); return result; } diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObject.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObject.java index bf482e9004..f92102a813 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObject.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObject.java @@ -20,14 +20,14 @@ */ package org.wise.portal.domain.authentication.impl; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -53,7 +53,7 @@ public class PersistentAclTargetObject implements MutableAclTargetObject { public static final String COLUMN_NAME_CLASSNAME = "class"; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id; diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObjectIdentity.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObjectIdentity.java index 11b2a2d731..85df9d6b55 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObjectIdentity.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentAclTargetObjectIdentity.java @@ -24,22 +24,22 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -124,7 +124,7 @@ public class PersistentAclTargetObjectIdentity implements MutableAclTargetObject private Set tags = new HashSet(); @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id; diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentGrantedAuthority.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentGrantedAuthority.java index 0029428ecb..e69e06c19f 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentGrantedAuthority.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentGrantedAuthority.java @@ -20,14 +20,14 @@ */ package org.wise.portal.domain.authentication.impl; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -53,7 +53,7 @@ public class PersistentGrantedAuthority implements MutableGrantedAuthority { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter private Long id; @@ -77,8 +77,7 @@ public PersistentGrantedAuthority(String authority) { public int hashCode() { final int PRIME = 31; int result = 1; - result = PRIME * result - + ((this.authority == null) ? 0 : this.authority.hashCode()); + result = PRIME * result + ((this.authority == null) ? 0 : this.authority.hashCode()); return result; } diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentUserDetails.java b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentUserDetails.java index 3c972faba3..8eaa657a09 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/PersistentUserDetails.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/PersistentUserDetails.java @@ -27,20 +27,20 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -112,7 +112,7 @@ public class PersistentUserDetails implements MutableUserDetails { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter private Long id = null; diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/StudentUserDetails.java b/src/main/java/org/wise/portal/domain/authentication/impl/StudentUserDetails.java index f583a8fd90..43677ed532 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/StudentUserDetails.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/StudentUserDetails.java @@ -27,10 +27,10 @@ import java.util.Date; import java.util.HashMap; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/org/wise/portal/domain/authentication/impl/TeacherUserDetails.java b/src/main/java/org/wise/portal/domain/authentication/impl/TeacherUserDetails.java index 76f7e51340..00ad04b65c 100644 --- a/src/main/java/org/wise/portal/domain/authentication/impl/TeacherUserDetails.java +++ b/src/main/java/org/wise/portal/domain/authentication/impl/TeacherUserDetails.java @@ -26,10 +26,10 @@ import java.util.Date; import java.util.HashMap; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/org/wise/portal/domain/group/impl/GroupParameters.java b/src/main/java/org/wise/portal/domain/group/impl/GroupParameters.java index 91f4fbfa84..1769b0866a 100644 --- a/src/main/java/org/wise/portal/domain/group/impl/GroupParameters.java +++ b/src/main/java/org/wise/portal/domain/group/impl/GroupParameters.java @@ -39,7 +39,7 @@ public class GroupParameters implements Serializable { private String name; - private Long parentId = new Long(0); + private Long parentId = Long.valueOf(0); private Long[] memberIds = new Long[0]; } diff --git a/src/main/java/org/wise/portal/domain/group/impl/PersistentGroup.java b/src/main/java/org/wise/portal/domain/group/impl/PersistentGroup.java index 73076031b7..33223f3e46 100644 --- a/src/main/java/org/wise/portal/domain/group/impl/PersistentGroup.java +++ b/src/main/java/org/wise/portal/domain/group/impl/PersistentGroup.java @@ -23,20 +23,20 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -76,7 +76,7 @@ public class PersistentGroup implements Group { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id = null; @@ -89,7 +89,8 @@ public class PersistentGroup implements Group { // TODO: why is the EAGER fetched? @ManyToMany(targetEntity = UserImpl.class, fetch = FetchType.EAGER) - @JoinTable(name = USERS_JOIN_TABLE_NAME, joinColumns = { @JoinColumn(name = GROUPS_JOIN_COLUMN_NAME, nullable = false) }, inverseJoinColumns = @JoinColumn(name = USERS_JOIN_COLUMN_NAME, nullable = false)) + @JoinTable(name = USERS_JOIN_TABLE_NAME, joinColumns = { + @JoinColumn(name = GROUPS_JOIN_COLUMN_NAME, nullable = false) }, inverseJoinColumns = @JoinColumn(name = USERS_JOIN_COLUMN_NAME, nullable = false)) @Getter @Setter private Set members = new HashSet(); @@ -100,7 +101,7 @@ public class PersistentGroup implements Group { private String name; @ManyToOne(targetEntity = PersistentGroup.class, fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) - @Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE }) + @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE }) @JoinColumn(name = COLUMN_NAME_PARENT_FK) @Getter @Setter @@ -133,8 +134,8 @@ public boolean equals(Object obj) { return true; if (obj == null) return false; - if (obj instanceof HibernateProxy) { - if (getClass() != (( HibernateProxy) obj).getHibernateLazyInitializer().getImplementation().getClass()) { + if (obj instanceof HibernateProxy proxy) { + if (getClass() != proxy.getHibernateLazyInitializer().getImplementation().getClass()) { return false; } } else if (getClass() != obj.getClass()) diff --git a/src/main/java/org/wise/portal/domain/group/impl/StringToGroupConverter.java b/src/main/java/org/wise/portal/domain/group/impl/StringToGroupConverter.java new file mode 100644 index 0000000000..f597616c0c --- /dev/null +++ b/src/main/java/org/wise/portal/domain/group/impl/StringToGroupConverter.java @@ -0,0 +1,24 @@ +package org.wise.portal.domain.group.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; +import org.wise.portal.dao.ObjectNotFoundException; +import org.wise.portal.domain.group.Group; +import org.wise.portal.service.group.GroupService; + +@Component +public class StringToGroupConverter implements Converter { + + @Autowired + private GroupService groupService; + + @Override + public Group convert(String id) { + try { + return groupService.retrieveById(Long.parseLong(id)); + } catch (ObjectNotFoundException e) { + throw new IllegalArgumentException("Invalid group ID: " + id); + } + } +} diff --git a/src/main/java/org/wise/portal/domain/impl/TagImpl.java b/src/main/java/org/wise/portal/domain/impl/TagImpl.java index bc3204472d..8efe1118d7 100644 --- a/src/main/java/org/wise/portal/domain/impl/TagImpl.java +++ b/src/main/java/org/wise/portal/domain/impl/TagImpl.java @@ -23,17 +23,17 @@ */ package org.wise.portal.domain.impl; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -59,12 +59,13 @@ public class TagImpl implements Tag { @Column private String name; - @ManyToOne(targetEntity = RunImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "runId") @JsonIgnore private Run run; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; } diff --git a/src/main/java/org/wise/portal/domain/newsitem/impl/NewsItemImpl.java b/src/main/java/org/wise/portal/domain/newsitem/impl/NewsItemImpl.java index 1b0a5b7166..a7485fc474 100644 --- a/src/main/java/org/wise/portal/domain/newsitem/impl/NewsItemImpl.java +++ b/src/main/java/org/wise/portal/domain/newsitem/impl/NewsItemImpl.java @@ -25,16 +25,16 @@ import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import lombok.Getter; import lombok.Setter; @@ -75,7 +75,7 @@ public class NewsItemImpl implements NewsItem, Comparable { @Transient private static final long serialVersionUID = 1L; - @Column(name = NewsItemImpl.COLUMN_NAME_NEWS, length=64000, columnDefinition = "text", nullable = false) + @Column(name = NewsItemImpl.COLUMN_NAME_NEWS, length = 64000, columnDefinition = "text", nullable = false) private String news = null; @Column(name = NewsItemImpl.COLUMN_NAME_DATE, nullable = false) @@ -89,13 +89,13 @@ public class NewsItemImpl implements NewsItem, Comparable { private String title; @Column(name = NewsItemImpl.COLUMN_NAME_TYPE, nullable = false) - private String type; // type of news item: [public,teacherOnly] + private String type; // type of news item: [public,teacherOnly] @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; - public int compareTo(NewsItem news){ + public int compareTo(NewsItem news) { return news.getDate().compareTo(this.getDate()); } diff --git a/src/main/java/org/wise/portal/domain/peergroup/impl/PeerGroupImpl.java b/src/main/java/org/wise/portal/domain/peergroup/impl/PeerGroupImpl.java index f3e68b1366..d66ed2b9ba 100644 --- a/src/main/java/org/wise/portal/domain/peergroup/impl/PeerGroupImpl.java +++ b/src/main/java/org/wise/portal/domain/peergroup/impl/PeerGroupImpl.java @@ -26,18 +26,18 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -65,19 +65,18 @@ public class PeerGroupImpl implements PeerGroup { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; - @ManyToOne(targetEntity = PeerGroupingImpl.class, cascade = { CascadeType.PERSIST }, - fetch = FetchType.LAZY) + @ManyToOne(targetEntity = PeerGroupingImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "peerGroupingId", nullable = false) @JsonIgnore private PeerGrouping peerGrouping; @ManyToMany(targetEntity = WorkgroupImpl.class) - @JoinTable(name = "peer_groups_related_to_workgroups", - joinColumns = { @JoinColumn(name = "peer_group_fk", nullable = false)}, - inverseJoinColumns = @JoinColumn(name = "workgroup_fk", nullable = false)) + @JoinTable(name = "peer_groups_related_to_workgroups", joinColumns = { + @JoinColumn(name = "peer_group_fk", nullable = false) }, inverseJoinColumns = @JoinColumn(name = "workgroup_fk", nullable = false)) private Set members = new HashSet(); @OneToOne(targetEntity = PersistentGroup.class, fetch = FetchType.LAZY) @@ -85,7 +84,8 @@ public class PeerGroupImpl implements PeerGroup { @JsonIgnore private Group period; - public PeerGroupImpl() {} + public PeerGroupImpl() { + } public PeerGroupImpl(PeerGrouping peerGrouping, Group period, Set members) { this.peerGrouping = peerGrouping; diff --git a/src/main/java/org/wise/portal/domain/peergroup/impl/StringToPeerGroupConverter.java b/src/main/java/org/wise/portal/domain/peergroup/impl/StringToPeerGroupConverter.java new file mode 100644 index 0000000000..b3c75a003a --- /dev/null +++ b/src/main/java/org/wise/portal/domain/peergroup/impl/StringToPeerGroupConverter.java @@ -0,0 +1,23 @@ +package org.wise.portal.domain.peergroup.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; +import org.wise.portal.dao.ObjectNotFoundException; +import org.wise.portal.domain.peergroup.PeerGroup; +import org.wise.portal.service.peergroup.PeerGroupService; + +@Component +public class StringToPeerGroupConverter implements Converter { + @Autowired + private PeerGroupService peerGroupService; + + @Override + public PeerGroup convert(String id) { + try { + return peerGroupService.getById(Long.valueOf(id)); + } catch (ObjectNotFoundException e) { + throw new IllegalArgumentException("Invalid peer group ID: " + id); + } + } +} diff --git a/src/main/java/org/wise/portal/domain/peergrouping/impl/PeerGroupingImpl.java b/src/main/java/org/wise/portal/domain/peergrouping/impl/PeerGroupingImpl.java index afe5c82de0..8f9af1e523 100644 --- a/src/main/java/org/wise/portal/domain/peergrouping/impl/PeerGroupingImpl.java +++ b/src/main/java/org/wise/portal/domain/peergrouping/impl/PeerGroupingImpl.java @@ -23,18 +23,18 @@ */ package org.wise.portal.domain.peergrouping.impl; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -52,9 +52,9 @@ * @author Hiroki Terashima */ @Entity -@Table(name = "peer_groupings", - indexes = { @Index(columnList = "runId", name = "peerGroupingsRunIdIndex") }, - uniqueConstraints = { @UniqueConstraint(columnNames = { "runId", "tag" }) }) +@Table(name = "peer_groupings", indexes = { + @Index(columnList = "runId", name = "peerGroupingsRunIdIndex") }, uniqueConstraints = { + @UniqueConstraint(columnNames = { "runId", "tag" }) }) @Getter @Setter public class PeerGroupingImpl implements PeerGrouping { @@ -62,7 +62,7 @@ public class PeerGroupingImpl implements PeerGrouping { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @ManyToOne(targetEntity = RunImpl.class, cascade = { diff --git a/src/main/java/org/wise/portal/domain/portal/impl/PortalImpl.java b/src/main/java/org/wise/portal/domain/portal/impl/PortalImpl.java index 761894bc75..3126cef063 100644 --- a/src/main/java/org/wise/portal/domain/portal/impl/PortalImpl.java +++ b/src/main/java/org/wise/portal/domain/portal/impl/PortalImpl.java @@ -25,14 +25,14 @@ import java.util.Properties; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -73,16 +73,16 @@ public class PortalImpl implements Portal { private String comments; @Column(name = "settings", length = 32768, columnDefinition = "text") - private String settings; // text (blob) 2^15 + private String settings; // text (blob) 2^15 @Column(name = "projectLibraryGroups", length = 32768, columnDefinition = "text") private String projectLibraryGroups; @Column(name = "run_survey_template", length = 32768, columnDefinition = "text") - private String runSurveyTemplate; // text (blob) 2^15 + private String runSurveyTemplate; // text (blob) 2^15 @Column(name = "projectMetadataSettings", length = 32768, columnDefinition = "text") - private String projectMetadataSettings; // text (blob) 2^15 + private String projectMetadataSettings; // text (blob) 2^15 @Column(name = "announcement", length = 32768, columnDefinition = "text") private String announcement; @@ -91,7 +91,7 @@ public class PortalImpl implements Portal { private String structures; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", columnDefinition = "tinyint") public Integer id = null; @@ -105,7 +105,7 @@ public boolean isLoginAllowed() { return settings.getBoolean("isLoginAllowed"); } catch (JSONException e) { } - return true; // allow login by default if there was an exception + return true; // allow login by default if there was an exception } public void setLoginAllowed(boolean loginAllowed) { @@ -123,7 +123,7 @@ public boolean isSendStatisticsToHub() { return settings.getBoolean("isSendStatisticsToHub"); } catch (JSONException e) { } - return false; // don't send statistics by default if there was an exception + return false; // don't send statistics by default if there was an exception } public void setSendStatisticsToHub(boolean doSendStatistics) { diff --git a/src/main/java/org/wise/portal/domain/portal/impl/PortalStatisticsImpl.java b/src/main/java/org/wise/portal/domain/portal/impl/PortalStatisticsImpl.java index 8000ce2fe0..c5231b7033 100644 --- a/src/main/java/org/wise/portal/domain/portal/impl/PortalStatisticsImpl.java +++ b/src/main/java/org/wise/portal/domain/portal/impl/PortalStatisticsImpl.java @@ -26,13 +26,13 @@ import java.io.Serializable; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import org.wise.portal.domain.portal.PortalStatistics; import org.json.JSONException; @@ -40,13 +40,13 @@ @Entity @Table(name = "portal_statistics") -public class PortalStatisticsImpl implements PortalStatistics { +public class PortalStatisticsImpl implements PortalStatistics { @Transient private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", columnDefinition = "smallint") public Integer id = null; diff --git a/src/main/java/org/wise/portal/domain/project/impl/PreviewProjectParameters.java b/src/main/java/org/wise/portal/domain/project/impl/PreviewProjectParameters.java index bd025d200f..019c055ca3 100644 --- a/src/main/java/org/wise/portal/domain/project/impl/PreviewProjectParameters.java +++ b/src/main/java/org/wise/portal/domain/project/impl/PreviewProjectParameters.java @@ -23,7 +23,7 @@ */ package org.wise.portal.domain.project.impl; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/org/wise/portal/domain/project/impl/ProjectImpl.java b/src/main/java/org/wise/portal/domain/project/impl/ProjectImpl.java index 57c166cb2a..749f3e5925 100644 --- a/src/main/java/org/wise/portal/domain/project/impl/ProjectImpl.java +++ b/src/main/java/org/wise/portal/domain/project/impl/ProjectImpl.java @@ -31,7 +31,7 @@ import java.util.Set; import java.util.TreeSet; -import javax.persistence.*; +import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; @@ -361,7 +361,7 @@ public Integer getWiseVersion() { if (this.wiseVersion != null) { return this.wiseVersion; } else { - return new Integer(4); + return Integer.valueOf(4); } } diff --git a/src/main/java/org/wise/portal/domain/project/impl/ProjectMetadataImpl.java b/src/main/java/org/wise/portal/domain/project/impl/ProjectMetadataImpl.java index bccf190fe3..9a49eb05fa 100644 --- a/src/main/java/org/wise/portal/domain/project/impl/ProjectMetadataImpl.java +++ b/src/main/java/org/wise/portal/domain/project/impl/ProjectMetadataImpl.java @@ -26,13 +26,13 @@ import java.io.Serializable; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import org.json.JSONArray; import lombok.Getter; @@ -52,7 +52,7 @@ public class ProjectMetadataImpl implements ProjectMetadata, Serializable { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Getter @Setter private Long id = null; diff --git a/src/main/java/org/wise/portal/domain/project/impl/StringToProjectConverter.java b/src/main/java/org/wise/portal/domain/project/impl/StringToProjectConverter.java new file mode 100644 index 0000000000..f58f0fa41e --- /dev/null +++ b/src/main/java/org/wise/portal/domain/project/impl/StringToProjectConverter.java @@ -0,0 +1,23 @@ +package org.wise.portal.domain.project.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; +import org.wise.portal.dao.ObjectNotFoundException; +import org.wise.portal.domain.project.Project; +import org.wise.portal.service.project.ProjectService; + +@Component +public class StringToProjectConverter implements Converter { + @Autowired + private ProjectService projectService; + + @Override + public Project convert(String id) { + try { + return projectService.getById(Long.parseLong(id)); + } catch (ObjectNotFoundException e) { + throw new IllegalArgumentException("Invalid project ID: " + id); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/wise/portal/domain/run/impl/RunImpl.java b/src/main/java/org/wise/portal/domain/run/impl/RunImpl.java index 5300ac46ef..809b79ba0a 100644 --- a/src/main/java/org/wise/portal/domain/run/impl/RunImpl.java +++ b/src/main/java/org/wise/portal/domain/run/impl/RunImpl.java @@ -39,7 +39,7 @@ import org.wise.portal.domain.user.User; import org.wise.portal.domain.user.impl.UserImpl; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.*; /** @@ -306,7 +306,7 @@ public boolean isPaused() { int end = this.info.indexOf(""); String isPausedStr = this.info.substring(start + 10, end); System.out.println(isPausedStr); - return new Boolean(isPausedStr).booleanValue(); + return Boolean.valueOf(isPausedStr).booleanValue(); } } return false; diff --git a/src/main/java/org/wise/portal/domain/run/impl/StringToRunConverter.java b/src/main/java/org/wise/portal/domain/run/impl/StringToRunConverter.java new file mode 100644 index 0000000000..9ec51bb5f8 --- /dev/null +++ b/src/main/java/org/wise/portal/domain/run/impl/StringToRunConverter.java @@ -0,0 +1,23 @@ +package org.wise.portal.domain.run.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; +import org.wise.portal.dao.ObjectNotFoundException; +import org.wise.portal.domain.run.Run; +import org.wise.portal.service.run.RunService; + +@Component +public class StringToRunConverter implements Converter { + @Autowired + private RunService runService; + + @Override + public Run convert(String id) { + try { + return runService.retrieveById(Long.parseLong(id)); + } catch (ObjectNotFoundException e) { + throw new IllegalArgumentException("Invalid project ID: " + id); + } + } +} diff --git a/src/main/java/org/wise/portal/domain/user/impl/UserImpl.java b/src/main/java/org/wise/portal/domain/user/impl/UserImpl.java index 813fe67cc9..f4deb7fb69 100644 --- a/src/main/java/org/wise/portal/domain/user/impl/UserImpl.java +++ b/src/main/java/org/wise/portal/domain/user/impl/UserImpl.java @@ -23,17 +23,17 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import org.hibernate.proxy.HibernateProxy; import org.wise.portal.domain.authentication.MutableUserDetails; @@ -63,7 +63,7 @@ public class UserImpl implements User { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @Version @@ -135,9 +135,8 @@ public boolean equals(Object obj) { return true; if (obj == null) return false; - if (obj instanceof HibernateProxy) { - if (getClass() != ((HibernateProxy) obj).getHibernateLazyInitializer().getImplementation() - .getClass()) { + if (obj instanceof HibernateProxy proxy) { + if (getClass() != proxy.getHibernateLazyInitializer().getImplementation().getClass()) { return false; } } else if (getClass() != obj.getClass()) diff --git a/src/main/java/org/wise/portal/domain/usertag/impl/UserTagImpl.java b/src/main/java/org/wise/portal/domain/usertag/impl/UserTagImpl.java index fb3f87a0da..d95b4f7798 100644 --- a/src/main/java/org/wise/portal/domain/usertag/impl/UserTagImpl.java +++ b/src/main/java/org/wise/portal/domain/usertag/impl/UserTagImpl.java @@ -3,16 +3,16 @@ import java.util.HashMap; import java.util.Map; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import org.wise.portal.domain.user.User; import org.wise.portal.domain.user.impl.UserImpl; @@ -36,7 +36,7 @@ public class UserTagImpl implements UserTag { public static final String DATA_STORE_NAME = "user_tags"; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @ManyToOne(targetEntity = UserImpl.class, fetch = FetchType.LAZY) @@ -66,4 +66,4 @@ public Map toMap() { map.put("color", this.color); return map; } -} \ No newline at end of file +} diff --git a/src/main/java/org/wise/portal/domain/workgroup/impl/StringToWorkgroupConverter.java b/src/main/java/org/wise/portal/domain/workgroup/impl/StringToWorkgroupConverter.java new file mode 100644 index 0000000000..8d9ad40109 --- /dev/null +++ b/src/main/java/org/wise/portal/domain/workgroup/impl/StringToWorkgroupConverter.java @@ -0,0 +1,23 @@ +package org.wise.portal.domain.workgroup.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.converter.Converter; +import org.wise.portal.domain.workgroup.Workgroup; +import org.wise.portal.service.workgroup.WorkgroupService; +import org.wise.portal.dao.ObjectNotFoundException; +import org.springframework.stereotype.Component; + +@Component +public class StringToWorkgroupConverter implements Converter { + @Autowired + private WorkgroupService workgroupService; + + @Override + public Workgroup convert(String id) { + try { + return workgroupService.retrieveById(Long.parseLong(id)); + } catch (ObjectNotFoundException e) { + throw new IllegalArgumentException("Invalid workgroup ID: " + id); + } + } +} diff --git a/src/main/java/org/wise/portal/domain/workgroup/impl/WorkgroupImpl.java b/src/main/java/org/wise/portal/domain/workgroup/impl/WorkgroupImpl.java index ac8d024205..7142f0c9ec 100644 --- a/src/main/java/org/wise/portal/domain/workgroup/impl/WorkgroupImpl.java +++ b/src/main/java/org/wise/portal/domain/workgroup/impl/WorkgroupImpl.java @@ -26,19 +26,20 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.Version; import lombok.Getter; import lombok.Setter; @@ -68,14 +69,14 @@ public class WorkgroupImpl implements Workgroup, Comparable { private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) public Long id = null; @Version @Column(name = "OPTLOCK") private Integer version = null; - @OneToOne(targetEntity = RunImpl.class, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, fetch = FetchType.LAZY) @JoinColumn(name = "run_fk", nullable = false) private Run run; @@ -83,7 +84,7 @@ public class WorkgroupImpl implements Workgroup, Comparable { @JoinColumn(name = "group_fk", nullable = false) private Group group = new PersistentGroup(); - @OneToOne(targetEntity = PersistentGroup.class, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = PersistentGroup.class, fetch = FetchType.LAZY) @JoinColumn(name = "period") private Group period; @@ -91,10 +92,12 @@ public class WorkgroupImpl implements Workgroup, Comparable { private boolean teacherWorkgroup; @ManyToMany(targetEntity = TagImpl.class, fetch = FetchType.LAZY) - @JoinTable(name = "workgroups_related_to_tags", joinColumns = { @JoinColumn(name = "workgroups_fk", nullable = false) }, inverseJoinColumns = @JoinColumn(name = "tags_fk", nullable = false)) + @JoinTable(name = "workgroups_related_to_tags", joinColumns = { + @JoinColumn(name = "workgroups_fk", nullable = false) }, inverseJoinColumns = @JoinColumn(name = "tags_fk", nullable = false)) private Set tags = new HashSet(); - public WorkgroupImpl() {} + public WorkgroupImpl() { + } /** * Alternate WorkgroupImpl constructor with default users @@ -116,8 +119,9 @@ public WorkgroupImpl(String name, Set members, Run run, Group period) { this.setPeriod(period); if ((run.getOwner() != null && members.size() == 1 && run.getOwner().equals(members.iterator().next())) - || (members.size() > 0 && run.getSharedowners() != null && run.getSharedowners().containsAll(members))) { - this.setTeacherWorkgroup(true); + || (members.size() > 0 && run.getSharedowners() != null + && run.getSharedowners().containsAll(members))) { + this.setTeacherWorkgroup(true); } } @@ -169,8 +173,7 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((group == null) ? 0 : group.hashCode()); - result = prime * result - + ((run == null) ? 0 : run.hashCode()); + result = prime * result + ((run == null) ? 0 : run.hashCode()); return result; } @@ -180,8 +183,8 @@ public boolean equals(Object obj) { return true; if (obj == null) return false; - if (obj instanceof HibernateProxy) { - if (getClass() != (( HibernateProxy) obj).getHibernateLazyInitializer().getImplementation().getClass()) { + if (obj instanceof HibernateProxy proxy) { + if (getClass() != proxy.getHibernateLazyInitializer().getImplementation().getClass()) { return false; } } else if (getClass() != obj.getClass()) diff --git a/src/main/java/org/wise/portal/presentation/util/http/Base64.java b/src/main/java/org/wise/portal/presentation/util/http/Base64.java index 22e0696a0b..dcbbbd6e26 100644 --- a/src/main/java/org/wise/portal/presentation/util/http/Base64.java +++ b/src/main/java/org/wise/portal/presentation/util/http/Base64.java @@ -854,7 +854,7 @@ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int op if( off + len > source.length ){ throw new IllegalArgumentException( - String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); + "Cannot have offset of %d and length of %d with array of length %d".formatted(off, len, source.length)); } // end if: off < 0 // Compress? @@ -987,12 +987,12 @@ private static int decode4to3( throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ - throw new IllegalArgumentException( String.format( - "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); + throw new IllegalArgumentException( + "Source array with length %d cannot have offset of %d and still process four bytes.".formatted(source.length, srcOffset) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ - throw new IllegalArgumentException( String.format( - "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); + throw new IllegalArgumentException( + "Destination array with length %d cannot have offset of %d and still store three bytes.".formatted(destination.length, destOffset) ); } // end if @@ -1095,8 +1095,8 @@ public static byte[] decode( byte[] source, int off, int len, int options ) throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ - throw new IllegalArgumentException( String.format( - "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); + throw new IllegalArgumentException( + "Source array with length %d cannot have offset of %d and process %d bytes.".formatted(source.length, off, len) ); } // end if if( len == 0 ){ @@ -1140,8 +1140,8 @@ public static byte[] decode( byte[] source, int off, int len, int options ) } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. - throw new java.io.IOException( String.format( - "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); + throw new java.io.IOException( + "Bad Base64 input character decimal %d in array position %d".formatted(((int) source[i]) & 0xFF, i) ); } // end else: } // each input character diff --git a/src/main/java/org/wise/portal/presentation/web/config/GoogleOpenIdConnectConfig.java b/src/main/java/org/wise/portal/presentation/web/config/GoogleOpenIdConnectConfig.java deleted file mode 100644 index 0e56bb305d..0000000000 --- a/src/main/java/org/wise/portal/presentation/web/config/GoogleOpenIdConnectConfig.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.wise.portal.presentation.web.config; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.oauth2.client.OAuth2ClientContext; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; -import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; - -import java.util.Arrays; - -@Configuration -@EnableOAuth2Client -public class GoogleOpenIdConnectConfig { - - @Value("${google.clientId:}") - private String googleClientId; - - @Value("${google.clientSecret:}") - private String googleClientSecret; - - @Value("${google.accessTokenUri:}") - private String googleAccessTokenUri; - - @Value("${google.userAuthorizationUri:}") - private String googleUserAuthorizationUri; - - @Value("${google.redirectUri:}") - private String googleRedirectUri; - - @Bean - public OAuth2ProtectedResourceDetails googleOpenId() { - final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); - details.setClientId(googleClientId); - details.setClientSecret(googleClientSecret); - details.setAccessTokenUri(googleAccessTokenUri); - details.setUserAuthorizationUri(googleUserAuthorizationUri); - details.setScope(Arrays.asList("openid", "email")); - details.setPreEstablishedRedirectUri(googleRedirectUri); - details.setUseCurrentUri(false); - return details; - } - - @Bean - public OAuth2RestTemplate googleOpenIdRestTemplate(final OAuth2ClientContext clientContext) { - final OAuth2RestTemplate template = new OAuth2RestTemplate(googleOpenId(), clientContext); - return template; - } -} diff --git a/src/main/java/org/wise/portal/presentation/web/config/MicrosoftOpenIdConnectConfig.java b/src/main/java/org/wise/portal/presentation/web/config/MicrosoftOpenIdConnectConfig.java deleted file mode 100644 index a4ba1b37f7..0000000000 --- a/src/main/java/org/wise/portal/presentation/web/config/MicrosoftOpenIdConnectConfig.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.wise.portal.presentation.web.config; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.oauth2.client.OAuth2ClientContext; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; -import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; - -import java.util.Arrays; - -@Configuration -@EnableOAuth2Client -public class MicrosoftOpenIdConnectConfig { - - @Value("${microsoft.accessTokenUri:}") - private String accessTokenUri; - - @Value("${microsoft.clientId:}") - private String clientId; - - @Value("${microsoft.clientSecret:}") - private String clientSecret; - - @Value("${microsoft.redirectUri:}") - private String redirectUri; - - @Value("${microsoft.userAuthorizationUri:}") - private String userAuthorizationUri; - - @Bean("microsoftOAuth2ProtectedResourceDetails") - public OAuth2ProtectedResourceDetails microsoftOpenId() { - final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); - details.setClientId(clientId); - details.setClientSecret(clientSecret); - details.setAccessTokenUri(accessTokenUri); - details.setUserAuthorizationUri(userAuthorizationUri); - details.setScope(Arrays.asList("openid", "email", "profile")); - details.setPreEstablishedRedirectUri(redirectUri); - details.setUseCurrentUri(false); - return details; - } - - @Bean("microsoftOpenIdRestTemplate") - public OAuth2RestTemplate microsoftOpenIdRestTemplate(final OAuth2ClientContext clientContext) { - final OAuth2RestTemplate template = new OAuth2RestTemplate(microsoftOpenId(), clientContext); - return template; - } -} diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/AnnouncementController.java b/src/main/java/org/wise/portal/presentation/web/controllers/AnnouncementController.java index 429805619b..7473151040 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/AnnouncementController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/AnnouncementController.java @@ -17,7 +17,7 @@ public class AnnouncementController { @ResponseBody @GetMapping("/api/announcement") protected String getAnnouncement() throws ObjectNotFoundException { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); return portal.getAnnouncement(); } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/ControllerUtil.java b/src/main/java/org/wise/portal/presentation/web/controllers/ControllerUtil.java index 82d1f5f42e..50db0f7241 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/ControllerUtil.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/ControllerUtil.java @@ -33,10 +33,10 @@ import java.util.Properties; import java.util.Set; -import javax.annotation.PostConstruct; import javax.net.ssl.HttpsURLConnection; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.annotation.PostConstruct; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/DebugController.java b/src/main/java/org/wise/portal/presentation/web/controllers/DebugController.java new file mode 100644 index 0000000000..36502c1861 --- /dev/null +++ b/src/main/java/org/wise/portal/presentation/web/controllers/DebugController.java @@ -0,0 +1,35 @@ +package org.wise.portal.presentation.web.controllers; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/debug") +public class DebugController { + + @GetMapping("/auth") + public Map getAuthInfo(Authentication auth) { + Map info = new HashMap<>(); + if (auth != null) { + info.put("authenticated", auth.isAuthenticated()); + info.put("principal", auth.getPrincipal().toString()); + info.put("name", auth.getName()); + info.put("authorities", + auth.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.toList())); + info.put("details", auth.getDetails()); + } else { + info.put("authenticated", false); + info.put("message", "No authentication found"); + } + return info; + } +} diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/InformationController.java b/src/main/java/org/wise/portal/presentation/web/controllers/InformationController.java index b0fb2d7532..9b60179c64 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/InformationController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/InformationController.java @@ -29,8 +29,8 @@ import java.util.Locale; import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; @@ -55,7 +55,6 @@ import org.wise.portal.domain.project.Project; import org.wise.portal.domain.project.impl.ProjectImpl; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter; @@ -114,7 +113,7 @@ public void handleGetUserInfo(HttpServletRequest request, HttpServletResponse re * periods given runcode */ @RequestMapping("/runInfo") - public void handleRunInfo(@RequestParam("runcode") String runcode, HttpServletResponse response) + public void handleRunInfo(@RequestParam String runcode, HttpServletResponse response) throws Exception { try { Run run = runService.retrieveRunByRuncode(runcode); @@ -205,8 +204,7 @@ public void handleGetConfigWISE5Preview(HttpServletRequest request, HttpServletR @GetMapping("/config/studentRun/{runId}") public void getConfigWISE5StudentRun(HttpServletRequest request, HttpServletResponse response, - @PathVariable("runId") RunImpl run) - throws ObjectNotFoundException, IOException, JSONException { + @PathVariable("runId") Run run) throws ObjectNotFoundException, IOException, JSONException { JSONObject config = new JSONObject(); config.put("mode", "studentRun"); getRunConfigParameters(request, config, run); @@ -217,7 +215,7 @@ public void getConfigWISE5StudentRun(HttpServletRequest request, HttpServletResp @GetMapping("/config/classroomMonitor/{runId}") public void getConfigWISE5ClassroomMonitor(HttpServletRequest request, - HttpServletResponse response, @PathVariable("runId") RunImpl run) + HttpServletResponse response, @PathVariable("runId") Run run) throws ObjectNotFoundException, IOException, JSONException { JSONObject config = new JSONObject(); config.put("mode", "classroomMonitor"); @@ -496,7 +494,7 @@ private void addPreviewConfigParametersWISE4(HttpServletRequest request, User si * This is set if the request is to preview the project and use a specific workgroup id. * This is usually used to test branching based on workgroup id. */ - config.put("workgroupId", new Integer(workgroupIdString)); + config.put("workgroupId", Integer.valueOf(workgroupIdString)); } } catch (JSONException e) { e.printStackTrace(); @@ -599,8 +597,8 @@ private void addRetrievalTimestamp(JSONObject config) throws JSONException { } private void addStudentMaxTotalAssetSize(JSONObject config) throws JSONException { - Long studentMaxTotalAssetsSizeBytes = new Long( - appProperties.getProperty("student_max_total_assets_size", "5242880")); + Long studentMaxTotalAssetsSizeBytes = Long + .valueOf(appProperties.getProperty("student_max_total_assets_size", "5242880")); config.put("studentMaxTotalAssetsSize", studentMaxTotalAssetsSizeBytes); } @@ -771,12 +769,28 @@ private void addProjectBaseURL(JSONObject config, String projectURL) throws JSON */ private void addDummyUserInfoToConfig(JSONObject config) { try { - String dummyUserInfoJSONString = "{\"myUserInfo\": {" + "\"periodId\": 1," - + "\"workgroupId\": 1," + "\"myClassInfo\": {" + "\"classmateUserInfos\": []," - + "\"sharedTeacherUserInfos\": []," + "\"periods\": [{" + "\"periodId\": 1," - + "\"periodName\": \"1\"" + "}]," + "\"teacherUserInfo\": {" + "\"workgroupId\": 1," - + "\"username\": \"Preview Teacher\"" + "}" + "}," + "\"userIds\": [1]," - + "\"periodName\": \"1\"," + "\"username\": \"Preview Team\"" + "}" + "}"; + String dummyUserInfoJSONString = """ + {"myUserInfo": {\ + "periodId": 1,\ + "workgroupId": 1,\ + "myClassInfo": {\ + "classmateUserInfos": [],\ + "sharedTeacherUserInfos": [],\ + "periods": [{\ + "periodId": 1,\ + "periodName": "1"\ + }],\ + "teacherUserInfo": {\ + "workgroupId": 1,\ + "username": "Preview Teacher"\ + }\ + },\ + "userIds": [1],\ + "periodName": "1",\ + "username": "Preview Team"\ + }\ + }\ + """; JSONObject userInfoJSONObject = new JSONObject(dummyUserInfoJSONString); config.put("userInfo", userInfoJSONObject); } catch (JSONException e) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/LoginController.java b/src/main/java/org/wise/portal/presentation/web/controllers/LoginController.java index 7c19ef5c76..b8de4cd108 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/LoginController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/LoginController.java @@ -23,8 +23,8 @@ import java.io.IOException; import java.util.Properties; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -60,7 +60,7 @@ public void renewSession(HttpServletResponse response) throws IOException { User loggedInUser = ControllerUtil.getSignedInUser(); if (loggedInUser != null) { try { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); if (!portal.isLoginAllowed()) { response.getWriter().print("requestLogout"); } else { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/OutsideErrorController.java b/src/main/java/org/wise/portal/presentation/web/controllers/OutsideErrorController.java index ab035cf2e9..1b8aa51618 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/OutsideErrorController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/OutsideErrorController.java @@ -23,8 +23,8 @@ */ package org.wise.portal.presentation.web.controllers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/PreviewProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/PreviewProjectController.java index 2b0c3f4e97..fdaab76042 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/PreviewProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/PreviewProjectController.java @@ -26,13 +26,12 @@ import java.util.Set; import java.util.TreeSet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.project.FamilyTag; import org.wise.portal.domain.project.Project; @@ -73,7 +72,7 @@ public class PreviewProjectController { @Autowired private RunService runService; - @RequestMapping(value = "/previewproject.html", method = RequestMethod.GET) + @GetMapping("/previewproject.html") protected ModelAndView getPreviewPage(HttpServletRequest request, HttpServletResponse response) throws Exception { String projectIdStr = request.getParameter(PROJECT_ID_PARAM_NAME); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/StatisticsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/StatisticsController.java index bb56928dc1..7466c76ef1 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/StatisticsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/StatisticsController.java @@ -25,8 +25,8 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/VLEController.java b/src/main/java/org/wise/portal/presentation/web/controllers/VLEController.java index 59669eb366..c1ea18795c 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/VLEController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/VLEController.java @@ -23,7 +23,7 @@ */ package org.wise.portal.presentation.web.controllers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminIndexController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminIndexController.java index 29793ae7c0..795fcb6bf1 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminIndexController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminIndexController.java @@ -28,7 +28,7 @@ import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminUtilsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminUtilsController.java index 03518ec5e5..4f0ac1522d 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminUtilsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/AdminUtilsController.java @@ -32,7 +32,7 @@ import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.project.ProjectService; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/BatchCreateUserAccountsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/BatchCreateUserAccountsController.java index 1426aa3307..49ebfa3e21 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/BatchCreateUserAccountsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/BatchCreateUserAccountsController.java @@ -33,9 +33,10 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.AccountQuestion; @@ -65,7 +66,7 @@ public class BatchCreateUserAccountsController { @Autowired private StudentService studentService; - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected ModelAndView onSubmit( @ModelAttribute("csvFile") BatchCreateUserAccountsUpload csvUpload, BindingResult result) throws Exception { @@ -138,7 +139,7 @@ protected ModelAndView onSubmit( return modelAndView; } - @RequestMapping(method = RequestMethod.GET) + @GetMapping public ModelAndView initializeForm(ModelMap model) { ModelAndView mav = new ModelAndView(); mav.addObject("csvFile", new BatchCreateUserAccountsUpload()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/CurrentlyAuthoredProjectsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/CurrentlyAuthoredProjectsController.java index 0baee5aa4a..1a804a3bdf 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/CurrentlyAuthoredProjectsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/CurrentlyAuthoredProjectsController.java @@ -26,8 +26,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.wise.portal.domain.project.Project; import org.wise.portal.service.project.ProjectService; import org.wise.portal.service.session.SessionService; @@ -49,7 +49,7 @@ public class CurrentlyAuthoredProjectsController { @Autowired private SessionService sessionService; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String showCurrentlyAuthoredProjects(ModelMap modelMap) throws Exception { Set currentlyAuthoredProjects = sessionService.getCurrentlyAuthoredProjects(); HashMap> projectsToAuthors = new HashMap<>(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/EnableDisableUserController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/EnableDisableUserController.java index e40c3c53e1..8c9186e99b 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/EnableDisableUserController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/EnableDisableUserController.java @@ -25,14 +25,15 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.wise.portal.domain.user.User; import org.wise.portal.service.user.UserService; @@ -48,14 +49,14 @@ public class EnableDisableUserController { @Autowired private UserService userService; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String handleGET(ModelMap modelMap) { List disabledUsers = userService.retrieveDisabledUsers(); modelMap.put("disabledUsers", disabledUsers); return "/admin/account/enabledisableuser"; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected String handlePOST(HttpServletRequest request, HttpServletResponse response) throws Exception { String doEnable = request.getParameter("doEnable"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsController.java index f86767870e..2b60844010 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsController.java @@ -59,8 +59,8 @@ public class FindProjectRunsController { @GetMapping protected String findRun( - @RequestParam(value = "runLookupType", required = true) String runLookupType, - @RequestParam(value = "runLookupValue", required = true) String runLookupValue, + @RequestParam(required = true) String runLookupType, + @RequestParam(required = true) String runLookupValue, ModelMap modelMap) { List runList = new ArrayList(); if ("runId".equals(runLookupType)) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ImportProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ImportProjectController.java index 27af788592..a2379d03ea 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ImportProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ImportProjectController.java @@ -35,7 +35,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -79,7 +79,7 @@ public class ImportProjectController { @PostMapping("/admin/project/importFromHub") protected String importFromHub( - @RequestParam(value = "importableProjectId", required = true) String importableProjectId, + @RequestParam(required = true) String importableProjectId, ModelMap modelMap) throws Exception { String getImportableProjectURL = getWISEProjectsURL + "?id=" + importableProjectId; try { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/LookupUserController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/LookupUserController.java index 0f9b93adc5..153d05abee 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/LookupUserController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/LookupUserController.java @@ -26,7 +26,7 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageAllProjectsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageAllProjectsController.java index a165bc2220..03c19f3bc2 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageAllProjectsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageAllProjectsController.java @@ -26,12 +26,13 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.project.FamilyTag; import org.wise.portal.domain.project.Project; @@ -53,7 +54,7 @@ public class ManageAllProjectsController { private static final String INTERNAL_PROJECT_LIST_PARAM_NAME = "internal_project_list"; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected ModelAndView handleGET( HttpServletRequest request) throws Exception { List internalProjectList = new ArrayList(); @@ -75,12 +76,12 @@ protected ModelAndView handleGET( return modelAndView; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected ModelAndView handleRequestInternal(HttpServletRequest request) { ModelAndView mav = new ModelAndView(); try { String projectIdStr = request.getParameter("projectId"); - Long projectId = new Long(projectIdStr); + Long projectId = Long.valueOf(projectIdStr); Project project = projectService.getById(projectId); String attr = request.getParameter("attr"); if (attr.equals("isCurrent")) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalController.java index 78a5218470..7784f81c67 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalController.java @@ -29,8 +29,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.wise.portal.domain.portal.Portal; import org.wise.portal.service.portal.PortalService; @@ -50,9 +51,9 @@ public class ManagePortalController { @Autowired private ProjectService projectService; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String showPortalSettings(ModelMap modelMap, - @RequestParam(value = "portalId", defaultValue = "1") Integer portalId) throws Exception { + @RequestParam(defaultValue = "1") Integer portalId) throws Exception { Portal portal = portalService.getById(portalId); modelMap.put("portal", portal); modelMap.put("defaultAnnouncement", portalService.getDefaultAnnouncement()); @@ -61,12 +62,12 @@ protected String showPortalSettings(ModelMap modelMap, return "admin/portal/manage"; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected void savePortalChanges( ModelMap modelMap, - @RequestParam(value = "portalId", defaultValue = "1") Integer portalId, - @RequestParam(value = "attr") String attr, - @RequestParam(value = "val") String val) throws Exception { + @RequestParam(defaultValue = "1") Integer portalId, + @RequestParam String attr, + @RequestParam String val) throws Exception { Portal portal = portalService.getById(portalId); try { if (attr.equals("portalName")) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageUserRolesController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageUserRolesController.java index 5462caab08..429f66aaf9 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageUserRolesController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/ManageUserRolesController.java @@ -25,15 +25,16 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.wise.portal.domain.authentication.MutableGrantedAuthority; import org.wise.portal.domain.user.User; import org.wise.portal.service.authentication.UserDetailsService; @@ -54,7 +55,7 @@ public class ManageUserRolesController { @Autowired private UserDetailsService userDetailsService; - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected String handleGET(HttpServletRequest request, ModelMap modelMap) { List allAuthorities = userDetailsService.retrieveAllAuthorities(); modelMap.put("allAuthorities", allAuthorities); @@ -64,7 +65,7 @@ protected String handleGET(HttpServletRequest request, ModelMap modelMap) { return "admin/account/manageuserroles"; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected String handlePOST(HttpServletRequest request, ModelMap modelMap) throws Exception { List allAuthorities = userDetailsService.retrieveAllAuthorities(); modelMap.put("allAuthorities", allAuthorities); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/NewsItemController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/NewsItemController.java index ee87fa45a1..39335b242a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/NewsItemController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/NewsItemController.java @@ -25,16 +25,12 @@ import java.util.Calendar; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.*; import org.wise.portal.domain.newsitem.NewsItem; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.newsitem.NewsItemService; @@ -50,47 +46,44 @@ public class NewsItemController { @Autowired private NewsItemService newsItemService; - @RequestMapping(method = RequestMethod.GET, value="/manage") + @GetMapping("/manage") protected String showAllNews(ModelMap modelMap) throws Exception { modelMap.put("allNews", newsItemService.retrieveAllNewsItem()); return "admin/news/managenewsitems"; } - @RequestMapping(method = RequestMethod.GET, value="/add") + @GetMapping("/add") protected String showAddNews() throws Exception { return "admin/news/addnewsitem"; } - @RequestMapping(method = RequestMethod.GET, value="/edit/{newsItemId}") - protected String showEditNews(ModelMap modelMap, - @PathVariable Integer newsItemId) throws Exception { + @GetMapping("/edit/{newsItemId}") + protected String showEditNews(ModelMap modelMap, @PathVariable Integer newsItemId) + throws Exception { modelMap.put("newsItem", newsItemService.retrieveById(newsItemId)); return "admin/news/editnewsitem"; } - @RequestMapping(method = RequestMethod.POST, value="/add") - protected String addNews(@RequestParam("title") String title, - @RequestParam("news") String news, - @RequestParam("type") String type) throws Exception { - newsItemService.createNewsItem( - Calendar.getInstance().getTime(), ControllerUtil.getSignedInUser(), title, news, type); + @PostMapping("/add") + protected String addNews(@RequestParam String title, @RequestParam String news, + @RequestParam String type) throws Exception { + newsItemService.createNewsItem(Calendar.getInstance().getTime(), + ControllerUtil.getSignedInUser(), title, news, type); return "admin/news/success"; } - @RequestMapping(method = RequestMethod.POST, value="/edit/{newsItemId}") - protected String editNews(@PathVariable Integer newsItemId, - @RequestParam("title") String title, - @RequestParam("news") String news, - @RequestParam("type") String type) throws Exception { + @PostMapping("/edit/{newsItemId}") + protected String editNews(@PathVariable Integer newsItemId, @RequestParam String title, + @RequestParam String news, @RequestParam String type) throws Exception { NewsItem newsItem = newsItemService.retrieveById(newsItemId); - newsItemService.updateNewsItem( - newsItem.getId(), newsItem.getDate(), newsItem.getOwner(), title, news, type); + newsItemService.updateNewsItem(newsItem.getId(), newsItem.getDate(), newsItem.getOwner(), title, + news, type); return "admin/news/success"; } - @RequestMapping(method = RequestMethod.POST, value="/delete/{newsItemId}") - protected void deleteNews(@PathVariable Integer newsItemId, - HttpServletResponse response) throws Exception { + @PostMapping("/delete/{newsItemId}") + protected void deleteNews(@PathVariable Integer newsItemId, HttpServletResponse response) + throws Exception { newsItemService.deleteNewsItem(newsItemId); response.getWriter().print("success"); } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/RunStatisticsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/RunStatisticsController.java index 1a84d0611e..aac4bd4b58 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/RunStatisticsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/RunStatisticsController.java @@ -26,15 +26,13 @@ import java.util.Calendar; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.attendance.StudentAttendance; import org.wise.portal.domain.run.Run; import org.wise.portal.service.attendance.StudentAttendanceService; @@ -52,9 +50,8 @@ public class RunStatisticsController { @Autowired private StudentAttendanceService studentAttendanceService; - @RequestMapping(value = "/admin/run/stats", method = RequestMethod.GET) - protected String showRunStatistics( - @RequestParam(value = "period", required = false) String period, + @GetMapping("/admin/run/stats") + protected String showRunStatistics(@RequestParam(required = false) String period, ModelMap modelMap) throws Exception { List runs = runService.getRunsRunWithinTimePeriod(period); int lookBackPeriod = 0; @@ -65,10 +62,9 @@ protected String showRunStatistics( } else if (period.equals("month")) { lookBackPeriod = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH); } - for (Run run: runs) { - List studentAttendanceByRunIdAndPeriod = - studentAttendanceService.getStudentAttendanceByRunIdAndPeriod( - run.getId(), lookBackPeriod); + for (Run run : runs) { + List studentAttendanceByRunIdAndPeriod = studentAttendanceService + .getStudentAttendanceByRunIdAndPeriod(run.getId(), lookBackPeriod); run.setStudentAttendance(studentAttendanceByRunIdAndPeriod); } @@ -82,7 +78,7 @@ protected String showRunStatistics( return "admin/run/stats"; } - @RequestMapping(value = "/admin/run/stats-by-activity", method = RequestMethod.GET) + @GetMapping("/admin/run/stats-by-activity") protected String showRunStatisticsByActivity(HttpServletRequest request, ModelMap modelMap) throws Exception { modelMap.put("runs", runService.getRunsByActivity()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateProjectSharedPermissionsAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateProjectSharedPermissionsAPIController.java index 74a352317b..aa0ed51bb4 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateProjectSharedPermissionsAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateProjectSharedPermissionsAPIController.java @@ -2,7 +2,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.model.Permission; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.authentication.MutableUserDetails; import org.wise.portal.domain.project.Project; @@ -26,9 +29,9 @@ public class UpdateProjectSharedPermissionsAPIController { * Project Owner * The Shared Owners and their permission numbers */ - @RequestMapping(value = "/view", method = RequestMethod.GET) - protected String viewProjectPermissions(@RequestParam(value = "min", required = false) Long min, - @RequestParam(value = "max", required = false) Long max) { + @GetMapping("/view") + protected String viewProjectPermissions(@RequestParam(required = false) Long min, + @RequestParam(required = false) Long max) { User signedInUser = ControllerUtil.getSignedInUser(); if (signedInUser.isAdmin()) { long startTime = System.currentTimeMillis(); @@ -36,7 +39,7 @@ protected String viewProjectPermissions(@RequestParam(value = "min", required = Integer sharedProjectsCount = 0; List allSharedProjects = projectService.getAllSharedProjects(); - for (Project project: allSharedProjects) { + for (Project project : allSharedProjects) { Long projectId = (Long) project.getId(); if (isInRange(projectId, min, max)) { outputProject(projectsSB, project); @@ -69,9 +72,9 @@ protected String viewProjectPermissions(@RequestParam(value = "min", required = * permission 16. For those shared owners with permission 16, add the permission 1 (view), and the * permission 2 (edit) if they do not already have them. */ - @RequestMapping(value = "/update", method = RequestMethod.GET) - protected String updateProjectPermissions(@RequestParam(value = "min", required = false) Long min, - @RequestParam(value = "max", required = false) Long max) { + @GetMapping("/update") + protected String updateProjectPermissions(@RequestParam(required = false) Long min, + @RequestParam(required = false) Long max) { User signedInUser = ControllerUtil.getSignedInUser(); if (signedInUser.isAdmin()) { long startTime = System.currentTimeMillis(); @@ -81,7 +84,7 @@ protected String updateProjectPermissions(@RequestParam(value = "min", required int sharedOwnersChangedCount = 0; List allSharedProjects = projectService.getAllSharedProjects(); - for (Project project: allSharedProjects) { + for (Project project : allSharedProjects) { Long projectId = (Long) project.getId(); if (isInRange(projectId, min, max)) { int tempSharedOwnersChangedCount = updatePermissionsIfNecessary(project); @@ -139,7 +142,7 @@ private StringBuffer outputProject(StringBuffer sb, Project project) { outputLineBreak(sb); Set sharedOwners = project.getSharedowners(); - for (User sharedOwner: sharedOwners) { + for (User sharedOwner : sharedOwners) { outputSharedTeacherPermissions(sb, project, sharedOwner); outputLineBreak(sb); } @@ -159,7 +162,8 @@ private StringBuffer outputProjectOwner(StringBuffer sb, Project project) { return outputString(sb, "Project Owner: " + project.getOwner().getUserDetails().getUsername()); } - private StringBuffer outputSharedTeacherPermissions(StringBuffer sb, Project project, User sharedOwner) { + private StringBuffer outputSharedTeacherPermissions(StringBuffer sb, Project project, + User sharedOwner) { MutableUserDetails userDetails = sharedOwner.getUserDetails(); String username = userDetails.getUsername(); outputString(sb, username); @@ -168,10 +172,12 @@ private StringBuffer outputSharedTeacherPermissions(StringBuffer sb, Project pro return sb; } - private StringBuffer ouputSharedTeacherPermissionIds(StringBuffer sb, Project project, User sharedOwner) { + private StringBuffer ouputSharedTeacherPermissionIds(StringBuffer sb, Project project, + User sharedOwner) { StringBuffer sbPermissionIds = new StringBuffer(); - List sharedTeacherPermissions = projectService.getSharedTeacherPermissions(project, sharedOwner); - for (Permission permission: sharedTeacherPermissions) { + List sharedTeacherPermissions = projectService.getSharedTeacherPermissions(project, + sharedOwner); + for (Permission permission : sharedTeacherPermissions) { if (sbPermissionIds.length() != 0) { sbPermissionIds.append(","); } @@ -186,9 +192,11 @@ private int updatePermissionsIfNecessary(Project project) { int sharedOwnersChangedCount = 0; Long projectId = (Long) project.getId(); Set sharedOwners = project.getSharedowners(); - for (User sharedOwner: sharedOwners) { - List sharedTeacherPermissions = projectService.getSharedTeacherPermissions(project, sharedOwner); - boolean changed = addViewAndEditPermissionToAdminPermission(projectId, sharedOwner.getId(), sharedTeacherPermissions); + for (User sharedOwner : sharedOwners) { + List sharedTeacherPermissions = projectService + .getSharedTeacherPermissions(project, sharedOwner); + boolean changed = addViewAndEditPermissionToAdminPermission(projectId, sharedOwner.getId(), + sharedTeacherPermissions); if (changed) { sharedOwnersChangedCount += 1; } @@ -196,12 +204,13 @@ private int updatePermissionsIfNecessary(Project project) { return sharedOwnersChangedCount; } - private boolean addViewAndEditPermissionToAdminPermission(Long projectId, Long userId, List sharedTeacherPermissions) { + private boolean addViewAndEditPermissionToAdminPermission(Long projectId, Long userId, + List sharedTeacherPermissions) { boolean hasPermission1 = false; boolean hasPermission2 = false; boolean hasPermission16 = false; - for (Permission permission: sharedTeacherPermissions) { + for (Permission permission : sharedTeacherPermissions) { int mask = permission.getMask(); if (mask == 1) { hasPermission1 = true; @@ -255,11 +264,13 @@ private StringBuffer outputSharedProjectCount(StringBuffer sb, Integer sharedPro return outputString(sb, "Shared Projects: " + sharedProjectsCount); } - private StringBuffer outputSharedProjectsChangedCount(StringBuffer sb, int sharedProjectsChangedCount) { + private StringBuffer outputSharedProjectsChangedCount(StringBuffer sb, + int sharedProjectsChangedCount) { return outputString(sb, "Shared Projects Changed: " + sharedProjectsChangedCount); } - private StringBuffer outputSharedOwnersChangedCount(StringBuffer sb, int sharedOwnersChangedCount) { + private StringBuffer outputSharedOwnersChangedCount(StringBuffer sb, + int sharedOwnersChangedCount) { return outputString(sb, "Shared Owners Changed: " + sharedOwnersChangedCount); } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateSharedProjectsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateSharedProjectsController.java index 69070fab16..4a90f91465 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateSharedProjectsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/admin/UpdateSharedProjectsController.java @@ -2,15 +2,15 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/admin/project/updatesharedprojects") public class UpdateSharedProjectsController { - @RequestMapping(method= RequestMethod.GET) + @GetMapping public ModelAndView initializeForm(ModelMap model) { ModelAndView mav = new ModelAndView(); return mav; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/archive/ArchiveProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/archive/ArchiveProjectController.java index 3a26d4426b..fa117759ac 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/archive/ArchiveProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/archive/ArchiveProjectController.java @@ -18,7 +18,6 @@ import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.project.Project; -import org.wise.portal.domain.project.impl.ProjectImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.usertag.UserTag; import org.wise.portal.presentation.web.response.ResponseEntityGenerator; @@ -44,7 +43,7 @@ public class ArchiveProjectController { @PutMapping("/project/{projectId}/archived") protected ResponseEntity> archiveProject(Authentication auth, - @PathVariable("projectId") ProjectImpl project) { + @PathVariable("projectId") Project project) { User user = userService.retrieveUserByUsername(auth.getName()); UserTag archivedTag = getOrCreateArchivedTag(user); userTagsService.applyTag(project, archivedTag); @@ -74,7 +73,7 @@ private UserTag getOrCreateArchivedTag(User user) { @DeleteMapping("/project/{projectId}/archived") protected ResponseEntity> unarchiveProject(Authentication auth, - @PathVariable("projectId") ProjectImpl project) { + @PathVariable("projectId") Project project) { User user = userService.retrieveUserByUsername(auth.getName()); UserTag archivedTag = userTagsService.get(user, ARCHIVED_TAG); if (archivedTag != null) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIController.java index 6b3b243b09..353e0e1e19 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIController.java @@ -39,9 +39,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -71,7 +71,6 @@ import org.wise.portal.domain.portal.Portal; import org.wise.portal.domain.project.Project; import org.wise.portal.domain.project.ProjectMetadata; -import org.wise.portal.domain.project.impl.ProjectImpl; import org.wise.portal.domain.project.impl.ProjectMetadataImpl; import org.wise.portal.domain.project.impl.ProjectParameters; import org.wise.portal.domain.project.impl.ProjectType; @@ -130,7 +129,6 @@ public class AuthorAPIController { private String featuredProjectIconsFolderRelativePath; - @Autowired public AuthorAPIController(Environment appProperties) { featuredProjectIconsFolderRelativePath = appProperties.getProperty("project_icons_base_dir"); } @@ -139,7 +137,7 @@ public AuthorAPIController(Environment appProperties) { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { try { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); if (!portal.isLoginAllowed()) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { @@ -183,7 +181,7 @@ protected String createProject(Authentication auth, @RequestBody ObjectNode obje pParams.setOwner(user); pParams.setProjectname(projectName); pParams.setProjectType(ProjectType.LD); - pParams.setWiseVersion(new Integer(5)); + pParams.setWiseVersion(Integer.valueOf(5)); ProjectMetadata metadata = new ProjectMetadataImpl(); metadata.setTitle(projectName); @@ -247,12 +245,12 @@ protected Project copyProject(Authentication auth, @PathVariable Long projectId) @PostMapping("/project/save/{projectId}") @ResponseBody protected SimpleResponse saveProject(Authentication auth, - @PathVariable("projectId") ProjectImpl project, @RequestBody String projectJSONString) + @PathVariable("projectId") Project project, @RequestBody String projectJSONString) throws JSONException, ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); if (projectService.canAuthorProject(project, user)) { try { - projectService.evictProjectContentCache(project.getId()); + projectService.evictProjectContentCache((Long) project.getId()); projectService.saveProjectContentToDisk(projectJSONString, project); projectService.updateMetadataAndLicenseIfNecessary(project, projectJSONString); projectService.saveProjectToDatabase(project, user, projectJSONString); @@ -287,7 +285,7 @@ protected HashMap getDefaultAuthorProjectConfig(Authentication a config.put("teacherDataURL", contextPath + "/api/teacher/data"); config.put("sessionTimeout", request.getSession().getMaxInactiveInterval()); - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); String projectMetadataSettings = portal.getProjectMetadataSettings(); if (projectMetadataSettings == null) { projectMetadataSettings = portalService.getDefaultProjectMetadataSettings(); @@ -324,7 +322,7 @@ protected HashMap getDefaultAuthorProjectConfig(Authentication a projectMap.put("id", project.getId()); projectMap.put("name", project.getName()); String projectIdString = project.getId().toString(); - Long projectId = new Long(projectIdString); + Long projectId = Long.valueOf(projectIdString); Run run = getRun(projectId, runsOwnedByUser); if (run != null) { projectMap.put("runId", run.getId()); @@ -346,7 +344,7 @@ protected HashMap getDefaultAuthorProjectConfig(Authentication a projectMap.put("id", project.getId()); projectMap.put("name", project.getName()); String projectIdString = project.getId().toString(); - Long projectId = new Long(projectIdString); + Long projectId = Long.valueOf(projectIdString); Run run = getRun(projectId, sharedRuns); if (run != null) { projectMap.put("runId", run.getId()); @@ -379,7 +377,7 @@ protected HashMap getDefaultAuthorProjectConfig(Authentication a @GetMapping("/config/{projectId}") @ResponseBody protected HashMap getAuthorProjectConfig(Authentication auth, - HttpServletRequest request, @PathVariable("projectId") ProjectImpl project) + HttpServletRequest request, @PathVariable("projectId") Project project) throws IOException, ObjectNotFoundException { HashMap config = getDefaultAuthorProjectConfig(auth, request); String contextPath = request.getContextPath(); @@ -389,14 +387,15 @@ protected HashMap getAuthorProjectConfig(Authentication auth, String projectBaseURL = projectURL.substring(0, projectURL.indexOf("project.json")); Long projectAssetTotalSizeMax = project.getMaxTotalAssetsSize(); if (projectAssetTotalSizeMax == null) { - projectAssetTotalSizeMax = new Long( - appProperties.getProperty("project_max_total_assets_size", "15728640")); + projectAssetTotalSizeMax = Long + .valueOf(appProperties.getProperty("project_max_total_assets_size", "15728640")); } - config.put("projectId", project.getId()); + config.put("projectId", (Long) project.getId()); config.put("projectURL", projectURL); config.put("projectAssetTotalSizeMax", projectAssetTotalSizeMax); - config.put("projectAssetURL", contextPath + "/api/author/project/asset/" + project.getId()); + config.put("projectAssetURL", + contextPath + "/api/author/project/asset/" + (Long) project.getId()); config.put("projectBaseURL", projectBaseURL); config.put("previewProjectURL", contextPath + "/preview/unit/" + project.getId()); config.put("chatGptEnabled", !StringUtils.isEmpty(appProperties.getProperty("OPENAI_API_KEY"))); @@ -414,7 +413,7 @@ protected HashMap getAuthorProjectConfig(Authentication auth, config.put("saveProjectURL", contextPath + "/api/author/project/save/" + project.getId()); config.put("commitProjectURL", contextPath + "/project/commit/" + project.getId()); } - List projectRuns = runService.getProjectRuns(project.getId()); + List projectRuns = runService.getProjectRuns((Long) project.getId()); if (projectRuns.size() > 0) { Run projectRun = projectRuns.get(0); config.put("canGradeStudentWork", runService.isAllowedToGradeStudentWork(projectRun, user)); @@ -443,23 +442,22 @@ private Run getRun(Long projectId, List runs) { @PostMapping("/project/notify/{projectId}/{isBegin}") @ResponseBody protected void notifyAuthorBeginEnd(Authentication auth, - @PathVariable("projectId") ProjectImpl project, @PathVariable boolean isBegin) - throws Exception { + @PathVariable("projectId") Project project, @PathVariable boolean isBegin) throws Exception { User user = userService.retrieveUserByUsername(auth.getName()); if (projectService.canAuthorProject(project, user)) { if (isBegin) { - sessionService.addCurrentAuthor(project.getId(), auth.getName()); + sessionService.addCurrentAuthor((Long) project.getId(), auth.getName()); } else { - sessionService.removeCurrentAuthor(project.getId(), auth.getName()); + sessionService.removeCurrentAuthor((Long) project.getId(), auth.getName()); } - notifyCurrentAuthors(project.getId()); + notifyCurrentAuthors((Long) project.getId()); } } private void notifyCurrentAuthors(Long projectId) throws JSONException { JSONObject message = new JSONObject(); message.put("type", "currentAuthors"); - message.put("topic", String.format("/topic/current-authors/%s", projectId)); + message.put("topic", "/topic/current-authors/%s".formatted(projectId)); message.put("currentAuthors", sessionService.getCurrentAuthors(projectId)); redisPublisher.publish(message.toString()); } @@ -538,9 +536,11 @@ protected List getAssetFileNames(String stepsText) { String stepsTextModified = stepsText.replaceAll("%20", " "); // Regex string to match asset file references in the step/component content. e.g. carbon.png - String patternString = "(\'|\"|\\\\\'|\\\\\")([^:][^/]?[^/]?[a-zA-Z0-9@\\._\\/\\s\\-]*[.]" - + "(png|PNG|jpe?g|JPE?G|pdf|PDF|gif|GIF|mov|MOV|mp4|MP4|mp3|MP3|wav|WAV|swf|SWF|css|CSS" - + "|txt|TXT|json|JSON|xlsx?|XLSX?|doc|DOC|html.*?|HTML.*?|js|JS)).*?(\'|\"|\\\\\'|\\\\\")"; + String patternString = """ + ('|"|\\\\'|\\\\")([^:][^/]?[^/]?[a-zA-Z0-9@\\._\\/\\s\\-]*[.]\ + (png|PNG|jpe?g|JPE?G|pdf|PDF|gif|GIF|mov|MOV|mp4|MP4|mp3|MP3|wav|WAV|swf|SWF|css|CSS\ + |txt|TXT|json|JSON|xlsx?|XLSX?|doc|DOC|html.*?|HTML.*?|js|JS)).*?('|"|\\\\'|\\\\")\ + """; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(stepsTextModified); HashSet fileNames = new HashSet(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/ProjectAssetAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/ProjectAssetAPIController.java index d3290d81dd..7e91f97c9a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/ProjectAssetAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/ProjectAssetAPIController.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.tika.detect.Detector; @@ -61,8 +61,12 @@ public class ProjectAssetAPIController { @Autowired protected Environment appProperties; - private String EXCEEDED_MAX_PROJECT_SIZE_MESSAGE = "Exceeded project max asset size.\n" - + "Please delete unused assets.\n\nContact WISE if your project needs more disk space."; + private String EXCEEDED_MAX_PROJECT_SIZE_MESSAGE = """ + Exceeded project max asset size. + Please delete unused assets. + + Contact WISE if your project needs more disk space.\ + """; private String UPLOADING_THIS_FILE_NOT_ALLOWED_MESSAGE = "Uploading this file is not allowed."; @GetMapping("/{projectId}") diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslateProjectAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslateProjectAPIController.java index c21b3d509b..94dbea53f2 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslateProjectAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslateProjectAPIController.java @@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import org.wise.portal.domain.project.impl.ProjectImpl; +import org.wise.portal.domain.project.Project; import org.wise.portal.domain.user.User; import org.wise.portal.service.project.ProjectService; import org.wise.portal.service.project.translation.TranslateProjectService; @@ -34,9 +34,8 @@ public class TranslateProjectAPIController { @PostMapping("{projectId}/{locale}") @ResponseBody - protected void saveTranslations(Authentication auth, - @PathVariable("projectId") ProjectImpl project, @PathVariable("locale") String locale, - @RequestBody ObjectNode translations) throws IOException { + protected void saveTranslations(Authentication auth, @PathVariable("projectId") Project project, + @PathVariable String locale, @RequestBody ObjectNode translations) throws IOException { User user = userService.retrieveUserByUsername(auth.getName()); if (projectService.canAuthorProject(project, user)) { translateProjectService.saveTranslations(project, locale, translations.toString()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/contact/ContactAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/contact/ContactAPIController.java index b16388626a..79489d8c23 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/contact/ContactAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/contact/ContactAPIController.java @@ -11,7 +11,10 @@ import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.authentication.impl.TeacherUserDetails; import org.wise.portal.domain.general.contactwise.IssueType; @@ -24,7 +27,7 @@ import org.wise.portal.service.run.RunService; import org.wise.portal.service.user.UserService; -import javax.mail.MessagingException; +import jakarta.mail.MessagingException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -58,17 +61,17 @@ public class ContactAPIController { private static final String userAgentParseURL = "http://api.whatismybrowser.com/api/v1/user_agent_parse"; - @RequestMapping(value = "", method = RequestMethod.POST) - protected String sendContactMessage(@RequestParam(value = "name") String name, - @RequestParam(value = "email", required = false) String email, - @RequestParam(value = "teacherUsername", required = false) String teacherUsername, - @RequestParam(value = "issueType") String issueType, - @RequestParam(value = "summary") String summary, - @RequestParam(value = "description") String description, - @RequestParam(value = "runId", required = false) Long runId, - @RequestParam(value = "projectId", required = false) Integer projectId, - @RequestParam(value = "userAgent", required = false) String userAgent, - @RequestParam(value = "recaptchaResponse", required = false) String recaptchaResponse) + @PostMapping("") + protected String sendContactMessage(@RequestParam String name, + @RequestParam(required = false) String email, + @RequestParam(required = false) String teacherUsername, + @RequestParam String issueType, + @RequestParam String summary, + @RequestParam String description, + @RequestParam(required = false) Long runId, + @RequestParam(required = false) Integer projectId, + @RequestParam(required = false) String userAgent, + @RequestParam(required = false) String recaptchaResponse) throws JSONException { if (this.isAuthorized(recaptchaResponse)) { boolean isStudent = isStudent(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/news/NewsAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/news/NewsAPIController.java index cf7df012bd..677ccbfad1 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/news/NewsAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/news/NewsAPIController.java @@ -4,8 +4,8 @@ import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.domain.newsitem.NewsItem; import org.wise.portal.service.newsitem.NewsItemService; @@ -19,7 +19,7 @@ public class NewsAPIController { @Autowired private NewsItemService newsItemService; - @RequestMapping(value = "", method = RequestMethod.GET) + @GetMapping("") protected String getNews() { List newsItems = newsItemService.retrieveAllNewsItem(); JSONArray newsItemsJSON = getNewsItemsJSON(newsItems); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/notebook/NotebookController.java b/src/main/java/org/wise/portal/presentation/web/controllers/notebook/NotebookController.java index 92b2473a92..ba9a33d8ad 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/notebook/NotebookController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/notebook/NotebookController.java @@ -16,10 +16,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.run.RunService; import org.wise.portal.service.user.UserService; import org.wise.portal.service.vle.wise5.VLEService; @@ -51,8 +49,8 @@ public class NotebookController { @Secured("ROLE_TEACHER") @ResponseBody @GetMapping("/{runId}") - protected List getNotebookItems(@PathVariable("runId") RunImpl run, - Authentication auth, @RequestParam(required = false) String exportType) + protected List getNotebookItems(@PathVariable("runId") Run run, Authentication auth, + @RequestParam(required = false) String exportType) throws ObjectNotFoundException, AccessDeniedException { if (runService.hasReadPermission(auth, run)) { if ("allNotebookItems".equals(exportType)) { @@ -69,8 +67,8 @@ protected List getNotebookItems(@PathVariable("runId") RunImpl run @Secured("ROLE_STUDENT") @ResponseBody @GetMapping("/{runId}/workgroup/{workgroupId}") - protected List getNotebookItems(@PathVariable("runId") RunImpl run, - @PathVariable("workgroupId") WorkgroupImpl workgroup, Authentication auth) + protected List getNotebookItems(@PathVariable("runId") Run run, + @PathVariable("workgroupId") Workgroup workgroup, Authentication auth) throws ObjectNotFoundException, AccessDeniedException { if (!isUserInRunAndWorkgroup(auth, run, workgroup)) { throw new AccessDeniedException("Not allowed to view notebook items"); @@ -80,22 +78,20 @@ protected List getNotebookItems(@PathVariable("runId") RunImpl run @ResponseBody @PostMapping("/{runId}") - protected NotebookItem saveNotebookItem(@PathVariable("runId") RunImpl run, - @RequestParam(value = "periodId", required = false) Integer periodId, - @RequestParam(value = "workgroupId") WorkgroupImpl workgroup, - @RequestParam(value = "notebookItemId", required = false) Integer notebookItemId, - @RequestParam(value = "nodeId", required = false) String nodeId, - @RequestParam(value = "componentId", required = false) String componentId, - @RequestParam(value = "studentWorkId", required = false) Integer studentWorkId, - @RequestParam(value = "studentAssetId", required = false) Integer studentAssetId, - @RequestParam(value = "localNotebookItemId", required = false) String localNotebookItemId, - @RequestParam(value = "type", required = false) String type, - @RequestParam(value = "title", required = false) String title, - @RequestParam(value = "content", required = false) String content, - @RequestParam(value = "groups", required = false) String groups, - @RequestParam(value = "clientSaveTime", required = true) String clientSaveTime, - @RequestParam(value = "clientDeleteTime", required = false) String clientDeleteTime, - Authentication auth) throws ObjectNotFoundException, AccessDeniedException { + protected NotebookItem saveNotebookItem(@PathVariable("runId") Run run, + @RequestParam(required = false) Integer periodId, + @RequestParam(value = "workgroupId") Workgroup workgroup, + @RequestParam(required = false) Integer notebookItemId, + @RequestParam(required = false) String nodeId, + @RequestParam(required = false) String componentId, + @RequestParam(required = false) Integer studentWorkId, + @RequestParam(required = false) Integer studentAssetId, + @RequestParam(required = false) String localNotebookItemId, + @RequestParam(required = false) String type, @RequestParam(required = false) String title, + @RequestParam(required = false) String content, @RequestParam(required = false) String groups, + @RequestParam(required = true) String clientSaveTime, + @RequestParam(required = false) String clientDeleteTime, Authentication auth) + throws ObjectNotFoundException, AccessDeniedException { if (!isUserInRunAndWorkgroup(auth, run, workgroup)) { throw new AccessDeniedException("Not allowed to save notebook items"); } @@ -107,11 +103,10 @@ protected NotebookItem saveNotebookItem(@PathVariable("runId") RunImpl run, @ResponseBody @PostMapping("/{runId}/group/{group}") - protected NotebookItem addNotebookItemToGroup(@PathVariable("runId") RunImpl run, - @PathVariable String group, @RequestParam(value = "workgroupId") WorkgroupImpl workgroup, - @RequestParam(value = "notebookItemId", required = true) Integer notebookItemId, - @RequestParam(value = "clientSaveTime", required = true) String clientSaveTime, - Authentication auth) + protected NotebookItem addNotebookItemToGroup(@PathVariable("runId") Run run, + @PathVariable String group, @RequestParam(value = "workgroupId") Workgroup workgroup, + @RequestParam(required = true) Integer notebookItemId, + @RequestParam(required = true) String clientSaveTime, Authentication auth) throws ObjectNotFoundException, NotebookItemAlreadyInGroupException, AccessDeniedException { if (!isUserInRunAndWorkgroup(auth, run, workgroup)) { throw new AccessDeniedException("Not allowed to add notebook item to group"); @@ -121,11 +116,11 @@ protected NotebookItem addNotebookItemToGroup(@PathVariable("runId") RunImpl run @ResponseBody @DeleteMapping("/{runId}/group/{group}") - protected NotebookItem removeNotebookItemFromGroup(@PathVariable("runId") RunImpl run, - @PathVariable String group, @RequestParam(value = "workgroupId") WorkgroupImpl workgroup, - @RequestParam(value = "notebookItemId", required = true) Integer notebookItemId, - @RequestParam(value = "clientSaveTime", required = true) String clientSaveTime, - Authentication auth) throws ObjectNotFoundException, AccessDeniedException { + protected NotebookItem removeNotebookItemFromGroup(@PathVariable("runId") Run run, + @PathVariable String group, @RequestParam(value = "workgroupId") Workgroup workgroup, + @RequestParam(required = true) Integer notebookItemId, + @RequestParam(required = true) String clientSaveTime, Authentication auth) + throws ObjectNotFoundException, AccessDeniedException { if (!isUserInRunAndWorkgroup(auth, run, workgroup)) { throw new AccessDeniedException("Not allowed to remove notebook item from group"); } @@ -134,10 +129,9 @@ protected NotebookItem removeNotebookItemFromGroup(@PathVariable("runId") RunImp @ResponseBody @GetMapping("/{runId}/group/{group}") - protected List getNotebookItemsInGroup(@PathVariable("runId") RunImpl run, - @PathVariable String group, - @RequestParam(value = "periodId", required = false) Integer periodId, Authentication auth) - throws AccessDeniedException, ObjectNotFoundException { + protected List getNotebookItemsInGroup(@PathVariable("runId") Run run, + @PathVariable String group, @RequestParam(required = false) Integer periodId, + Authentication auth) throws AccessDeniedException, ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); if (!userService.isUserAssociatedWithRun(user, run)) { throw new AccessDeniedException("Not allowed to get notebook items in group"); @@ -147,11 +141,11 @@ protected List getNotebookItemsInGroup(@PathVariable("runId") RunI @ResponseBody @PostMapping("/{runId}/parent/{parentNotebookItemId}") - protected NotebookItem copyNotebookItem(@PathVariable("runId") RunImpl run, + protected NotebookItem copyNotebookItem(@PathVariable("runId") Run run, @PathVariable Integer parentNotebookItemId, - @RequestParam(value = "workgroupId") WorkgroupImpl workgroup, - @RequestParam(value = "clientSaveTime", required = true) String clientSaveTime, - Authentication auth) throws ObjectNotFoundException, AccessDeniedException { + @RequestParam(value = "workgroupId") Workgroup workgroup, + @RequestParam(required = true) String clientSaveTime, Authentication auth) + throws ObjectNotFoundException, AccessDeniedException { if (!isUserInRunAndWorkgroup(auth, run, workgroup)) { throw new AccessDeniedException("Not allowed to copy notebook items"); } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIController.java index 01e7863658..63d77b872e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIController.java @@ -35,10 +35,8 @@ import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.peergrouping.PeerGrouping; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.peergroup.PeerGroupCreationException; import org.wise.portal.service.peergroup.PeerGroupService; import org.wise.portal.service.peergrouping.PeerGroupingService; @@ -63,13 +61,12 @@ public class PeerGroupAPIController { private PeerGroupingService peerGroupingService; @GetMapping("/{runId}/{workgroupId}/{peerGroupingTag}") - PeerGroup getPeerGroup(@PathVariable("runId") RunImpl run, - @PathVariable("workgroupId") WorkgroupImpl workgroup, - @PathVariable String peerGroupingTag, Authentication auth) - throws JSONException, PeerGroupCreationException { + PeerGroup getPeerGroup(@PathVariable("runId") Run run, + @PathVariable("workgroupId") Workgroup workgroup, @PathVariable String peerGroupingTag, + Authentication auth) throws JSONException, PeerGroupCreationException { User user = userService.retrieveUserByUsername(auth.getName()); - if (workgroupService.isUserInWorkgroupForRun(user, run, workgroup) || - run.isTeacherAssociatedToThisRun(user)) { + if (workgroupService.isUserInWorkgroupForRun(user, run, workgroup) + || run.isTeacherAssociatedToThisRun(user)) { return getPeerGroup(run, peerGroupingTag, workgroup); } else { throw new AccessDeniedException("Not permitted"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAnnotationsAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAnnotationsAPIController.java index 7adfa353ac..8f16e98af8 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAnnotationsAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAnnotationsAPIController.java @@ -14,13 +14,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.domain.peergroup.PeerGroup; -import org.wise.portal.domain.peergroup.impl.PeerGroupImpl; import org.wise.portal.domain.peergrouping.PeerGrouping; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.peergroup.PeerGroupCreationException; import org.wise.portal.service.peergrouping.PeerGroupingNotFoundException; import org.wise.portal.service.vle.wise5.AnnotationService; @@ -38,7 +35,7 @@ public class PeerGroupAnnotationsAPIController extends AbstractPeerGroupAPIContr private WorkgroupService workgroupService; @GetMapping("/{peerGroupId}/{nodeId}/{componentId}/annotations") - List getPeerGroupAnnotations(@PathVariable("peerGroupId") PeerGroupImpl peerGroup, + List getPeerGroupAnnotations(@PathVariable("peerGroupId") PeerGroup peerGroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) { if (isUserInPeerGroup(peerGroup, auth)) { Set workgroups = peerGroup.getMembers(); @@ -51,8 +48,8 @@ List getPeerGroupAnnotations(@PathVariable("peerGroupId") PeerGroupI @Secured("ROLE_TEACHER") @GetMapping("/{runId}/{workgroupId}/{nodeId}/{componentId}/annotations") - List getPeerGroupAnnotations(@PathVariable("runId") RunImpl run, - @PathVariable("workgroupId") WorkgroupImpl workgroup, @PathVariable String nodeId, + List getPeerGroupAnnotations(@PathVariable("runId") Run run, + @PathVariable("workgroupId") Workgroup workgroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) throws JSONException, PeerGroupingNotFoundException, PeerGroupCreationException { User user = userService.retrieveUserByUsername(auth.getName()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateController.java index fc3937ee26..006ee73d51 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateController.java @@ -8,10 +8,10 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import org.wise.portal.domain.group.impl.PersistentGroup; +import org.wise.portal.domain.group.Group; import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.peergrouping.PeerGrouping; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; import org.wise.portal.service.peergroup.PeerGroupCreateService; import org.wise.portal.service.peergrouping.PeerGroupingService; import org.wise.portal.service.run.RunService; @@ -31,9 +31,8 @@ public class PeerGroupCreateController { private RunService runService; @PostMapping("/{runId}/{periodId}/{peerGroupingTag}") - PeerGroup create(@PathVariable("runId") RunImpl run, - @PathVariable("periodId") PersistentGroup period, @PathVariable String peerGroupingTag, - Authentication auth) { + PeerGroup create(@PathVariable("runId") Run run, @PathVariable("periodId") Group period, + @PathVariable String peerGroupingTag, Authentication auth) { if (canCreatePeerGroup(run, period, auth)) { PeerGrouping peerGrouping = peerGroupingService.getByTag(run, peerGroupingTag); return peerGroupCreateService.create(peerGrouping, period); @@ -41,7 +40,7 @@ PeerGroup create(@PathVariable("runId") RunImpl run, throw new AccessDeniedException("Not permitted"); } - private boolean canCreatePeerGroup(RunImpl run, PersistentGroup period, Authentication auth) { + private boolean canCreatePeerGroup(Run run, Group period, Authentication auth) { return runService.hasWritePermission(auth, run) && run.getPeriods().contains(period); } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipController.java index b6f60cc619..a163c263a2 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipController.java @@ -12,6 +12,7 @@ import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.peergroup.impl.PeerGroupImpl; import org.wise.portal.domain.run.Run; +import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.peergroup.PeerGroupMembershipService; import org.wise.portal.service.run.RunService; @@ -28,24 +29,24 @@ public class PeerGroupMembershipController { private RunService runService; @PostMapping("/add/{peerGroupId}/{workgroupId}") - PeerGroup addMember(@PathVariable("peerGroupId") PeerGroupImpl peerGroup, - @PathVariable("workgroupId") WorkgroupImpl workgroup, Authentication auth) { - if (canChangeMembership(peerGroup, workgroup, auth)) { + PeerGroup addMember(@PathVariable("peerGroupId") PeerGroup peerGroup, + @PathVariable("workgroupId") Workgroup workgroup, Authentication auth) { + if (canChangeMembership((PeerGroupImpl) peerGroup, (WorkgroupImpl) workgroup, auth)) { return peerGroupMembershipService.addMember(peerGroup, workgroup); } throw new AccessDeniedException("Not permitted"); } @DeleteMapping("/{peerGroupId}/{workgroupId}") - PeerGroup removeMember(@PathVariable("peerGroupId") PeerGroupImpl peerGroup, - @PathVariable("workgroupId") WorkgroupImpl workgroup, Authentication auth) { - if (canChangeMembership(peerGroup, workgroup, auth)) { + PeerGroup removeMember(@PathVariable("peerGroupId") PeerGroup peerGroup, + @PathVariable("workgroupId") Workgroup workgroup, Authentication auth) { + if (canChangeMembership((PeerGroupImpl) peerGroup, (WorkgroupImpl) workgroup, auth)) { return peerGroupMembershipService.removeMember(peerGroup, workgroup); } throw new AccessDeniedException("Not permitted"); } - private boolean canChangeMembership(PeerGroupImpl peerGroup, WorkgroupImpl workgroup, + private boolean canChangeMembership(PeerGroup peerGroup, Workgroup workgroup, Authentication auth) { Run run = peerGroup.getPeerGrouping().getRun(); return runService.hasWritePermission(auth, run) && run.equals(workgroup.getRun()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationController.java index ff0c5b8400..2ca61814dd 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationController.java @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; -import org.wise.portal.domain.peergroup.impl.PeerGroupImpl; +import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.project.impl.ProjectComponent; import org.wise.portal.domain.run.Run; import org.wise.portal.presentation.web.controllers.student.AbstractPeerGroupWorkController; @@ -37,7 +37,7 @@ public class PeerGroupStudentWorkAnnotationController extends AbstractPeerGroupW @GetMapping("/dynamic-prompt") List getStudentDataForDynamicPrompt( - @PathVariable("peerGroupId") PeerGroupImpl peerGroup, @PathVariable String nodeId, + @PathVariable("peerGroupId") PeerGroup peerGroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) throws Exception { checkPermissions(auth, peerGroup); return getStudentDataForReferenceComponent(peerGroup, nodeId, componentId, "dynamicPrompt"); @@ -45,20 +45,20 @@ List getStudentDataForDynamicPrompt( @GetMapping("/question-bank") List getStudentDataForQuestionBank( - @PathVariable("peerGroupId") PeerGroupImpl peerGroup, @PathVariable String nodeId, + @PathVariable("peerGroupId") PeerGroup peerGroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) throws Exception { checkPermissions(auth, peerGroup); return getStudentDataForReferenceComponent(peerGroup, nodeId, componentId, "questionBank"); } - private void checkPermissions(Authentication auth, PeerGroupImpl peerGroup) + private void checkPermissions(Authentication auth, PeerGroup peerGroup) throws ObjectNotFoundException { if (!isUserInPeerGroup(auth, peerGroup)) { throw new AccessDeniedException("Not permitted"); } } - private List getStudentDataForReferenceComponent(PeerGroupImpl peerGroup, + private List getStudentDataForReferenceComponent(PeerGroup peerGroup, String nodeId, String componentId, String fieldName) throws Exception { Run run = peerGroup.getPeerGrouping().getRun(); ReferenceComponent component = getReferenceComponent(run, nodeId, componentId, fieldName); @@ -73,7 +73,7 @@ private List getStudentDataForReferenceComponent(PeerGrou } } - private List getStudentDataForMultipleChoice(PeerGroupImpl peerGroup, + private List getStudentDataForMultipleChoice(PeerGroup peerGroup, ReferenceComponent component) { List studentWorkList = studentWorkService.getStudentWork(peerGroup.getMembers(), component.getNodeId(), component.getComponentId()); @@ -81,7 +81,7 @@ private List getStudentDataForMultipleChoice(PeerGroupImp .collect(Collectors.toList()); } - private List getStudentDataForOpenResponse(PeerGroupImpl peerGroup, + private List getStudentDataForOpenResponse(PeerGroup peerGroup, ReferenceComponent component) { List annotations = annotationService.getLatest(peerGroup.getMembers(), component.getNodeId(), component.getComponentId(), "autoScore"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIController.java index af49ed89c6..abb3445703 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIController.java @@ -11,11 +11,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.domain.peergroup.PeerGroup; -import org.wise.portal.domain.peergroup.impl.PeerGroupImpl; import org.wise.portal.domain.peergrouping.PeerGrouping; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; +import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.service.peergroup.PeerGroupCreationException; import org.wise.portal.service.peergrouping.PeerGroupingNotFoundException; import org.wise.vle.domain.work.StudentWork; @@ -26,7 +25,7 @@ public class PeerGroupWorkAPIController extends AbstractPeerGroupAPIController { @GetMapping("/{peerGroupId}/{nodeId}/{componentId}/student-work") - List getPeerGroupWork(@PathVariable("peerGroupId") PeerGroupImpl peerGroup, + List getPeerGroupWork(@PathVariable("peerGroupId") PeerGroup peerGroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) { if (isUserInPeerGroup(peerGroup, auth)) { return peerGroupService.getStudentWork(peerGroup, nodeId, componentId); @@ -37,8 +36,8 @@ List getPeerGroupWork(@PathVariable("peerGroupId") PeerGroupImpl pe @Secured("ROLE_TEACHER") @GetMapping("/{runId}/{workgroupId}/{nodeId}/{componentId}/student-work") - List getPeerGroupWork(@PathVariable("runId") RunImpl run, - @PathVariable("workgroupId") WorkgroupImpl workgroup, @PathVariable String nodeId, + List getPeerGroupWork(@PathVariable("runId") Run run, + @PathVariable("workgroupId") Workgroup workgroup, @PathVariable String nodeId, @PathVariable String componentId, Authentication auth) throws JSONException, PeerGroupingNotFoundException, PeerGroupCreationException { User user = userService.retrieveUserByUsername(auth.getName()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupingAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupingAPIController.java index f530d0a8da..5a28fff096 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupingAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupingAPIController.java @@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.RestController; import org.wise.portal.domain.peergrouping.impl.PeerGroupingImpl; import org.wise.portal.domain.project.Project; +import org.wise.portal.domain.run.Run; import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.presentation.web.response.ResponseEntityGenerator; @@ -34,9 +35,9 @@ public class PeerGroupingAPIController { private UserService userService; @PostMapping - Object create(Authentication auth, @PathVariable("runId") RunImpl run, + Object create(Authentication auth, @PathVariable("runId") Run run, @RequestBody PeerGroupingImpl peerGrouping) { - if (isAuthorized(auth, run)) { + if (isAuthorized(auth, (RunImpl) run)) { try { return peerGroupingService.createPeerGrouping(run, peerGrouping); } catch (Exception e) { @@ -48,9 +49,9 @@ Object create(Authentication auth, @PathVariable("runId") RunImpl run, } @PutMapping("/{tag}") - Object update(Authentication auth, @PathVariable("runId") RunImpl run, - @PathVariable("tag") String tag, @RequestBody PeerGroupingImpl peerGrouping) { - if (isAuthorized(auth, run)) { + Object update(Authentication auth, @PathVariable("runId") Run run, @PathVariable String tag, + @RequestBody PeerGroupingImpl peerGrouping) { + if (isAuthorized(auth, (RunImpl) run)) { return peerGroupingService.updatePeerGrouping(run, tag, peerGrouping); } else { return ResponseEntityGenerator.createError("notAuthorized"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIController.java index 6924fbfc40..5cd68d93ef 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIController.java @@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; import org.wise.portal.service.peergroup.PeerGroupInfoService; import org.wise.portal.service.peergrouping.PeerGroupingService; import org.wise.portal.service.run.RunService; @@ -34,12 +34,11 @@ public class TeacherPeerGroupInfoAPIController { private RunService runService; @GetMapping("/{runId}/{peerGroupingTag}") - public Map getPeerGroupsInfo(@PathVariable("runId") RunImpl run, - @PathVariable String peerGroupingTag, Authentication auth) - throws ObjectNotFoundException { + public Map getPeerGroupsInfo(@PathVariable("runId") Run run, + @PathVariable String peerGroupingTag, Authentication auth) throws ObjectNotFoundException { if (runService.hasReadPermission(auth, run)) { - return peerGroupInfoService.getPeerGroupInfo(peerGroupingService.getByTag(run, - peerGroupingTag)); + return peerGroupInfoService + .getPeerGroupInfo(peerGroupingService.getByTag(run, peerGroupingTag)); } else { throw new AccessDeniedException("Not permitted"); } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectAPIController.java index 535910e2ad..61fda5d9c6 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectAPIController.java @@ -16,7 +16,6 @@ import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.portal.Portal; import org.wise.portal.domain.project.Project; -import org.wise.portal.domain.project.impl.ProjectImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.usertag.UserTag; import org.wise.portal.presentation.web.controllers.ControllerUtil; @@ -48,7 +47,7 @@ public class ProjectAPIController { @GetMapping("/library") protected String getLibraryProjects(ModelMap modelMap) throws ObjectNotFoundException, JSONException { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); String projectLibraryGroups = portal.getProjectLibraryGroups(); JSONArray projectLibraryGroupsJSON = new JSONArray(projectLibraryGroups); for (int g = 0; g < projectLibraryGroupsJSON.length(); g++) { @@ -118,7 +117,7 @@ protected String getPersonalAndSharedProjects(ModelMap modelMap) throws JSONExce } @GetMapping("/info/{projectId}") - protected String getProjectInfo(@PathVariable("projectId") ProjectImpl project) + protected String getProjectInfo(@PathVariable("projectId") Project project) throws ObjectNotFoundException, JSONException { JSONObject projectJSON = ControllerUtil.getProjectJSON(project); return projectJSON.toString(); @@ -177,11 +176,11 @@ private JSONObject populateProjectMetadata(JSONObject projectLibraryGroup) throw } @PostMapping("/copy") - protected String copyProject(@RequestParam("projectId") ProjectImpl project) throws Exception { + protected String copyProject(@RequestParam("projectId") Project project) throws Exception { User user = ControllerUtil.getSignedInUser(); if (SecurityUtils.isTeacher(user)) { if (this.projectService.canReadProject(project, user)) { - Project newProject = projectService.copyProject(project.getId(), user); + Project newProject = projectService.copyProject((Long) project.getId(), user); return ControllerUtil.getProjectJSON(newProject).toString(); } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectTagController.java b/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectTagController.java index 5f0efde3f9..104c8f2dd5 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectTagController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/project/ProjectTagController.java @@ -23,8 +23,8 @@ */ package org.wise.portal.presentation.web.controllers.project; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/run/MergeSpreadsheetsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/run/MergeSpreadsheetsController.java index 3ea8b92d9b..5731b4365e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/run/MergeSpreadsheetsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/run/MergeSpreadsheetsController.java @@ -27,7 +27,7 @@ import java.util.HashMap; import java.util.Iterator; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; @@ -64,8 +64,8 @@ public class MergeSpreadsheetsController { @PostMapping protected ModelAndView mergeSpreadsheets( - @RequestParam("uploadFile") MultipartFile uploadFile, - @RequestParam("mergeColumnTitle") String mergeColumnTitle, + @RequestParam MultipartFile uploadFile, + @RequestParam String mergeColumnTitle, HttpServletResponse response ) throws Exception { BufferedInputStream fis = new BufferedInputStream(uploadFile.getInputStream()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/run/ReplaceBase64WithPNGController.java b/src/main/java/org/wise/portal/presentation/web/controllers/run/ReplaceBase64WithPNGController.java index 1ac9d4a1a7..ffb4d4552b 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/run/ReplaceBase64WithPNGController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/run/ReplaceBase64WithPNGController.java @@ -6,8 +6,8 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.dao.work.StudentWorkDao; @@ -17,7 +17,7 @@ import org.wise.vle.domain.work.StudentWork; import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.*; import java.sql.Timestamp; @@ -48,11 +48,11 @@ public class ReplaceBase64WithPNGController { @Autowired private StudentWorkDao studentWorkDao; - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected ModelAndView onSubmit( - @RequestParam("runId") Integer runId, - @RequestParam("nodeId") String nodeId, - @RequestParam("componentId") String componentId, + @RequestParam Integer runId, + @RequestParam String nodeId, + @RequestParam String componentId, HttpServletResponse response ) throws Exception { @@ -101,7 +101,7 @@ protected ModelAndView onSubmit( debugOutput(writer, response, ""); // get all the workgroups for the run - List workgroups = runService.getWorkgroups(new Long(runId)); + List workgroups = runService.getWorkgroups(Long.valueOf(runId)); debugOutput(writer, response, "Found " + workgroups.size() + " Workgroups"); debugOutput(writer, response, ""); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIController.java index 503d00a014..1a76b1acfc 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIController.java @@ -147,7 +147,7 @@ private boolean canWriteTag(Authentication auth, Workgroup workgroup, User user) private void broadcastTags(Workgroup workgroup) throws JSONException, JsonProcessingException { JSONObject message = new JSONObject(); message.put("type", "tagsToWorkgroup"); - message.put("topic", String.format("/topic/workgroup/%s", workgroup.getId())); + message.put("topic", "/topic/workgroup/%s".formatted(workgroup.getId())); ObjectMapper mapper = new ObjectMapper(); message.put("tags", mapper.writeValueAsString(workgroup.getTags())); redisPublisher.publish(message.toString()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataController.java index 96faab838f..5166acb1d9 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataController.java @@ -14,7 +14,6 @@ import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.group.Group; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.vle.domain.annotation.wise5.Annotation; import org.wise.vle.domain.work.StudentWork; @@ -27,9 +26,8 @@ public class ClassmateDiscussionDataController extends ClassmateDataController { @GetMapping("/student-work/{runId}/{periodId}/{nodeId}/{componentId}") public List getClassmateDiscussionWork(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable Long periodId, @PathVariable String nodeId, - @PathVariable String componentId) - throws IOException, JSONException, ObjectNotFoundException { + @PathVariable("runId") Run run, @PathVariable Long periodId, @PathVariable String nodeId, + @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { Group period = groupService.retrieveById(periodId); if (isAllowedToGetData(auth, run, period, nodeId, componentId)) { return getStudentWork(run, period, nodeId, componentId); @@ -40,7 +38,7 @@ public List getClassmateDiscussionWork(Authentication auth, @GetMapping("/annotations/{runId}/{periodId}/{nodeId}/{componentId}") public List getClassmateDiscussionAnnotations(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable Long periodId, @PathVariable String nodeId, + @PathVariable("runId") Run run, @PathVariable Long periodId, @PathVariable String nodeId, @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { Group period = groupService.retrieveById(periodId); if (isAllowedToGetData(auth, run, period, nodeId, componentId)) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataController.java index 7f6293a8ae..2f9982dce5 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataController.java @@ -17,7 +17,6 @@ import org.wise.portal.domain.group.Group; import org.wise.portal.domain.project.impl.ProjectComponent; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.vle.domain.work.StudentWork; @RestController @@ -32,10 +31,9 @@ public class ClassmateGraphDataController extends ClassmateDataController { @GetMapping("/student-work/{runId}/{nodeId}/{componentId}/{showWorkNodeId}/{showWorkComponentId}/period/{periodId}") public List getClassmateGraphWorkInPeriod(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable String nodeId, - @PathVariable String componentId, @PathVariable String showWorkNodeId, - @PathVariable String showWorkComponentId, @PathVariable Long periodId) - throws IOException, JSONException, ObjectNotFoundException { + @PathVariable("runId") Run run, @PathVariable String nodeId, @PathVariable String componentId, + @PathVariable String showWorkNodeId, @PathVariable String showWorkComponentId, + @PathVariable Long periodId) throws IOException, JSONException, ObjectNotFoundException { Group period = groupService.retrieveById(periodId); if (isAllowedToGetData(auth, run, period, nodeId, componentId, showWorkNodeId, showWorkComponentId, PERIOD_SOURCE)) { @@ -46,9 +44,8 @@ public List getClassmateGraphWorkInPeriod(Authentication auth, @GetMapping("/student-work/{runId}/{nodeId}/{componentId}/{showWorkNodeId}/{showWorkComponentId}/class") public List getClassmateGraphWorkInClass(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable String nodeId, - @PathVariable String componentId, @PathVariable String showWorkNodeId, - @PathVariable String showWorkComponentId) + @PathVariable("runId") Run run, @PathVariable String nodeId, @PathVariable String componentId, + @PathVariable String showWorkNodeId, @PathVariable String showWorkComponentId) throws IOException, JSONException, ObjectNotFoundException { if (isAllowedToGetData(auth, run, nodeId, componentId, showWorkNodeId, showWorkComponentId, CLASS_SOURCE)) { @@ -67,8 +64,8 @@ private boolean isAllowedToGetData(Authentication auth, Run run, Group period, S private boolean isAllowedToGetData(Authentication auth, Run run, String nodeId, String componentId, String showWorkNodeId, String showWorkComponentId, String showClassmateWorkSource) throws IOException, JSONException, ObjectNotFoundException { - return isStudentInRun(auth, run) && isValidGraphComponent(run, nodeId, componentId, showWorkNodeId, - showWorkComponentId, showClassmateWorkSource); + return isStudentInRun(auth, run) && isValidGraphComponent(run, nodeId, componentId, + showWorkNodeId, showWorkComponentId, showClassmateWorkSource); } private boolean isValidGraphComponent(Run run, String nodeId, String componentId, diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataController.java index 32504873b2..de4e825d59 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataController.java @@ -17,7 +17,6 @@ import org.wise.portal.domain.group.Group; import org.wise.portal.domain.project.impl.ProjectComponent; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.vle.domain.annotation.wise5.Annotation; import org.wise.vle.domain.work.StudentWork; @@ -32,9 +31,8 @@ public class ClassmateSummaryDataController extends ClassmateDataController { @GetMapping("/student-work/{runId}/{nodeId}/{componentId}/period/{periodId}") public List getClassmateSummaryWorkInPeriod(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable Long periodId, @PathVariable String nodeId, - @PathVariable String componentId) - throws IOException, JSONException, ObjectNotFoundException { + @PathVariable("runId") Run run, @PathVariable Long periodId, @PathVariable String nodeId, + @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { Group period = groupService.retrieveById(periodId); if (isAllowedToGetData(auth, run, period, nodeId, componentId)) { return getLatestStudentWork(run, period, nodeId, componentId); @@ -44,8 +42,7 @@ public List getClassmateSummaryWorkInPeriod(Authentication auth, @GetMapping("/student-work/{runId}/{nodeId}/{componentId}/class") public List getClassmateSummaryWorkInClass(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable String nodeId, - @PathVariable String componentId) + @PathVariable("runId") Run run, @PathVariable String nodeId, @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { if (isAllowedToGetData(auth, run, nodeId, componentId)) { return getLatestStudentWork(run, nodeId, componentId); @@ -55,9 +52,8 @@ public List getClassmateSummaryWorkInClass(Authentication auth, @GetMapping("/scores/{runId}/{nodeId}/{componentId}/period/{periodId}") public List getClassmateSummaryScoresInPeriod(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable Long periodId, @PathVariable String nodeId, - @PathVariable String componentId) - throws IOException, JSONException, ObjectNotFoundException { + @PathVariable("runId") Run run, @PathVariable Long periodId, @PathVariable String nodeId, + @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { Group period = groupService.retrieveById(periodId); if (isAllowedToGetData(auth, run, period, nodeId, componentId)) { return getLatestScoreAnnotations(getAnnotations(run, period, nodeId, componentId)); @@ -67,8 +63,7 @@ public List getClassmateSummaryScoresInPeriod(Authentication auth, @GetMapping("/scores/{runId}/{nodeId}/{componentId}/class") public List getClassmateSummaryScoresInClass(Authentication auth, - @PathVariable("runId") RunImpl run, @PathVariable String nodeId, - @PathVariable String componentId) + @PathVariable("runId") Run run, @PathVariable String nodeId, @PathVariable String componentId) throws IOException, JSONException, ObjectNotFoundException { if (isAllowedToGetData(auth, run, nodeId, componentId)) { return getLatestScoreAnnotations(getAnnotations(run, nodeId, componentId)); @@ -78,25 +73,25 @@ public List getClassmateSummaryScoresInClass(Authentication auth, private boolean isAllowedToGetData(Authentication auth, Run run, Group period, String nodeId, String componentId) throws IOException, JSONException, ObjectNotFoundException { - return (isStudent(auth) && isStudentInRunAndPeriod(auth, run, period) && - isValidSummaryComponent(run, nodeId, componentId)) || - (isTeacher(auth) && isTeacherOfRun(auth, run)); + return (isStudent(auth) && isStudentInRunAndPeriod(auth, run, period) + && isValidSummaryComponent(run, nodeId, componentId)) + || (isTeacher(auth) && isTeacherOfRun(auth, run)); } private boolean isAllowedToGetData(Authentication auth, Run run, String nodeId, String componentId) throws IOException, JSONException, ObjectNotFoundException { - return (isStudent(auth) && isStudentInRun(auth, run) && - isValidSummaryComponent(run, nodeId, componentId)) || - (isTeacher(auth) && isTeacherOfRun(auth, run)); + return (isStudent(auth) && isStudentInRun(auth, run) + && isValidSummaryComponent(run, nodeId, componentId)) + || (isTeacher(auth) && isTeacherOfRun(auth, run)); } private boolean isValidSummaryComponent(Run run, String nodeId, String componentId) throws IOException, JSONException, ObjectNotFoundException { List projectComponents = getProjectComponents(run); for (ProjectComponent projectComponent : projectComponents) { - if (projectComponent.getString("type").equals(SUMMARY_TYPE) && - projectComponent.getString("summaryNodeId").equals(nodeId) && - projectComponent.getString("summaryComponentId").equals(componentId)) { + if (projectComponent.getString("type").equals(SUMMARY_TYPE) + && projectComponent.getString("summaryNodeId").equals(nodeId) + && projectComponent.getString("summaryComponentId").equals(componentId)) { return true; } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerChatTypingStatusController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerChatTypingStatusController.java index bf4df57607..2106e13e14 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerChatTypingStatusController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerChatTypingStatusController.java @@ -1,6 +1,6 @@ package org.wise.portal.presentation.web.controllers.student; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import org.json.JSONException; import org.json.JSONObject; @@ -34,7 +34,7 @@ public void sendTypingStatusToPeerGroup(Authentication auth, PeerGroup peerGroup = peerGroupService.getById(peerGroupId); if (isUserInPeerGroup(auth, peerGroup) || isUserTeacherOfPeerGroup(auth, peerGroup)) { JSONObject message = new JSONObject(); - message.put("topic", String.format("/topic/peer-group/%s/is-typing", peerGroupId)); + message.put("topic", "/topic/peer-group/%s/is-typing".formatted(peerGroupId)); message.put("type", "isTyping"); JSONObject body = new JSONObject(); body.put("nodeId", nodeId); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerGroupWorkController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerGroupWorkController.java index 8dc260646e..b308a97a2d 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerGroupWorkController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/PeerGroupWorkController.java @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; -import org.wise.portal.domain.peergroup.impl.PeerGroupImpl; +import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.project.impl.ProjectComponent; import org.wise.portal.domain.run.Run; import org.wise.vle.domain.work.StudentWork; @@ -26,7 +26,7 @@ public class PeerGroupWorkController extends AbstractPeerGroupWorkController { @GetMapping("{peerGroupId}/{showPeerGroupWorkNodeId}/{showPeerGroupWorkComponentId}/{showWorkNodeId}/{showWorkComponentId}") public List getPeerGroupWork(Authentication auth, - @PathVariable("peerGroupId") PeerGroupImpl peerGroup, + @PathVariable("peerGroupId") PeerGroup peerGroup, @PathVariable String showPeerGroupWorkNodeId, @PathVariable String showPeerGroupWorkComponentId, @PathVariable String showWorkNodeId, @PathVariable String showWorkComponentId) diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/SendStudentWorkToClassmateController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/SendStudentWorkToClassmateController.java index 88e6fa1b26..6740a08bc0 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/SendStudentWorkToClassmateController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/SendStudentWorkToClassmateController.java @@ -40,7 +40,7 @@ public void sendStudentWorkToClassmate(Authentication auth, if (isInSameRun(auth, workgroupId)) { JSONObject message = new JSONObject(); message.put("type", "classmateStudentWork"); - message.put("topic", String.format("/topic/workgroup/%s", workgroupId)); + message.put("topic", "/topic/workgroup/%s".formatted(workgroupId)); message.put("studentWork", new JSONObject(studentWork)); redisPublisher.publish(message.toString()); } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentAPIController.java index dbd089162c..c9cb17b5d7 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentAPIController.java @@ -34,7 +34,7 @@ import java.util.Properties; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.hibernate.StaleObjectStateException; @@ -84,7 +84,6 @@ */ @RestController @RequestMapping("/api/student") -@Secured({ "ROLE_STUDENT" }) public class StudentAPIController extends UserAPIController { @Autowired @@ -99,7 +98,7 @@ public class StudentAPIController extends UserAPIController { @Autowired private Properties i18nProperties; - @Value("${google.clientId:}") + @Value("${spring.security.oauth2.client.registration.google.client-id:}") private String googleClientId; @GetMapping("/runs") @@ -112,12 +111,11 @@ List> getRuns(Authentication authentication) { return runList; } + @Secured({ "ROLE_STUDENT" }) @PostMapping("/run/launch") - HashMap launchRun(Authentication auth, @RequestParam("runId") Long runId, - @RequestParam(value = "workgroupId", required = false) Long workgroupId, - @RequestParam("presentUserIds") String presentUserIds, - @RequestParam("absentUserIds") String absentUserIds, HttpServletRequest request) - throws Exception { + HashMap launchRun(Authentication auth, @RequestParam Long runId, + @RequestParam(required = false) Long workgroupId, @RequestParam String presentUserIds, + @RequestParam String absentUserIds, HttpServletRequest request) throws Exception { Run run = runService.retrieveById(runId); presentUserIds = presentUserIds.substring(1, presentUserIds.length() - 1); String[] presentUserIdsArray = presentUserIds.split(",", 0); @@ -222,9 +220,10 @@ private Set getUsers(String[] userIds) throws ObjectNotFoundException { * information about the run. If the student is not successfully added to the run, we will * return a map containing an error field with an error string. */ + @Secured({ "ROLE_STUDENT" }) @PostMapping("/run/register") - HashMap addStudentToRun(Authentication auth, - @RequestParam("runCode") String runCode, @RequestParam("period") String period) { + HashMap addStudentToRun(Authentication auth, @RequestParam String runCode, + @RequestParam String period) { User user = userService.retrieveUserByUsername(auth.getName()); Run run = getRun(runCode); if (run == null || run.getProject().getWiseVersion() == 4) { @@ -363,8 +362,9 @@ List> getSecurityQuestions() { return questions; } + @Secured({ "ROLE_STUDENT" }) @PostMapping("/profile/update") - SimpleResponse updateProfile(Authentication auth, @RequestParam("language") String language) { + SimpleResponse updateProfile(Authentication auth, @RequestParam String language) { User user = userService.retrieveUserByUsername(auth.getName()); StudentUserDetails studentUserDetails = (StudentUserDetails) user.getUserDetails(); studentUserDetails.setLanguage(language); @@ -372,6 +372,7 @@ SimpleResponse updateProfile(Authentication auth, @RequestParam("language") Stri return new SimpleResponse("success", "profileUpdated"); } + @Secured({ "ROLE_STUDENT" }) @GetMapping("/teacher-list") Set> getAssociatedTeachers(Authentication auth) { User user = userService.retrieveUserByUsername(auth.getName()); @@ -387,11 +388,11 @@ Set> getAssociatedTeachers(Authentication auth) { return teachers; } + @Secured({ "ROLE_STUDENT" }) @GetMapping("/can-be-added-to-workgroup") - HashMap canBeAddedToWorkgroup(Authentication auth, - @RequestParam("runId") Long runId, - @RequestParam(value = "workgroupId", required = false) Long workgroupId, - @RequestParam("userId") Long userId) throws ObjectNotFoundException { + HashMap canBeAddedToWorkgroup(Authentication auth, @RequestParam Long runId, + @RequestParam(required = false) Long workgroupId, @RequestParam Long userId) + throws ObjectNotFoundException { User user = userService.retrieveById(userId); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIController.java index dbf8909d77..4b5148f1d6 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIController.java @@ -36,9 +36,9 @@ public class StudentForgotAccountAPIController { private Properties i18nProperties; @GetMapping("/username/search") - protected String getStudentUsernames(@RequestParam("firstName") String firstName, - @RequestParam("lastName") String lastName, @RequestParam("birthMonth") Integer birthMonth, - @RequestParam("birthDay") Integer birthDay) { + protected String getStudentUsernames(@RequestParam String firstName, + @RequestParam String lastName, @RequestParam Integer birthMonth, + @RequestParam Integer birthDay) { List accountsThatMatch = userService.retrieveStudentsByNameAndBirthday(firstName, lastName, birthMonth, birthDay); return getUsernamesJSON(accountsThatMatch).toString(); @@ -54,7 +54,7 @@ private JSONArray getUsernamesJSON(List users) { } @GetMapping("/password/security-question") - protected String getSecurityQuestion(@RequestParam("username") String username) + protected String getSecurityQuestion(@RequestParam String username) throws JSONException { User user = userService.retrieveUserByUsername(username); JSONObject response; @@ -71,8 +71,8 @@ protected String getSecurityQuestion(@RequestParam("username") String username) } @PostMapping("/password/security-question") - protected String checkSecurityAnswer(@RequestParam("username") String username, - @RequestParam("answer") String answer, @RequestParam("token") String token) + protected String checkSecurityAnswer(@RequestParam String username, + @RequestParam String answer, @RequestParam String token) throws JSONException { if (ControllerUtil.isReCaptchaEnabled() && !ControllerUtil.isReCaptchaResponseValid(token)) { return ControllerUtil.createErrorResponse("recaptchaResponseInvalid").toString(); @@ -93,9 +93,9 @@ protected String checkSecurityAnswer(@RequestParam("username") String username, @PostMapping("/password/change") protected ResponseEntity> changePassword( - @RequestParam("username") String username, @RequestParam("answer") String answer, - @RequestParam("password") String password, - @RequestParam("confirmPassword") String confirmPassword) throws JSONException { + @RequestParam String username, @RequestParam String answer, + @RequestParam String password, + @RequestParam String confirmPassword) throws JSONException { User user = userService.retrieveUserByUsername(username); if (user == null) { return ResponseEntityGenerator.createError("invalidUsername"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIController.java index a475e5c719..409485a74d 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIController.java @@ -23,9 +23,9 @@ import java.util.Date; import java.util.Locale; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -85,8 +85,8 @@ private void handleSurveyLaunched(HttpServletResponse response, HttpServletReque StudentUserAlreadyAssociatedWithRunException, RunHasEndedException { Object principal = getSecurityContextHolderPrincipal(); - if (principal instanceof StudentUserDetails - && isStudentAssociatedWithRun(run, (StudentUserDetails) principal)) { + if (principal instanceof StudentUserDetails details + && isStudentAssociatedWithRun(run, details)) { sendRedirect(response, "/student/unit/" + run.getId()); return; } else { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/tag/TagProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/tag/TagProjectController.java index da561ffa11..30b8bb0817 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/tag/TagProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/tag/TagProjectController.java @@ -39,7 +39,7 @@ public class TagProjectController { @PutMapping("/projects/tag/{tagId}") protected List> addTagToProjects(Authentication auth, - @RequestBody List projectIds, @PathVariable("tagId") Long tagId) throws Exception { + @RequestBody List projectIds, @PathVariable Long tagId) throws Exception { User user = userService.retrieveUserByUsername(auth.getName()); UserTag userTag = userTagsService.get(tagId); List projects = getProjects(projectIds); @@ -51,7 +51,7 @@ protected List> addTagToProjects(Authentication auth, @DeleteMapping("/projects/tag/{tagId}") protected List> removeTagFromProjects(Authentication auth, - @RequestParam List projectIds, @PathVariable("tagId") Long tagId) throws Exception { + @RequestParam List projectIds, @PathVariable Long tagId) throws Exception { User user = userService.retrieveUserByUsername(auth.getName()); UserTag userTag = userTagsService.get(tagId); List projects = getProjects(projectIds); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/tag/UserTagController.java b/src/main/java/org/wise/portal/presentation/web/controllers/tag/UserTagController.java index b10e7352f4..7167131f4a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/tag/UserTagController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/tag/UserTagController.java @@ -59,7 +59,7 @@ protected List> getTags(Authentication auth) { } @PutMapping("/user/tag/{tagId}") - protected Map updateTag(Authentication auth, @PathVariable("tagId") Long tagId, + protected Map updateTag(Authentication auth, @PathVariable Long tagId, @RequestBody Map tag) throws TagAlreadyExistsException { User user = userService.retrieveUserByUsername(auth.getName()); String tagText = ((String) tag.get("text")).trim(); @@ -74,7 +74,7 @@ protected Map updateTag(Authentication auth, @PathVariable("tagI } @DeleteMapping("/user/tag/{tagId}") - protected Map deleteTag(Authentication auth, @PathVariable("tagId") Long tagId) { + protected Map deleteTag(Authentication auth, @PathVariable Long tagId) { User user = userService.retrieveUserByUsername(auth.getName()); UserTag tag = userTagsService.get(tagId); userTagsService.deleteTag(user, tag); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/GoogleClassroomAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/GoogleClassroomAPIController.java index f3087d5e05..18f7136ed4 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/GoogleClassroomAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/GoogleClassroomAPIController.java @@ -19,17 +19,14 @@ import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.wise.portal.domain.authentication.MutableUserDetails; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.authentication.UserDetailsService; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; @@ -47,10 +44,10 @@ public class GoogleClassroomAPIController { @Autowired private UserDetailsService userDetailsService; - @Value("${google.clientId:}") + @Value("${spring.security.oauth2.client.registration.google.client-id:}") private String googleClientId; - @Value("${google.clientSecret:}") + @Value("${spring.security.oauth2.client.registration.google.client-secret:}") private String googleClientSecret; @Value("${wise.name:}") @@ -67,7 +64,7 @@ public class GoogleClassroomAPIController { SCOPES.add(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS); } - @RequestMapping(value = "/oauth", method = RequestMethod.GET) + @GetMapping("/oauth") private String googleOAuthToken(@RequestParam String code, HttpServletRequest request) throws GeneralSecurityException, IOException { String state = request.getParameter("state"); @@ -82,8 +79,9 @@ private String googleOAuthToken(@RequestParam String code, HttpServletRequest re credentials.setClientSecret(googleClientSecret); GoogleClientSecrets clientSecrets = new GoogleClientSecrets(); clientSecrets.setInstalled(credentials); - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, - clientSecrets, SCOPES).setDataStoreFactory(new FileDataStoreFactory(new java.io.File(tokensDirectoryPath))) + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, + JSON_FACTORY, clientSecrets, SCOPES) + .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(tokensDirectoryPath))) .build(); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(getRedirectUri()).execute(); flow.createAndStoreCredential(response, username); @@ -97,19 +95,22 @@ private ImmutablePair authorize(String username) throws Exce credentials.setClientSecret(googleClientSecret); GoogleClientSecrets clientSecrets = new GoogleClientSecrets(); clientSecrets.setInstalled(credentials); - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, - clientSecrets, SCOPES).setDataStoreFactory(new FileDataStoreFactory(new java.io.File(tokensDirectoryPath))) + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, + JSON_FACTORY, clientSecrets, SCOPES) + .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(tokensDirectoryPath))) .build(); Credential credential = flow.loadCredential(username); - if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || - credential.getExpiresInSeconds() > 60)) { + if (credential != null && (credential.getRefreshToken() != null + || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) { return new ImmutablePair<>(null, credential); } - AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(getRedirectUri()); + AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl() + .setRedirectUri(getRedirectUri()); String state = getState(); String authorizationUri = authorizationUrl.setState(state).build(); - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder + .currentRequestAttributes()).getRequest(); request.getSession().setAttribute("state", state); return new ImmutablePair<>(authorizationUri, null); } @@ -124,44 +125,45 @@ private String getRedirectUri() { private Classroom connectToClassroomAPI(Credential credential) throws Exception { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - return new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName).build(); + return new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) + .setApplicationName(applicationName).build(); } - @RequestMapping(value = "/get-authorization-url", method = RequestMethod.GET) - protected String getClassroomAuthorizationUrl(@RequestParam("username") String username) throws Exception { + @GetMapping("/get-authorization-url") + protected String getClassroomAuthorizationUrl(@RequestParam String username) throws Exception { JSONObject response = new JSONObject(); response.put("authorizationUrl", authorize(username).getLeft()); return response.toString(); } - @RequestMapping(value = "/list-courses", method = RequestMethod.GET) - protected List getClassroomCourses(@RequestParam("username") String username) throws Exception { + @GetMapping("/list-courses") + protected List getClassroomCourses(@RequestParam String username) throws Exception { Credential credential = authorize(username).getRight(); if (credential == null) { return null; } List activeCourses = new ArrayList<>(); - List courses = connectToClassroomAPI(credential).courses().list().execute().getCourses(); + List courses = connectToClassroomAPI(credential).courses().list().execute() + .getCourses(); if (courses == null) { return activeCourses; } - MutableUserDetails userDetails = (MutableUserDetails) userDetailsService.loadUserByUsername(username); - for (Course course: courses) { - if (!course.getCourseState().equals("ARCHIVED") && course.getOwnerId().equals(userDetails.getGoogleUserId())) { + MutableUserDetails userDetails = (MutableUserDetails) userDetailsService + .loadUserByUsername(username); + for (Course course : courses) { + if (!course.getCourseState().equals("ARCHIVED") + && course.getOwnerId().equals(userDetails.getGoogleUserId())) { activeCourses.add(course); } } return activeCourses; } - @RequestMapping(value = "/create-assignment", method = RequestMethod.POST) - protected String addToClassroom(HttpServletRequest request, - @RequestParam("accessCode") String accessCode, - @RequestParam("unitTitle") String unitTitle, - @RequestParam("username") String username, - @RequestParam("endTime") String endTime, - @RequestParam("description") String description, - @RequestParam("courseIds") String courseIdsString) throws Exception { + @PostMapping("/create-assignment") + protected String addToClassroom(HttpServletRequest request, @RequestParam String accessCode, + @RequestParam String unitTitle, @RequestParam String username, @RequestParam String endTime, + @RequestParam String description, @RequestParam("courseIds") String courseIdsString) + throws Exception { JSONObject response = new JSONObject(); ImmutablePair pair = authorize(username); String authorizationUrl = pair.getLeft(); @@ -221,7 +223,7 @@ private JSONObject addAssignmentToCourse(Classroom classroom, CourseWork coursew try { classroom.courses().courseWork().create(courseId, coursework).execute(); courseJSON.put("success", true); - } catch(Exception e) { + } catch (Exception e) { courseJSON.put("success", false); } return courseJSON; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherController.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIController.java index 559ba9040a..93f0f22a44 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIController.java @@ -8,14 +8,14 @@ import java.util.Set; import java.util.TreeSet; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; +import jakarta.mail.MessagingException; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.annotation.Secured; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.acls.model.Permission; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; @@ -32,7 +32,6 @@ import org.wise.portal.domain.group.Group; import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; -import org.wise.portal.domain.usertag.UserTag; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.presentation.web.controllers.user.UserAPIController; import org.wise.portal.presentation.web.exception.InvalidNameException; @@ -51,7 +50,6 @@ */ @RestController @RequestMapping("/api/teacher") -@Secured({ "ROLE_TEACHER" }) public class TeacherAPIController extends UserAPIController { @Autowired @@ -60,13 +58,14 @@ public class TeacherAPIController extends UserAPIController { @Autowired private UserTagsService userTagsService; - @Value("${google.clientId:}") + @Value("${spring.security.oauth2.client.registration.google.client-id:}") private String googleClientId; - @Value("${google.clientSecret:}") + @Value("${spring.security.oauth2.client.registration.google.client-secret:}") private String googleClientSecret; @GetMapping("/runs") + @PreAuthorize("hasRole('ROLE_TEACHER')") List> getRuns(Authentication auth, @RequestParam(required = false) Integer max) { User user = userService.retrieveUserByUsername(auth.getName()); @@ -91,6 +90,7 @@ private List> getRunsList(User user, List runs) { } @GetMapping("/run/{runId}") + @PreAuthorize("hasRole('ROLE_TEACHER')") HashMap getRun(Authentication auth, @PathVariable Long runId) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); @@ -112,6 +112,7 @@ protected HashMap getRunMap(User user, Run run) { } @GetMapping("/projectlastrun/{projectId}") + @PreAuthorize("hasRole('ROLE_TEACHER')") HashMap getProjectLastRun(Authentication auth, @PathVariable Long projectId) { User user = userService.retrieveUserByUsername(auth.getName()); List runsOfProject = runService.getProjectRuns(projectId); @@ -125,12 +126,13 @@ HashMap getProjectLastRun(Authentication auth, @PathVariable Lon } @GetMapping("/usernames") + @PreAuthorize("hasRole('ROLE_TEACHER')") List getAllTeacherUsernames() { return userDetailsService.retrieveAllTeacherUsernames(); } @PostMapping("/register") - @Secured({ "ROLE_ANONYMOUS" }) + @PreAuthorize("permitAll()") ResponseEntity> createTeacherAccount( @RequestBody Map teacherFields, HttpServletRequest request) throws DuplicateUsernameException, InvalidNameException { @@ -253,14 +255,12 @@ private List getSharedOwnerPermissionsList(Run run, User user) { } @PostMapping("/run/create") + @PreAuthorize("hasRole('ROLE_TEACHER')") HashMap createRun(Authentication auth, HttpServletRequest request, - @RequestParam("projectId") Long projectId, @RequestParam("periods") String periods, - @RequestParam boolean isSurvey, - @RequestParam("maxStudentsPerTeam") Integer maxStudentsPerTeam, - @RequestParam("startDate") Long startDate, - @RequestParam(value = "endDate", required = false) Long endDate, - @RequestParam(value = "isLockedAfterEndDate", defaultValue = "false") Boolean isLockedAfterEndDate) - throws Exception { + @RequestParam Long projectId, @RequestParam String periods, @RequestParam boolean isSurvey, + @RequestParam Integer maxStudentsPerTeam, @RequestParam Long startDate, + @RequestParam(required = false) Long endDate, + @RequestParam(defaultValue = "false") Boolean isLockedAfterEndDate) throws Exception { User user = userService.retrieveUserByUsername(auth.getName()); Locale locale = request.getLocale(); Set periodNames = createPeriodNamesSet(periods); @@ -279,11 +279,11 @@ private Set createPeriodNamesSet(String periodsString) { } @PostMapping("/profile/update") - SimpleResponse updateProfile(Authentication auth, @RequestParam("displayName") String displayName, - @RequestParam("email") String email, @RequestParam("city") String city, - @RequestParam("state") String state, @RequestParam("country") String country, - @RequestParam("schoolName") String schoolName, - @RequestParam("schoolLevel") String schoolLevel, @RequestParam("language") String language) { + @PreAuthorize("hasRole('ROLE_TEACHER')") + SimpleResponse updateProfile(Authentication auth, @RequestParam String displayName, + @RequestParam String email, @RequestParam String city, @RequestParam String state, + @RequestParam String country, @RequestParam String schoolName, + @RequestParam String schoolLevel, @RequestParam String language) { User user = userService.retrieveUserByUsername(auth.getName()); TeacherUserDetails tud = (TeacherUserDetails) user.getUserDetails(); tud.setEmailAddress(email); @@ -299,8 +299,9 @@ SimpleResponse updateProfile(Authentication auth, @RequestParam("displayName") S } @PostMapping("/run/add/period") - HashMap addPeriodToRun(Authentication auth, @RequestParam("runId") Long runId, - @RequestParam("periodName") String periodName) throws ObjectNotFoundException { + @PreAuthorize("hasRole('ROLE_TEACHER')") + HashMap addPeriodToRun(Authentication auth, @RequestParam Long runId, + @RequestParam String periodName) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); @@ -323,9 +324,9 @@ HashMap addPeriodToRun(Authentication auth, @RequestParam("runId } @PostMapping("/run/delete/period") - HashMap deletePeriodFromRun(Authentication auth, - @RequestParam("runId") Long runId, @RequestParam("periodName") String periodName) - throws ObjectNotFoundException, PeriodNotFoundException { + @PreAuthorize("hasRole('ROLE_TEACHER')") + HashMap deletePeriodFromRun(Authentication auth, @RequestParam Long runId, + @RequestParam String periodName) throws ObjectNotFoundException, PeriodNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); @@ -347,9 +348,9 @@ HashMap deletePeriodFromRun(Authentication auth, } @PostMapping("/run/update/studentsperteam") - HashMap editRunStudentsPerTeam(Authentication auth, - @RequestParam("runId") Long runId, @RequestParam("maxStudentsPerTeam") Integer newMax) - throws ObjectNotFoundException { + @PreAuthorize("hasRole('ROLE_TEACHER')") + HashMap editRunStudentsPerTeam(Authentication auth, @RequestParam Long runId, + @RequestParam("maxStudentsPerTeam") Integer newMax) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); @@ -370,9 +371,9 @@ HashMap editRunStudentsPerTeam(Authentication auth, } @PostMapping("/run/update/starttime") - HashMap editRunStartTime(Authentication authentication, - @RequestParam("runId") Long runId, @RequestParam("startTime") Long startTime) - throws ObjectNotFoundException { + @PreAuthorize("hasRole('ROLE_TEACHER')") + HashMap editRunStartTime(Authentication authentication, @RequestParam Long runId, + @RequestParam Long startTime) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(authentication.getName()); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); @@ -394,10 +395,9 @@ HashMap editRunStartTime(Authentication authentication, } @PostMapping("/run/update/endtime") - HashMap editRunEndTime(Authentication authentication, - @RequestParam("runId") Long runId, - @RequestParam(value = "endTime", required = false) Long endTime) - throws ObjectNotFoundException { + @PreAuthorize("hasRole('ROLE_TEACHER')") + HashMap editRunEndTime(Authentication authentication, @RequestParam Long runId, + @RequestParam(required = false) Long endTime) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(authentication.getName()); Run run = runService.retrieveById(runId); HashMap response = new HashMap(); @@ -418,9 +418,9 @@ HashMap editRunEndTime(Authentication authentication, } @PostMapping("/run/update/islockedafterenddate") + @PreAuthorize("hasRole('ROLE_TEACHER')") HashMap editRunIsLockedAfterEndDate(Authentication authentication, - @RequestParam("runId") Long runId, - @RequestParam("isLockedAfterEndDate") Boolean isLockedAfterEndDate) + @RequestParam Long runId, @RequestParam Boolean isLockedAfterEndDate) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(authentication.getName()); Run run = runService.retrieveById(runId); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIController.java index 2618ab5892..afa412e576 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIController.java @@ -19,8 +19,8 @@ import org.wise.portal.service.password.PasswordService; import org.wise.portal.service.user.UserService; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; +import jakarta.mail.MessagingException; +import jakarta.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.Locale; @@ -47,7 +47,7 @@ public class TeacherForgotAccountAPIController { @PostMapping("/username") protected String sendForgotUsernameEmail(HttpServletRequest request, - @RequestParam("email") String email) throws JSONException { + @RequestParam String email) throws JSONException { List users = userService.retrieveUserByEmailAddress(email); JSONObject response; if (users.isEmpty()) { @@ -89,7 +89,7 @@ private boolean sendEmail(String[] to, String subject, String body, String from) @GetMapping("/password/verification-code") protected String sendVerificationCodeEmail(HttpServletRequest request, - @RequestParam("username") String username, @RequestParam("token") String token) + @RequestParam String username, @RequestParam String token) throws JSONException { if (ControllerUtil.isReCaptchaEnabled() && !ControllerUtil.isReCaptchaResponseValid(token)) { return getInvalidRecaptchaErrorResponse().toString(); @@ -152,8 +152,8 @@ private boolean isWithinLast10Minutes(Date date) { } @PostMapping("/password/verification-code") - protected String checkVerificationCode(@RequestParam("username") String username, - @RequestParam("verificationCode") String verificationCode) throws JSONException { + protected String checkVerificationCode(@RequestParam String username, + @RequestParam String verificationCode) throws JSONException { JSONObject response = new JSONObject(); User user = userService.retrieveUserByUsername(username); if (user != null) { @@ -195,10 +195,10 @@ private void incrementFailedVerificationCodeAttempt(User user) { @PostMapping("/password/change") protected ResponseEntity> changePassword( - @RequestParam("username") String username, - @RequestParam("verificationCode") String verificationCode, - @RequestParam("password") String password, - @RequestParam("confirmPassword") String confirmPassword) throws JSONException { + @RequestParam String username, + @RequestParam String verificationCode, + @RequestParam String password, + @RequestParam String confirmPassword) throws JSONException { User user = userService.retrieveUserByUsername(username); if (user == null) { return ResponseEntityGenerator.createError("usernameNotFound"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherProjectPermissionsAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherProjectPermissionsAPIController.java index 17beac8f0e..652821f956 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherProjectPermissionsAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherProjectPermissionsAPIController.java @@ -21,7 +21,7 @@ public class TeacherProjectPermissionsAPIController { @Autowired private ProjectService projectService; - @RequestMapping(value = "/{projectId}/{username}", method = RequestMethod.PUT) + @PutMapping("/{projectId}/{username}") protected SharedOwner addSharedOwner(@PathVariable Long projectId, @PathVariable String username) { try { @@ -33,7 +33,7 @@ protected SharedOwner addSharedOwner(@PathVariable Long projectId, } } - @RequestMapping(value = "/{projectId}/{username}", method = RequestMethod.DELETE) + @DeleteMapping("/{projectId}/{username}") protected SimpleResponse removeSharedOwner(@PathVariable Long projectId, @PathVariable String username) { try { @@ -44,7 +44,7 @@ protected SimpleResponse removeSharedOwner(@PathVariable Long projectId, } } - @RequestMapping(value = "/{projectId}/{userId}/{permissionId}", method = RequestMethod.PUT) + @PutMapping("/{projectId}/{userId}/{permissionId}") protected SimpleResponse addPermission(@PathVariable Long projectId, @PathVariable Long userId, @PathVariable Integer permissionId) { @@ -56,7 +56,7 @@ protected SimpleResponse addPermission(@PathVariable Long projectId, } } - @RequestMapping(value = "/{projectId}/{userId}/{permissionId}", method = RequestMethod.DELETE) + @DeleteMapping("/{projectId}/{userId}/{permissionId}") protected SimpleResponse deletePermission(@PathVariable Long projectId, @PathVariable Long userId, @PathVariable Integer permissionId) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherRunPermissionsAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherRunPermissionsAPIController.java index bf885c9b39..2e5d63467a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherRunPermissionsAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/TeacherRunPermissionsAPIController.java @@ -21,7 +21,7 @@ public class TeacherRunPermissionsAPIController { @Autowired private RunService runService; - @RequestMapping(value = "/{runId}/{teacherUsername}", method = RequestMethod.PUT) + @PutMapping("/{runId}/{teacherUsername}") protected SharedOwner addSharedOwner(@PathVariable Long runId, @PathVariable String teacherUsername) { try { @@ -43,7 +43,7 @@ protected String transferRunOwnership(@PathVariable Long runId, } } - @RequestMapping(value = "/{runId}/{username}", method = RequestMethod.DELETE) + @DeleteMapping("/{runId}/{username}") protected SimpleResponse removeSharedOwner(@PathVariable Long runId, @PathVariable String username) { try { @@ -54,7 +54,7 @@ protected SimpleResponse removeSharedOwner(@PathVariable Long runId, } } - @RequestMapping(value = "/{runId}/{userId}/{permissionId}", method = RequestMethod.PUT) + @PutMapping("/{runId}/{userId}/{permissionId}") protected SimpleResponse addPermission(@PathVariable Long runId, @PathVariable Long userId, @PathVariable Integer permissionId) { try { @@ -65,7 +65,7 @@ protected SimpleResponse addPermission(@PathVariable Long runId, @PathVariable L } } - @RequestMapping(value = "/{runId}/{userId}/{permissionId}", method = RequestMethod.DELETE) + @DeleteMapping("/{runId}/{userId}/{permissionId}") protected SimpleResponse deletePermission(@PathVariable Long runId, @PathVariable Long userId, @PathVariable Integer permissionId) { try { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkController.java index e87cd1ae4b..00f889390e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkController.java @@ -23,8 +23,8 @@ */ package org.wise.portal.presentation.web.controllers.teacher.grading; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordController.java index 82fa15bbba..db6c8db00e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordController.java @@ -25,17 +25,14 @@ import java.util.Iterator; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.domain.BasePermission; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.authentication.impl.BatchStudentChangePasswordParameters; @@ -86,7 +83,7 @@ public class BatchStudentChangePasswordController { * @return the path of the view to display * @throws Exception */ - @RequestMapping(method = RequestMethod.GET) + @GetMapping public String initializeForm(ModelMap model, HttpServletRequest request) throws Exception { User user = ControllerUtil.getSignedInUser(); Run run = runService.retrieveById(Long.parseLong(request.getParameter("runId"))); @@ -112,9 +109,9 @@ public String initializeForm(ModelMap model, HttpServletRequest request) throws * @param bindingResult the object used for validation in which errors will be stored * @param sessionStatus the session status object */ - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected String onSubmit( - @ModelAttribute("batchStudentChangePasswordParameters") BatchStudentChangePasswordParameters batchStudentChangePasswordParameters, + @ModelAttribute BatchStudentChangePasswordParameters batchStudentChangePasswordParameters, BindingResult bindingResult, SessionStatus sessionStatus) { String view = ""; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeUserPasswordController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeUserPasswordController.java index 9dc653c48d..e67aa92390 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeUserPasswordController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeUserPasswordController.java @@ -23,16 +23,12 @@ */ package org.wise.portal.presentation.web.controllers.teacher.management; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.authentication.impl.ChangeStudentPasswordParameters; @@ -49,8 +45,7 @@ */ @Controller @SessionAttributes("changeStudentPasswordParameters") -@RequestMapping(value = { - "/**/changepassword.html"}) +@RequestMapping(value = { "/changepassword.html" }) public class ChangeUserPasswordController { @Autowired @@ -70,7 +65,7 @@ public class ChangeUserPasswordController { * @param request the http request * @return the path of the view to display */ - @RequestMapping(method = RequestMethod.GET) + @GetMapping public ModelAndView initializeForm(HttpServletRequest request) { User signedInUser = ControllerUtil.getSignedInUser(); String username = request.getParameter(USER_NAME); @@ -112,13 +107,14 @@ public ModelAndView initializeForm(HttpServletRequest request) { * @return */ private boolean canChangePassword(User loggedInUser, User userToChange) { - return (loggedInUser.getUserDetails().hasGrantedAuthority(UserDetailsService.ADMIN_ROLE) && - !userToChange.getUserDetails().getUsername().equals("admin")) + return (loggedInUser.getUserDetails().hasGrantedAuthority(UserDetailsService.ADMIN_ROLE) + && !userToChange.getUserDetails().getUsername().equals("admin")) || userToChange.equals(loggedInUser) || (userToChange.getUserDetails().hasGrantedAuthority(UserDetailsService.STUDENT_ROLE) - && loggedInUser.getUserDetails().hasGrantedAuthority(UserDetailsService.RESEARCHER_ROLE)) + && loggedInUser.getUserDetails() + .hasGrantedAuthority(UserDetailsService.RESEARCHER_ROLE)) || (userToChange.getUserDetails().hasGrantedAuthority(UserDetailsService.STUDENT_ROLE) - && studentService.isStudentAssociatedWithTeacher(userToChange, loggedInUser)); + && studentService.isStudentAssociatedWithTeacher(userToChange, loggedInUser)); } /** @@ -130,12 +126,10 @@ private boolean canChangePassword(User loggedInUser, User userToChange) { * @return the path of the view to display * */ - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected ModelAndView onSubmit( @ModelAttribute("changeStudentPasswordParameters") ChangeStudentPasswordParameters params, - HttpServletRequest request, - BindingResult bindingResult, - SessionStatus sessionStatus) { + HttpServletRequest request, BindingResult bindingResult, SessionStatus sessionStatus) { changePasswordParametersValidator.validate(params, bindingResult); if (bindingResult.hasErrors()) { return new ModelAndView(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ManageStudentsController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ManageStudentsController.java index 6bc9d868e6..6402039c6f 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ManageStudentsController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/management/ManageStudentsController.java @@ -30,8 +30,8 @@ import java.util.Set; import java.util.TreeSet; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; @@ -90,7 +90,7 @@ private boolean userCanViewRun(User user, Run run) { * @throws Exception */ @GetMapping("/studentlist") - protected ModelAndView getStudentList(@RequestParam("runId") Long runId) throws Exception { + protected ModelAndView getStudentList(@RequestParam Long runId) throws Exception { Run run = runService.retrieveById(runId); if (userCanViewRun(ControllerUtil.getSignedInUser(), run)) { Set periods = run.getPeriods(); @@ -116,7 +116,7 @@ protected ModelAndView getStudentList(@RequestParam("runId") Long runId) throws * @throws Exception */ @GetMapping("/studentListExport") - protected void exportStudentList(@RequestParam("runId") Long runId, + protected void exportStudentList(@RequestParam Long runId, HttpServletResponse response) throws Exception { Run run = runService.retrieveById(runId); Project project = run.getProject(); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ExportProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ExportProjectController.java index 54397a7735..a2f1c7375e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ExportProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ExportProjectController.java @@ -32,8 +32,8 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -46,7 +46,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.wise.portal.domain.project.Project; import org.wise.portal.domain.project.ProjectMetadata; -import org.wise.portal.domain.project.impl.ProjectImpl; import org.wise.portal.domain.user.User; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.authentication.UserDetailsService; @@ -77,7 +76,7 @@ public class ExportProjectController { * @throws Exception when there was an error while exporting the project */ @GetMapping - protected void exportProject(@PathVariable("projectId") ProjectImpl project, + protected void exportProject(@PathVariable("projectId") Project project, HttpServletResponse response) throws Exception { User signedInUser = ControllerUtil.getSignedInUser(); if (authorize(signedInUser, project)) { @@ -97,13 +96,15 @@ protected void exportProject(@PathVariable("projectId") ProjectImpl project, String projectJSONDir = projectJSONFullPath.substring(0, projectJSONFullPath.lastIndexOf(sep)); response.setContentType("application/zip"); - response.addHeader("Content-Disposition", "attachment;filename=\"" + foldername+".zip" + "\""); + response.addHeader("Content-Disposition", + "attachment;filename=\"" + foldername + ".zip" + "\""); ProjectMetadata metadata = project.getMetadata(); String metadataJSONString = metadata.toJSONString(); if (project.getWiseVersion().equals(4)) { - String metaFileName = projectJSONDir + sep + "wise4.project-meta.json";; + String metaFileName = projectJSONDir + sep + "wise4.project-meta.json"; + ; PrintWriter metaOut = new PrintWriter(metaFileName); metaOut.println(metadataJSONString); metaOut.close(); @@ -141,15 +142,16 @@ protected void exportProject(@PathVariable("projectId") ProjectImpl project, */ private boolean authorize(User signedInUser, Project project) { if (signedInUser != null) { - Collection authorities = signedInUser.getUserDetails().getAuthorities(); + Collection authorities = signedInUser.getUserDetails() + .getAuthorities(); for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(UserDetailsService.ADMIN_ROLE)) { // if signed in user is an admin, (s)he can export all projects. return true; } else if (authority.getAuthority().equals(UserDetailsService.TEACHER_ROLE)) { //the signed in user is a teacher - return this.projectService.canAuthorProject(project, signedInUser) || - this.projectService.canReadProject(project, signedInUser); + return this.projectService.canAuthorProject(project, signedInUser) + || this.projectService.canReadProject(project, signedInUser); } } } @@ -177,7 +179,8 @@ private void addFolderToZip(File folder, ZipOutputStream zip, String baseName) } else { String name = file.getAbsolutePath().substring(baseName.length()); String updatedFilename = null; - if (name.endsWith("wise4.project.json") && !"wise4.project.json".equals(this.projectJSONFilename)) { + if (name.endsWith("wise4.project.json") + && !"wise4.project.json".equals(this.projectJSONFilename)) { // jump to the next iteration, since we don't need to add this file (wise4.project.json) to the zip. // we want to add the other *.project.json file (e.g. "GCC.project.json") as wise4.project.json to the zip. continue; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ShareProjectController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ShareProjectController.java index 2841d37a8f..a5d6e8025a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ShareProjectController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/project/ShareProjectController.java @@ -34,9 +34,9 @@ import java.util.Properties; import java.util.Set; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.mail.MessagingException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -270,7 +270,7 @@ protected String onSubmit( protected void unshareSelfFromProject( @RequestParam("projectId") String projectIdStr, HttpServletResponse response) throws Exception { - Long projectId = new Long(projectIdStr); + Long projectId = Long.valueOf(projectIdStr); Project project = projectService.getById(projectId); String username = ControllerUtil.getSignedInUser().getUserDetails().getUsername(); User user = userService.retrieveUserByUsername(username); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/PausePeriodController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/PausePeriodController.java index 8eb80da495..b03c24e1f1 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/PausePeriodController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/PausePeriodController.java @@ -20,7 +20,7 @@ public void pausePeriod(@DestinationVariable Integer runId, @DestinationVariable throws Exception { JSONObject message = new JSONObject(); message.put("type", "pause"); - message.put("topic", String.format("/topic/classroom/%s/%s", runId, periodId)); + message.put("topic", "/topic/classroom/%s/%s".formatted(runId, periodId)); redisPublisher.publish(message.toString()); } @@ -29,7 +29,7 @@ public void unpausePeriod(@DestinationVariable Integer runId, @DestinationVariable Integer periodId) throws Exception { JSONObject message = new JSONObject(); message.put("type", "unpause"); - message.put("topic", String.format("/topic/classroom/%s/%s", runId, periodId)); + message.put("topic", "/topic/classroom/%s/%s".formatted(runId, periodId)); redisPublisher.publish(message.toString()); } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/SendNodeToPeriodController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/SendNodeToPeriodController.java index 408d05aab0..459c465f6e 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/SendNodeToPeriodController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/SendNodeToPeriodController.java @@ -33,7 +33,7 @@ public void sendNodeToPeriod(Authentication auth, @DestinationVariable Long runI JSONObject msg = new JSONObject(); msg.put("type", "node"); msg.put("node", new JSONObject(node)); - msg.put("topic", String.format("/topic/classroom/%s/%s", run.getId(), periodId)); + msg.put("topic", "/topic/classroom/%s/%s".formatted(run.getId(), periodId)); redisPublisher.publish(msg.toString()); } } diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunController.java index fc056a7910..2bb8642b8d 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunController.java @@ -48,9 +48,9 @@ import org.wise.portal.service.user.UserService; import org.wise.portal.service.workgroup.WorkgroupService; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.mail.MessagingException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.*; @@ -116,7 +116,7 @@ public class ShareProjectRunController { * @param request the http request object * @return the path of the view to display */ - @RequestMapping(method = RequestMethod.GET, value = "/teacher/run/shareprojectrun.html") + @GetMapping("/teacher/run/shareprojectrun.html") public String initializeForm(ModelMap modelMap, HttpServletRequest request) throws Exception { User user = ControllerUtil.getSignedInUser(); Run run = runService.retrieveById(Long.parseLong(request.getParameter(RUNID_PARAM_NAME))); @@ -178,7 +178,7 @@ private Map populateModel(Map modelMap, * @param model the object that contains values to be displayed on the page * @return the path of the view to display */ - @RequestMapping(method = RequestMethod.POST, value = "/teacher/run/shareprojectrun.html") + @PostMapping("/teacher/run/shareprojectrun.html") protected String onSubmit( @ModelAttribute("addSharedTeacherParameters") AddSharedTeacherParameters params, HttpServletRequest request, @@ -247,11 +247,11 @@ protected String onSubmit( * @return * @throws Exception */ - @RequestMapping(method = RequestMethod.POST, value = "/teacher/run/unshareprojectrun") + @PostMapping("/teacher/run/unshareprojectrun") protected ModelAndView unshareSelfFromRun( - @RequestParam("runId") String runId, + @RequestParam String runId, HttpServletResponse response) throws Exception { - Long runIdToRemove = new Long(runId); + Long runIdToRemove = Long.valueOf(runId); String usernameToRemove = ControllerUtil.getSignedInUser().getUserDetails().getUsername(); runService.removeSharedTeacher(usernameToRemove, runIdToRemove); response.getWriter().write("success"); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIController.java index 223e06dfb4..82dc965226 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIController.java @@ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; import org.wise.portal.service.user.UserService; import org.wise.portal.service.vle.wise5.VLEService; @@ -25,12 +25,8 @@ public class TeacherRunAPIController { @Autowired private VLEService vleService; - /** - * Returns all student statuses for a given run - */ @GetMapping("/api/teacher/run/{runId}/student-status") - public List getStudentStatus(Authentication auth, - @PathVariable("runId") RunImpl run) { + public List getStudentStatus(Authentication auth, @PathVariable("runId") Run run) { User user = userService.retrieveUserByUsername(auth.getName()); if (run.isTeacherAssociatedToThisRun(user) || user.isAdmin()) { return vleService.getStudentStatusesByRunId(run.getId()); diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIController.java index 6044b32bcd..30b7fec774 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIController.java @@ -14,7 +14,6 @@ import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.impl.ChangeWorkgroupParameters; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.service.run.RunService; import org.wise.portal.service.user.UserService; @@ -34,7 +33,7 @@ public class WorkgroupMembershipAPIController { private WorkgroupService workgroupService; @PostMapping("/api/teacher/run/{runId}/workgroup/move-user/{userId}") - protected Long moveUserBetweenWorkgroups(Authentication auth, @PathVariable("runId") RunImpl run, + protected Long moveUserBetweenWorkgroups(Authentication auth, @PathVariable("runId") Run run, @PathVariable Long userId, @RequestBody JsonNode postedParams) throws Exception { Workgroup workgroup = null; if (runService.hasWritePermission(auth, run)) { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIController.java index eb827c0180..5c5338429a 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIController.java @@ -4,7 +4,7 @@ import java.util.Locale; import java.util.Map; -import javax.mail.MessagingException; +import jakarta.mail.MessagingException; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/user/UserAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/user/UserAPIController.java index ca965b81fb..85824bb703 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/user/UserAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/user/UserAPIController.java @@ -8,7 +8,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -19,6 +19,7 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.web.authentication.switchuser.SwitchUserFilter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -85,19 +86,19 @@ public class UserAPIController { @Autowired protected StudentService studentService; - @Value("${google.clientId:}") + @Value("${spring.security.oauth2.client.registration.google.client-id:}") protected String googleClientId = ""; - @Value("${google.clientSecret:}") + @Value("${spring.security.oauth2.client.registration.google.client-secret:}") private String googleClientSecret = ""; protected static final String PROJECT_THUMB_PATH = "/assets/project_thumb.png"; @GetMapping("/info") HashMap getUserInfo(Authentication auth, - @RequestParam(value = "username", required = false) String username) { + @RequestParam(required = false) String username) { HashMap info = new HashMap(); - if (auth != null) { + if (auth != null && !(auth instanceof OAuth2AuthenticationToken)) { User user = userService.retrieveUserByUsername(auth.getName()); info.put("id", user.getId()); MutableUserDetails ud = user.getUserDetails(); @@ -180,8 +181,8 @@ private boolean isGoogleClassroomEnabled() { } @PostMapping("/check-authentication") - HashMap checkAuthentication(@RequestParam("username") String username, - @RequestParam("password") String password) { + HashMap checkAuthentication(@RequestParam String username, + @RequestParam String password) { User user = userService.retrieveUserByUsername(username); HashMap response = new HashMap(); if (user == null) { @@ -200,8 +201,7 @@ HashMap checkAuthentication(@RequestParam("username") String use @PostMapping("/password") ResponseEntity> changePassword(Authentication auth, - @RequestParam("oldPassword") String oldPassword, - @RequestParam("newPassword") String newPassword) { + @RequestParam String oldPassword, @RequestParam String newPassword) { if (!passwordService.isValid(newPassword)) { Map map = passwordService.getErrors(newPassword); return ResponseEntityGenerator.createError(map); @@ -315,8 +315,8 @@ protected HashMap convertUserToMap(User user) { map.put("firstName", userDetails.getFirstname()); map.put("lastName", userDetails.getLastname()); map.put("isGoogleUser", userDetails.isGoogleUser()); - if (userDetails instanceof TeacherUserDetails) { - map.put("displayName", ((TeacherUserDetails) userDetails).getDisplayname()); + if (userDetails instanceof TeacherUserDetails details) { + map.put("displayName", details.getDisplayname()); } return map; } diff --git a/src/main/java/org/wise/portal/presentation/web/filters/AbstractOpenIdConnectFilter.java b/src/main/java/org/wise/portal/presentation/web/filters/AbstractOpenIdConnectFilter.java deleted file mode 100644 index a0e4e01b2e..0000000000 --- a/src/main/java/org/wise/portal/presentation/web/filters/AbstractOpenIdConnectFilter.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.wise.portal.presentation.web.filters; - -import java.net.URL; -import java.security.interfaces.RSAPublicKey; -import java.util.Date; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.jwt.crypto.sign.RsaVerifier; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; -import org.wise.portal.service.authentication.UserDetailsService; - -import com.auth0.jwk.Jwk; -import com.auth0.jwk.JwkProvider; -import com.auth0.jwk.UrlJwkProvider; - -public abstract class AbstractOpenIdConnectFilter extends AbstractAuthenticationProcessingFilter { - - protected String clientId; - protected String issuer; - protected String jwkUrl; - protected OAuth2RestTemplate openIdRestTemplate; - - @Autowired - protected UserDetailsService userDetailsService; - - protected AbstractOpenIdConnectFilter(String defaultFilterProcessesUrl) { - super(defaultFilterProcessesUrl); - setAuthenticationManager(new NoopAuthenticationManager()); - } - - protected OAuth2AccessToken getAccessToken() { - OAuth2AccessToken accessToken; - try { - accessToken = openIdRestTemplate.getAccessToken(); - } catch (final OAuth2Exception e) { - throw new BadCredentialsException("Could not obtain access token", e); - } - return accessToken; - } - - protected void saveRequestParams(HttpServletRequest request) { - saveRequestParameter(request, "accessCode"); - saveRequestParameter(request, "redirectUrl"); - } - - protected void saveRequestParameter(HttpServletRequest request, String parameterName) { - String parameterValue = request.getParameter(parameterName); - String parameterFromState = (String) openIdRestTemplate.getOAuth2ClientContext() - .removePreservedState(parameterName); - openIdRestTemplate.getOAuth2ClientContext().setPreservedState(parameterName, parameterValue); - request.setAttribute(parameterName, parameterFromState); - } - - protected void verifyClaims(Map claims) { - int exp = (int) claims.get("exp"); - Date expireDate = new Date(exp * 1000L); - Date now = new Date(); - if (expireDate.before(now) || !claims.get("iss").equals(issuer) - || !claims.get("aud").equals(clientId)) { - throw new RuntimeException("Invalid claims"); - } - } - - protected RsaVerifier verifier(String kid) throws Exception { - JwkProvider provider = new UrlJwkProvider(new URL(jwkUrl)); - Jwk jwk = provider.get(kid); - return new RsaVerifier((RSAPublicKey) jwk.getPublicKey()); - } - - protected void invalidateAccessToken() { - openIdRestTemplate.getOAuth2ClientContext().setAccessToken((OAuth2AccessToken) null); - } - - protected abstract void setClientId(String clientId); - - protected abstract void setIssuer(String issuer); - - protected abstract void setJwkUrl(String jwkUrl); - - protected abstract void setOpenIdRestTemplate(OAuth2RestTemplate template); -} diff --git a/src/main/java/org/wise/portal/presentation/web/filters/GoogleOpenIdConnectFilter.java b/src/main/java/org/wise/portal/presentation/web/filters/GoogleOpenIdConnectFilter.java deleted file mode 100644 index 96ceb84459..0000000000 --- a/src/main/java/org/wise/portal/presentation/web/filters/GoogleOpenIdConnectFilter.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2008-2019 Regents of the University of California (Regents). - * Created by WISE, Graduate School of Education, University of California, Berkeley. - * - * This software is distributed under the GNU General Public License, v3, - * or (at your option) any later version. - * - * Permission is hereby granted, without written agreement and without license - * or royalty fees, to use, copy, modify, and distribute this software and its - * documentation for any purpose, provided that the above copyright notice and - * the following two paragraphs appear in all copies of this software. - * - * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED - * HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE - * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - * - * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, - * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, - * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF - * REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.wise.portal.presentation.web.filters; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.jwt.Jwt; -import org.springframework.security.jwt.JwtHelper; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.wise.portal.domain.authentication.MutableUserDetails; -import org.wise.portal.service.session.SessionService; - -public class GoogleOpenIdConnectFilter extends AbstractOpenIdConnectFilter { - - @Autowired - protected SessionService sessionService; - - public GoogleOpenIdConnectFilter(String defaultFilterProcessesUrl) { - super(defaultFilterProcessesUrl); - } - - @Override - public Authentication attemptAuthentication(HttpServletRequest request, - HttpServletResponse response) throws AuthenticationException, IOException { - saveRequestParams(request); - OAuth2AccessToken accessToken = getAccessToken(); - try { - final String idToken = accessToken.getAdditionalInformation().get("id_token").toString(); - String kid = JwtHelper.headers(idToken).get("kid"); - final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid)); - final Map authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), - Map.class); - verifyClaims(authInfo); - final UserDetails user = userDetailsService.loadUserByGoogleUserId(authInfo.get("sub")); - invalidateAccesToken(); - if (user != null) { - return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); - } else { - throw new BadCredentialsException("google user not found"); - } - } catch (final Exception e) { - throw new BadCredentialsException("Could not obtain user details from token", e); - } - } - - private void invalidateAccesToken() { - openIdRestTemplate.getOAuth2ClientContext().setAccessToken((OAuth2AccessToken) null); - } - - @Override - protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, - FilterChain chain, Authentication authentication) throws IOException, ServletException { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - sessionService.addSignedInUser(userDetails); - userDetailsService.updateStatsOnSuccessfulLogin((MutableUserDetails) userDetails); - super.successfulAuthentication(request, response, chain, authentication); - } - - @Value("${google.clientId:}") - protected void setClientId(String clientId) { - this.clientId = clientId; - } - - @Value("${google.issuer:}") - protected void setIssuer(String issuer) { - this.issuer = issuer; - } - - @Value("${google.jwkUrl:}") - protected void setJwkUrl(String jwkUrl) { - this.jwkUrl = jwkUrl; - } - - @Autowired - @Qualifier("googleOpenIdRestTemplate") - protected void setOpenIdRestTemplate(OAuth2RestTemplate template) { - this.openIdRestTemplate = template; - } -} diff --git a/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftAuthenticationFailureHandler.java b/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftAuthenticationFailureHandler.java index 3617708df9..6471a4f1f9 100644 --- a/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftAuthenticationFailureHandler.java +++ b/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftAuthenticationFailureHandler.java @@ -2,9 +2,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; diff --git a/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftOpenIdConnectFilter.java b/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftOpenIdConnectFilter.java deleted file mode 100644 index 28f549dd67..0000000000 --- a/src/main/java/org/wise/portal/presentation/web/filters/MicrosoftOpenIdConnectFilter.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.wise.portal.presentation.web.filters; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.jwt.Jwt; -import org.springframework.security.jwt.JwtHelper; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.wise.portal.presentation.web.exception.MicrosoftUserNotFoundException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class MicrosoftOpenIdConnectFilter extends AbstractOpenIdConnectFilter { - - public MicrosoftOpenIdConnectFilter(String defaultFilterProcessesUrl) { - super(defaultFilterProcessesUrl); - } - - @Override - public Authentication attemptAuthentication(HttpServletRequest request, - HttpServletResponse response) throws AuthenticationException, IOException, ServletException { - saveRequestParams(request); - OAuth2AccessToken accessToken = getAccessToken(); - final String idToken = accessToken.getAdditionalInformation().get("id_token").toString(); - String kid = JwtHelper.headers(idToken).get("kid"); - Jwt tokenDecoded = null; - try { - tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid)); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - final Map authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), - Map.class); - verifyClaims(authInfo); - final UserDetails user = userDetailsService.loadUserByMicrosoftUserId(authInfo.get("sub")); - invalidateAccessToken(); - if (user != null) { - if (request.getAttribute("redirectUrl").toString().contains("join")) { - response.sendRedirect("/join/microsoftUserAlreadyExists"); - return null; - } else { - return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); - } - } else { - throw new MicrosoftUserNotFoundException("Microsoft user not found", authInfo); - } - } - - @Value("${microsoft.clientId:}") - protected void setClientId(String clientId) { - this.clientId = clientId; - } - - @Value("${microsoft.issuer:}") - protected void setIssuer(String issuer) { - this.issuer = issuer; - } - - @Value("${microsoft.jwkUrl:}") - protected void setJwkUrl(String jwkUrl) { - this.jwkUrl = jwkUrl; - } - - @Autowired - @Qualifier("microsoftOpenIdRestTemplate") - protected void setOpenIdRestTemplate(OAuth2RestTemplate template) { - this.openIdRestTemplate = template; - } -} diff --git a/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationFailureHandler.java b/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationFailureHandler.java new file mode 100644 index 0000000000..94e188f1f6 --- /dev/null +++ b/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationFailureHandler.java @@ -0,0 +1,31 @@ +package org.wise.portal.presentation.web.filters; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * Handles failed OAuth2/OpenID Connect authentication attempts. + * Redirects to an error page or login page with error message. + */ +@Component +public class OAuth2AuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) throws IOException, ServletException { + + // Log the error for debugging + System.err.println("OAuth2 authentication failed: " + exception.getMessage()); + exception.printStackTrace(); + + // Redirect to login page with error parameter + response.sendRedirect("/login?error=oauth2&message=" + + java.net.URLEncoder.encode(exception.getMessage(), "UTF-8")); + } +} diff --git a/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationSuccessHandler.java b/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationSuccessHandler.java new file mode 100644 index 0000000000..1b1dff87f9 --- /dev/null +++ b/src/main/java/org/wise/portal/presentation/web/filters/OAuth2AuthenticationSuccessHandler.java @@ -0,0 +1,81 @@ +package org.wise.portal.presentation.web.filters; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.stereotype.Component; +import org.wise.portal.domain.user.User; +import org.wise.portal.service.user.UserService; + +import java.io.IOException; + +/** + * Handles successful OAuth2/OpenID Connect authentication. + * Looks up the WISE user by their Google user ID and creates a proper authentication + * with WISE UserDetails (Teacher or Student). + */ +@Component +public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { + + @Autowired + private UserService userService; + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + + if (authentication.getPrincipal() instanceof OidcUser) { + OidcUser oidcUser = (OidcUser) authentication.getPrincipal(); + String googleUserId = oidcUser.getSubject(); + + try { + User user = userService.retrieveUserByGoogleUserId(googleUserId); + if (user != null) { + saveUserToSession(request, user); + if (user.isStudent()) { + response.sendRedirect("/student"); + } else { + response.sendRedirect("/teacher"); + } + } else { + invalidateSession(request); + response.sendRedirect("/join?googleUserNotFound=true"); + } + } catch (Exception e) { + invalidateSession(request); + response.sendRedirect("/join?googleUserNotFound=true"); + } + } else { + response.sendRedirect("/"); + } + } + + private void saveUserToSession(HttpServletRequest request, User user) { + UserDetails userDetails = user.getUserDetails(); + UsernamePasswordAuthenticationToken wiseAuth = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(wiseAuth); + SecurityContextHolder.setContext(context); + HttpSession session = request.getSession(true); + session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context); + } + + private void invalidateSession(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session != null) { + session.invalidate(); + } + } +} diff --git a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationFailureHandler.java b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationFailureHandler.java index 966614832d..78beab7dfa 100644 --- a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationFailureHandler.java +++ b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationFailureHandler.java @@ -36,9 +36,9 @@ import org.wise.portal.presentation.web.exception.RecaptchaVerificationException; import org.wise.portal.service.user.UserService; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; diff --git a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationProcessingFilter.java b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationProcessingFilter.java index 61b874c006..1a5ff12682 100644 --- a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationProcessingFilter.java +++ b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationProcessingFilter.java @@ -25,11 +25,11 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationSuccessHandler.java b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationSuccessHandler.java index 1fd9480912..7a7d741b56 100644 --- a/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationSuccessHandler.java +++ b/src/main/java/org/wise/portal/presentation/web/filters/WISEAuthenticationSuccessHandler.java @@ -41,9 +41,9 @@ import org.wise.portal.service.authentication.UserDetailsService; import org.wise.portal.service.portal.PortalService; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; import java.util.Locale; @@ -103,7 +103,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo // if user is not admin and login is disallowed, log out user and redirect them to the "we are undergoing maintenance" page try { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); if (!userIsAdmin && !portal.isLoginAllowed()) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { @@ -132,7 +132,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo if (ControllerUtil.isUserPreviousAdministrator()) { response.sendRedirect(getUserHomeUrl(userDetails, locale)); } - //super.handle(request, response, authentication); + super.onAuthenticationSuccess(request, response, authentication); } private void handleRedirectRequest(String redirectUrl, HttpServletRequest request, diff --git a/src/main/java/org/wise/portal/presentation/web/filters/WISESwitchUserFilter.java b/src/main/java/org/wise/portal/presentation/web/filters/WISESwitchUserFilter.java index 64844373dc..7bc57c03a9 100644 --- a/src/main/java/org/wise/portal/presentation/web/filters/WISESwitchUserFilter.java +++ b/src/main/java/org/wise/portal/presentation/web/filters/WISESwitchUserFilter.java @@ -23,7 +23,7 @@ */ package org.wise.portal.presentation.web.filters; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InsufficientAuthenticationException; diff --git a/src/main/java/org/wise/portal/presentation/web/listeners/WISESessionListener.java b/src/main/java/org/wise/portal/presentation/web/listeners/WISESessionListener.java index c324f03db9..1d2110b866 100644 --- a/src/main/java/org/wise/portal/presentation/web/listeners/WISESessionListener.java +++ b/src/main/java/org/wise/portal/presentation/web/listeners/WISESessionListener.java @@ -23,8 +23,8 @@ */ package org.wise.portal.presentation.web.listeners; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; +import jakarta.servlet.http.HttpSessionEvent; +import jakarta.servlet.http.HttpSessionListener; /** * @author Hiroki Terashima diff --git a/src/main/java/org/wise/portal/service/acl/impl/AclServiceImpl.java b/src/main/java/org/wise/portal/service/acl/impl/AclServiceImpl.java index f3ce90c16c..6d8d329f25 100644 --- a/src/main/java/org/wise/portal/service/acl/impl/AclServiceImpl.java +++ b/src/main/java/org/wise/portal/service/acl/impl/AclServiceImpl.java @@ -25,7 +25,7 @@ import java.util.Collection; import java.util.List; -import org.hibernate.proxy.HibernateProxyHelper; +import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityImpl; @@ -60,8 +60,8 @@ public class AclServiceImpl implements AclService { public void addPermission(T object, Permission permission) { if (object != null) { MutableAcl acl = null; - ObjectIdentity objectIdentity = new ObjectIdentityImpl( - HibernateProxyHelper.getClassWithoutInitializingProxy(object), object.getId()); + ObjectIdentity objectIdentity = new ObjectIdentityImpl(Hibernate.getClass(object), + object.getId()); try { acl = (MutableAcl) mutableAclService.readAclById(objectIdentity); } catch (NotFoundException nfe) { @@ -78,8 +78,8 @@ public void addPermission(T object, Permission permission) { public void addPermission(T object, Permission permission, User user) { if (object != null) { MutableAcl acl = null; - ObjectIdentity objectIdentity = new ObjectIdentityImpl( - HibernateProxyHelper.getClassWithoutInitializingProxy(object), object.getId()); + ObjectIdentity objectIdentity = new ObjectIdentityImpl(Hibernate.getClass(object), + object.getId()); try { acl = (MutableAcl) mutableAclService.readAclById(objectIdentity); } catch (NotFoundException nfe) { @@ -96,8 +96,8 @@ public void addPermission(T object, Permission permission, User user) { public void removePermission(T object, Permission permission, User user) { if (object != null) { MutableAcl acl = null; - ObjectIdentity objectIdentity = new ObjectIdentityImpl( - HibernateProxyHelper.getClassWithoutInitializingProxy(object), object.getId()); + ObjectIdentity objectIdentity = new ObjectIdentityImpl(Hibernate.getClass(object), + object.getId()); List sid = new ArrayList(); sid.add(new PrincipalSid(user.getUserDetails().getUsername())); @@ -128,8 +128,8 @@ public List getPermissions(T object, UserDetails userDetails) { if (object != null) { MutableAcl acl = null; - ObjectIdentity objectIdentity = new ObjectIdentityImpl( - HibernateProxyHelper.getClassWithoutInitializingProxy(object), object.getId()); + ObjectIdentity objectIdentity = new ObjectIdentityImpl(Hibernate.getClass(object), + object.getId()); List sid = new ArrayList(); sid.add(new PrincipalSid(userDetails.getUsername())); @@ -205,15 +205,15 @@ public boolean hasPermission(Authentication authentication, Object targetDomainO private ArrayList convertPermissionToList(Object permissionObj) { ArrayList permissionsList = new ArrayList(); // separate possibly comma-separated permissions string into array of permissions - if (permissionObj instanceof String) { - String[] permissions = ((String) permissionObj).split(","); + if (permissionObj instanceof String string) { + String[] permissions = string.split(","); for (String permissionStr : permissions) { permissionsList.add(getBasePermission(permissionStr).getMask()); } - } else if (permissionObj instanceof Integer) { - permissionsList.add((Integer) permissionObj); - } else if (permissionObj instanceof BasePermission) { - permissionsList.add(((BasePermission) permissionObj).getMask()); + } else if (permissionObj instanceof Integer integer) { + permissionsList.add(integer); + } else if (permissionObj instanceof BasePermission permission) { + permissionsList.add(permission.getMask()); } return permissionsList; } diff --git a/src/main/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImpl.java b/src/main/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImpl.java index b5b639e83f..3faace780f 100644 --- a/src/main/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImpl.java +++ b/src/main/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImpl.java @@ -60,10 +60,12 @@ public UserDetails loadUserByUsername(String username) return userDetails; } + @Transactional(readOnly = true) public UserDetails loadUserByGoogleUserId(String googleUserId) { return this.userDetailsDao.retrieveByGoogleUserId(googleUserId); } + @Transactional(readOnly = true) public UserDetails loadUserByMicrosoftUserId(String userId) { return this.userDetailsDao.retrieveByMicrosoftUserId(userId); } diff --git a/src/main/java/org/wise/portal/service/group/impl/GroupServiceImpl.java b/src/main/java/org/wise/portal/service/group/impl/GroupServiceImpl.java index f60823c130..6e5ac55f99 100644 --- a/src/main/java/org/wise/portal/service/group/impl/GroupServiceImpl.java +++ b/src/main/java/org/wise/portal/service/group/impl/GroupServiceImpl.java @@ -81,7 +81,7 @@ public Group createGroup(GroupParameters groupParameters) { Group parentGroup = groupDao.getById(parentId); group.setParent(parentGroup); } catch (ObjectNotFoundException e) { - parentId = new Long(0); + parentId = Long.valueOf(0); } } @@ -125,8 +125,10 @@ public void moveGroup(Group newParent, Group groupToBeMoved) throws CyclicalGrou if (cycleExists(groupToBeMoved)) { // if cycle exists, reset groupToBeMoved's parent groupToBeMoved.setParent(previousParent); - throw new CyclicalGroupException("Cycle will be created" - + " when this group is moved."); + throw new CyclicalGroupException(""" + Cycle will be created\ + when this group is moved.\ + """); } groupDao.save(groupToBeMoved); } diff --git a/src/main/java/org/wise/portal/service/mail/IMailFacade.java b/src/main/java/org/wise/portal/service/mail/IMailFacade.java index 02af361d9b..7cbbc34919 100644 --- a/src/main/java/org/wise/portal/service/mail/IMailFacade.java +++ b/src/main/java/org/wise/portal/service/mail/IMailFacade.java @@ -23,7 +23,7 @@ */ package org.wise.portal.service.mail; -import javax.mail.MessagingException; +import jakarta.mail.MessagingException; /** * @author Anthony Perritano diff --git a/src/main/java/org/wise/portal/service/mail/MailService.java b/src/main/java/org/wise/portal/service/mail/MailService.java index 9a9c764cfb..3343fd4f9e 100644 --- a/src/main/java/org/wise/portal/service/mail/MailService.java +++ b/src/main/java/org/wise/portal/service/mail/MailService.java @@ -23,8 +23,8 @@ */ package org.wise.portal.service.mail; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; diff --git a/src/main/java/org/wise/portal/service/peergroup/PeerGroupMembershipService.java b/src/main/java/org/wise/portal/service/peergroup/PeerGroupMembershipService.java index d8fdd5526f..a44e73bb9a 100644 --- a/src/main/java/org/wise/portal/service/peergroup/PeerGroupMembershipService.java +++ b/src/main/java/org/wise/portal/service/peergroup/PeerGroupMembershipService.java @@ -1,5 +1,6 @@ package org.wise.portal.service.peergroup; +import org.springframework.transaction.annotation.Transactional; import org.wise.portal.domain.peergroup.PeerGroup; import org.wise.portal.domain.workgroup.Workgroup; @@ -15,6 +16,7 @@ public interface PeerGroupMembershipService { * @param workgroup Workgroup to move into PeerGroup * @return PeerGroup updated PeerGroup */ + @Transactional PeerGroup addMember(PeerGroup peerGroup, Workgroup workgroup); /** @@ -24,5 +26,6 @@ public interface PeerGroupMembershipService { * @param workgroup Workgroup to remove from PeerGroup * @return PeerGroup updated PeerGroup */ + @Transactional PeerGroup removeMember(PeerGroup peerGroup, Workgroup workgroup); } diff --git a/src/main/java/org/wise/portal/service/portal/impl/PortalServiceImpl.java b/src/main/java/org/wise/portal/service/portal/impl/PortalServiceImpl.java index db6857bbaa..a6f291055d 100644 --- a/src/main/java/org/wise/portal/service/portal/impl/PortalServiceImpl.java +++ b/src/main/java/org/wise/portal/service/portal/impl/PortalServiceImpl.java @@ -48,6 +48,7 @@ public class PortalServiceImpl implements PortalService { private String defaultAnnouncement = "{\"visible\":false,\"bannerText\":\"\",\"bannerButton\":\"\",\"title\":\"\",\"content\":\"\",\"buttons\":[]}"; + @Transactional() public Portal getById(Serializable id) throws ObjectNotFoundException { return portalDao.getById(id); } diff --git a/src/main/java/org/wise/portal/service/project/impl/ProjectServiceImpl.java b/src/main/java/org/wise/portal/service/project/impl/ProjectServiceImpl.java index 774ab33d20..1c6703bcc0 100644 --- a/src/main/java/org/wise/portal/service/project/impl/ProjectServiceImpl.java +++ b/src/main/java/org/wise/portal/service/project/impl/ProjectServiceImpl.java @@ -41,9 +41,9 @@ import java.util.Set; import java.util.TreeSet; -import javax.annotation.PostConstruct; import javax.management.timer.Timer; +import jakarta.annotation.PostConstruct; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.text.WordUtils; @@ -791,9 +791,12 @@ public void writeProjectLicenseFile(Project project) throws JSONException { authors = parentAuthors; } license += WordUtils.wrap( - "License pertains to original content created " - + "by the author(s). Authors are responsible for the usage and " - + "attribution of any third-party content linked to or included in " + "this work.", + """ + License pertains to original content created \ + by the author(s). Authors are responsible for the usage and \ + attribution of any third-party content linked to or included in \ + this work.\ + """, 72); String ccLicenseText = ""; InputStream ccLicense = FileManager.class.getClassLoader().getResourceAsStream("cc-by-sa.txt"); diff --git a/src/main/java/org/wise/portal/service/run/impl/RunServiceImpl.java b/src/main/java/org/wise/portal/service/run/impl/RunServiceImpl.java index 70f5dae547..9aaef8a5e2 100644 --- a/src/main/java/org/wise/portal/service/run/impl/RunServiceImpl.java +++ b/src/main/java/org/wise/portal/service/run/impl/RunServiceImpl.java @@ -82,16 +82,18 @@ @Service public class RunServiceImpl implements RunService { - private String DEFAULT_RUNCODE_PREFIXES = "Ant,Ape,Asp,Badger,Bat,Bear,Bee,Beetle,Bird,Bison,Boa," - + "Bobcat,Bug,Camel,Carp,Cat,Cicada,Clam,Cobra,Cougar,Cow,Coyote,Crab,Crane,Crow,Deer,Dingo," - + "Dodo,Dog,Donkey,Dragon,Duck,Eagle,Eel,Elk,Emu,Falcon,Ferret,Finch,Fish,Flea,Fly,Fox,Frog," - + "Gator,Gecko,Goat,Goose,Gopher,Guppy,Hare,Hawk,Heron,Horse,Hyena,Ibex,Iguana,Impala,Jackal," - + "Jaguar,Kiwi,Koala,Krill,Leech,Lemur,Liger,Lion,Lizard,Llama,Loon,Lynx,Mako,Manta,Mantis," - + "Marmot,Mink,Mole,Monkey,Moose,Moth,Mouse,Mule,Newt,Nutria,Orca,Otter,Owl,Ox,Oyster,Panda," - + "Parrot,Pig,Pigeon,Pika,Poodle,Prawn,Puffin,Pug,Puma,Python,Quail,Rabbit,Ray,Rhino,Robin," - + "Sable,Salmon,Seal,Shark,Sheep,Shrimp,Skunk,Sloth,Slug,Snail,Snake,Spider,Squid,Stoat," - + "Stork,Swan,Tapir,Thrush,Tiger,Toad,Toucan,Trout,Tuna,Turkey,Turtle,Urchin,Viper,Wasp," - + "Whale,Wolf,Wombat,Worm,Yak,Yeti,Zebra"; + private String DEFAULT_RUNCODE_PREFIXES = """ + Ant,Ape,Asp,Badger,Bat,Bear,Bee,Beetle,Bird,Bison,Boa,\ + Bobcat,Bug,Camel,Carp,Cat,Cicada,Clam,Cobra,Cougar,Cow,Coyote,Crab,Crane,Crow,Deer,Dingo,\ + Dodo,Dog,Donkey,Dragon,Duck,Eagle,Eel,Elk,Emu,Falcon,Ferret,Finch,Fish,Flea,Fly,Fox,Frog,\ + Gator,Gecko,Goat,Goose,Gopher,Guppy,Hare,Hawk,Heron,Horse,Hyena,Ibex,Iguana,Impala,Jackal,\ + Jaguar,Kiwi,Koala,Krill,Leech,Lemur,Liger,Lion,Lizard,Llama,Loon,Lynx,Mako,Manta,Mantis,\ + Marmot,Mink,Mole,Monkey,Moose,Moth,Mouse,Mule,Newt,Nutria,Orca,Otter,Owl,Ox,Oyster,Panda,\ + Parrot,Pig,Pigeon,Pika,Poodle,Prawn,Puffin,Pug,Puma,Python,Quail,Rabbit,Ray,Rhino,Robin,\ + Sable,Salmon,Seal,Shark,Sheep,Shrimp,Skunk,Sloth,Slug,Snail,Snake,Spider,Squid,Stoat,\ + Stork,Swan,Tapir,Thrush,Tiger,Toad,Toucan,Trout,Tuna,Turkey,Turtle,Urchin,Viper,Wasp,\ + Whale,Wolf,Wombat,Worm,Yak,Yeti,Zebra\ + """; private static final int MAX_RUNCODE_DIGIT = 10000; @@ -218,7 +220,7 @@ public Run createRun(RunParameters runParameters) { // set default survey template for this run, if any try { - Portal portal = portalService.getById(new Integer(1)); + Portal portal = portalService.getById(Integer.valueOf(1)); String runSurveyTemplate = portal.getRunSurveyTemplate(); if (runSurveyTemplate != null) { run.setSurvey(runSurveyTemplate); diff --git a/src/main/java/org/wise/portal/service/student/impl/StudentServiceImpl.java b/src/main/java/org/wise/portal/service/student/impl/StudentServiceImpl.java index 912381d810..72b838a9f2 100644 --- a/src/main/java/org/wise/portal/service/student/impl/StudentServiceImpl.java +++ b/src/main/java/org/wise/portal/service/student/impl/StudentServiceImpl.java @@ -100,7 +100,7 @@ public void sendNewWorkgroupJoinedRunMessage(Run run, Group period) { try { JSONObject message = new JSONObject(); message.put("type", "newWorkgroupJoinedRun"); - message.put("topic", String.format("/topic/classroom/%s/%s", run.getId(), period.getId())); + message.put("topic", "/topic/classroom/%s/%s".formatted(run.getId(), period.getId())); redisPublisher.publish(message.toString()); } catch (JSONException e) { e.printStackTrace(); diff --git a/src/main/java/org/wise/portal/service/usertags/impl/UserTagsServiceImpl.java b/src/main/java/org/wise/portal/service/usertags/impl/UserTagsServiceImpl.java index 5ac7f5a4a6..bf8cc31978 100644 --- a/src/main/java/org/wise/portal/service/usertags/impl/UserTagsServiceImpl.java +++ b/src/main/java/org/wise/portal/service/usertags/impl/UserTagsServiceImpl.java @@ -5,7 +5,7 @@ import java.util.Set; import java.util.stream.Collectors; -import org.hibernate.proxy.HibernateProxyHelper; +import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.acls.domain.ObjectIdentityImpl; @@ -94,8 +94,8 @@ public void removeTag(Project project, UserTag tag) { } private MutableAclTargetObjectIdentity getMutableObjectIdentity(Project project) { - ObjectIdentity objectIdentity = new ObjectIdentityImpl( - HibernateProxyHelper.getClassWithoutInitializingProxy(project), project.getId()); + ObjectIdentity objectIdentity = new ObjectIdentityImpl(Hibernate.getClass(project), + project.getId()); return aclTargetObjectIdentityDao.retrieveByObjectIdentity(objectIdentity); } diff --git a/src/main/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImpl.java b/src/main/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImpl.java index eb34d6de8f..95ed43ac39 100644 --- a/src/main/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImpl.java +++ b/src/main/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImpl.java @@ -29,7 +29,7 @@ import java.util.HashMap; import java.util.List; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import org.apache.commons.lang3.RandomStringUtils; import org.json.JSONArray; @@ -130,7 +130,7 @@ public List getStudentWorkList(Integer id, Integer runId, Integer p Run run = null; if (runId != null) { try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -138,7 +138,7 @@ public List getStudentWorkList(Integer id, Integer runId, Integer p Group period = null; if (periodId != null) { try { - period = groupService.retrieveById(new Long(periodId)); + period = groupService.retrieveById(Long.valueOf(periodId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -146,7 +146,7 @@ public List getStudentWorkList(Integer id, Integer runId, Integer p Workgroup workgroup = null; if (workgroupId != null) { try { - workgroup = workgroupService.retrieveById(new Long(workgroupId)); + workgroup = workgroupService.retrieveById(Long.valueOf(workgroupId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -213,7 +213,7 @@ public List getLatestNotebookItemsExport(Run run) { public JSONArray getNotificationsExport(Integer runId) { try { - Run run = runService.retrieveById(new Long(runId)); + Run run = runService.retrieveById(Long.valueOf(runId)); List notificationsList = notificationDao.getExport(run); JSONArray notificationsJSONArray = new JSONArray(); for (int n = 0; n < notificationsList.size(); n++) { @@ -245,21 +245,21 @@ public StudentWork saveStudentWork(Integer id, Integer runId, Integer periodId, } if (runId != null) { try { - studentWork.setRun(runService.retrieveById(new Long(runId))); + studentWork.setRun(runService.retrieveById(Long.valueOf(runId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (periodId != null) { try { - studentWork.setPeriod(groupService.retrieveById(new Long(periodId))); + studentWork.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (workgroupId != null) { try { - studentWork.setWorkgroup(workgroupService.retrieveById(new Long(workgroupId))); + studentWork.setWorkgroup(workgroupService.retrieveById(Long.valueOf(workgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -294,7 +294,7 @@ public StudentWork saveStudentWork(Integer id, Integer runId, Integer periodId, studentWork.setComponentType(componentType); } if (clientSaveTime != null) { - Timestamp clientSaveTimestamp = new Timestamp(new Long(clientSaveTime)); + Timestamp clientSaveTimestamp = new Timestamp(Long.valueOf(clientSaveTime)); studentWork.setClientSaveTime(clientSaveTimestamp); } @@ -317,7 +317,7 @@ public List getEvents(Integer id, Integer runId, Integer periodId, Intege Run run = null; if (runId != null) { try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -325,7 +325,7 @@ public List getEvents(Integer id, Integer runId, Integer periodId, Intege Group period = null; if (periodId != null) { try { - period = groupService.retrieveById(new Long(periodId)); + period = groupService.retrieveById(Long.valueOf(periodId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -333,7 +333,7 @@ public List getEvents(Integer id, Integer runId, Integer periodId, Intege Workgroup workgroup = null; if (workgroupId != null) { try { - workgroup = workgroupService.retrieveById(new Long(workgroupId)); + workgroup = workgroupService.retrieveById(Long.valueOf(workgroupId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -376,21 +376,21 @@ public Event saveEvent(Integer id, Integer runId, Integer periodId, Integer work } if (runId != null) { try { - event.setRun(runService.retrieveById(new Long(runId))); + event.setRun(runService.retrieveById(Long.valueOf(runId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (periodId != null) { try { - event.setPeriod(groupService.retrieveById(new Long(periodId))); + event.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (workgroupId != null) { try { - event.setWorkgroup(workgroupService.retrieveById(new Long(workgroupId))); + event.setWorkgroup(workgroupService.retrieveById(Long.valueOf(workgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -417,19 +417,19 @@ public Event saveEvent(Integer id, Integer runId, Integer periodId, Integer work event.setData(data); } if (clientSaveTime != null) { - Timestamp clientSaveTimestamp = new Timestamp(new Long(clientSaveTime)); + Timestamp clientSaveTimestamp = new Timestamp(Long.valueOf(clientSaveTime)); event.setClientSaveTime(clientSaveTimestamp); } if (projectId != null) { try { - event.setProject(projectService.getById(new Long(projectId))); + event.setProject(projectService.getById(Long.valueOf(projectId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (userId != null) { try { - event.setUser(userService.retrieveById(new Long(userId))); + event.setUser(userService.retrieveById(Long.valueOf(userId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -488,7 +488,7 @@ public List getAnnotations(Integer id, Integer runId, Integer period Run run = null; if (runId != null) { try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -496,7 +496,7 @@ public List getAnnotations(Integer id, Integer runId, Integer period Group period = null; if (periodId != null) { try { - period = groupService.retrieveById(new Long(periodId)); + period = groupService.retrieveById(Long.valueOf(periodId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -504,7 +504,7 @@ public List getAnnotations(Integer id, Integer runId, Integer period Workgroup fromWorkgroup = null; if (fromWorkgroupId != null) { try { - fromWorkgroup = workgroupService.retrieveById(new Long(fromWorkgroupId)); + fromWorkgroup = workgroupService.retrieveById(Long.valueOf(fromWorkgroupId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -512,7 +512,7 @@ public List getAnnotations(Integer id, Integer runId, Integer period Workgroup toWorkgroup = null; if (toWorkgroupId != null) { try { - toWorkgroup = workgroupService.retrieveById(new Long(toWorkgroupId)); + toWorkgroup = workgroupService.retrieveById(Long.valueOf(toWorkgroupId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -569,28 +569,28 @@ public Annotation saveAnnotation(Integer id, Integer runId, Integer periodId, } if (runId != null) { try { - annotation.setRun(runService.retrieveById(new Long(runId))); + annotation.setRun(runService.retrieveById(Long.valueOf(runId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (periodId != null) { try { - annotation.setPeriod(groupService.retrieveById(new Long(periodId))); + annotation.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (fromWorkgroupId != null) { try { - annotation.setFromWorkgroup(workgroupService.retrieveById(new Long(fromWorkgroupId))); + annotation.setFromWorkgroup(workgroupService.retrieveById(Long.valueOf(fromWorkgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (toWorkgroupId != null) { try { - annotation.setToWorkgroup(workgroupService.retrieveById(new Long(toWorkgroupId))); + annotation.setToWorkgroup(workgroupService.retrieveById(Long.valueOf(toWorkgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -625,7 +625,7 @@ public Annotation saveAnnotation(Integer id, Integer runId, Integer periodId, annotation.setData(data); } if (clientSaveTime != null) { - Timestamp clientSaveTimestamp = new Timestamp(new Long(clientSaveTime)); + Timestamp clientSaveTimestamp = new Timestamp(Long.valueOf(clientSaveTime)); annotation.setClientSaveTime(clientSaveTimestamp); } Calendar now = Calendar.getInstance(); @@ -663,21 +663,21 @@ public StudentAsset saveStudentAsset(Integer id, Long runId, Integer periodId, } if (runId != null) { try { - studentAsset.setRun(runService.retrieveById(new Long(runId))); + studentAsset.setRun(runService.retrieveById(Long.valueOf(runId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (periodId != null) { try { - studentAsset.setPeriod(groupService.retrieveById(new Long(periodId))); + studentAsset.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (workgroupId != null) { try { - studentAsset.setWorkgroup(workgroupService.retrieveById(new Long(workgroupId))); + studentAsset.setWorkgroup(workgroupService.retrieveById(Long.valueOf(workgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -704,14 +704,14 @@ public StudentAsset saveStudentAsset(Integer id, Long runId, Integer periodId, studentAsset.setFileSize(fileSize); } if (clientSaveTime != null) { - Timestamp clientSaveTimestamp = new Timestamp(new Long(clientSaveTime)); + Timestamp clientSaveTimestamp = new Timestamp(Long.valueOf(clientSaveTime)); studentAsset.setClientSaveTime(clientSaveTimestamp); Calendar now = Calendar.getInstance(); Timestamp serverSaveTimestamp = new Timestamp(now.getTimeInMillis()); studentAsset.setServerSaveTime(serverSaveTimestamp); } if (clientDeleteTime != null) { - Timestamp clientDeleteTimestamp = new Timestamp(new Long(clientDeleteTime)); + Timestamp clientDeleteTimestamp = new Timestamp(Long.valueOf(clientDeleteTime)); studentAsset.setClientDeleteTime(clientDeleteTimestamp); Calendar now = Calendar.getInstance(); Timestamp serverDeleteTimestamp = new Timestamp(now.getTimeInMillis()); @@ -782,7 +782,7 @@ public NotebookItem saveNotebookItem(Integer id, Run run, Integer periodId, notebookItem.setRun(run); if (periodId != null) { try { - notebookItem.setPeriod(groupService.retrieveById(new Long(periodId))); + notebookItem.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -826,14 +826,14 @@ public NotebookItem saveNotebookItem(Integer id, Run run, Integer periodId, notebookItem.setGroups(null); } if (clientSaveTime != null && !clientSaveTime.isEmpty()) { - Timestamp clientSaveTimestamp = new Timestamp(new Long(clientSaveTime)); + Timestamp clientSaveTimestamp = new Timestamp(Long.valueOf(clientSaveTime)); notebookItem.setClientSaveTime(clientSaveTimestamp); Calendar now = Calendar.getInstance(); Timestamp serverSaveTimestamp = new Timestamp(now.getTimeInMillis()); notebookItem.setServerSaveTime(serverSaveTimestamp); } if (clientDeleteTime != null && !clientDeleteTime.isEmpty()) { - Timestamp clientDeleteTimestamp = new Timestamp(new Long(clientDeleteTime)); + Timestamp clientDeleteTimestamp = new Timestamp(Long.valueOf(clientDeleteTime)); notebookItem.setClientDeleteTime(clientDeleteTimestamp); if (notebookItem.getServerDeleteTime() == null) { Calendar now = Calendar.getInstance(); @@ -867,7 +867,7 @@ public NotebookItem addNotebookItemToGroup(Integer notebookItemId, String group, } groupsJSONArray.put(group); copiedNotebookItem.setGroups(groupsJSONArray.toString()); - copiedNotebookItem.setClientSaveTime(new Timestamp(new Long(clientSaveTime))); + copiedNotebookItem.setClientSaveTime(new Timestamp(Long.valueOf(clientSaveTime))); notebookItemDao.save(copiedNotebookItem); } catch (JSONException e) { e.printStackTrace(); @@ -902,7 +902,7 @@ public NotebookItem removeNotebookItemFromGroup(Integer notebookItemId, String g } else { copiedNotebookItem.setGroups(groupsJSONArray.toString()); } - copiedNotebookItem.setClientSaveTime(new Timestamp(new Long(clientSaveTime))); + copiedNotebookItem.setClientSaveTime(new Timestamp(Long.valueOf(clientSaveTime))); notebookItemDao.save(copiedNotebookItem); } catch (JSONException e) { e.printStackTrace(); @@ -920,7 +920,7 @@ public NotebookItem copyNotebookItem(Workgroup workgroup, Integer parentNotebook NotebookItem notebookItem = (NotebookItem) notebookItemDao.getById(parentNotebookItemId); NotebookItem copiedNotebookItem = notebookItem.copy(); copiedNotebookItem.setWorkgroup(workgroup); - copiedNotebookItem.setClientSaveTime(new Timestamp(new Long(clientSaveTime))); + copiedNotebookItem.setClientSaveTime(new Timestamp(Long.valueOf(clientSaveTime))); copiedNotebookItem .setLocalNotebookItemId(RandomStringUtils.randomAlphanumeric(10).toLowerCase()); copiedNotebookItem.setGroups(null); @@ -944,7 +944,7 @@ public List getNotifications(Integer id, Run run, Integer periodId Group period = null; if (periodId != null) { try { - period = groupService.retrieveById(new Long(periodId)); + period = groupService.retrieveById(Long.valueOf(periodId)); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -974,28 +974,28 @@ public Notification saveNotification(Integer id, Integer runId, Integer periodId } if (runId != null) { try { - notification.setRun(runService.retrieveById(new Long(runId))); + notification.setRun(runService.retrieveById(Long.valueOf(runId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (periodId != null) { try { - notification.setPeriod(groupService.retrieveById(new Long(periodId))); + notification.setPeriod(groupService.retrieveById(Long.valueOf(periodId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (fromWorkgroupId != null) { try { - notification.setFromWorkgroup(workgroupService.retrieveById(new Long(fromWorkgroupId))); + notification.setFromWorkgroup(workgroupService.retrieveById(Long.valueOf(fromWorkgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } if (toWorkgroupId != null) { try { - notification.setToWorkgroup(workgroupService.retrieveById(new Long(toWorkgroupId))); + notification.setToWorkgroup(workgroupService.retrieveById(Long.valueOf(toWorkgroupId))); } catch (ObjectNotFoundException e) { e.printStackTrace(); } @@ -1022,11 +1022,11 @@ public Notification saveNotification(Integer id, Integer runId, Integer periodId notification.setData(data); } if (timeGenerated != null) { - Timestamp timeGeneratedTimestamp = new Timestamp(new Long(timeGenerated)); + Timestamp timeGeneratedTimestamp = new Timestamp(Long.valueOf(timeGenerated)); notification.setTimeGenerated(timeGeneratedTimestamp); } if (timeDismissed != null) { - Timestamp timeDismissedTimestamp = new Timestamp(new Long(timeDismissed)); + Timestamp timeDismissedTimestamp = new Timestamp(Long.valueOf(timeDismissed)); notification.setTimeDismissed(timeDismissedTimestamp); } Calendar now = Calendar.getInstance(); diff --git a/src/main/java/org/wise/portal/spring/impl/CustomContextLoaderListener.java b/src/main/java/org/wise/portal/spring/impl/CustomContextLoaderListener.java index 8e6369e9d9..21f45c32c4 100644 --- a/src/main/java/org/wise/portal/spring/impl/CustomContextLoaderListener.java +++ b/src/main/java/org/wise/portal/spring/impl/CustomContextLoaderListener.java @@ -22,7 +22,7 @@ import java.security.InvalidParameterException; -import javax.servlet.ServletContext; +import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/src/main/java/org/wise/portal/spring/impl/CustomDispatcherServlet.java b/src/main/java/org/wise/portal/spring/impl/CustomDispatcherServlet.java index 28d447d586..8f4f841410 100644 --- a/src/main/java/org/wise/portal/spring/impl/CustomDispatcherServlet.java +++ b/src/main/java/org/wise/portal/spring/impl/CustomDispatcherServlet.java @@ -30,8 +30,6 @@ import org.springframework.web.servlet.DispatcherServlet; import org.wise.portal.spring.SpringConfiguration; -import javax.servlet.annotation.WebServlet; - /** * @author Cynick Young */ @@ -65,16 +63,15 @@ public void setContextConfigClass(String contextConfigClass) { protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException { try { - SpringConfiguration springConfig = - (SpringConfiguration) BeanUtils.instantiateClass(Class.forName(contextConfigClass)); + SpringConfiguration springConfig = (SpringConfiguration) BeanUtils + .instantiateClass(Class.forName(contextConfigClass)); setContextConfigLocation(StringUtils.arrayToDelimitedString( springConfig.getDispatcherServletContextConfigLocations(), ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS)); } catch (ClassNotFoundException e) { if (logger.isErrorEnabled()) { - logger.error( - CONFIG_CLASS_PARAM + " <" + contextConfigClass + "> not found.", e); + logger.error(CONFIG_CLASS_PARAM + " <" + contextConfigClass + "> not found.", e); } throw new InvalidParameterException("ClassNotFoundException: " + contextConfigClass); } diff --git a/src/main/java/org/wise/portal/spring/impl/DefaultPasswordEncoderFactories.java b/src/main/java/org/wise/portal/spring/impl/DefaultPasswordEncoderFactories.java index 6aff39d0ac..8e3a6f2b2d 100644 --- a/src/main/java/org/wise/portal/spring/impl/DefaultPasswordEncoderFactories.java +++ b/src/main/java/org/wise/portal/spring/impl/DefaultPasswordEncoderFactories.java @@ -25,14 +25,19 @@ public static PasswordEncoder createDelegatingPasswordEncoder(String salt) { encoders.put(encodingId, new BCryptPasswordEncoder()); encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder()); encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder()); - encoders.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5")); - encoders.put("noop", org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()); - encoders.put("pbkdf2", new Pbkdf2PasswordEncoder()); - encoders.put("scrypt", new SCryptPasswordEncoder()); - encoders.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1")); - encoders.put("SHA-256", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256")); + encoders.put("MD5", + new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5")); + encoders.put("noop", + org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()); + encoders.put("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()); + encoders.put("scrypt", SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8()); + encoders.put("SHA-1", + new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1")); + encoders.put("SHA-256", + new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256")); - DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId, encoders); + DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId, + encoders); delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new CustomPasswordEncoder(salt)); return delegatingPasswordEncoder; } diff --git a/src/main/java/org/wise/portal/spring/impl/HibernateConfig.java b/src/main/java/org/wise/portal/spring/impl/HibernateConfig.java index a8b187f972..164d415b2f 100644 --- a/src/main/java/org/wise/portal/spring/impl/HibernateConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/HibernateConfig.java @@ -29,6 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @@ -47,7 +48,7 @@ public class HibernateConfig { @Autowired Environment appProperties; - @Value("${spring.jpa.properties.hibernate.dialect:org.hibernate.dialect.MySQL5Dialect}") + @Value("${spring.jpa.properties.hibernate.dialect:org.hibernate.dialect.MySQLDialect}") private String hibernateDialect; @Value("${spring.jpa.properties.hibernate.storage_engine:innodb}") @@ -59,16 +60,18 @@ public class HibernateConfig { @Value("${spring.jpa.hibernate.ddl-auto:none}") private String hibernateDDLAuto; - @Bean(name = {"sessionFactory", "entityManagerFactory"}) + @Bean(name = { "sessionFactory", "entityManagerFactory" }) + @DependsOnDatabaseInitialization public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource); - sessionFactory.setPackagesToScan(new String[]{"org.wise.portal.domain", "org.wise.vle.domain"}); + sessionFactory + .setPackagesToScan(new String[] { "org.wise.portal.domain", "org.wise.vle.domain" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } - @Bean(name = {"hibernateTransactionManager", "transactionManager"}) + @Bean(name = { "hibernateTransactionManager", "transactionManager" }) public PlatformTransactionManager hibernateTransactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); diff --git a/src/main/java/org/wise/portal/spring/impl/MethodSecurityConfig.java b/src/main/java/org/wise/portal/spring/impl/MethodSecurityConfig.java index 6d01573029..6f2b54b89e 100644 --- a/src/main/java/org/wise/portal/spring/impl/MethodSecurityConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/MethodSecurityConfig.java @@ -27,5 +27,6 @@ import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; @Configuration -@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true) -public class MethodSecurityConfig {} +@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) +public class MethodSecurityConfig { +} diff --git a/src/main/java/org/wise/portal/spring/impl/RedisConfig.java b/src/main/java/org/wise/portal/spring/impl/RedisConfig.java index 2b5f1fd78d..a4e89e7270 100644 --- a/src/main/java/org/wise/portal/spring/impl/RedisConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/RedisConfig.java @@ -13,12 +13,14 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.GenericToStringSerializer; import org.springframework.session.data.redis.config.ConfigureRedisAction; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisIndexedHttpSession; import org.wise.portal.spring.data.redis.MessagePublisher; import org.wise.portal.spring.data.redis.RedisMessagePublisher; import org.wise.portal.spring.data.redis.RedisMessageSubscriber; import redis.clients.jedis.JedisPoolConfig; @Configuration +@EnableRedisIndexedHttpSession public class RedisConfig { @Value("${spring.redis.host}") @@ -39,7 +41,8 @@ public RedisConnectionFactory redisConnectionFactory() { poolConfig.setMaxTotal(redisPoolMaxTotal); poolConfig.setTestOnBorrow(true); poolConfig.setTestOnReturn(true); - RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHostName, redisPort); + RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHostName, + redisPort); if (redisPassword != null) { config.setPassword(redisPassword); } diff --git a/src/main/java/org/wise/portal/spring/impl/SocketSecurityConfig.java b/src/main/java/org/wise/portal/spring/impl/SocketSecurityConfig.java index d4876ebfde..3c1cddb39b 100644 --- a/src/main/java/org/wise/portal/spring/impl/SocketSecurityConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/SocketSecurityConfig.java @@ -1,21 +1,27 @@ package org.wise.portal.spring.impl; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry; -import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.config.annotation.web.socket.EnableWebSocketSecurity; +import org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager; @Configuration -public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { +@EnableWebSocketSecurity +public class SocketSecurityConfig { - @Override - protected boolean sameOriginDisabled() { - return true; - } + @Bean + AuthorizationManager> authorizationManager( + MessageMatcherDelegatingAuthorizationManager.Builder messages) { + messages.simpDestMatchers("/app/**", "/app/**/**").authenticated().anyMessage().authenticated(); + return messages.build(); + } - @Override - protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { - messages - .simpDestMatchers("/app/**", "/app/**/**").authenticated() - .anyMessage().authenticated(); - } + @Bean + public ChannelInterceptor csrfChannelInterceptor() { + return new ChannelInterceptor() { + }; + } } diff --git a/src/main/java/org/wise/portal/spring/impl/WISELogoutHandler.java b/src/main/java/org/wise/portal/spring/impl/WISELogoutHandler.java index 21d5c295a2..b298df7285 100644 --- a/src/main/java/org/wise/portal/spring/impl/WISELogoutHandler.java +++ b/src/main/java/org/wise/portal/spring/impl/WISELogoutHandler.java @@ -25,8 +25,8 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; diff --git a/src/main/java/org/wise/portal/spring/impl/WISESimpleMappingExceptionResolver.java b/src/main/java/org/wise/portal/spring/impl/WISESimpleMappingExceptionResolver.java index 6f260763a3..86db218db0 100644 --- a/src/main/java/org/wise/portal/spring/impl/WISESimpleMappingExceptionResolver.java +++ b/src/main/java/org/wise/portal/spring/impl/WISESimpleMappingExceptionResolver.java @@ -29,9 +29,9 @@ import java.util.Calendar; import java.util.Date; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.mail.MessagingException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; diff --git a/src/main/java/org/wise/portal/spring/impl/WebConfig.java b/src/main/java/org/wise/portal/spring/impl/WebConfig.java index 12799845a6..fdf07b9655 100644 --- a/src/main/java/org/wise/portal/spring/impl/WebConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/WebConfig.java @@ -61,13 +61,33 @@ import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; +import org.wise.portal.domain.group.impl.StringToGroupConverter; +import org.wise.portal.domain.peergroup.impl.StringToPeerGroupConverter; +import org.wise.portal.domain.project.impl.StringToProjectConverter; +import org.wise.portal.domain.run.impl.StringToRunConverter; +import org.wise.portal.domain.workgroup.impl.StringToWorkgroupConverter; @EnableWebMvc @Configuration @ComponentScan(basePackages = { "org.wise.portal.presentation", "org.wise.portal.service", - "org.wise.portal.dao", "org.wise.vle.web", "org.wise.vle.utils" }) + "org.wise.portal.dao", "org.wise.vle.web", "org.wise.vle.utils", "org.wise.portal.domain" }) public class WebConfig implements WebMvcConfigurer { + @Autowired + private StringToProjectConverter stringToProjectConverter; + + @Autowired + private StringToRunConverter stringToRunConverter; + + @Autowired + private StringToWorkgroupConverter stringToWorkgroupConverter; + + @Autowired + private StringToPeerGroupConverter stringToPeerGroupConverter; + + @Autowired + private StringToGroupConverter stringToGroupConverter; + @Value("${google_analytics_id:}") private String googleAnalyticsId; @@ -77,6 +97,15 @@ public class WebConfig implements WebMvcConfigurer { @Autowired private ObjectMapper objectMapper; + @Override + public void addFormatters(org.springframework.format.FormatterRegistry registry) { + registry.addConverter(stringToProjectConverter); + registry.addConverter(stringToRunConverter); + registry.addConverter(stringToWorkgroupConverter); + registry.addConverter(stringToPeerGroupConverter); + registry.addConverter(stringToGroupConverter); + } + public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.setOrder(Ordered.HIGHEST_PRECEDENCE); registry.addResourceHandler("/pages/resources/**") @@ -192,7 +221,7 @@ public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); simpleUrlHandlerMapping.setOrder(2); Properties mappings = new Properties(); - mappings.setProperty("/**/*", "urlFilenameViewController"); + mappings.setProperty("/**", "urlFilenameViewController"); simpleUrlHandlerMapping.setMappings(mappings); simpleUrlHandlerMapping.setInterceptors(localeChangeInterceptor()); return simpleUrlHandlerMapping; diff --git a/src/main/java/org/wise/portal/spring/impl/WebSecurityConfig.java b/src/main/java/org/wise/portal/spring/impl/WebSecurityConfig.java index b608d1272e..7415efb802 100644 --- a/src/main/java/org/wise/portal/spring/impl/WebSecurityConfig.java +++ b/src/main/java/org/wise/portal/spring/impl/WebSecurityConfig.java @@ -26,8 +26,8 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSessionListener; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSessionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; @@ -41,10 +41,11 @@ import org.springframework.security.access.vote.ConsensusBased; import org.springframework.security.access.vote.RoleVoter; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @@ -56,9 +57,9 @@ import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.session.Session; -import org.wise.portal.presentation.web.filters.GoogleOpenIdConnectFilter; import org.wise.portal.presentation.web.filters.MicrosoftAuthenticationFailureHandler; -import org.wise.portal.presentation.web.filters.MicrosoftOpenIdConnectFilter; +import org.wise.portal.presentation.web.filters.OAuth2AuthenticationFailureHandler; +import org.wise.portal.presentation.web.filters.OAuth2AuthenticationSuccessHandler; import org.wise.portal.presentation.web.filters.WISEAuthenticationFailureHandler; import org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter; import org.wise.portal.presentation.web.filters.WISEAuthenticationSuccessHandler; @@ -67,43 +68,77 @@ import org.wise.portal.service.authentication.UserDetailsService; @Configuration -@EnableWebSecurity(debug = false) +@EnableWebSecurity(debug = true) @Order(SecurityProperties.BASIC_AUTH_ORDER - 10) -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired private UserDetailsService userDetailsService; - @Autowired - private AuthenticationManager authenticationManager; + // @Autowired + // private AuthenticationManager authenticationManager; - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable() + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) + throws Exception { + return authConfig.getAuthenticationManager(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, + AuthenticationManager authenticationManager) throws Exception { + http.csrf(csrf -> csrf.disable()) + .securityContext(securityContext -> securityContext.requireExplicitSave(false)) + .sessionManagement( + session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)) .addFilterAfter(openSessionInViewFilter(), SecurityContextHolderAwareRequestFilter.class) - .addFilterAfter(oAuth2ClientContextFilter(), OpenSessionInViewFilter.class) - .addFilterAfter(googleOpenIdConnectFilter(), OAuth2ClientContextFilter.class) - .addFilterAfter(microsoftOpenIdConnectFilter(), OAuth2ClientContextFilter.class) - .addFilterAfter(authenticationProcessingFilter(), GoogleOpenIdConnectFilter.class) - .authorizeRequests().antMatchers("/api/login/impersonate") - .hasAnyRole("ADMINISTRATOR", "RESEARCHER").antMatchers("/admin/**") - .hasAnyRole("ADMINISTRATOR", "RESEARCHER").antMatchers("/author/**").hasAnyRole("TEACHER") - .antMatchers("/project/notifyAuthor*/**").hasAnyRole("TEACHER") - .antMatchers("/student/account/info").hasAnyRole("TEACHER").antMatchers("/student/**") - .hasAnyRole("STUDENT").antMatchers("/studentStatus").hasAnyRole("TEACHER", "STUDENT") - .antMatchers("/teacher/**").hasAnyRole("TEACHER").antMatchers("/sso/discourse") - .hasAnyRole("TEACHER", "STUDENT").antMatchers("/").permitAll(); - http.formLogin().loginPage("/login").permitAll(); - http.logout().addLogoutHandler(wiseLogoutHandler()) - .logoutRequestMatcher(new AntPathRequestMatcher("/api/logout")); - http.logout().logoutSuccessHandler((request, response, authentication) -> { - response.setStatus(HttpServletResponse.SC_OK); - }); - http.headers().frameOptions().sameOrigin(); - } - - @Bean - public WISEAuthenticationProcessingFilter authenticationProcessingFilter() { + .addFilterAfter(authenticationProcessingFilter(authenticationManager), + SecurityContextHolderAwareRequestFilter.class) + .authorizeHttpRequests( + auth -> auth.requestMatchers(new AntPathRequestMatcher("/api/login/impersonate")) + .hasAnyRole("ADMINISTRATOR", "RESEARCHER") + .requestMatchers(new AntPathRequestMatcher("/admin/**")) + .hasAnyRole("ADMINISTRATOR", "RESEARCHER") + .requestMatchers(new AntPathRequestMatcher("/author/**")).hasAnyRole("TEACHER") + .requestMatchers(new AntPathRequestMatcher("/project/notifyAuthor*/**")) + .hasAnyRole("TEACHER") + .requestMatchers(new AntPathRequestMatcher("/student/account/info")) + .hasAnyRole("TEACHER").requestMatchers(new AntPathRequestMatcher("/student/**")) + .hasAnyRole("STUDENT").requestMatchers(new AntPathRequestMatcher("/studentStatus")) + .hasAnyRole("TEACHER", "STUDENT") + .requestMatchers(new AntPathRequestMatcher("/oauth2/**")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/login/oauth2/**")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/api/google-login")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/api/teacher/register")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/api/student/register")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/api/*/register/**")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/api/teacher/**")).hasAnyRole("TEACHER") + .requestMatchers(new AntPathRequestMatcher("/sso/discourse")) + .hasAnyRole("TEACHER", "STUDENT") + .requestMatchers(new AntPathRequestMatcher("/api/user/tags")).hasAnyRole("TEACHER") + .requestMatchers(new AntPathRequestMatcher("/api/user/tag/**")) + .hasAnyRole("TEACHER").requestMatchers(new AntPathRequestMatcher("/api/debug/**")) + .permitAll().requestMatchers(new AntPathRequestMatcher("/api/user/info")) + .permitAll().requestMatchers(new AntPathRequestMatcher("/api/user/config")) + .permitAll().requestMatchers(new AntPathRequestMatcher("/login")).permitAll() + .requestMatchers(new AntPathRequestMatcher("/")).permitAll().anyRequest() + .authenticated()) + .formLogin(form -> form.loginPage("/login").permitAll()) + .oauth2Login(oauth2 -> oauth2.loginPage("/login") + .successHandler(oauth2AuthenticationSuccessHandler()) + .failureHandler(oauth2AuthenticationFailureHandler())) + .logout(logout -> logout.addLogoutHandler(wiseLogoutHandler()) + .logoutRequestMatcher(new AntPathRequestMatcher("/api/logout")) + .logoutSuccessHandler((request, response, authentication) -> response + .setStatus(HttpServletResponse.SC_OK))) + .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); + + return http.build(); + } + + @Bean + public WISEAuthenticationProcessingFilter authenticationProcessingFilter( + AuthenticationManager authenticationManager) { WISEAuthenticationProcessingFilter filter = new WISEAuthenticationProcessingFilter(); filter.setAuthenticationManager(authenticationManager); filter.setAuthenticationSuccessHandler(authSuccessHandler()); @@ -113,29 +148,18 @@ public WISEAuthenticationProcessingFilter authenticationProcessingFilter() { } @Bean - public GoogleOpenIdConnectFilter googleOpenIdConnectFilter() { - GoogleOpenIdConnectFilter filter = new GoogleOpenIdConnectFilter("/api/google-login"); - filter.setAuthenticationSuccessHandler(authSuccessHandler()); - filter.setAuthenticationFailureHandler(authFailureHandler()); - return filter; - } - - @Bean - public MicrosoftOpenIdConnectFilter microsoftOpenIdConnectFilter() { - MicrosoftOpenIdConnectFilter filter = new MicrosoftOpenIdConnectFilter("/api/microsoft-login"); - filter.setAuthenticationSuccessHandler(authSuccessHandler()); - filter.setAuthenticationFailureHandler(microsoftAuthFailureHandler()); - return filter; + public OpenSessionInViewFilter openSessionInViewFilter() { + return new OpenSessionInViewFilter(); } @Bean - public OpenSessionInViewFilter openSessionInViewFilter() { - return new OpenSessionInViewFilter(); + public OAuth2AuthenticationSuccessHandler oauth2AuthenticationSuccessHandler() { + return new OAuth2AuthenticationSuccessHandler(); } @Bean - public OAuth2ClientContextFilter oAuth2ClientContextFilter() { - return new OAuth2ClientContextFilter(); + public OAuth2AuthenticationFailureHandler oauth2AuthenticationFailureHandler() { + return new OAuth2AuthenticationFailureHandler(); } @Bean diff --git a/src/main/java/org/wise/util/DBInitExporter.java b/src/main/java/org/wise/util/DBInitExporter.java index 3e8464d294..77e7b03523 100644 --- a/src/main/java/org/wise/util/DBInitExporter.java +++ b/src/main/java/org/wise/util/DBInitExporter.java @@ -27,9 +27,7 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; -import java.util.EnumSet; -import org.hibernate.tool.hbm2ddl.SchemaExport; import org.springframework.beans.BeanUtils; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -66,13 +64,13 @@ public static void exportSchemaToFile(String springConfigClassname, String outpu throws ClassNotFoundException, IOException { ConfigurableApplicationContext applicationContext = null; try { - SpringConfiguration springConfig = - (SpringConfiguration) BeanUtils.instantiateClass(Class.forName(springConfigClassname)); + SpringConfiguration springConfig = (SpringConfiguration) BeanUtils + .instantiateClass(Class.forName(springConfigClassname)); applicationContext = new ClassPathXmlApplicationContext( springConfig.getRootApplicationContextConfigLocations()); - final boolean printScriptToConsole = false, exportScriptToDb = false, - justDrop = false, justCreate = true; + final boolean printScriptToConsole = false, exportScriptToDb = false, justDrop = false, + justCreate = true; /* final SchemaExport schemaExport = new SchemaExport(); @@ -86,11 +84,12 @@ public static void exportSchemaToFile(String springConfigClassname, String outpu // now append initial data, which we read in from import.sql File initialDataFile = new File("src/main/resources/import.sql"); FileInputStream initialDataFileInputStream = new FileInputStream(initialDataFile); - BufferedReader initialDataFileReader = - new BufferedReader(new InputStreamReader(initialDataFileInputStream)); + BufferedReader initialDataFileReader = new BufferedReader( + new InputStreamReader(initialDataFileInputStream)); boolean doAppend = true; - BufferedWriter outputFileWriter = new BufferedWriter(new FileWriter(outputFilename, doAppend)); + BufferedWriter outputFileWriter = new BufferedWriter( + new FileWriter(outputFilename, doAppend)); String aLine; while ((aLine = initialDataFileReader.readLine()) != null) { diff --git a/src/main/java/org/wise/vle/domain/achievement/Achievement.java b/src/main/java/org/wise/vle/domain/achievement/Achievement.java index 095cdacd9b..7736301deb 100644 --- a/src/main/java/org/wise/vle/domain/achievement/Achievement.java +++ b/src/main/java/org/wise/vle/domain/achievement/Achievement.java @@ -34,7 +34,7 @@ import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.vle.domain.PersistableDomain; -import javax.persistence.*; +import jakarta.persistence.*; import java.sql.Timestamp; /** @@ -44,39 +44,40 @@ */ @Entity @Table(name = "achievements", indexes = { - @Index(columnList = "runId", name = "achievementsRunIdIndex"), - @Index(columnList = "workgroupId", name = "achievementsWorkgroupIdIndex") -}) + @Index(columnList = "runId", name = "achievementsRunIdIndex"), + @Index(columnList = "workgroupId", name = "achievementsWorkgroupIdIndex") }) @Inheritance(strategy = InheritanceType.JOINED) @Getter @Setter public class Achievement extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; - @ManyToOne(targetEntity = RunImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "runId", nullable = false) @JsonIgnore private Run run; - @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "workgroupId", nullable = false) @JsonIgnore private Workgroup workgroup; @Column(name = "achievementId", length = 32, nullable = false) - private String achievementId; // id of this achievement like "xyzwbc" or "achievementX", defined in project content + private String achievementId; // id of this achievement like "xyzwbc" or "achievementX", defined in project content @Column(name = "type", length = 64, nullable = false) - private String type; // type of this achievement like "completion" or "milestone", defined in project content + private String type; // type of this achievement like "completion" or "milestone", defined in project content @Column(name = "achievementTime", nullable = false) - private Timestamp achievementTime; // when the achievement occurred, saved as server time + private Timestamp achievementTime; // when the achievement occurred, saved as server time @Column(name = "data", length = 65536, columnDefinition = "text", nullable = false) - private String data; // achievement data, actual achievement content stored in the project + private String data; // achievement data, actual achievement content stored in the project @Transient private long runId; diff --git a/src/main/java/org/wise/vle/domain/annotation/wise5/Annotation.java b/src/main/java/org/wise/vle/domain/annotation/wise5/Annotation.java index 730bd3f7d6..b3d1ec05c3 100644 --- a/src/main/java/org/wise/vle/domain/annotation/wise5/Annotation.java +++ b/src/main/java/org/wise/vle/domain/annotation/wise5/Annotation.java @@ -39,7 +39,7 @@ import org.wise.vle.domain.work.NotebookItem; import org.wise.vle.domain.work.StudentWork; -import javax.persistence.*; +import jakarta.persistence.*; import java.sql.Timestamp; /** @@ -57,7 +57,7 @@ public class Annotation extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; @ManyToOne(targetEntity = RunImpl.class, cascade = { diff --git a/src/main/java/org/wise/vle/domain/notification/Notification.java b/src/main/java/org/wise/vle/domain/notification/Notification.java index a0e17c9b91..b800c7975a 100644 --- a/src/main/java/org/wise/vle/domain/notification/Notification.java +++ b/src/main/java/org/wise/vle/domain/notification/Notification.java @@ -37,7 +37,7 @@ import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.vle.domain.PersistableDomain; -import javax.persistence.*; +import jakarta.persistence.*; import java.sql.Timestamp; /** @@ -45,65 +45,68 @@ * @author Hiroki Terashima */ @Entity -@Table(name = "notification", indexes = { +@Table(name = "notification", indexes = { @Index(columnList = "runId", name = "notificationRunIdIndex"), @Index(columnList = "toWorkgroupId", name = "notificationToWorkgroupIdIndex"), - @Index(columnList = "fromWorkgroupId", name = "notificationFromWorkgroupIdIndex") -}) + @Index(columnList = "fromWorkgroupId", name = "notificationFromWorkgroupIdIndex") }) @Getter @Setter public class Notification extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; - @ManyToOne(targetEntity = RunImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "runId", nullable = false) @JsonIgnore private Run run; - @ManyToOne(targetEntity = PersistentGroup.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = PersistentGroup.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "periodId", nullable = false) @JsonIgnore private Group period; - @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "toWorkgroupId", nullable = false) @JsonIgnore private Workgroup toWorkgroup; - @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "fromWorkgroupId", nullable = false) @JsonIgnore private Workgroup fromWorkgroup; @Column(name = "groupId", length = 30) - private String groupId; // id of the group of notifications this notification belongs to, if any. + private String groupId; // id of the group of notifications this notification belongs to, if any. @Column(name = "nodeId", length = 30) - private String nodeId; // which node created this notification, if any + private String nodeId; // which node created this notification, if any @Column(name = "componentId", length = 30) - private String componentId; // which component created this notification, if any + private String componentId; // which component created this notification, if any @Column(name = "componentType", length = 30) - private String componentType; // type of component that created this notification, if any + private String componentType; // type of component that created this notification, if any @Column(name = "type", nullable = false) - private String type; // type of this notification, ex: component, node, vle, teacherToStudent, etc + private String type; // type of this notification, ex: component, node, vle, teacherToStudent, etc @Column(name = "message", nullable = false) - private String message; // message of the notification + private String message; // message of the notification @Column(name = "data", length = 5120000, columnDefinition = "mediumtext") - private String data; // other specific information about this notification + private String data; // other specific information about this notification @Column(name = "timeGenerated", nullable = false) - private Timestamp timeGenerated; // when this notification was generated, client time + private Timestamp timeGenerated; // when this notification was generated, client time @Column(name = "timeDismissed") - private Timestamp timeDismissed; // when this notification was dismissed, client time + private Timestamp timeDismissed; // when this notification was dismissed, client time @Column(name = "serverSaveTime", nullable = false) private Timestamp serverSaveTime; diff --git a/src/main/java/org/wise/vle/domain/statistics/VLEStatistics.java b/src/main/java/org/wise/vle/domain/statistics/VLEStatistics.java index b7065e48a7..ad17473ab8 100644 --- a/src/main/java/org/wise/vle/domain/statistics/VLEStatistics.java +++ b/src/main/java/org/wise/vle/domain/statistics/VLEStatistics.java @@ -25,12 +25,12 @@ import java.sql.Timestamp; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; @@ -50,7 +50,7 @@ public class VLEStatistics extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @Column(name = "timestamp") diff --git a/src/main/java/org/wise/vle/domain/status/RunStatus.java b/src/main/java/org/wise/vle/domain/status/RunStatus.java index 3600bac89d..4c3754ac37 100644 --- a/src/main/java/org/wise/vle/domain/status/RunStatus.java +++ b/src/main/java/org/wise/vle/domain/status/RunStatus.java @@ -25,7 +25,7 @@ import java.sql.Timestamp; import java.util.Calendar; -import javax.persistence.*; +import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; import org.wise.vle.domain.PersistableDomain; @@ -34,14 +34,13 @@ * @author Geoffrey Kwan */ @Entity -@Table(name = "runstatus", indexes = { - @Index(columnList = "runId", name = "runstatusRunIdIndex") } ) +@Table(name = "runstatus", indexes = { @Index(columnList = "runId", name = "runstatusRunIdIndex") }) @Getter @Setter public class RunStatus extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @Column(name = "runId") diff --git a/src/main/java/org/wise/vle/domain/status/StudentStatus.java b/src/main/java/org/wise/vle/domain/status/StudentStatus.java index 7d35a9cec2..09d358c382 100644 --- a/src/main/java/org/wise/vle/domain/status/StudentStatus.java +++ b/src/main/java/org/wise/vle/domain/status/StudentStatus.java @@ -26,7 +26,7 @@ import java.sql.Timestamp; import java.util.Calendar; -import javax.persistence.*; +import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; @@ -36,15 +36,15 @@ * @author Geoffrey Kwan */ @Entity -@Table(name = "studentstatus", - indexes = { @Index(columnList = "runId", name = "studentstatusRunIdIndex"), - @Index(columnList = "workgroupId", name = "studentstatusWorkgroupIdIndex")} ) +@Table(name = "studentstatus", indexes = { + @Index(columnList = "runId", name = "studentstatusRunIdIndex"), + @Index(columnList = "workgroupId", name = "studentstatusWorkgroupIdIndex") }) @Getter @Setter public class StudentStatus extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = null; @Column(name = "runId") diff --git a/src/main/java/org/wise/vle/domain/webservice/crater/CRaterService.java b/src/main/java/org/wise/vle/domain/webservice/crater/CRaterService.java index 4d976422a1..4a94c1712d 100644 --- a/src/main/java/org/wise/vle/domain/webservice/crater/CRaterService.java +++ b/src/main/java/org/wise/vle/domain/webservice/crater/CRaterService.java @@ -24,6 +24,7 @@ package org.wise.vle.domain.webservice.crater; import java.io.IOException; +import java.util.Base64; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHeaders; @@ -82,8 +83,8 @@ private String post(CRaterRequest request) throws JSONException { try { String password = appProperties.getProperty( request.forBerkeleyEndpoint() ? "berkeley_cRater_password" : "cRater_password"); - String authHeader = "Basic " + javax.xml.bind.DatatypeConverter - .printBase64Binary(("extsyscrtr02dev:" + password).getBytes()); + String authHeader = "Basic " + + Base64.getEncoder().encodeToString(("extsyscrtr02dev:" + password).getBytes()); post.setHeader(HttpHeaders.AUTHORIZATION, authHeader); post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8"); post.setEntity(new StringEntity(request.generateBodyData(), ContentType.APPLICATION_JSON)); diff --git a/src/main/java/org/wise/vle/domain/work/Event.java b/src/main/java/org/wise/vle/domain/work/Event.java index 6ccfb0ccfd..b116318a22 100644 --- a/src/main/java/org/wise/vle/domain/work/Event.java +++ b/src/main/java/org/wise/vle/domain/work/Event.java @@ -39,11 +39,11 @@ import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.vle.domain.PersistableDomain; -import javax.persistence.*; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Index; -import javax.persistence.Table; +import jakarta.persistence.*; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Index; +import jakarta.persistence.Table; import java.sql.Timestamp; @@ -63,7 +63,7 @@ public class Event extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; @ManyToOne(targetEntity = ProjectImpl.class, cascade = { diff --git a/src/main/java/org/wise/vle/domain/work/NotebookItem.java b/src/main/java/org/wise/vle/domain/work/NotebookItem.java index 63b8e7a241..64c89d10db 100644 --- a/src/main/java/org/wise/vle/domain/work/NotebookItem.java +++ b/src/main/java/org/wise/vle/domain/work/NotebookItem.java @@ -26,18 +26,18 @@ import java.sql.Timestamp; import java.util.Calendar; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -59,27 +59,30 @@ * @author Hiroki Terashima */ @Entity -@Table(name = "notebookItems", indexes = { +@Table(name = "notebookItems", indexes = { @Index(columnList = "runId", name = "notebookItemsRunIdIndex"), - @Index(columnList = "workgroupId", name = "notebookItemsWorkgroupIdIndex")}) + @Index(columnList = "workgroupId", name = "notebookItemsWorkgroupIdIndex") }) @Getter @Setter public class NotebookItem extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; - @ManyToOne(targetEntity = RunImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "runId", nullable = false) private Run run; - @ManyToOne(targetEntity = PersistentGroup.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = PersistentGroup.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "periodId") @JsonIgnore private Group period; - @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "workgroupId", nullable = false) @JsonIgnore private Workgroup workgroup; @@ -90,18 +93,20 @@ public class NotebookItem extends PersistableDomain { @Column(name = "componentId", length = 30, nullable = true) private String componentId; - @OneToOne(targetEntity = StudentWork.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @OneToOne(targetEntity = StudentWork.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "studentWorkId", nullable = true) @JsonIgnore private StudentWork studentWork; - @OneToOne(targetEntity = StudentAsset.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @OneToOne(targetEntity = StudentAsset.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "studentAssetId", nullable = true) @JsonIgnore private StudentAsset studentAsset; @Column(name = "localNotebookItemId", length = 30, nullable = true) - private String localNotebookItemId; // ex: [ "1", "letterToACongressperson", "z5hc4jeu12" ] + private String localNotebookItemId; // ex: [ "1", "letterToACongressperson", "z5hc4jeu12" ] @Column(name = "parentNotebookItemId") private Integer parentNotebookItemId; @@ -110,10 +115,10 @@ public class NotebookItem extends PersistableDomain { private String groups; @Column(name = "type", length = 30, nullable = true) - private String type; // ex: [ "note", "bookmark", "question" ] + private String type; // ex: [ "note", "bookmark", "question" ] @Column(name = "title", nullable = true) - private String title; // ex: "my note on step 1.2" + private String title; // ex: "my note on step 1.2" @Column(name = "content", columnDefinition = "text", nullable = true) private String content; // ex: { note: "my notes with attachments", attachments: [ {studentAssetId: 1, url: "car.png" } ] } diff --git a/src/main/java/org/wise/vle/domain/work/StudentAsset.java b/src/main/java/org/wise/vle/domain/work/StudentAsset.java index e45043b163..6c21a6c9c6 100644 --- a/src/main/java/org/wise/vle/domain/work/StudentAsset.java +++ b/src/main/java/org/wise/vle/domain/work/StudentAsset.java @@ -25,17 +25,17 @@ import java.sql.Timestamp; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import org.wise.portal.domain.group.Group; import org.wise.portal.domain.group.impl.PersistentGroup; @@ -53,26 +53,29 @@ * @author Hiroki Terashima */ @Entity -@Table(name = "studentAssets", indexes = { +@Table(name = "studentAssets", indexes = { @Index(columnList = "runId", name = "studentAssetsRunIdIndex"), - @Index(columnList = "workgroupId", name = "studentAssetsWorkgroupIdIndex")}) + @Index(columnList = "workgroupId", name = "studentAssetsWorkgroupIdIndex") }) @Getter @Setter public class StudentAsset extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; - @ManyToOne(targetEntity = RunImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = RunImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "runId", nullable = false) private Run run; - @ManyToOne(targetEntity = PersistentGroup.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = PersistentGroup.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "periodId", nullable = false) private Group period; - @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = WorkgroupImpl.class, cascade = { + CascadeType.PERSIST }, fetch = FetchType.LAZY) @JoinColumn(name = "workgroupId", nullable = false) private Workgroup workgroup; diff --git a/src/main/java/org/wise/vle/domain/work/StudentWork.java b/src/main/java/org/wise/vle/domain/work/StudentWork.java index b262be8142..fc2f190697 100644 --- a/src/main/java/org/wise/vle/domain/work/StudentWork.java +++ b/src/main/java/org/wise/vle/domain/work/StudentWork.java @@ -25,7 +25,7 @@ import java.sql.Timestamp; -import javax.persistence.*; +import jakarta.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -57,7 +57,7 @@ public class StudentWork extends PersistableDomain { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; @ManyToOne(targetEntity = RunImpl.class, cascade = { diff --git a/src/main/java/org/wise/vle/web/AssetManager.java b/src/main/java/org/wise/vle/web/AssetManager.java index 2ba9279b08..ab768542cc 100644 --- a/src/main/java/org/wise/vle/web/AssetManager.java +++ b/src/main/java/org/wise/vle/web/AssetManager.java @@ -39,8 +39,8 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -51,8 +51,9 @@ import org.springframework.core.env.Environment; import org.springframework.security.acls.domain.BasePermission; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @@ -92,7 +93,7 @@ public AssetManager() { super(); } - @RequestMapping(method = RequestMethod.GET) + @GetMapping protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String command = request.getParameter("command"); @@ -103,7 +104,7 @@ protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse res String runId = request.getParameter("runId"); Run run = null; try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { @@ -149,7 +150,7 @@ protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse res String runId = request.getParameter("runId"); Run run = null; try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { @@ -168,7 +169,7 @@ protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse res return null; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping protected ModelAndView doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String command = request.getParameter("command"); @@ -179,7 +180,7 @@ protected ModelAndView doPost(HttpServletRequest request, HttpServletResponse re String runId = request.getParameter("runId"); Run run = null; try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { @@ -199,7 +200,7 @@ protected ModelAndView doPost(HttpServletRequest request, HttpServletResponse re String runId = request.getParameter("runId"); Run run = null; try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { @@ -222,7 +223,7 @@ protected ModelAndView doPost(HttpServletRequest request, HttpServletResponse re String runId = request.getParameter("runId"); Run run = null; try { - run = runService.retrieveById(new Long(runId)); + run = runService.retrieveById(Long.valueOf(runId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { @@ -234,7 +235,7 @@ protected ModelAndView doPost(HttpServletRequest request, HttpServletResponse re Long workgroupId = workgroup.getId(); String dirName = run.getId() + "/" + workgroupId + "/unreferenced"; String path = appProperties.getProperty("studentuploads_base_dir"); - Long studentMaxTotalAssetsSize = new Long(appProperties.getProperty("student_max_total_assets_size", "5242880")); + Long studentMaxTotalAssetsSize = Long.valueOf(appProperties.getProperty("student_max_total_assets_size", "5242880")); String pathToCheckSize = path + "/" + dirName; StandardMultipartHttpServletRequest multiRequest = (StandardMultipartHttpServletRequest) request; Map fileMap = multiRequest.getFileMap(); diff --git a/src/main/java/org/wise/vle/web/RunStatusController.java b/src/main/java/org/wise/vle/web/RunStatusController.java index ec948bfa62..bcd9ad6ccb 100644 --- a/src/main/java/org/wise/vle/web/RunStatusController.java +++ b/src/main/java/org/wise/vle/web/RunStatusController.java @@ -27,14 +27,15 @@ import java.sql.Timestamp; import java.util.Calendar; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.user.User; @@ -49,14 +50,14 @@ public class RunStatusController { @Autowired private VLEService vleService; - @RequestMapping(method = RequestMethod.GET) + @GetMapping public ModelAndView doGet(@RequestParam(value = "runId") String runIdString, HttpServletResponse response) throws IOException { User signedInUser = ControllerUtil.getSignedInUser(); Long runId = null; String statusString = null; try { - runId = new Long(runIdString); + runId = Long.valueOf(runIdString); } catch (NumberFormatException e) { e.printStackTrace(); } @@ -114,14 +115,14 @@ public ModelAndView doGet(@RequestParam(value = "runId") String runIdString, return null; } - @RequestMapping(method = RequestMethod.POST) + @PostMapping public ModelAndView doPost(@RequestParam(value = "runId") String runIdString, - @RequestParam(value = "status") String status, HttpServletResponse response) + @RequestParam String status, HttpServletResponse response) throws IOException { User signedInUser = ControllerUtil.getSignedInUser(); Long runId = null; try { - runId = new Long(runIdString); + runId = Long.valueOf(runIdString); } catch (NumberFormatException e) { e.printStackTrace(); } diff --git a/src/main/java/org/wise/vle/web/SecurityUtils.java b/src/main/java/org/wise/vle/web/SecurityUtils.java index 6db47bff6e..c1ea2cfbb0 100644 --- a/src/main/java/org/wise/vle/web/SecurityUtils.java +++ b/src/main/java/org/wise/vle/web/SecurityUtils.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; diff --git a/src/main/java/org/wise/vle/web/StudentStatusController.java b/src/main/java/org/wise/vle/web/StudentStatusController.java index 80d12d53d0..fcf82afd9f 100644 --- a/src/main/java/org/wise/vle/web/StudentStatusController.java +++ b/src/main/java/org/wise/vle/web/StudentStatusController.java @@ -27,7 +27,7 @@ import java.sql.Timestamp; import java.util.Calendar; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -45,7 +45,7 @@ import org.springframework.web.servlet.ModelAndView; import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; +import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.run.RunService; import org.wise.portal.service.user.UserService; @@ -98,19 +98,19 @@ public ModelAndView saveStudentStatus(@RequestBody ObjectNode postedParams, Long workgroupId = null; try { - runId = new Long(runIdString); + runId = Long.valueOf(runIdString); } catch (NumberFormatException e) { e.printStackTrace(); } try { - periodId = new Long(periodIdString); + periodId = Long.valueOf(periodIdString); } catch (NumberFormatException e) { e.printStackTrace(); } try { - workgroupId = new Long(workgroupIdString); + workgroupId = Long.valueOf(workgroupIdString); } catch (NumberFormatException e) { e.printStackTrace(); } @@ -160,7 +160,7 @@ public void broadcastStudentStatusToTeacher(StudentStatus studentStatus) throws @GetMapping("/{workgroupId}") StudentStatus getStudentStatus(Authentication auth, - @PathVariable("workgroupId") WorkgroupImpl workgroup) throws AccessDeniedException { + @PathVariable("workgroupId") Workgroup workgroup) throws AccessDeniedException { User user = userService.retrieveUserByUsername(auth.getName()); if (workgroupService.isUserInWorkgroupForRun(user, workgroup.getRun(), workgroup)) { return vleService.getStudentStatusByWorkgroupId(workgroup.getId()); diff --git a/src/main/java/org/wise/vle/web/wise5/AchievementController.java b/src/main/java/org/wise/vle/web/wise5/AchievementController.java index e9bfb52f9b..8324a02d6e 100644 --- a/src/main/java/org/wise/vle/web/wise5/AchievementController.java +++ b/src/main/java/org/wise/vle/web/wise5/AchievementController.java @@ -16,10 +16,8 @@ import org.springframework.web.bind.annotation.RestController; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.user.UserService; import org.wise.portal.service.vle.wise5.VLEService; import org.wise.portal.service.workgroup.WorkgroupService; @@ -43,12 +41,12 @@ public class AchievementController { private WorkgroupService workgroupService; @GetMapping("/{runId}") - public List getWISE5StudentAchievements(@PathVariable("runId") RunImpl run, - @RequestParam(value = "id", required = false) Integer id, - @RequestParam(value = "workgroupId", required = false) WorkgroupImpl workgroup, - @RequestParam(value = "achievementId", required = false) String achievementId, - @RequestParam(value = "type", required = false) String type, - Authentication auth) throws ObjectNotFoundException { + public List getWISE5StudentAchievements(@PathVariable("runId") Run run, + @RequestParam(required = false) Integer id, + @RequestParam(value = "workgroupId", required = false) Workgroup workgroup, + @RequestParam(required = false) String achievementId, + @RequestParam(required = false) String type, Authentication auth) + throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); if (!isAssociatedWithRun(run, user, workgroup)) { throw new AccessDeniedException("Not associated with run"); @@ -71,17 +69,16 @@ private Boolean isTeacherAssociatedWithRun(Run run, User user) { } @PostMapping("/{runId}") - public Achievement saveAchievement(@PathVariable("runId") RunImpl run, - @RequestParam(value = "id", required = false) Integer id, - @RequestParam(value = "workgroupId", required = true) WorkgroupImpl workgroup, - @RequestParam(value = "achievementId", required = true) String achievementId, - @RequestParam(value = "type", required = true) String type, - @RequestParam(value = "data", required = true) String data, + public Achievement saveAchievement(@PathVariable("runId") Run run, + @RequestParam(required = false) Integer id, + @RequestParam(value = "workgroupId", required = true) Workgroup workgroup, + @RequestParam(required = true) String achievementId, + @RequestParam(required = true) String type, @RequestParam(required = true) String data, Authentication auth) throws JSONException, ObjectNotFoundException, IOException { User user = userService.retrieveUserByUsername(auth.getName()); if (isAllowedToSave(run, user, workgroup)) { - Achievement achievement = vleService.saveAchievement(id, run, workgroup, achievementId, - type, data); + Achievement achievement = vleService.saveAchievement(id, run, workgroup, achievementId, type, + data); achievement.convertToClientAchievement(); broadcastAchievementToTeacher(achievement); return achievement; @@ -90,11 +87,11 @@ public Achievement saveAchievement(@PathVariable("runId") RunImpl run, } private boolean isAllowedToSave(Run run, User user, Workgroup workgroup) { - if (user.isStudent() && run.isStudentAssociatedToThisRun(user) && - workgroupService.isUserInWorkgroupForRun(user, run, workgroup)) { + if (user.isStudent() && run.isStudentAssociatedToThisRun(user) + && workgroupService.isUserInWorkgroupForRun(user, run, workgroup)) { return true; - } else if (user.isTeacher() && - (run.getOwner().equals(user) || run.getSharedowners().contains(user))) { + } else if (user.isTeacher() + && (run.getOwner().equals(user) || run.getSharedowners().contains(user))) { return true; } else { return false; diff --git a/src/main/java/org/wise/vle/web/wise5/ExportController.java b/src/main/java/org/wise/vle/web/wise5/ExportController.java index 08212cf0c4..9ee57ac96c 100644 --- a/src/main/java/org/wise/vle/web/wise5/ExportController.java +++ b/src/main/java/org/wise/vle/web/wise5/ExportController.java @@ -2,7 +2,7 @@ import java.io.IOException; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; diff --git a/src/main/java/org/wise/vle/web/wise5/ExportEventsController.java b/src/main/java/org/wise/vle/web/wise5/ExportEventsController.java index 643d16ccd5..23048294aa 100644 --- a/src/main/java/org/wise/vle/web/wise5/ExportEventsController.java +++ b/src/main/java/org/wise/vle/web/wise5/ExportEventsController.java @@ -4,7 +4,7 @@ import java.io.PrintWriter; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; @@ -18,7 +18,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.service.run.RunService; import org.wise.portal.service.vle.wise5.VLEService; import org.wise.vle.domain.work.Event; @@ -36,9 +35,8 @@ public class ExportEventsController { @GetMapping public void export(HttpServletResponse response, Authentication auth, - @RequestParam(value = "runId") RunImpl run, - @RequestParam(value = "includeStudentEvents") boolean includeStudentEvents, - @RequestParam(value = "includeTeacherEvents") boolean includeTeacherEvents) + @RequestParam(value = "runId") Run run, @RequestParam boolean includeStudentEvents, + @RequestParam boolean includeTeacherEvents) throws JSONException, ObjectNotFoundException, IOException { JSONObject result = new JSONObject(); if (runService.hasReadPermission(auth, run)) { @@ -51,7 +49,8 @@ public void export(HttpServletResponse response, Authentication auth, writer.close(); } - private List getEvents(Run run, boolean includeStudentEvents, boolean includeTeacherEvents) { + private List getEvents(Run run, boolean includeStudentEvents, + boolean includeTeacherEvents) { List events = vleService.getAllEvents(run); if (includeStudentEvents && includeTeacherEvents) { events = vleService.getAllEvents(run); diff --git a/src/main/java/org/wise/vle/web/wise5/ExportNotificationsController.java b/src/main/java/org/wise/vle/web/wise5/ExportNotificationsController.java index 846d6d0436..6ab610b5ce 100644 --- a/src/main/java/org/wise/vle/web/wise5/ExportNotificationsController.java +++ b/src/main/java/org/wise/vle/web/wise5/ExportNotificationsController.java @@ -3,7 +3,7 @@ import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.springframework.beans.factory.annotation.Autowired; @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; import org.wise.portal.service.vle.wise5.VLEService; @Secured("ROLE_TEACHER") @@ -24,7 +24,7 @@ public class ExportNotificationsController extends ExportController { private VLEService vleService; @GetMapping - public void export(@PathVariable("runId") RunImpl run, HttpServletResponse response) + public void export(@PathVariable("runId") Run run, HttpServletResponse response) throws IOException { if (canExport(run)) { JSONArray resultArray = vleService.getNotificationsExport(run.getId().intValue()); diff --git a/src/main/java/org/wise/vle/web/wise5/ExportStudentAssetsController.java b/src/main/java/org/wise/vle/web/wise5/ExportStudentAssetsController.java index 911e46564d..abf9667e62 100644 --- a/src/main/java/org/wise/vle/web/wise5/ExportStudentAssetsController.java +++ b/src/main/java/org/wise/vle/web/wise5/ExportStudentAssetsController.java @@ -7,8 +7,8 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.run.Run; @Secured("ROLE_TEACHER") @Controller @@ -29,7 +29,7 @@ public class ExportStudentAssetsController extends ExportController { private Environment appProperties; @GetMapping - public void export(@PathVariable("runId") RunImpl run, HttpServletResponse response) + public void export(@PathVariable("runId") Run run, HttpServletResponse response) throws IOException { if (canExport(run)) { Long runId = run.getId(); diff --git a/src/main/java/org/wise/vle/web/wise5/NotificationController.java b/src/main/java/org/wise/vle/web/wise5/NotificationController.java index f0b12e5d11..d78ffa3754 100644 --- a/src/main/java/org/wise/vle/web/wise5/NotificationController.java +++ b/src/main/java/org/wise/vle/web/wise5/NotificationController.java @@ -22,10 +22,8 @@ import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.authentication.impl.StudentUserDetails; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; -import org.wise.portal.domain.workgroup.impl.WorkgroupImpl; import org.wise.portal.service.notification.NotificationService; import org.wise.portal.service.run.RunService; import org.wise.portal.service.user.UserService; @@ -60,22 +58,17 @@ public void broadcastNotification(Notification notification) throws JSONExceptio notification.convertToClientNotification(); JSONObject message = new JSONObject(); message.put("type", "notification"); - message.put("topic", String.format("/topic/workgroup/%s", notification.getToWorkgroupId())); + message.put("topic", "/topic/workgroup/%s".formatted(notification.getToWorkgroupId())); message.put("notification", notification.toJSON()); redisPublisher.publish(message.toString()); } @GetMapping("/notification/{runId}") - protected List getNotifications( - Authentication auth, - @PathVariable("runId") RunImpl run, - @RequestParam(value = "id", required = false) Integer id, - @RequestParam(value = "periodId", required = false) Integer periodId, - @RequestParam(value = "toWorkgroupId", required = false) WorkgroupImpl toWorkgroup, - @RequestParam(value = "groupId", required = false) String groupId, - @RequestParam(value = "nodeId", required = false) String nodeId, - @RequestParam(value = "componentId", required = false) String componentId) - throws ObjectNotFoundException { + protected List getNotifications(Authentication auth, @PathVariable("runId") Run run, + @RequestParam(required = false) Integer id, @RequestParam(required = false) Integer periodId, + @RequestParam(value = "toWorkgroupId", required = false) Workgroup toWorkgroup, + @RequestParam(required = false) String groupId, @RequestParam(required = false) String nodeId, + @RequestParam(required = false) String componentId) throws ObjectNotFoundException { User user = userService.retrieveUserByUsername(auth.getName()); if (toWorkgroup != null) { if (isStudentAndNotAllowedToSaveNotification(user, run, toWorkgroup)) { @@ -89,7 +82,7 @@ protected List getNotifications( } @PostMapping("/notification/{runId}") - protected Notification saveNotification(@PathVariable("runId") RunImpl run, + protected Notification saveNotification(@PathVariable("runId") Run run, @RequestBody Notification notification, Authentication authentication) throws Exception { User user = userService.retrieveUserByUsername(authentication.getName()); Workgroup fromWorkgroup = notification.getFromWorkgroup(); @@ -120,13 +113,12 @@ protected Notification saveNotification(@PathVariable("runId") RunImpl run, private boolean isStudentAndNotAllowedToSaveNotification(User user, Run run, Workgroup fromWorkgroup) { - return user.getUserDetails() instanceof StudentUserDetails && - (!run.isStudentAssociatedToThisRun(user) || - !fromWorkgroup.getMembers().contains(user)); + return user.getUserDetails() instanceof StudentUserDetails + && (!run.isStudentAssociatedToThisRun(user) || !fromWorkgroup.getMembers().contains(user)); } @PostMapping("/notification/{runId}/dismiss") - protected Notification dismissNotification(@PathVariable("runId") RunImpl run, + protected Notification dismissNotification(@PathVariable("runId") Run run, @RequestBody Notification notification, Authentication authentication) throws IOException, ObjectNotFoundException, JSONException { User user = userService.retrieveUserByUsername(authentication.getName()); @@ -150,8 +142,7 @@ protected Notification dismissNotification(@PathVariable("runId") RunImpl run, } private boolean canDismissNotification(User user, Notification notification, Run run) { - return user.isAdmin() || - runService.hasRunPermission(run, user, BasePermission.READ) || - notification.getToWorkgroup().getMembers().contains(user); + return user.isAdmin() || runService.hasRunPermission(run, user, BasePermission.READ) + || notification.getToWorkgroup().getMembers().contains(user); } } diff --git a/src/main/java/org/wise/vle/web/wise5/StudentAssetController.java b/src/main/java/org/wise/vle/web/wise5/StudentAssetController.java index 42cedaa3ac..6879c66173 100644 --- a/src/main/java/org/wise/vle/web/wise5/StudentAssetController.java +++ b/src/main/java/org/wise/vle/web/wise5/StudentAssetController.java @@ -26,7 +26,7 @@ import java.io.IOException; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -46,7 +46,6 @@ import org.springframework.web.multipart.MultipartFile; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.domain.workgroup.Workgroup; import org.wise.portal.presentation.web.controllers.ControllerUtil; @@ -97,22 +96,17 @@ protected List getWorkgroupAssets(@PathVariable Long runId, @PostMapping("/student/asset/{runId}") @ResponseBody - protected StudentAsset postStudentAsset( - @RequestParam("clientSaveTime") String clientSaveTime, - @RequestParam(value = "componentId", required = false) String componentId, - @RequestParam(value = "componentType", required = false) String componentType, - @RequestParam("files") List files, - @RequestParam(value = "nodeId", required = false) String nodeId, - @RequestParam("periodId") Integer periodId, - @PathVariable("runId") RunImpl run, - @RequestParam("workgroupId") Integer workgroupId - ) throws Exception { + protected StudentAsset postStudentAsset(@RequestParam String clientSaveTime, + @RequestParam(required = false) String componentId, + @RequestParam(required = false) String componentType, @RequestParam List files, + @RequestParam(required = false) String nodeId, @RequestParam Integer periodId, + @PathVariable("runId") Run run, @RequestParam Integer workgroupId) throws Exception { String dirName = run.getId() + "/" + workgroupId + "/unreferenced"; String path = appProperties.getProperty("studentuploads_base_dir"); - Long studentMaxAssetSize = Long.valueOf( - appProperties.getProperty("student_max_asset_size", "5242880")); - Long studentMaxTotalAssetsSize = Long.valueOf( - appProperties.getProperty("student_max_total_assets_size", "10485760")); + Long studentMaxAssetSize = Long + .valueOf(appProperties.getProperty("student_max_asset_size", "5242880")); + Long studentMaxTotalAssetsSize = Long + .valueOf(appProperties.getProperty("student_max_total_assets_size", "10485760")); String pathToCheckSize = path + "/" + dirName; for (MultipartFile file : files) { if (file.getSize() > studentMaxAssetSize) { @@ -144,11 +138,10 @@ protected StudentAsset postStudentAsset( @DeleteMapping("/student/asset/{runId}/delete") @ResponseBody protected StudentAsset removeStudentAsset(@PathVariable Integer runId, - @RequestParam(value = "studentAssetId", required = true) Integer studentAssetId, - @RequestParam(value = "workgroupId", required = true) Integer workgroupId, - @RequestParam(value = "clientDeleteTime", required = true) Long clientDeleteTime) - throws Exception { - Run run = runService.retrieveById(new Long(runId)); + @RequestParam(required = true) Integer studentAssetId, + @RequestParam(required = true) Integer workgroupId, + @RequestParam(required = true) Long clientDeleteTime) throws Exception { + Run run = runService.retrieveById(Long.valueOf(runId)); StudentAsset studentAsset = vleService.getStudentAssetById(studentAssetId); String assetFileName = studentAsset.getFileName(); String dirName = run.getId() + "/" + workgroupId + "/unreferenced"; diff --git a/src/main/java/org/wise/vle/web/wise5/TeacherGetDataController.java b/src/main/java/org/wise/vle/web/wise5/TeacherGetDataController.java index a567544c2a..c6e525c7fa 100644 --- a/src/main/java/org/wise/vle/web/wise5/TeacherGetDataController.java +++ b/src/main/java/org/wise/vle/web/wise5/TeacherGetDataController.java @@ -14,7 +14,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.wise.portal.domain.run.Run; -import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.domain.user.User; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.vle.wise5.VLEService; @@ -29,29 +28,27 @@ public class TeacherGetDataController { private VLEService vleService; @GetMapping("/api/teacher/data") - protected HashMap getData(@RequestParam("runId") RunImpl run, - @RequestParam(value = "getStudentWork", defaultValue = "false") boolean getStudentWork, - @RequestParam(value = "getEvents", defaultValue = "false") boolean getEvents, - @RequestParam(value = "getAnnotations", defaultValue = "false") boolean getAnnotations, - @RequestParam(value = "id", required = false) Integer id, - @RequestParam(value = "periodId", required = false) Integer periodId, - @RequestParam(value = "workgroupId", required = false) Integer workgroupId, - @RequestParam(value = "isAutoSave", required = false) Boolean isAutoSave, - @RequestParam(value = "isSubmit", required = false) Boolean isSubmit, - @RequestParam(value = "nodeId", required = false) String nodeId, - @RequestParam(value = "componentId", required = false) String componentId, - @RequestParam(value = "componentType", required = false) String componentType, - @RequestParam(value = "context", required = false) String context, - @RequestParam(value = "category", required = false) String category, - @RequestParam(value = "event", required = false) String event, - @RequestParam(value = "fromWorkgroupId", required = false) Integer fromWorkgroupId, - @RequestParam(value = "toWorkgroupId", required = false) Integer toWorkgroupId, - @RequestParam(value = "studentWorkId", required = false) Integer studentWorkId, - @RequestParam(value = "localNotebookItemId", required = false) String localNotebookItemId, - @RequestParam(value = "notebookItemId", required = false) Integer notebookItemId, - @RequestParam(value = "annotationType", required = false) String annotationType, - @RequestParam(value = "components", required = false) String components, - @RequestParam(value = "onlyGetLatest", required = false) Boolean onlyGetLatest) { + protected HashMap getData(@RequestParam("runId") Run run, + @RequestParam(defaultValue = "false") boolean getStudentWork, + @RequestParam(defaultValue = "false") boolean getEvents, + @RequestParam(defaultValue = "false") boolean getAnnotations, + @RequestParam(required = false) Integer id, @RequestParam(required = false) Integer periodId, + @RequestParam(required = false) Integer workgroupId, + @RequestParam(required = false) Boolean isAutoSave, + @RequestParam(required = false) Boolean isSubmit, + @RequestParam(required = false) String nodeId, + @RequestParam(required = false) String componentId, + @RequestParam(required = false) String componentType, + @RequestParam(required = false) String context, + @RequestParam(required = false) String category, @RequestParam(required = false) String event, + @RequestParam(required = false) Integer fromWorkgroupId, + @RequestParam(required = false) Integer toWorkgroupId, + @RequestParam(required = false) Integer studentWorkId, + @RequestParam(required = false) String localNotebookItemId, + @RequestParam(required = false) Integer notebookItemId, + @RequestParam(required = false) String annotationType, + @RequestParam(required = false) String components, + @RequestParam(required = false) Boolean onlyGetLatest) { if (canGetData(run)) { HashMap data = new HashMap(); int runId = run.getId().intValue(); diff --git a/src/main/java/org/wise/vle/web/wise5/TeacherPostDataController.java b/src/main/java/org/wise/vle/web/wise5/TeacherPostDataController.java index 9d68ed8aab..47117c7142 100644 --- a/src/main/java/org/wise/vle/web/wise5/TeacherPostDataController.java +++ b/src/main/java/org/wise/vle/web/wise5/TeacherPostDataController.java @@ -5,7 +5,7 @@ import java.util.Calendar; import java.util.Set; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; @@ -15,8 +15,8 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.wise.portal.domain.project.impl.ProjectImpl; -import org.wise.portal.domain.run.impl.RunImpl; +import org.wise.portal.domain.project.Project; +import org.wise.portal.domain.run.Run; import org.wise.portal.domain.user.User; import org.wise.portal.presentation.web.controllers.ControllerUtil; import org.wise.portal.service.vle.wise5.VLEService; @@ -37,10 +37,10 @@ public class TeacherPostDataController { @PostMapping("/api/teacher/data") public void postData(HttpServletResponse response, - @RequestParam(value = "projectId", required = false) ProjectImpl project, - @RequestParam(value = "runId", required = false) RunImpl run, - @RequestParam(value = "annotations", required = false) String annotations, - @RequestParam(value = "events", required = false) String events) { + @RequestParam(value = "projectId", required = false) Project project, + @RequestParam(value = "runId", required = false) Run run, + @RequestParam(required = false) String annotations, + @RequestParam(required = false) String events) { JSONObject result = new JSONObject(); try { User signedInUser = ControllerUtil.getSignedInUser(); @@ -222,7 +222,7 @@ public void broadcastAnnotationToStudent(Long toWorkgroupId, Annotation annotati annotation.convertToClientAnnotation(); JSONObject message = new JSONObject(); message.put("type", "annotationToStudent"); - message.put("topic", String.format("/topic/workgroup/%s", toWorkgroupId)); + message.put("topic", "/topic/workgroup/%s".formatted(toWorkgroupId)); message.put("annotation", annotation.toJSON()); redisPublisher.publish(message.toString()); } @@ -232,7 +232,7 @@ public void broadcastNotificationToStudent(Long toWorkgroupId, Notification noti notification.convertToClientNotification(); JSONObject message = new JSONObject(); message.put("type", "notification"); - message.put("topic", String.format("/topic/workgroup/%s", toWorkgroupId)); + message.put("topic", "/topic/workgroup/%s".formatted(toWorkgroupId)); message.put("notification", notification.toJSON()); redisPublisher.publish(message.toString()); } diff --git a/src/main/java/org/wise/vle/web/wise5/student/StudentGetDataController.java b/src/main/java/org/wise/vle/web/wise5/student/StudentGetDataController.java index 105f946ab0..498d29b4e4 100644 --- a/src/main/java/org/wise/vle/web/wise5/student/StudentGetDataController.java +++ b/src/main/java/org/wise/vle/web/wise5/student/StudentGetDataController.java @@ -37,29 +37,29 @@ public class StudentGetDataController { @GetMapping("/api/student/data") public HashMap getStudentData(Authentication authentication, - @RequestParam(value = "getStudentWork", defaultValue = "false") boolean getStudentWork, - @RequestParam(value = "getEvents", defaultValue = "false") boolean getEvents, - @RequestParam(value = "getAnnotations", defaultValue = "false") boolean getAnnotations, - @RequestParam(value = "id", required = false) Integer id, - @RequestParam(value = "runId", required = false) Integer runId, - @RequestParam(value = "periodId", required = false) Integer periodId, - @RequestParam(value = "workgroupId", required = false) Integer workgroupId, - @RequestParam(value = "isAutoSave", required = false) Boolean isAutoSave, - @RequestParam(value = "isSubmit", required = false) Boolean isSubmit, - @RequestParam(value = "nodeId", required = false) String nodeId, - @RequestParam(value = "componentId", required = false) String componentId, - @RequestParam(value = "componentType", required = false) String componentType, - @RequestParam(value = "context", required = false) String context, - @RequestParam(value = "category", required = false) String category, - @RequestParam(value = "event", required = false) String event, - @RequestParam(value = "fromWorkgroupId", required = false) Integer fromWorkgroupId, - @RequestParam(value = "toWorkgroupId", required = false) Integer toWorkgroupId, - @RequestParam(value = "studentWorkId", required = false) Integer studentWorkId, - @RequestParam(value = "localNotebookItemId", required = false) String localNotebookItemId, - @RequestParam(value = "notebookItemId", required = false) Integer notebookItemId, - @RequestParam(value = "annotationType", required = false) String annotationType, - @RequestParam(value = "components", required = false) List components, - @RequestParam(value = "onlyGetLatest", required = false) Boolean onlyGetLatest) + @RequestParam(defaultValue = "false") boolean getStudentWork, + @RequestParam(defaultValue = "false") boolean getEvents, + @RequestParam(defaultValue = "false") boolean getAnnotations, + @RequestParam(required = false) Integer id, + @RequestParam(required = false) Integer runId, + @RequestParam(required = false) Integer periodId, + @RequestParam(required = false) Integer workgroupId, + @RequestParam(required = false) Boolean isAutoSave, + @RequestParam(required = false) Boolean isSubmit, + @RequestParam(required = false) String nodeId, + @RequestParam(required = false) String componentId, + @RequestParam(required = false) String componentType, + @RequestParam(required = false) String context, + @RequestParam(required = false) String category, + @RequestParam(required = false) String event, + @RequestParam(required = false) Integer fromWorkgroupId, + @RequestParam(required = false) Integer toWorkgroupId, + @RequestParam(required = false) Integer studentWorkId, + @RequestParam(required = false) String localNotebookItemId, + @RequestParam(required = false) Integer notebookItemId, + @RequestParam(required = false) String annotationType, + @RequestParam(required = false) List components, + @RequestParam(required = false) Boolean onlyGetLatest) throws ObjectNotFoundException { HashMap data = new HashMap(); User user = userService.retrieveUser((StudentUserDetails) authentication.getPrincipal()); diff --git a/src/main/java/org/wise/vle/web/wise5/student/StudentPostDataController.java b/src/main/java/org/wise/vle/web/wise5/student/StudentPostDataController.java index 4902b463d9..8ffb12e707 100644 --- a/src/main/java/org/wise/vle/web/wise5/student/StudentPostDataController.java +++ b/src/main/java/org/wise/vle/web/wise5/student/StudentPostDataController.java @@ -5,7 +5,7 @@ import java.util.HashMap; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; @@ -70,7 +70,7 @@ public void postStudentData(HttpServletResponse response, @RequestBody ObjectNod String annotations = postedParams.get("annotations").asText(); JSONObject result = new JSONObject(); try { - Run run = runService.retrieveById(new Long(runId)); + Run run = runService.retrieveById(Long.valueOf(runId)); if (run.isActive() && run.isStudentAssociatedToThisRun(user)) { List workgroups = workgroupService.getWorkgroupListByRunAndUser(run, user); if (workgroups.size() == 0) { diff --git a/src/main/resources/application-dockerdev-sample.properties b/src/main/resources/application-dockerdev-sample.properties index 6c97c6c28f..7aeaac1103 100644 --- a/src/main/resources/application-dockerdev-sample.properties +++ b/src/main/resources/application-dockerdev-sample.properties @@ -90,9 +90,9 @@ spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=true spring.jpa.hibernate.use-new-id-generator-mappings=false spring.session.store-type=redis -spring.redis.host=wise-redis +spring.data.redis.host=wise-redis #spring.redis.password= # Login password of the redis server. -spring.redis.port=6379 +spring.data.redis.port=6379 spring.redis.pool.max.total=128 #spring.session.redis.flush-mode=on-save # Sessions flush mode. #spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. @@ -179,17 +179,11 @@ trustedAuthorAllowedProjectAssetContentTypes=text/html,application/javascript,ap ########## Optional Plugins ########## -### Google Open Id (log in with Google) ### - -google.clientId= -google.clientSecret= - -google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token -google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth?prompt=select_account -google.redirectUri=http://localhost:81/api/google-login -google.issuer=accounts.google.com -google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs -google.tokens.dir= +# OAuth2 Client Configuration for Google +spring.security.oauth2.client.registration.google.client-id= +spring.security.oauth2.client.registration.google.client-secret= +spring.security.oauth2.client.registration.google.scope=openid,email,profile +spring.security.oauth2.client.registration.google.redirect-uri= ### Microsoft Open Id (log in with Microsoft) ### diff --git a/src/main/resources/application_sample.properties b/src/main/resources/application_sample.properties index e0b196554c..4e6d80e40e 100644 --- a/src/main/resources/application_sample.properties +++ b/src/main/resources/application_sample.properties @@ -90,9 +90,9 @@ spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=true spring.jpa.hibernate.use-new-id-generator-mappings=false spring.session.store-type=redis -spring.redis.host=localhost +spring.data.redis.host=localhost #spring.redis.password= # Login password of the redis server. -spring.redis.port=6379 +spring.data.redis.port=6379 spring.redis.pool.max.total=128 #spring.session.redis.flush-mode=on-save # Sessions flush mode. #spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. @@ -179,17 +179,11 @@ trustedAuthorAllowedProjectAssetContentTypes=text/html,application/javascript,ap ########## Optional Plugins ########## -### Google Open Id (log in with Google) ### - -google.clientId= -google.clientSecret= - -google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token -google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth?prompt=select_account -google.redirectUri=http://localhost:8080/google-login -google.issuer=accounts.google.com -google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs -google.tokens.dir= +# OAuth2 Client Configuration for Google +spring.security.oauth2.client.registration.google.client-id= +spring.security.oauth2.client.registration.google.client-secret= +spring.security.oauth2.client.registration.google.scope=openid,email,profile +spring.security.oauth2.client.registration.google.redirect-uri= ### Microsoft Open Id (log in with Microsoft) ### diff --git a/src/test/java/org/wise/portal/dao/AbstractTransactionalDaoTests.java b/src/test/java/org/wise/portal/dao/AbstractTransactionalDaoTests.java index e6ea0b4383..e1f12253ed 100644 --- a/src/test/java/org/wise/portal/dao/AbstractTransactionalDaoTests.java +++ b/src/test/java/org/wise/portal/dao/AbstractTransactionalDaoTests.java @@ -36,7 +36,7 @@ public abstract class AbstractTransactionalDaoTests(1), new HashMap(1), URL, HttpStatus.SC_OK); } - protected void tearDown() throws Exception { - super.tearDown(); + @AfterEach + public void tearDown() throws Exception { method = null; request = null; } - public void testIsValidResponseStatus_shouldThrowHttpStatusCodeException() - throws Exception { + @Test + public void testIsValidResponseStatus_shouldThrowHttpStatusCodeException() + throws Exception { EasyMock.expect(method.getStatusText()).andReturn("whatever") .anyTimes(); EasyMock.expect(method.getResponseBodyAsString()).andReturn("whatever") @@ -70,8 +67,9 @@ public void testIsValidResponseStatus_shouldThrowHttpStatusCodeException() } EasyMock.verify(method); } - - public void testIsValidResponseStatus() throws Exception { + + @Test + public void testIsValidResponseStatus() throws Exception { EasyMock.replay(method); assertTrue(request.isValidResponseStatus(method, request .getExpectedResponseStatusCode())); diff --git a/src/test/java/org/wise/portal/domain/webservice/http/HttpPostRequestTest.java b/src/test/java/org/wise/portal/domain/webservice/http/HttpPostRequestTest.java index bede3d3ae2..6d29b3ef23 100644 --- a/src/test/java/org/wise/portal/domain/webservice/http/HttpPostRequestTest.java +++ b/src/test/java/org/wise/portal/domain/webservice/http/HttpPostRequestTest.java @@ -17,11 +17,14 @@ */ package org.wise.portal.domain.webservice.http; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.HashMap; import java.util.Map; -import junit.framework.TestCase; - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.wise.vle.domain.webservice.BadHeaderException; import org.wise.vle.domain.webservice.http.HttpPostRequest; @@ -31,7 +34,7 @@ * @version $Id$ * */ -public class HttpPostRequestTest extends TestCase { +public class HttpPostRequestTest { private static final Map requestHeaders = new HashMap(); @@ -44,23 +47,24 @@ public class HttpPostRequestTest extends TestCase { private static final int expectedResponseStatusCode = 0; /** - * @see junit.framework.TestCase#setUp() + * @see */ - protected void setUp() throws Exception { - super.setUp(); + @BeforeEach + public void setUp() throws Exception { } /** - * @see junit.framework.TestCase#tearDown() + * @see */ - protected void tearDown() throws Exception { - super.tearDown(); + @AfterEach + public void tearDown() throws Exception { } /** * Test method for * {@link net.sf.sail.webapp.domain.webservice.http.HttpPostRequest#HttpPostRequest(java.util.Map, java.util.Map, java.lang.String, java.lang.String, int)}. */ + @Test public void testHttpPostRequest() { requestHeaders.put("legal-field-name", "legal field content"); assertNotNull(new HttpPostRequest(requestHeaders, requestParameters, diff --git a/src/test/java/org/wise/portal/domain/work/AchievementTest.java b/src/test/java/org/wise/portal/domain/work/AchievementTest.java index d1771ea816..10dd575af7 100644 --- a/src/test/java/org/wise/portal/domain/work/AchievementTest.java +++ b/src/test/java/org/wise/portal/domain/work/AchievementTest.java @@ -1,6 +1,6 @@ package org.wise.portal.domain.work; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Timestamp; @@ -44,7 +44,9 @@ public void setup() { @Test public void serialize() throws JsonProcessingException { String json = mapper.writeValueAsString(achievement); - assertEquals("{\"id\":12,\"runId\":1,\"workgroupId\":64,\"achievementId\":\"achievement_1\"," - + "\"type\":\"milestoneReport\",\"achievementTime\":1,\"data\":{}}", json); + assertEquals(""" + {"id":12,"runId":1,"workgroupId":64,"achievementId":"achievement_1",\ + "type":"milestoneReport","achievementTime":1,"data":{}}\ + """, json); } } diff --git a/src/test/java/org/wise/portal/domain/work/EventTest.java b/src/test/java/org/wise/portal/domain/work/EventTest.java index 345a253660..926297f01e 100644 --- a/src/test/java/org/wise/portal/domain/work/EventTest.java +++ b/src/test/java/org/wise/portal/domain/work/EventTest.java @@ -52,12 +52,14 @@ public void serialize() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new EventJsonModule()); String json = mapper.writeValueAsString(event); - String expectedJson = "{\"id\":100000,\"category\":\"Navigation\"," - + "\"clientSaveTime\":1000000000000,\"componentId\":\"4t890paw3t\"," - + "\"componentType\":\"MultipleChoice\",\"context\":\"VLE\"," - + "\"data\":{\"selectedChoice\":\"dbf9824t1m\"},\"event\":\"choiceSelected\"," - + "\"nodeId\":\"node1\",\"periodId\":100,\"projectId\":10,\"runId\":1," - + "\"serverSaveTime\":2000000000000,\"workgroupId\":64,\"userId\":10000}"; + String expectedJson = """ + {"id":100000,"category":"Navigation",\ + "clientSaveTime":1000000000000,"componentId":"4t890paw3t",\ + "componentType":"MultipleChoice","context":"VLE",\ + "data":{"selectedChoice":"dbf9824t1m"},"event":"choiceSelected",\ + "nodeId":"node1","periodId":100,"projectId":10,"runId":1,\ + "serverSaveTime":2000000000000,"workgroupId":64,"userId":10000}\ + """; assertEquals(expectedJson, json); } @@ -74,10 +76,12 @@ public void serializeWithNullableFields() throws Exception { event.setProject(null); event.setUser(null); String json = mapper.writeValueAsString(event); - String expectedJson = "{\"id\":100000,\"category\":\"Navigation\"," - + "\"clientSaveTime\":1000000000000,\"componentId\":null,\"componentType\":null," - + "\"context\":\"VLE\",\"data\":{\"selectedChoice\":\"dbf9824t1m\"}," - + "\"event\":\"choiceSelected\",\"nodeId\":null,\"serverSaveTime\":2000000000000}"; + String expectedJson = """ + {"id":100000,"category":"Navigation",\ + "clientSaveTime":1000000000000,"componentId":null,"componentType":null,\ + "context":"VLE","data":{"selectedChoice":"dbf9824t1m"},\ + "event":"choiceSelected","nodeId":null,"serverSaveTime":2000000000000}\ + """; assertEquals(expectedJson, json); } } diff --git a/src/test/java/org/wise/portal/domain/work/NotebookItemTest.java b/src/test/java/org/wise/portal/domain/work/NotebookItemTest.java index a3e98c8398..2eea5beb33 100644 --- a/src/test/java/org/wise/portal/domain/work/NotebookItemTest.java +++ b/src/test/java/org/wise/portal/domain/work/NotebookItemTest.java @@ -1,6 +1,6 @@ package org.wise.portal.domain.work; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Timestamp; @@ -51,11 +51,13 @@ public void serialize() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new NotebookItemJsonModule()); String json = mapper.writeValueAsString(item); - assertEquals("{\"id\":99,\"runId\":1,\"workgroupId\":64,\"type\":\"note\"" - + ",\"localNotebookItemId\":\"ooacs8tls7\"" - + ",\"content\":\"{\\\"text\\\":\\\"my note!\\\"}\"" - + ",\"clientSaveTime\":1582337976000,\"serverSaveTime\":1582338031000" - + ",\"periodId\":100,\"nodeId\":\"node78\",\"title\":\"Note from first step\"}", json); + assertEquals(""" + {"id":99,"runId":1,"workgroupId":64,"type":"note"\ + ,"localNotebookItemId":"ooacs8tls7"\ + ,"content":"{\\"text\\":\\"my note!\\"}"\ + ,"clientSaveTime":1582337976000,"serverSaveTime":1582338031000\ + ,"periodId":100,"nodeId":"node78","title":"Note from first step"}\ + """, json); } } diff --git a/src/test/java/org/wise/portal/domain/work/StudentWorkTest.java b/src/test/java/org/wise/portal/domain/work/StudentWorkTest.java index dfa4f8d3a1..512e1bdced 100644 --- a/src/test/java/org/wise/portal/domain/work/StudentWorkTest.java +++ b/src/test/java/org/wise/portal/domain/work/StudentWorkTest.java @@ -57,11 +57,13 @@ public void setup() { @Test public void serialize() throws Exception { String json = mapper.writeValueAsString(studentWork); - String expectedJson = "{\"id\":1000,\"clientSaveTime\":1582338031000," - + "\"componentId\":\"9gyphw34j8\",\"componentType\":\"OpenResponse\",\"isAutoSave\":true," - + "\"isSubmit\":false,\"nodeId\":\"node1\",\"periodId\":10,\"runId\":1," - + "\"serverSaveTime\":1582338031000,\"studentData\":{\"response\":\"Hello World\"}," - + "\"workgroupId\":100}"; + String expectedJson = """ + {"id":1000,"clientSaveTime":1582338031000,\ + "componentId":"9gyphw34j8","componentType":"OpenResponse","isAutoSave":true,\ + "isSubmit":false,"nodeId":"node1","periodId":10,"runId":1,\ + "serverSaveTime":1582338031000,"studentData":{"response":"Hello World"},\ + "workgroupId":100}\ + """; assertEquals(expectedJson, json); } @@ -70,10 +72,12 @@ public void serializeWithNullableFields() throws Exception { studentWork.setComponentId(null); studentWork.setComponentType(null); String json = mapper.writeValueAsString(studentWork); - String expectedJson = "{\"id\":1000,\"clientSaveTime\":1582338031000,\"componentId\":null," - + "\"componentType\":null,\"isAutoSave\":true,\"isSubmit\":false,\"nodeId\":\"node1\"," - + "\"periodId\":10,\"runId\":1,\"serverSaveTime\":1582338031000," - + "\"studentData\":{\"response\":\"Hello World\"},\"workgroupId\":100}"; + String expectedJson = """ + {"id":1000,"clientSaveTime":1582338031000,"componentId":null,\ + "componentType":null,"isAutoSave":true,"isSubmit":false,"nodeId":"node1",\ + "periodId":10,"runId":1,"serverSaveTime":1582338031000,\ + "studentData":{"response":"Hello World"},"workgroupId":100}\ + """; assertEquals(expectedJson, json); } } diff --git a/src/test/java/org/wise/portal/junit/AbstractTransactionalDbTests.java b/src/test/java/org/wise/portal/junit/AbstractTransactionalDbTests.java index 8b8781ff09..e4362aab51 100644 --- a/src/test/java/org/wise/portal/junit/AbstractTransactionalDbTests.java +++ b/src/test/java/org/wise/portal/junit/AbstractTransactionalDbTests.java @@ -23,10 +23,11 @@ import java.util.Set; import org.hibernate.SessionFactory; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; import org.testcontainers.containers.GenericContainer; @@ -68,7 +69,7 @@ * @author Hiroki Terashima */ @WebAppConfiguration -@ContextConfiguration +@SpringJUnitConfig @Testcontainers public abstract class AbstractTransactionalDbTests extends AbstractTransactionalJUnit4SpringContextTests { diff --git a/src/test/java/org/wise/portal/mail/JavaMailTest.java b/src/test/java/org/wise/portal/mail/JavaMailTest.java index e765e7c9f9..d7e163fc5d 100644 --- a/src/test/java/org/wise/portal/mail/JavaMailTest.java +++ b/src/test/java/org/wise/portal/mail/JavaMailTest.java @@ -23,7 +23,7 @@ package org.wise.portal.mail; -import javax.mail.MessagingException; +import jakarta.mail.MessagingException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/org/wise/portal/presentation/validators/ChangePasswordParametersValidatorTest.java b/src/test/java/org/wise/portal/presentation/validators/ChangePasswordParametersValidatorTest.java index abf48dc999..4c4d099cc9 100644 --- a/src/test/java/org/wise/portal/presentation/validators/ChangePasswordParametersValidatorTest.java +++ b/src/test/java/org/wise/portal/presentation/validators/ChangePasswordParametersValidatorTest.java @@ -22,6 +22,9 @@ */ package org.wise.portal.presentation.validators; +import static org.junit.jupiter.api.Assertions.*; + + import org.easymock.EasyMock; import org.easymock.EasyMockExtension; import org.easymock.Mock; @@ -35,7 +38,6 @@ import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; -import junit.framework.TestCase; import org.wise.portal.domain.user.impl.UserImpl; import org.wise.portal.service.user.impl.UserServiceImpl; @@ -43,7 +45,7 @@ * @author Sally Ahn */ @ExtendWith(EasyMockExtension.class) -public class ChangePasswordParametersValidatorTest extends TestCase { +public class ChangePasswordParametersValidatorTest { private ChangePasswordParameters params; @@ -88,7 +90,7 @@ private void updateUserDetails(boolean isGoogle) { @BeforeEach public void setUp() { params = new ChangePasswordParameters(); - Long teacherId = new Long(1); + Long teacherId = Long.valueOf(1); params.setTeacherUser(teacherUser); params.setPasswd0(LEGAL_PASSWORD1); params.setPasswd1(LEGAL_PASSWORD2); diff --git a/src/test/java/org/wise/portal/presentation/validators/LookupParametersValidatorTest.java b/src/test/java/org/wise/portal/presentation/validators/LookupParametersValidatorTest.java index 855d72f567..5f6cbea5a5 100644 --- a/src/test/java/org/wise/portal/presentation/validators/LookupParametersValidatorTest.java +++ b/src/test/java/org/wise/portal/presentation/validators/LookupParametersValidatorTest.java @@ -22,17 +22,22 @@ */ package org.wise.portal.presentation.validators; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; -import org.wise.portal.domain.impl.LookupUserParameters; - +import org.wise.portal.domain.impl.LookupUserParameters; + /** * @author patrick lawler * */ -public class LookupParametersValidatorTest extends TestCase{ +public class LookupParametersValidatorTest{ private LookupUserParameters params; @@ -46,10 +51,10 @@ public class LookupParametersValidatorTest extends TestCase{ private final static String DATA = "Sarah"; - private final static String EMPTY = ""; - - @Override - protected void setUp(){ + private final static String EMPTY = ""; + + @BeforeEach + public void setUp() { this.params = new LookupUserParameters(); this.params.setLookupCriteria(CRITERIA); this.params.setLookupField(FIELD); @@ -57,22 +62,24 @@ protected void setUp(){ this.validator = new LookupUserParametersValidator(); this.errors = new BeanPropertyBindingResult(this.params, ""); - } - - @Override - protected void tearDown(){ + } + + @AfterEach + public void tearDown() { this.errors = null; this.validator = null; this.params = null; - } - - public void testAllOK(){ + } + + @Test + public void testAllOK() { this.validator.validate(params, errors); assertTrue(!errors.hasErrors()); - } - - public void testEmptyData(){ + } + + @Test + public void testEmptyData() { this.params.setLookupData(EMPTY); this.validator.validate(params, errors); @@ -80,9 +87,10 @@ public void testEmptyData(){ assertTrue(errors.hasErrors()); assertEquals(1, errors.getErrorCount()); assertTrue(errors.hasFieldErrors("lookupData")); - } - - public void testEmptyField(){ + } + + @Test + public void testEmptyField() { this.params.setLookupField(EMPTY); this.validator.validate(params, errors); @@ -90,9 +98,10 @@ public void testEmptyField(){ assertTrue(errors.hasErrors()); assertEquals(1, errors.getErrorCount()); assertTrue(errors.hasFieldErrors("lookupField")); - } - - public void testEmptyCriteria(){ + } + + @Test + public void testEmptyCriteria() { this.params.setLookupCriteria(EMPTY); this.validator.validate(params, errors); diff --git a/src/test/java/org/wise/portal/presentation/validators/teacher/ChangeWorkgroupParametersValidatorTest.java b/src/test/java/org/wise/portal/presentation/validators/teacher/ChangeWorkgroupParametersValidatorTest.java index aa9cba11bf..65d5b4a2aa 100644 --- a/src/test/java/org/wise/portal/presentation/validators/teacher/ChangeWorkgroupParametersValidatorTest.java +++ b/src/test/java/org/wise/portal/presentation/validators/teacher/ChangeWorkgroupParametersValidatorTest.java @@ -23,8 +23,12 @@ package org.wise.portal.presentation.validators.teacher; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import org.wise.portal.domain.impl.ChangeWorkgroupParameters; @@ -37,7 +41,7 @@ * @author Sally Ahn * @version $Id: $ */ -public class ChangeWorkgroupParametersValidatorTest extends TestCase{ +public class ChangeWorkgroupParametersValidatorTest{ private ChangeWorkgroupParameters params; @@ -51,14 +55,14 @@ public class ChangeWorkgroupParametersValidatorTest extends TestCase{ private final Workgroup WORKGROUP_TO = new WorkgroupImpl(); - private static final Long WORKGROUP_TO_ID = new Long(5); + private static final Long WORKGROUP_TO_ID = Long.valueOf(5); - private static final Long OFFERING_ID = new Long(10); + private static final Long OFFERING_ID = Long.valueOf(10); - private static final Long PERIOD_ID = new Long(2); - - @Override - protected void setUp() { + private static final Long PERIOD_ID = Long.valueOf(2); + + @BeforeEach + public void setUp() { validator = new ChangeWorkgroupParametersValidator(); params = new ChangeWorkgroupParameters(); params.setStudent(STUDENT); @@ -69,14 +73,16 @@ protected void setUp() { params.setPeriodId(PERIOD_ID); errors = new BeanPropertyBindingResult(params, ""); } - - public void testNoProblemValidate() { + + @Test + public void testNoProblemValidate() { validator.validate(params, errors); assertTrue(!errors.hasErrors()); } - - public void testEmptyStudentValidate() { + + @Test + public void testEmptyStudentValidate() { params.setStudent(null); validator.validate(params, errors); @@ -86,16 +92,18 @@ public void testEmptyStudentValidate() { assertNotNull(errors.getFieldError("student")); } - - public void testEmptyWorkgroupFromValidate() { + + @Test + public void testEmptyWorkgroupFromValidate() { params.setWorkgroupFrom(null); validator.validate(params, errors); assertTrue(!errors.hasErrors()); } - - public void testEmptyWorkgroupToIdValidate() { + + @Test + public void testEmptyWorkgroupToIdValidate() { params.setWorkgroupToId(null); validator.validate(params, errors); @@ -104,8 +112,9 @@ public void testEmptyWorkgroupToIdValidate() { assertEquals(1, errors.getErrorCount()); assertNotNull(errors.getFieldError("workgroupToId")); } - - public void testEmptyOfferingIdValidate() { + + @Test + public void testEmptyOfferingIdValidate() { params.setOfferingId(null); validator.validate(params, errors); @@ -114,8 +123,9 @@ public void testEmptyOfferingIdValidate() { assertEquals(1, errors.getErrorCount()); assertNotNull(errors.getFieldError("offeringId")); } - - public void testEmptyPeriodIdValidate() { + + @Test + public void testEmptyPeriodIdValidate() { params.setPeriodId(null); validator.validate(params, errors); @@ -124,9 +134,9 @@ public void testEmptyPeriodIdValidate() { assertEquals(1, errors.getErrorCount()); assertNotNull(errors.getFieldError("periodId")); } - - @Override - protected void tearDown() { + + @AfterEach + public void tearDown() { validator = null; params = null; errors = null; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/APIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/APIControllerTest.java index 4a9c0cf5f0..b12a2c804c 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/APIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/APIControllerTest.java @@ -5,7 +5,7 @@ import java.util.HashSet; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.easymock.Mock; import org.junit.jupiter.api.AfterEach; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/DiscourseSSOControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/DiscourseSSOControllerTest.java index ac814d8bc1..5322bb470d 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/DiscourseSSOControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/DiscourseSSOControllerTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.easymock.EasyMockExtension; import org.easymock.TestSubject; @@ -17,14 +17,18 @@ public class DiscourseSSOControllerTest extends APIControllerTest { @TestSubject private DiscourseSSOController discourseSSOController = new DiscourseSSOController(); - String base64EncodedSSO = "bm9uY2U9MWJmMDQwNzIzYmYwNDc2NzExZjAxMWY4MjYyNzQyMTQmcmV0dXJuX3Nzb191" - + "cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTkyOTIlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu"; + String base64EncodedSSO = """ + bm9uY2U9MWJmMDQwNzIzYmYwNDc2NzExZjAxMWY4MjYyNzQyMTQmcmV0dXJuX3Nzb191\ + cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTkyOTIlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu\ + """; String sigParam = "13f83c3dc28af7c37fac8d40f7792d63bf727cc2e7b293f3669a526dd861f71d"; - String redirectURL = "http://localhost:9292/session/sso_login?sso=bm9uY2U9MWJmMDQwNzIzYmYwNDc2N" - + "zExZjAxMWY4MjYyNzQyMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTkyOTIlMkZzZXN" - + "zaW9uJTJGc3NvX2xvZ2luJm5hbWU9U3F1aWR3YXJkK1RlbnRhY2xlcyZ1c2VybmFtZT1TcXVpZHdhcmRUZW50YWNsZ" - + "XMmZW1haWw9JmV4dGVybmFsX2lkPTk0MjEw&sig=9e6d86e5ac58afe16acf62fe7aa11aec4ef3540a8eb7c0d56a" - + "a6c585b90bee61"; + String redirectURL = """ + http://localhost:9292/session/sso_login?sso=bm9uY2U9MWJmMDQwNzIzYmYwNDc2N\ + zExZjAxMWY4MjYyNzQyMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTkyOTIlMkZzZXN\ + zaW9uJTJGc3NvX2xvZ2luJm5hbWU9U3F1aWR3YXJkK1RlbnRhY2xlcyZ1c2VybmFtZT1TcXVpZHdhcmRUZW50YWNsZ\ + XMmZW1haWw9JmV4dGVybmFsX2lkPTk0MjEw&sig=9e6d86e5ac58afe16acf62fe7aa11aec4ef3540a8eb7c0d56a\ + a6c585b90bee61\ + """; @Test public void discourseSSOLogin_ValidArgs_ReturnRedirectURL() throws Exception { diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/IndexControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/IndexControllerTest.java index fb0b686c34..b657cc271f 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/IndexControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/IndexControllerTest.java @@ -23,7 +23,7 @@ package org.wise.portal.presentation.web.controllers; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.easymock.EasyMock; import org.springframework.mock.web.MockHttpServletRequest; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsControllerTest.java index 7189206052..988ba6fad1 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/admin/FindProjectRunsControllerTest.java @@ -22,6 +22,8 @@ */ package org.wise.portal.presentation.web.controllers.admin; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.List; import org.easymock.EasyMock; @@ -38,13 +40,11 @@ import org.wise.portal.domain.run.impl.RunImpl; import org.wise.portal.service.run.impl.RunServiceImpl; -import junit.framework.TestCase; - /** * @author patrick lawler */ @ExtendWith(EasyMockExtension.class) -public class FindProjectRunsControllerTest extends TestCase { +public class FindProjectRunsControllerTest { @TestSubject private FindProjectRunsController controller = new FindProjectRunsController(); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalControllerTest.java index 56860bb78f..cdfd2da6e2 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ManagePortalControllerTest.java @@ -1,6 +1,5 @@ package org.wise.portal.presentation.web.controllers.admin; -import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.easymock.EasyMock; import org.easymock.EasyMockExtension; @@ -17,7 +16,7 @@ import java.io.IOException; @ExtendWith(EasyMockExtension.class) -public class ManagePortalControllerTest extends TestCase { +public class ManagePortalControllerTest { @TestSubject private ManagePortalController controller = new ManagePortalController(); @@ -32,9 +31,9 @@ public class ManagePortalControllerTest extends TestCase { public void addOfficialTagToProjectLibraryGroup_OK() throws JSONException, IOException { String projectLibraryGroupJSONString = IOUtils .toString(this.getClass().getResourceAsStream("/projectLibraryGroupSample.json"), "UTF-8"); - EasyMock.expect(projectService.addTagToProject("official", new Long(24447))).andReturn(1); - EasyMock.expect(projectService.addTagToProject("official", new Long(24449))).andReturn(1); - EasyMock.expect(projectService.addTagToProject("official", new Long(24358))).andReturn(1); + EasyMock.expect(projectService.addTagToProject("official", Long.valueOf(24447))).andReturn(1); + EasyMock.expect(projectService.addTagToProject("official", Long.valueOf(24449))).andReturn(1); + EasyMock.expect(projectService.addTagToProject("official", Long.valueOf(24358))).andReturn(1); EasyMock.replay(projectService); controller.addOfficialTagToProjectLibraryGroup(projectLibraryGroupJSONString); EasyMock.verify(projectService); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowAllUsersControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowAllUsersControllerTest.java index 3412ce75e7..05a31c3bc6 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowAllUsersControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowAllUsersControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.admin; -import static org.junit.Assert.assertEquals; import static org.easymock.EasyMock.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowOnlineUsersControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowOnlineUsersControllerTest.java index 8e3f674d01..abaac5defc 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowOnlineUsersControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/admin/ShowOnlineUsersControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.admin; -import static org.junit.Assert.assertEquals; import static org.easymock.EasyMock.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashSet; import java.util.Set; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/admin/UserInfoControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/admin/UserInfoControllerTest.java index 6481dd8161..1588ab0574 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/admin/UserInfoControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/admin/UserInfoControllerTest.java @@ -25,7 +25,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIControllerTest.java index 042fddeaac..8f9faf665d 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/author/project/AuthorAPIControllerTest.java @@ -67,7 +67,7 @@ public void getAuthorProjectConfig_HasProjectRun_ReturnCanGradeStudentWork() thr expect(runService.getProjectRuns(projectId1)).andReturn(projectRunList); expect(runService.isAllowedToGradeStudentWork(run1, teacher1)).andReturn(true); replay(runService); - expect(portalService.getById(new Integer(1))).andReturn(new PortalImpl()); + expect(portalService.getById(Integer.valueOf(1))).andReturn(new PortalImpl()); expect(portalService.getDefaultProjectMetadataSettings()).andReturn(""); replay(portalService); expect(request.getLocale()).andReturn(Locale.US); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/notebook/NotebookControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/notebook/NotebookControllerTest.java index 2958f32ebc..1f50681695 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/notebook/NotebookControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/notebook/NotebookControllerTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.file.AccessDeniedException; import java.util.ArrayList; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIControllerTest.java index cb0e3b4b5b..7d6504440d 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupAPIControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.EasyMockExtension; import org.easymock.TestSubject; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateControllerTest.java index ea6467ec2a..8d0a90ea7e 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupCreateControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipControllerTest.java index 295b65317e..49a7d3c799 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupMembershipControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationControllerTest.java index 14d7c27e57..b22c0beb26 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupStudentWorkAnnotationControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Arrays; @@ -10,7 +10,7 @@ import org.easymock.EasyMockExtension; import org.easymock.Mock; import org.easymock.TestSubject; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.security.access.AccessDeniedException; @@ -66,7 +66,7 @@ private void expectInvalidDynamicPromptContent() throws IOException { expect(projectService.getProjectContent(project1)).andReturn(project_sans_reference_component); } - @Ignore + @Disabled public void getStudentDataForDynamicPrompt_ReturnReferenceComponentWork() throws Exception { expectUserInPeerGroup(); expectValidDynamicPromptContent(); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIControllerTest.java index cdce63e521..08754680db 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/PeerGroupWorkAPIControllerTest.java @@ -1,8 +1,8 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.expect; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIControllerTest.java index eb6a7ff5df..b9e00e2218 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/peergroup/TeacherPeerGroupInfoAPIControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.peergroup; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/run/RunInfoAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/run/RunInfoAPIControllerTest.java index 067f148d9b..5bff02b25f 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/run/RunInfoAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/run/RunInfoAPIControllerTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIControllerTest.java index 8700e16237..6c812554b6 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/run/WorkgroupTagAPIControllerTest.java @@ -4,8 +4,8 @@ import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataControllerTest.java index 83a6d06cc4..7d104b4626 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateDiscussionDataControllerTest.java @@ -1,8 +1,6 @@ package org.wise.portal.presentation.web.controllers.student; -import static org.junit.Assert.assertThrows; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Arrays; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataControllerTest.java index 1fb2dc935b..8784b0553e 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateGraphDataControllerTest.java @@ -1,9 +1,7 @@ package org.wise.portal.presentation.web.controllers.student; import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Arrays; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataControllerTest.java index c142427c75..8c8eebaade 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/student/ClassmateSummaryDataControllerTest.java @@ -1,9 +1,7 @@ package org.wise.portal.presentation.web.controllers.student; import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertThrows; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.sql.Timestamp; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentAPIControllerTest.java index 914dee69f2..31072fd245 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentAPIControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.student; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Date; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIControllerTest.java index 14e443e66b..57aee3622c 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/student/StudentForgotAccountAPIControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.student; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.Map; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIControllerTest.java index 511c3d5de1..030f93808a 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/survey/SurveyAPIControllerTest.java @@ -13,9 +13,9 @@ import java.util.Set; import java.util.TreeSet; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherControllerTest.java index 024e6fb9ed..b91ccf9581 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/RegisterTeacherControllerTest.java @@ -28,8 +28,8 @@ import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIControllerTest.java index d070760700..f66a8d3a2a 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherAPIControllerTest.java @@ -5,9 +5,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIControllerTest.java index 01d7715fdc..2f8e9798e6 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/TeacherForgotAccountAPIControllerTest.java @@ -1,7 +1,7 @@ package org.wise.portal.presentation.web.controllers.teacher; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.Date; import java.util.Map; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkControllerTest.java index 65d022cf1a..82a4b82da2 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/grading/GradeWorkControllerTest.java @@ -25,7 +25,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.easymock.EasyMockExtension; import org.easymock.EasyMockRunner; @@ -35,7 +35,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runner.RunWith; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordControllerTest.java index 31706dc536..53e4464654 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/BatchStudentChangePasswordControllerTest.java @@ -25,11 +25,13 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashSet; import java.util.Set; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.easymock.EasyMock; import org.springframework.mock.web.MockHttpServletRequest; @@ -94,7 +96,7 @@ public class BatchStudentChangePasswordControllerTest extends AbstractModelAndVi private MutableUserDetails userDetails3; - private static final Long GROUPID = new Long(5); + private static final Long GROUPID = Long.valueOf(5); private static final String OLD_PASSWORD1 = "student1"; @@ -107,7 +109,7 @@ public class BatchStudentChangePasswordControllerTest extends AbstractModelAndVi private static final String FORM = "FORM VIEW"; /** - * @see junit.framework.TestCase#setUp() + * @see */ protected void setUp() throws Exception { super.setUp(); @@ -138,7 +140,7 @@ protected void setUp() throws Exception { } /** - * @see junit.framework.TestCase#tearDown() + * @see */ protected void tearDown() throws Exception { super.tearDown(); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeStudentPasswordControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeStudentPasswordControllerTest.java index c686852e77..b1cc9e14ae 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeStudentPasswordControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/ChangeStudentPasswordControllerTest.java @@ -25,8 +25,8 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Map; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/CreateWorkgroupControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/CreateWorkgroupControllerTest.java index 79394090c2..2dc5fc0e46 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/CreateWorkgroupControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/CreateWorkgroupControllerTest.java @@ -5,7 +5,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.util.HashSet; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/StudentListControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/StudentListControllerTest.java index a37caa340f..735f929e3f 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/StudentListControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/management/StudentListControllerTest.java @@ -29,7 +29,7 @@ import java.util.Set; import java.util.TreeSet; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.easymock.EasyMock; import org.junit.internal.runners.TestClassRunner; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/project/ProjectInfoControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/project/ProjectInfoControllerTest.java index fdf7037059..adf335a291 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/project/ProjectInfoControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/project/ProjectInfoControllerTest.java @@ -46,9 +46,9 @@ @ExtendWith(EasyMockExtension.class) public class ProjectInfoControllerTest extends AbstractModelAndViewTests { - private static final Long DEFAULT_PROJECT_ID = new Long(10); + private static final Long DEFAULT_PROJECT_ID = Long.valueOf(10); - private static final Long NON_EXISTING_PROJECT_ID = new Long(999999); + private static final Long NON_EXISTING_PROJECT_ID = Long.valueOf(999999); private ProjectInfoController projectInfoController; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunControllerTest.java index ab5403e03b..27f9b3d02c 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/ShareProjectRunControllerTest.java @@ -70,7 +70,7 @@ public class ShareProjectRunControllerTest extends AbstractModelAndViewTests { private UserService mockUserService; - private static final Long RUNID = new Long(4); + private static final Long RUNID = Long.valueOf(4); private BindingResult errors; @@ -85,7 +85,7 @@ public class ShareProjectRunControllerTest extends AbstractModelAndViewTests { private AddSharedTeacherParameters addSharedTeacherParameters; /** - * @see junit.framework.TestCase#setUp() + * @see */ protected void setUp() throws Exception { super.setUp(); @@ -113,7 +113,7 @@ protected void setUp() throws Exception { } /** - * @see junit.framework.TestCase#tearDown() + * @see */ protected void tearDown() throws Exception { super.tearDown(); diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIControllerTest.java index a78ab27709..5db19f4687 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/TeacherRunAPIControllerTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIControllerTest.java index c1496f3f54..ac5fff0918 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/teacher/run/WorkgroupMembershipAPIControllerTest.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import static org.easymock.EasyMock.*; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import org.easymock.EasyMockExtension; import org.easymock.TestSubject; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIControllerTest.java index 3e7c0e2dee..ab248577c4 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/user/GoogleUserAPIControllerTest.java @@ -3,9 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import java.util.Map; diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/user/UserAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/user/UserAPIControllerTest.java index f04cbf5f7a..86b5ec1efc 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/user/UserAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/user/UserAPIControllerTest.java @@ -3,9 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/test/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImplTest.java b/src/test/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImplTest.java index d814994342..3c40c0c45b 100644 --- a/src/test/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/authentication/impl/UserDetailsServiceImplTest.java @@ -21,8 +21,8 @@ import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/service/group/impl/GroupServiceImplTest.java b/src/test/java/org/wise/portal/service/group/impl/GroupServiceImplTest.java index e5f3abf9e7..96a5c1d18b 100644 --- a/src/test/java/org/wise/portal/service/group/impl/GroupServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/group/impl/GroupServiceImplTest.java @@ -27,9 +27,7 @@ import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.util.HashSet; import java.util.Set; @@ -42,7 +40,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runner.RunWith; import org.springframework.security.acls.domain.BasePermission; import org.wise.portal.dao.ObjectNotFoundException; import org.wise.portal.dao.group.GroupDao; @@ -175,7 +172,7 @@ private void createGroup3() throws Exception { group3.setName(DEFAULT_GROUP_NAMES[2]); group3.setParent(group1); - expect(groupDao.getById(new Long(3))).andReturn(group1); + expect(groupDao.getById(Long.valueOf(3))).andReturn(group1); groupDao.save(group3); expectLastCall(); replay(groupDao); @@ -186,7 +183,7 @@ private void createGroup3() throws Exception { GroupParameters groupParameters = new GroupParameters(); groupParameters.setName(DEFAULT_GROUP_NAMES[2]); - groupParameters.setParentId(new Long(3)); + groupParameters.setParentId(Long.valueOf(3)); group3 = groupService.createGroup(groupParameters); verify(groupDao); reset(groupDao); @@ -341,7 +338,7 @@ public void retrieveById_WithExistingGroupId_ShouldReturnGroup() throws Exceptio @Test public void retrieveById_WithNonExistingGroupId_ShouldThrowException() throws Exception { - Long groupId = new Long(-1); + Long groupId = Long.valueOf(-1); expect(groupDao.getById(groupId)).andThrow(new ObjectNotFoundException(groupId, Group.class)); replay(groupDao); diff --git a/src/test/java/org/wise/portal/service/impl/AclServiceImplTest.java b/src/test/java/org/wise/portal/service/impl/AclServiceImplTest.java index 87afa51b9c..565e11ac26 100644 --- a/src/test/java/org/wise/portal/service/impl/AclServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/impl/AclServiceImplTest.java @@ -21,7 +21,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Collections; @@ -80,7 +80,7 @@ public void setUp() { securityContext.setAuthentication(authority); SecurityContextHolder.setContext(securityContext); - expect(group.getId()).andReturn(new Long(1)).anyTimes(); + expect(group.getId()).andReturn(Long.valueOf(1)).anyTimes(); replay(group); mockMutableAcl = createNiceMock(MutableAcl.class); objectIdentity = new ObjectIdentityImpl(group.getClass(), group.getId()); diff --git a/src/test/java/org/wise/portal/service/impl/UserServiceImplTest.java b/src/test/java/org/wise/portal/service/impl/UserServiceImplTest.java index 88c63ef47b..6de32c054a 100644 --- a/src/test/java/org/wise/portal/service/impl/UserServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/impl/UserServiceImplTest.java @@ -22,11 +22,11 @@ */ package org.wise.portal.service.impl; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; import java.util.Calendar; import java.util.Date; @@ -111,7 +111,7 @@ public class UserServiceImplTest { private MutableGrantedAuthority userAuthority; - private Integer DEFAULT_NUMBEROFLOGINS = new Integer(9); + private Integer DEFAULT_NUMBEROFLOGINS = Integer.valueOf(9); private static final String DEFAULT_ACCOUNT_QUESTION = "what is the name of your middle name?"; diff --git a/src/test/java/org/wise/portal/service/newsitem/impl/NewsItemServiceImplTest.java b/src/test/java/org/wise/portal/service/newsitem/impl/NewsItemServiceImplTest.java index dd2aaac49f..0674b9066a 100644 --- a/src/test/java/org/wise/portal/service/newsitem/impl/NewsItemServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/newsitem/impl/NewsItemServiceImplTest.java @@ -27,10 +27,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Calendar; @@ -72,7 +69,7 @@ public class NewsItemServiceImplTest { private Date date2 = Calendar.getInstance().getTime(); - private Integer itemIdNotInDB = new Integer(-1); + private Integer itemIdNotInDB = Integer.valueOf(-1); private String news1 = "Hot off the presses!"; @@ -130,7 +127,7 @@ public void createNewsItem_NewNewsItem_ShouldSucceed() { @Test public void deleteNewsItem_ExistingNewsItemID_ShouldSucceed() throws Exception { - Integer id = new Integer(3); + Integer id = Integer.valueOf(3); newsItem1.setId(id); expect(newsItemDao.getById(id)).andReturn(newsItem1); newsItemDao.delete(newsItem1); @@ -174,7 +171,7 @@ public void retrieveAllNewsItem_TwoNewsItemsInDB_ShouldSucceed() { @Test public void retrieveById_ValidItemId_ShouldSucceed() throws ObjectNotFoundException { - Integer id = new Integer(3); + Integer id = Integer.valueOf(3); expect(newsItemDao.getById(id)).andReturn(newsItem1); replay(newsItemDao); @@ -200,7 +197,7 @@ public void retrieveById_InvalidItemID_ShouldThrowException() throws ObjectNotFo @Test public void updateNewsItem_ExistingNewsItem_ShouldSucceed() throws Exception { - Integer id = new Integer(3); + Integer id = Integer.valueOf(3); expect(newsItemDao.getById(id)).andReturn(newsItem1); newsItemDao.save(isA(NewsItem.class)); expectLastCall(); diff --git a/src/test/java/org/wise/portal/service/password/impl/PasswordServiceImplTest.java b/src/test/java/org/wise/portal/service/password/impl/PasswordServiceImplTest.java index f0f49d31b9..3f6498d9e2 100644 --- a/src/test/java/org/wise/portal/service/password/impl/PasswordServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/password/impl/PasswordServiceImplTest.java @@ -1,8 +1,6 @@ package org.wise.portal.service.password.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import java.util.Map; diff --git a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupInfoServiceImplTest.java b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupInfoServiceImplTest.java index 9937ba23a1..daa5612be5 100644 --- a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupInfoServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupInfoServiceImplTest.java @@ -26,7 +26,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.Map; diff --git a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupMembershipServiceImplTest.java b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupMembershipServiceImplTest.java index ccf5fb9c62..c19991773a 100644 --- a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupMembershipServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupMembershipServiceImplTest.java @@ -5,7 +5,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupServiceImplTest.java b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupServiceImplTest.java index c0acc2a21b..0387cd4592 100644 --- a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupServiceImplTest.java @@ -27,9 +27,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.HashSet; diff --git a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupThresholdServiceTest.java b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupThresholdServiceTest.java index 9d2629ab0b..b78d27fbf4 100644 --- a/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupThresholdServiceTest.java +++ b/src/test/java/org/wise/portal/service/peergroup/impl/PeerGroupThresholdServiceTest.java @@ -26,8 +26,8 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; diff --git a/src/test/java/org/wise/portal/service/peergroup/impl/WorkgroupWithDifferenceTest.java b/src/test/java/org/wise/portal/service/peergroup/impl/WorkgroupWithDifferenceTest.java index 6d95d79743..67c384e8b6 100644 --- a/src/test/java/org/wise/portal/service/peergroup/impl/WorkgroupWithDifferenceTest.java +++ b/src/test/java/org/wise/portal/service/peergroup/impl/WorkgroupWithDifferenceTest.java @@ -1,7 +1,7 @@ package org.wise.portal.service.peergroup.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.easymock.EasyMockExtension; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/wise/portal/service/peergrouping/PeerGroupingServiceImplTest.java b/src/test/java/org/wise/portal/service/peergrouping/PeerGroupingServiceImplTest.java index 89a8779435..93d79080e8 100644 --- a/src/test/java/org/wise/portal/service/peergrouping/PeerGroupingServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergrouping/PeerGroupingServiceImplTest.java @@ -24,7 +24,7 @@ package org.wise.portal.service.peergrouping; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; diff --git a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentIdeasLogicServiceImplTest.java b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentIdeasLogicServiceImplTest.java index 10d6423640..052e2d495a 100644 --- a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentIdeasLogicServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentIdeasLogicServiceImplTest.java @@ -5,7 +5,7 @@ import java.util.TreeSet; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.EasyMockExtension; import org.easymock.TestSubject; diff --git a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentKIScoresLogicServiceImplTest.java b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentKIScoresLogicServiceImplTest.java index 2a6101f6a7..6f88baa0fb 100644 --- a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentKIScoresLogicServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/DifferentKIScoresLogicServiceImplTest.java @@ -1,6 +1,6 @@ package org.wise.portal.service.peergrouping.logic.impl; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.Iterator; diff --git a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/PeerGroupAnnotationLogicServiceImplTest.java b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/PeerGroupAnnotationLogicServiceImplTest.java index f794e8d328..dee4fbf2ee 100644 --- a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/PeerGroupAnnotationLogicServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/PeerGroupAnnotationLogicServiceImplTest.java @@ -10,10 +10,10 @@ import java.util.stream.Collectors; import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.Mock; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.wise.portal.dao.annotation.wise5.AnnotationDao; import org.wise.portal.domain.peergrouping.PeerGrouping; import org.wise.portal.domain.peergrouping.impl.PeerGroupingImpl; @@ -36,7 +36,7 @@ public abstract class PeerGroupAnnotationLogicServiceImplTest Set workgroupsNotInPeerGroup; Map workgroupToAnnotation = new HashMap(); - @Before + @BeforeEach public void setup() throws Exception { super.setup(); workgroupsNotInPeerGroup = new HashSet(); diff --git a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/RandomLogicServiceImplTest.java b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/RandomLogicServiceImplTest.java index 5921299d16..92842152eb 100644 --- a/src/test/java/org/wise/portal/service/peergrouping/logic/impl/RandomLogicServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/peergrouping/logic/impl/RandomLogicServiceImplTest.java @@ -1,6 +1,6 @@ package org.wise.portal.service.peergrouping.logic.impl; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.HashSet; import java.util.Set; diff --git a/src/test/java/org/wise/portal/service/ping/impl/CRaterPingServiceImplTest.java b/src/test/java/org/wise/portal/service/ping/impl/CRaterPingServiceImplTest.java index c4c545a988..c35e355473 100644 --- a/src/test/java/org/wise/portal/service/ping/impl/CRaterPingServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/ping/impl/CRaterPingServiceImplTest.java @@ -3,8 +3,8 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import org.easymock.EasyMockExtension; diff --git a/src/test/java/org/wise/portal/service/project/impl/ProjectServiceImplTest.java b/src/test/java/org/wise/portal/service/project/impl/ProjectServiceImplTest.java index e3d957643f..16d8090b7f 100644 --- a/src/test/java/org/wise/portal/service/project/impl/ProjectServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/project/impl/ProjectServiceImplTest.java @@ -27,9 +27,7 @@ import static org.easymock.EasyMock.mock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.IOException; @@ -88,9 +86,9 @@ public class ProjectServiceImplTest { @Mock private GrantedAuthorityDao grantedAuthorityDao; - private static final Long EXISTING_PROJECT_ID = new Long(10); + private static final Long EXISTING_PROJECT_ID = Long.valueOf(10); - private static final Long NONEXISTING_PROJECT_ID = new Long(103); + private static final Long NONEXISTING_PROJECT_ID = Long.valueOf(103); private static final String tempProjectFolderPath = "src/test/webapp/curriculum/temp"; diff --git a/src/test/java/org/wise/portal/service/run/impl/RunServiceImplTest.java b/src/test/java/org/wise/portal/service/run/impl/RunServiceImplTest.java index 8ebff6aa11..2c860a5f59 100644 --- a/src/test/java/org/wise/portal/service/run/impl/RunServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/run/impl/RunServiceImplTest.java @@ -27,12 +27,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.util.Calendar; import java.util.Date; @@ -194,7 +189,7 @@ public void createRun_WithPeriods_ShouldCreateRun() throws Exception { @Test public void retrieveById_RunExists_ShouldReturnRun() throws Exception { Run run = new RunImpl(); - Long runId = new Long(5); + Long runId = Long.valueOf(5); expect(runDao.getById(runId)).andReturn(run); replay(runDao); Run retrievedRun = runService.retrieveById(runId); @@ -204,7 +199,7 @@ public void retrieveById_RunExists_ShouldReturnRun() throws Exception { @Test public void retrieveById_RunDoesNotExist_ShouldThrowException() throws ObjectNotFoundException { - Long runIdNotInDB = new Long(-1); + Long runIdNotInDB = Long.valueOf(-1); expect(runDao.getById(runIdNotInDB)) .andThrow(new ObjectNotFoundException(runIdNotInDB, Run.class)); replay(runDao); @@ -309,7 +304,7 @@ public void startRun_EndedRun_ShouldStartRun() { @Test public void setIsLockedAfterEndDate_ShouldSetToTrue() throws Exception { assertFalse(run.isLockedAfterEndDate()); - Long runId = new Long(1); + Long runId = Long.valueOf(1); expect(runDao.getById(runId)).andReturn(run); runDao.save(run); expectLastCall(); @@ -322,7 +317,7 @@ public void setIsLockedAfterEndDate_ShouldSetToTrue() throws Exception { public void setIsLockedAfterEndDate_ShouldSetToFalse() throws Exception { run.setLockedAfterEndDate(true); assertTrue(run.isLockedAfterEndDate()); - Long runId = new Long(1); + Long runId = Long.valueOf(1); expect(runDao.getById(runId)).andReturn(run); runDao.save(run); expectLastCall(); diff --git a/src/test/java/org/wise/portal/service/student/impl/StudentServiceImplTest.java b/src/test/java/org/wise/portal/service/student/impl/StudentServiceImplTest.java index 4375b522f2..bb62397cc5 100644 --- a/src/test/java/org/wise/portal/service/student/impl/StudentServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/student/impl/StudentServiceImplTest.java @@ -27,7 +27,7 @@ import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import java.util.ArrayList; @@ -98,7 +98,7 @@ public class StudentServiceImplTest { private Run run; - private final Long runId = new Long(3); + private final Long runId = Long.valueOf(3); @BeforeEach public void setUp() throws Exception { diff --git a/src/test/java/org/wise/portal/service/tag/TagServiceImplTest.java b/src/test/java/org/wise/portal/service/tag/TagServiceImplTest.java index c48c4a2b34..db37ef5498 100644 --- a/src/test/java/org/wise/portal/service/tag/TagServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/tag/TagServiceImplTest.java @@ -3,7 +3,8 @@ import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.easymock.EasyMockExtension; import org.easymock.Mock; import org.easymock.TestSubject; diff --git a/src/test/java/org/wise/portal/service/vle/wise5/impl/AnnotationServiceImplTest.java b/src/test/java/org/wise/portal/service/vle/wise5/impl/AnnotationServiceImplTest.java index 05b8819701..efd9d82baa 100644 --- a/src/test/java/org/wise/portal/service/vle/wise5/impl/AnnotationServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/vle/wise5/impl/AnnotationServiceImplTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.HashSet; diff --git a/src/test/java/org/wise/portal/service/vle/wise5/impl/StudentWorkServiceImplTest.java b/src/test/java/org/wise/portal/service/vle/wise5/impl/StudentWorkServiceImplTest.java index 9def09b746..7291d7e647 100644 --- a/src/test/java/org/wise/portal/service/vle/wise5/impl/StudentWorkServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/vle/wise5/impl/StudentWorkServiceImplTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashSet; import java.util.List; diff --git a/src/test/java/org/wise/portal/service/vle/wise5/impl/TeacherWorkServiceImplTest.java b/src/test/java/org/wise/portal/service/vle/wise5/impl/TeacherWorkServiceImplTest.java index e360c27ffb..a3b5dd8da5 100644 --- a/src/test/java/org/wise/portal/service/vle/wise5/impl/TeacherWorkServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/vle/wise5/impl/TeacherWorkServiceImplTest.java @@ -3,8 +3,8 @@ import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImplTest.java b/src/test/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImplTest.java index a1a444344b..6d40c58da0 100644 --- a/src/test/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/vle/wise5/impl/VLEServiceImplTest.java @@ -2,7 +2,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Timestamp; import java.util.ArrayList; diff --git a/src/test/java/org/wise/portal/service/work/impl/BroadcastStudentWorkServiceImplTest.java b/src/test/java/org/wise/portal/service/work/impl/BroadcastStudentWorkServiceImplTest.java index d36cf09ad0..7375c1059b 100644 --- a/src/test/java/org/wise/portal/service/work/impl/BroadcastStudentWorkServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/work/impl/BroadcastStudentWorkServiceImplTest.java @@ -38,8 +38,10 @@ public void setUp() throws Exception { @Test public void broadcastToClassroom_PublishClassroomTopic() { - redisPublisher.publish("{\"topic\":\"/topic/classroom/1/2\"," - + "\"studentWork\":{\"periodId\":2,\"runId\":1},\"type\":\"studentWorkToClassroom\"}"); + redisPublisher.publish(""" + {"topic":"/topic/classroom/1/2",\ + "studentWork":{"periodId":2,"runId":1},"type":"studentWorkToClassroom"}\ + """); expectLastCall(); replay(redisPublisher); service.broadcastToClassroom(studentWork); @@ -48,8 +50,10 @@ public void broadcastToClassroom_PublishClassroomTopic() { @Test public void broadcastToTeacher_PublishTeacherRunTopic() { - redisPublisher.publish("{\"topic\":\"/topic/teacher/1\"," - + "\"studentWork\":{\"periodId\":2,\"runId\":1},\"type\":\"studentWorkToTeacher\"}"); + redisPublisher.publish(""" + {"topic":"/topic/teacher/1",\ + "studentWork":{"periodId":2,"runId":1},"type":"studentWorkToTeacher"}\ + """); expectLastCall(); replay(redisPublisher); service.broadcastToTeacher(studentWork); diff --git a/src/test/java/org/wise/portal/service/workgroup/impl/WorkgroupServiceImplTest.java b/src/test/java/org/wise/portal/service/workgroup/impl/WorkgroupServiceImplTest.java index 3ff2f644e0..1bcf15d896 100644 --- a/src/test/java/org/wise/portal/service/workgroup/impl/WorkgroupServiceImplTest.java +++ b/src/test/java/org/wise/portal/service/workgroup/impl/WorkgroupServiceImplTest.java @@ -22,7 +22,7 @@ import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashSet; import java.util.LinkedList; diff --git a/src/test/java/org/wise/vle/utils/FileManagerTest.java b/src/test/java/org/wise/vle/utils/FileManagerTest.java index 5416a883d2..199aad7743 100644 --- a/src/test/java/org/wise/vle/utils/FileManagerTest.java +++ b/src/test/java/org/wise/vle/utils/FileManagerTest.java @@ -1,6 +1,7 @@ package org.wise.vle.utils; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.easymock.EasyMockExtension; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/wise/vle/web/CRaterControllerTest.java b/src/test/java/org/wise/vle/web/CRaterControllerTest.java index d739d78870..df24b34af5 100644 --- a/src/test/java/org/wise/vle/web/CRaterControllerTest.java +++ b/src/test/java/org/wise/vle/web/CRaterControllerTest.java @@ -1,9 +1,7 @@ package org.wise.vle.web; -import static junit.framework.TestCase.assertEquals; import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; import org.easymock.EasyMockExtension; import org.easymock.Mock; diff --git a/src/test/java/org/wise/vle/web/StudentStatusControllerTest.java b/src/test/java/org/wise/vle/web/StudentStatusControllerTest.java index 7f58abe2c2..7ac5c96b2c 100644 --- a/src/test/java/org/wise/vle/web/StudentStatusControllerTest.java +++ b/src/test/java/org/wise/vle/web/StudentStatusControllerTest.java @@ -1,8 +1,8 @@ package org.wise.vle.web; import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.easymock.EasyMockExtension; import org.easymock.TestSubject; diff --git a/src/test/java/org/wise/vle/web/wise5/NotificationControllerTest.java b/src/test/java/org/wise/vle/web/wise5/NotificationControllerTest.java index 9a40a2a643..9ab0596cc1 100644 --- a/src/test/java/org/wise/vle/web/wise5/NotificationControllerTest.java +++ b/src/test/java/org/wise/vle/web/wise5/NotificationControllerTest.java @@ -3,7 +3,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/org/wise/vle/web/wise5/teacher/TeacherWorkControllerTest.java b/src/test/java/org/wise/vle/web/wise5/teacher/TeacherWorkControllerTest.java index a526d7ecba..076de47fd1 100644 --- a/src/test/java/org/wise/vle/web/wise5/teacher/TeacherWorkControllerTest.java +++ b/src/test/java/org/wise/vle/web/wise5/teacher/TeacherWorkControllerTest.java @@ -4,7 +4,7 @@ import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.nio.file.AccessDeniedException; diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 8a64760ad2..2efa4bcb37 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -88,9 +88,9 @@ spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=create-drop spring.session.store-type=redis -spring.redis.host=localhost +spring.data.redis.host=localhost #spring.redis.password= # Login password of the redis server. -spring.redis.port=6379 +spring.data.redis.port=6379 spring.redis.pool.max.total=128 #spring.session.redis.flush-mode=on-save # Sessions flush mode. #spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. @@ -177,17 +177,12 @@ trustedAuthorAllowedProjectAssetContentTypes=text/html,application/javascript,ap ########## Optional Plugins ########## -### Google Open Id (log in with Google) ### +# OAuth2 Client Configuration for Google (dummy values for tests) +spring.security.oauth2.client.registration.google.client-id=test-client-id +spring.security.oauth2.client.registration.google.client-secret=test-client-secret +spring.security.oauth2.client.registration.google.scope=openid,email,profile +spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google -google.clientId= -google.clientSecret= - -google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token -google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth?prompt=select_account -google.redirectUri=http://localhost:8080/google-login -google.issuer=accounts.google.com -google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs -google.tokens.dir= ### Discourse Single Sign-On ### # discourse_url: URL to your Discourse.