diff --git a/embedded-tomcat/README.md b/embedded-tomcat/README.md
deleted file mode 100644
index 8ecfab9f..00000000
--- a/embedded-tomcat/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-Embedded Tomcat - integration testing war projects
-
-Moved from https://github.com/Opetushallitus/embedded-tomcat
\ No newline at end of file
diff --git a/embedded-tomcat/pom.xml b/embedded-tomcat/pom.xml
deleted file mode 100644
index 23b09033..00000000
--- a/embedded-tomcat/pom.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
- fi.vm.sade
- embedded-tomcat
- Embedded Tomcat runner for integration testing
- 1.2.1-SNAPSHOT
-
- 7.0.108
-
-
-
- commons-lang
- commons-lang
- 2.6
-
-
- commons-io
- commons-io
- 2.14.0
-
-
- org.apache.tomcat.embed
- tomcat-embed-core
- ${tomcat.version}
-
-
- org.apache.tomcat.embed
- tomcat-embed-logging-juli
- ${tomcat.version}
-
-
- org.apache.tomcat.embed
- tomcat-embed-jasper
- ${tomcat.version}
-
-
-
-
diff --git a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/EmbeddedTomcat.java b/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/EmbeddedTomcat.java
deleted file mode 100644
index cbb76fbb..00000000
--- a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/EmbeddedTomcat.java
+++ /dev/null
@@ -1,173 +0,0 @@
-package fi.vm.sade.integrationtest.tomcat;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletException;
-
-import org.apache.catalina.*;
-import org.apache.catalina.connector.Connector;
-import org.apache.catalina.startup.Tomcat;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-import fi.vm.sade.integrationtest.util.SpringProfile;
-import fi.vm.sade.integrationtest.util.PortChecker;
-
-public class EmbeddedTomcat {
- public final int port;
- public final int ajpPort;
- public final List apps = new ArrayList<>();
- private Tomcat tomcat;
-
- public EmbeddedTomcat(final int port, String moduleRoot, String contextPath) {
- this.port = port != 0 ? port : PortChecker.findFreeLocalPort();
- this.ajpPort = PortChecker.findFreeLocalPort();
- addWebApp(moduleRoot, contextPath);
- }
-
- public EmbeddedTomcat(final int port, final int ajpPort, String moduleRoot, String contextPath) {
- this.port = port != 0 ? port : PortChecker.findFreeLocalPort();
- this.ajpPort = ajpPort != 0 ? ajpPort : PortChecker.findFreeLocalPort();
- addWebApp(moduleRoot, contextPath);
- }
-
- public EmbeddedTomcat addWebApp(String moduleRoot, String contextPath) {
- apps.add(new WebAppConfig(moduleRoot, contextPath));
- return this;
- }
-
- public Server start() {
- if (tomcat == null) {
- try {
- this.tomcat = new Tomcat() {
- @Override
- public void start() throws LifecycleException {
- super.start();
- Runtime.getRuntime().addShutdownHook(new Thread("Tomcat work directory delete hook") {
- @Override
- public void run() {
- try {
- org.apache.commons.io.FileUtils.deleteDirectory(new File(basedir));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- });
- }
- };
- PortChecker.assertPortsAreFree(this.port, this.ajpPort);
- tomcat.setPort(this.port);
- for(WebAppConfig app : apps) {
- app.webappDirLocation = app.moduleRoot + "/src/main/webapp/";
- app.ctx = tomcat.addWebapp(app.contextPath, app.webappDirLocation);
- String webXml = getWebXml(app.moduleRoot);
- System.out.println("EmbeddedTomcat: starting " + app.contextPath + " from " + app.webappDirLocation + " with " + webXml);
- setInitialContext(app.moduleRoot, app.ctx);
- app.ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, webXml);
- }
- final Connector ajpConnector = new Connector("AJP/1.3");
- ajpConnector.setScheme("ajp");
- ajpConnector.setPort(this.ajpPort);
- tomcat.getService().addConnector(ajpConnector);
- tomcat.start();
- for(WebAppConfig app : apps) {
- if(!app.ctx.getState().isAvailable()) {
- tomcat.stop();
- tomcat.getServer().await();
- throw new RuntimeException("Tomcat context failed to start for " + app.contextPath + " at " + app.webappDirLocation);
- } else {
- System.out.println("EmbeddedTomcat: started " + app.contextPath + " from " + app.webappDirLocation);
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- return tomcat.getServer();
- }
-
- public Server getServer() {
- return tomcat.getServer();
- }
-
- public boolean appConfigIsEqual(EmbeddedTomcat currentlyRunning) {
- List currentlyRunningApps = currentlyRunning.apps;
- if(currentlyRunningApps.size() != apps.size()) {
- return false;
- }
- for (int i = 0; i < apps.size(); i++) {
- WebAppConfig webAppConfig = apps.get(i);
- WebAppConfig currentlyRunningConfig = currentlyRunningApps.get(i);
- if(!webAppConfig.contextPath.equals(currentlyRunningConfig.contextPath) || !webAppConfig.moduleRoot.equals(currentlyRunningConfig.moduleRoot)) {
- return false;
- }
- }
- return true;
- }
-
- public void stop() {
- try {
- tomcat.stop();
- } catch (LifecycleException e) {
- throw new RuntimeException(e);
- }
- }
-
- private String getWebXml(String moduleRoot) {
- if (SpringProfile.activeProfile().equals("it")) {
- // IT-profile: stubbed deps etc
- final String itProfileWebXml = moduleRoot + "/src/test/resources/it-profile-web.xml";
- if (new File(itProfileWebXml).exists()) return itProfileWebXml;
- }
- if (SpringProfile.activeProfile().equals("vagrant")) {
- // Vagrant-profile: use everything from vagrant
- final String vagrantProfileWebXml = moduleRoot + "/src/test/resources/vagrant-profile-web.xml";
- if (new File(vagrantProfileWebXml).exists()) return vagrantProfileWebXml;
- }
- // Other profile: just disable Spring security
- final String testWebXml = moduleRoot + "/src/test/resources/test-web.xml";
- if (new File(testWebXml).exists()) return testWebXml;
-
- final String defaultWebXml = moduleRoot + "/src/main/webapp/WEB-INF/web.xml";
- if (new File(defaultWebXml).exists()) return defaultWebXml;
-
- throw new RuntimeException("Could not find web.xml");
- }
-
- private void setInitialContext(String moduleRoot, Context webContext) {
- if (SpringProfile.activeProfile().equals("vagrant")) {
- final File vagrantContext = new File(moduleRoot + "/src/test/resources/vagrant-context.xml");
- if (vagrantContext.isFile()) {
- try {
- webContext.setConfigFile(vagrantContext.toURI().toURL());
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- @Override
- public String toString() {
- return ToStringBuilder.reflectionToString(this);
- }
-
- public class WebAppConfig {
- String moduleRoot;
- String contextPath;
- Context ctx;
- String webappDirLocation;
-
- WebAppConfig(String moduleRoot, String contextPath) {
- this.moduleRoot = moduleRoot;
- this.contextPath = contextPath;
- }
-
- public Context getContext() {
- return this.ctx;
- }
- }
-}
diff --git a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/SharedTomcat.java b/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/SharedTomcat.java
deleted file mode 100644
index 68e6b173..00000000
--- a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/tomcat/SharedTomcat.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package fi.vm.sade.integrationtest.tomcat;
-
-import fi.vm.sade.integrationtest.util.PortChecker;
-import fi.vm.sade.integrationtest.util.SpringProfile;
-import org.apache.catalina.Server;
-
-/**
- * Ensures that there is only one instance of webserver running.
- */
-public class SharedTomcat {
- private static EmbeddedTomcat shared;
-
- public final static int port = PortChecker.findFreeLocalPort();
-
- public static synchronized EmbeddedTomcat start(String moduleRoot, String contextPath) {
- create(moduleRoot, contextPath).start();
- return shared;
- }
-
- public static EmbeddedTomcat create(String moduleRoot, String contextPath) {
- SpringProfile.setProfile("it");
- return new EmbeddedTomcat(port, moduleRoot, contextPath){
- @Override
- public Server start() {
- synchronized (SharedTomcat.class) {
- if (shared != null && !shared.appConfigIsEqual(this)) {
- throw new IllegalStateException("Shared Tomcat already running with different contextPath or moduleRoot. Existing instance=" + shared);
- }
- if (shared == null) {
- shared = this;
- super.start();
- }
- return shared.getServer();
- }
- }
- };
- }
-}
diff --git a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/PortChecker.java b/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/PortChecker.java
deleted file mode 100644
index 840a28aa..00000000
--- a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/PortChecker.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package fi.vm.sade.integrationtest.util;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.util.Random;
-
-public class PortChecker {
-
- public static void assertPortsAreFree(Integer... ports) {
- for(int port: ports) {
- if(!isFreeLocalPort(port)) {
- throw new RuntimeException("TCP port is not free for localhost:" +port);
- }
- }
- }
-
- public final static boolean isFreeLocalPort(int port) {
- Socket socket = null;
- try {
- socket = new Socket("127.0.0.1", port);
- socket.close();
- } catch (IOException e) {
- return true;
- }
- return false;
- }
-
- public final static int findFreeLocalPort() {
- int port = new Random().nextInt(60000) + 1000;
- if (isFreeLocalPort(port)) {
- return port;
- } else {
- return findFreeLocalPort();
- }
- }
-}
diff --git a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/ProjectRootFinder.java b/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/ProjectRootFinder.java
deleted file mode 100644
index 25ec9f2c..00000000
--- a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/ProjectRootFinder.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package fi.vm.sade.integrationtest.util;
-
-import java.io.File;
-import java.io.IOException;
-
-public class ProjectRootFinder {
- public static File findProjectRoot() {
- try {
- return findRoot(new File(".").getCanonicalFile());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- private static File findRoot(final File currentDirectory) {
- if (!pomExists(currentDirectory) || parentPomExists(currentDirectory)) {
- return findRoot(currentDirectory.getParentFile());
- }
- return currentDirectory;
- }
-
- private static boolean parentPomExists(File currentDirectory) {
- final File parent = currentDirectory.getParentFile();
- if (parent != null) {
- return pomExists(parent) || parentPomExists(parent);
- }
- return false;
- }
-
- private static boolean pomExists(File currentDirectory) {
- return new File(currentDirectory, "pom.xml").exists();
- }
-}
\ No newline at end of file
diff --git a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/SpringProfile.java b/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/SpringProfile.java
deleted file mode 100644
index 13e83be4..00000000
--- a/embedded-tomcat/src/main/java/fi/vm/sade/integrationtest/util/SpringProfile.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package fi.vm.sade.integrationtest.util;
-
-public class SpringProfile {
- public final static String activeProfile() {
- return System.getProperty("spring.profiles.active", "default");
- }
-
- public static void setProfile(final String profile) {
- System.setProperty("spring.profiles.active", profile);
- }
-}
-
diff --git a/java-auth/pom.xml b/java-auth/pom.xml
deleted file mode 100644
index a99f1f26..00000000
--- a/java-auth/pom.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
- java-auth
- 0.4.2-SNAPSHOT
- jar
-
-
- org.slf4j
- slf4j-api
- 1.7.36
-
-
- fi.vm.sade.java-utils
- httpclient
- 1.0.1-SNAPSHOT
-
-
-
diff --git a/java-auth/src/main/java/fi/vm/sade/authorization/NotAuthorizedException.java b/java-auth/src/main/java/fi/vm/sade/authorization/NotAuthorizedException.java
deleted file mode 100644
index 26a5d75c..00000000
--- a/java-auth/src/main/java/fi/vm/sade/authorization/NotAuthorizedException.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package fi.vm.sade.authorization;
-
-public class NotAuthorizedException extends RuntimeException {
- public NotAuthorizedException() {
- super();
- }
-
- public NotAuthorizedException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public NotAuthorizedException(String message) {
- super(message);
- }
-
- public NotAuthorizedException(Throwable cause) {
- super(cause);
- }
-
- public String getErrorKey() {
- return NotAuthorizedException.class.getCanonicalName();
- }
-}
diff --git a/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationHierarchyAuthorizer.java b/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationHierarchyAuthorizer.java
deleted file mode 100644
index 70250b21..00000000
--- a/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationHierarchyAuthorizer.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package fi.vm.sade.authorization;
-
-import java.util.*;
-
-public class OrganizationHierarchyAuthorizer {
- public static final String ANY_ROLE = "*";
-
- private OrganizationOidProvider oidProvider;
-
-
- public OrganizationHierarchyAuthorizer(OrganizationOidProvider oidProvider) {
- this.oidProvider = oidProvider;
- }
-
- public void checkAccessToTargetOrParentOrganization(List userRoles, String targetOrganisationOid, String[] requiredRoles) throws NotAuthorizedException {
- if (requiredRoles == null || requiredRoles.length == 0) {
- throw new NotAuthorizedException("No required roles.");
- }
-
- List targetOrganisationAndParentsOids = oidProvider.getSelfAndParentOidsCached(targetOrganisationOid);
- if (targetOrganisationAndParentsOids == null || targetOrganisationAndParentsOids.size() == 0) {
- throw new NotAuthorizedException("Target organization and parents oids cannot be found.");
- }
-
- for (String role : requiredRoles) {
- for (String oid : targetOrganisationAndParentsOids) {
- for (String userRole : userRoles) {
- if (roleMatchesToAuthority(role, userRole) && authorityIsTargetedToOrganisation(userRole, oid)) {
- return;
- }
- }
- }
- }
- final String msg = "Not authorized! targetOrganisationAndParentsOids: " + targetOrganisationAndParentsOids + ", requiredRoles: " + Arrays.asList(requiredRoles) + ", userRoles: " + userRoles;
- throw new NotAuthorizedException(msg);
- }
-
- public void checkAccessToGivenRoles(List userRoles, String[] requiredRoles) throws NotAuthorizedException {
- if (requiredRoles == null || requiredRoles.length == 0) {
- throw new NotAuthorizedException("No required roles.");
- }
-
- for(String role: requiredRoles) {
- for(String authority : userRoles) {
- if(roleMatchesToAuthority(role, authority)) {
- return;
- }
- }
- }
-
- final String msg = "Not authorized! requiredRoles: " + Arrays.asList(requiredRoles) + ", userRoles: " + userRoles;
- throw new NotAuthorizedException(msg);
- }
-
- public static String getOrganizationTheUserHasPermissionTo(List userRoles, String... permissionCandidates) {
- List whatRoles = Arrays.asList(permissionCandidates);
- Set orgs = new HashSet();
- for (String userRole : userRoles) {
- if (!userRole.endsWith("READ") && !userRole.endsWith("READ_UPDATE") && !userRole.endsWith("CRUD")) {
- int x = userRole.lastIndexOf("_");
- if (x != -1) {
- String rolePart = userRole.substring(0, x);
- if (whatRoles.contains(rolePart)) {
- String orgPart = userRole.substring(x + 1);
- orgs.add(orgPart);
- }
- }
- }
- }
- if (orgs.isEmpty()) {
- return null;
- }
- if (orgs.size() > 1) {
- throw new RuntimeException("Not supported: user has role " + whatRoles + " to more than 1 organisaatios: " + orgs);
- }
- return orgs.iterator().next();
- }
-
- private static boolean roleMatchesToAuthority(String role, String authority) {
- if (ANY_ROLE.equals(role)) {
- return true;
- }
- role = stripRolePrefix(role);
- return authority.contains(role);
- }
-
- private static String stripRolePrefix(String role) {
- return role.replace("APP_", "").replace("ROLE_", "");
- }
-
- private static boolean authorityIsTargetedToOrganisation(String authority, String oid) {
- return authority.endsWith(oid);
- }
-
- public static OrganizationHierarchyAuthorizer createMockAuthorizer(final String parentOrg, final String[] childOrgs) {
- return new OrganizationHierarchyAuthorizer(new OrganizationOidProvider(){
- @Override
- public List getSelfAndParentOids(String organisaatioOid) {
- if (parentOrg.equals(organisaatioOid)) {
- return Arrays.asList(organisaatioOid);
- }
- if (Arrays.asList(childOrgs).contains(organisaatioOid)) {
- return Arrays.asList(organisaatioOid, parentOrg);
- }
- return new ArrayList();
- }
- });
- }
-}
diff --git a/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationOidProvider.java b/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationOidProvider.java
deleted file mode 100644
index 69fb7be1..00000000
--- a/java-auth/src/main/java/fi/vm/sade/authorization/OrganizationOidProvider.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package fi.vm.sade.authorization;
-
-import fi.vm.sade.javautils.httpclient.apache.ApacheOphHttpClient;
-import fi.vm.sade.javautils.httpclient.OphHttpClient;
-import fi.vm.sade.javautils.httpclient.OphHttpResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-public class OrganizationOidProvider {
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
- public static final int MAX_CACHE_SIZE = 10000;
-
- private String organisaatioServiceUrl;
- private String rootOrganisaatioOid;
- private String callerId;
-
- private static Map> cache = Collections.synchronizedMap(
- new LinkedHashMap>(MAX_CACHE_SIZE + 1, .75F, true) {
- public boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_CACHE_SIZE;
- }
- });
-
- protected OrganizationOidProvider() {}
-
- public OrganizationOidProvider(String rootOrganisaatioOid, String organisaatioServiceUrl, String callerId) {
- this.organisaatioServiceUrl = organisaatioServiceUrl;
- this.rootOrganisaatioOid = rootOrganisaatioOid;
- this.callerId = callerId;
- }
-
- public List getSelfAndParentOidsCached(String targetOrganisationOid) {
- String cacheKey = targetOrganisationOid;
- List cacheResult = cache.get(cacheKey);
- if (cacheResult == null) {
- cacheResult = getSelfAndParentOids(targetOrganisationOid);
- cache.put(cacheKey, cacheResult);
- }
- return cacheResult;
- }
-
- public List getSelfAndParentOids(String organisaatioOid) {
- try {
- String url = organisaatioServiceUrl + "/rest/organisaatio/" + organisaatioOid + "/parentoids";
- String result = httpGet(url, 200);
- return Arrays.asList(result.split("/"));
- } catch (Exception e) {
- LOGGER.warn("Failed to getSelfAndParentOids, exception: " + e.getMessage() + ", returning only rootOrganisaatioOid and organisaatioOid", e);
- return Arrays.asList(rootOrganisaatioOid, organisaatioOid);
- }
- }
-
- private String httpGet(String url, int expectedStatus) {
- OphHttpClient client = new OphHttpClient(ApacheOphHttpClient.createCustomBuilder().
- createClosableClient().
- setDefaultConfiguration(10000, 60).build(), "OrganisaatioOidProvider");
- client.setCallerId(callerId);
- return client.get(url).execute((OphHttpResponse response) -> {
- if(expectedStatus != response.getStatusCode()) {
- throw new RuntimeException("Failed to call '" + url + "', invalid status: " + response.getStatusCode());
- }
- return response.asText();
- });
- }
-}
diff --git a/java-cache/pom.xml b/java-cache/pom.xml
deleted file mode 100644
index d60f1384..00000000
--- a/java-cache/pom.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
-
- java-cache
- 0.1.0-SNAPSHOT
- jar
-
-
-
- junit
- junit
- 4.13.2
- test
-
-
-
diff --git a/java-cache/src/main/java/fi/vm/sade/security/SimpleCache.java b/java-cache/src/main/java/fi/vm/sade/security/SimpleCache.java
deleted file mode 100644
index b28fba0f..00000000
--- a/java-cache/src/main/java/fi/vm/sade/security/SimpleCache.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package fi.vm.sade.security;
-
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * @author Antti Salonen
- */
-public class SimpleCache {
-
- private SimpleCache() {
- }
-
- public static Map buildCache(final int MAX_CACHE_SIZE) {
- return Collections.synchronizedMap(new LinkedHashMap(MAX_CACHE_SIZE + 1, .75F, true) {
- // This method is called just after a new entry has been added
- public boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_CACHE_SIZE;
- }
- });
- }
-
-}
diff --git a/java-cache/src/test/java/fi/vm/sade/security/SimpleCacheTest.java b/java-cache/src/test/java/fi/vm/sade/security/SimpleCacheTest.java
deleted file mode 100644
index 5010013e..00000000
--- a/java-cache/src/test/java/fi/vm/sade/security/SimpleCacheTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package fi.vm.sade.security;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-public class SimpleCacheTest {
-
- int threadsDone = 0;
- int threads = 10;
- int maxCacheSize = 10000;
- Map> cache = SimpleCache.>buildCache(maxCacheSize);
-
- @Test
- public void testCache() throws InterruptedException {
- // add 1 entry
- cache.put("key_first", Arrays.asList("key_first"));
- // add MAX entries in threads
- for (int t = 0; t < threads; t++) {
- final int finalT = t;
- new Thread() {
- @Override
- public void run() {
- for (int i = 0; i < maxCacheSize / threads; i++) {
- String key = "key_" + (finalT * maxCacheSize / threads + i);
- cache.put(key, Arrays.asList(key));
- }
- threadsDone++;
- }
- }.start();
- }
- while (true) {
- Thread.sleep(100);
- if (threadsDone == threads) break;
- }
- // assert cache - first entry must be evicted
- Assert.assertTrue(cache.containsKey("key_0"));
- Assert.assertTrue(cache.containsKey("key_"+(9999)));
- Assert.assertFalse(cache.containsKey("key_first"));
- }
-
-}
diff --git a/java-cxf/pom.xml b/java-cxf/pom.xml
deleted file mode 100644
index 083c5ce6..00000000
--- a/java-cxf/pom.xml
+++ /dev/null
@@ -1,116 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
-
-
- java-cxf
- 0.4.2-SNAPSHOT
-
-
-
- 3.3.5
-
-
-
-
-
- org.jvnet.staxex
- stax-ex
- 1.8.3
-
-
- javax.xml.soap
- javax.xml.soap-api
- 1.4.0-b01
-
-
-
-
-
-
- junit
- junit
- 4.13.2
- test
-
-
- org.mortbay.jetty
- jetty
- 6.1.26
- test
-
-
- com.sun.jersey
- jersey-servlet
- 1.19.4
- test
-
-
- commons-codec
- commons-codec
- 1.15
- test
-
-
-
- org.apache.cxf
- cxf-core
- ${cxf.version}
-
-
- org.apache.cxf
- cxf-rt-rs-client
- ${cxf.version}
-
-
- org.ow2.asm
- asm
- 7.1
-
-
-
- commons-logging
- commons-logging
- 1.2
-
-
- commons-collections
- commons-collections
- 3.2.2
-
-
- commons-lang
- commons-lang
- 2.6
-
-
- org.slf4j
- slf4j-api
- 1.7.25
-
-
- org.slf4j
- slf4j-log4j12
- 1.7.25
- test
-
-
- org.apache.santuario
- xmlsec
- 1.4.6
-
-
- commons-logging
- commons-logging
-
-
-
-
-
-
diff --git a/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphCxfMessageUtil.java b/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphCxfMessageUtil.java
deleted file mode 100644
index aaebf319..00000000
--- a/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphCxfMessageUtil.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package fi.vm.sade.javautils.cxf;
-
-import org.apache.cxf.message.Message;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-public class OphCxfMessageUtil {
- public static List getHeader(Message message, String name) {
- Map> headers = getHeadersThatMayBeNull(message);
- return headers == null ? Collections.emptyList() : headers.getOrDefault(name, Collections.emptyList());
- }
-
- public static void addHeader(Message message, String name, String value) {
- resolveHeaders(message).put(name, Collections.singletonList(value));
- }
-
- public static void appendToHeader(Message message, String headerName, String valueToAppend, String separator) {
- Map> headers = resolveHeaders(message);
- List originalValues = headers.getOrDefault(headerName, new LinkedList<>());
- if (originalValues.isEmpty()) {
- headers.put(headerName, Collections.singletonList(valueToAppend));
- return;
- }
- headers.put(headerName, originalValues.stream().map(original -> {
- if (original == null) {
- return valueToAppend;
- } else {
- return original + separator + valueToAppend;
- }
- }).collect(Collectors.toList()));
- }
-
- @SuppressWarnings("unchecked")
- private static Map> resolveHeaders(Message message) {
- Map> outHeaders = getHeadersThatMayBeNull(message);
- if (outHeaders == null) {
- outHeaders = new HashMap<>();
- message.put(Message.PROTOCOL_HEADERS, outHeaders);
- }
- return outHeaders;
- }
-
- private static Map> getHeadersThatMayBeNull(Message message) {
- return (Map>) message.get(Message.PROTOCOL_HEADERS);
- }
-}
diff --git a/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptor.java b/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptor.java
deleted file mode 100644
index d99693e6..00000000
--- a/java-cxf/src/main/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptor.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package fi.vm.sade.javautils.cxf;
-
-import org.apache.cxf.interceptor.Fault;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.phase.AbstractPhaseInterceptor;
-import org.apache.cxf.phase.Phase;
-
-/**
- * Interceptor for adding Caller-Id header to all requests. Interceptor must be registered for all
- * services, in xml like following:
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- */
-public class OphRequestHeadersCxfInterceptor extends AbstractPhaseInterceptor {
- private final String callerId;
-
- public OphRequestHeadersCxfInterceptor(String callerId) {
- // Intercept before sending
- super(Phase.PRE_PROTOCOL);
- if (callerId == null) {
- throw new IllegalArgumentException("Missing callerId. Set callerId for OphRequestHeadersCxfInterceptor.");
- }
- this.callerId = callerId;
- }
-
- /**
- * Invoked on in- and outbound (if interceptor is registered for both, which makes no sense).
- */
- public void handleMessage(Message message) throws Fault {
- this.handleOutbound(message.getExchange().getOutMessage());
- }
-
- /**
- * Invoked on outbound (request).
- * @param message
- * @throws Fault
- */
- public void handleOutbound(Message message) throws Fault {
- OphCxfMessageUtil.addHeader(message, "Caller-Id", callerId);
- OphCxfMessageUtil.addHeader(message, "CSRF", "CSRF");
- OphCxfMessageUtil.appendToHeader(message, "Cookie", "CSRF=CSRF", "; ");
- }
-
- public String getCallerId() {
- return callerId;
- }
-}
diff --git a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/JettyJersey.java b/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/JettyJersey.java
deleted file mode 100644
index 09f8ff9c..00000000
--- a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/JettyJersey.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package fi.vm.sade.javautils.cxf;
-
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.util.Random;
-
-import org.mortbay.jetty.Server;
-import org.mortbay.jetty.servlet.Context;
-import org.mortbay.jetty.servlet.ServletHolder;
-
-/**
- * Helper class to start embedded jetty + jersey for tests.
- *
- * @author Antti Salonen
- */
-public class JettyJersey {
- static Server server;
- static int port;
-
- public static void startServer(String packageContainingJerseyRestResources, String jerseyFilterClasses) throws Exception {
-
- port = findFreeLocalPort();
-
- System.setProperty("cas_key", getUrl("testing"));
- System.setProperty("cas_service", getUrl("/httptest"));
- System.setProperty("web.url.cas", getUrl("/mock_cas/cas"));
-
- server = new Server(port);
- Context root = new Context(server, "/", Context.SESSIONS);
- ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
- servletHolder.setInitOrder(1); // have to be set so that jersey will load on startup (otherwise might cause problems in cache timeout tests..)
- servletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
- servletHolder.setInitParameter("com.sun.jersey.config.property.packages", packageContainingJerseyRestResources);
-// servletHolder.setInitParameter("com.sun.jersey.config.feature.Debug", "true");
-// servletHolder.setInitParameter("com.sun.jersey.config.feature.Trace", "true");
-// servletHolder.setInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.LoggingFilter");
- servletHolder.setInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", /*"com.sun.jersey.api.container.filter.LoggingFilter,"*/""+(jerseyFilterClasses != null ? jerseyFilterClasses : ""));
- root.addServlet(servletHolder, "/*");
- server.start();
- System.out.println("jetty started at port "+port);
- }
-
- public static void stopServer() {
- try {
- server.stop();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static int getPort() {
- return port;
- }
-
- public static String getUrl(String url) {
- return "http://localhost:"+ getPort()+url;
- }
-
- public final static boolean isFreeLocalPort(int port) {
- Socket socket = null;
- try {
- socket = new Socket("127.0.0.1", port);
- socket.close();
- } catch (IOException e) {
- return true;
- }
- return false;
- }
-
- public final static int findFreeLocalPort() {
- int port = new Random().nextInt(60000) + 1000;
- if (isFreeLocalPort(port)) {
- return port;
- } else {
- return findFreeLocalPort();
- }
- }
-}
diff --git a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/MirrorMockResource.java b/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/MirrorMockResource.java
deleted file mode 100644
index 19ca912c..00000000
--- a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/MirrorMockResource.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package fi.vm.sade.javautils.cxf;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import java.io.StringWriter;
-import java.util.Enumeration;
-
-/**
- * Mock resource for mirroring request for testing purposes.
- * @author Jouni Stam
- */
-@Path("/mirror")
-public class MirrorMockResource {
-
- /**
- * Returns request headers in the response body.
- * @param request
- * @return
- */
- @Path("/headers")
- @GET
- @Produces("text/plain")
- public Response mirrorHeaders(@Context HttpServletRequest request) {
- StringWriter out = new StringWriter();
- @SuppressWarnings("unchecked")
- Enumeration headerNames = request.getHeaderNames();
- while(headerNames.hasMoreElements()) {
- String one = headerNames.nextElement();
- out.write(one + ": " + request.getHeader(one) + "\n");
- }
-
- return Response.ok(out.toString()).build();
- }
-}
\ No newline at end of file
diff --git a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptorTest.java b/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptorTest.java
deleted file mode 100644
index 22beca88..00000000
--- a/java-cxf/src/test/java/fi/vm/sade/javautils/cxf/OphRequestHeadersCxfInterceptorTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package fi.vm.sade.javautils.cxf;
-
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.message.Message;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.ws.rs.core.MediaType;
-import java.io.IOException;
-import java.io.InputStream;
-public class OphRequestHeadersCxfInterceptorTest {
- private static final String CALLER_ID = "1.2.246.562.10.00000000001.java-cxf.TESTCLIENT";
- private String unprotectedTargetUrl = "/mirror/headers";
- private final OphRequestHeadersCxfInterceptor interceptor = createInterceptor();
-
- @Before
- public void setUp() throws Exception {
- JettyJersey.startServer("fi.vm.sade.javautils.cxf", null);
- }
-
- @After
- public void tearDown() {
- JettyJersey.stopServer();
- }
-
- @Test
- public void testCallerIdInsertion() throws IOException {
- String response = IOUtils.toString((InputStream) createClient(this.unprotectedTargetUrl, interceptor).get().getEntity());
- assertContains(response, "Caller-Id: " + CALLER_ID, "CSRF: CSRF", "Cookie: CSRF=CSRF");
- }
-
- @Test
- public void testMultipleCookieValues() throws IOException {
- WebClient client = createClient(this.unprotectedTargetUrl, interceptor)
- .header("Cookie", "X-Foo=baar; X-Wing=Destroyer");
- String response = IOUtils.toString((InputStream) client.get().getEntity());
- assertContains(response, "Caller-Id: " + CALLER_ID, "CSRF: CSRF", "Cookie: X-Foo=baar; X-Wing=Destroyer; CSRF=CSRF");
- }
-
- @Test
- public void clientWithNoHeadersInitiallyWorks() throws IOException {
- WebClient client = WebClient.create(getUrl(this.unprotectedTargetUrl));
- client.removeAllHeaders();
- WebClient.getConfig(client).getOutInterceptors().add(interceptor);
- String response = IOUtils.toString((InputStream) client.get().getEntity());
- assertContains(response, "Caller-Id: " + CALLER_ID, "CSRF: CSRF", "Cookie: CSRF=CSRF");
- }
-
- private static void assertContains(String from, String... args) {
- for(String arg: args) {
- Assert.assertTrue("String "+arg+" not found from: "+ from, from.contains(arg));
- }
- }
-
- private WebClient createClient(String url, OphRequestHeadersCxfInterceptor interceptor) {
- WebClient c = WebClient.create(getUrl(url)).accept(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON);
- // Add only as OUT interceptor
- WebClient.getConfig(c).getOutInterceptors().add(interceptor);
- return c;
- }
-
- private OphRequestHeadersCxfInterceptor createInterceptor() {
- return new OphRequestHeadersCxfInterceptor<>(CALLER_ID);
- }
-
- public static String getUrl(String url) {
- return JettyJersey.getUrl(url);
- }
-}
diff --git a/java-cxf/src/test/resources/log4j.properties b/java-cxf/src/test/resources/log4j.properties
deleted file mode 100644
index cd1cba6a..00000000
--- a/java-cxf/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,11 +0,0 @@
-# Root logger option
-log4j.rootLogger=INFO, CONSOLE
-
-# Direct log messages to stdout
-log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
-log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
-# Package specific logging configurations
-log4j.logger.org.springframework=INFO
-log4j.logger.fi.vm=DEBUG
diff --git a/java-legacy-cas/pom.xml b/java-legacy-cas/pom.xml
deleted file mode 100644
index c4c2f21a..00000000
--- a/java-legacy-cas/pom.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
- java-legacy-cas
- 1.0.1-SNAPSHOT
- jar
-
-
- 17
- 17
-
-
-
-
- org.slf4j
- slf4j-api
- 1.7.30
-
-
- fi.vm.sade.java-utils
- httpclient
- 1.0.1-SNAPSHOT
-
-
- org.apache.commons
- commons-lang3
- 3.17.0
-
-
-
diff --git a/java-legacy-cas/src/main/java/fi/vm/sade/javautils/cas/CasClient.java b/java-legacy-cas/src/main/java/fi/vm/sade/javautils/cas/CasClient.java
deleted file mode 100644
index d141dd0f..00000000
--- a/java-legacy-cas/src/main/java/fi/vm/sade/javautils/cas/CasClient.java
+++ /dev/null
@@ -1,226 +0,0 @@
-package fi.vm.sade.javautils.cas;
-
-import static fi.vm.sade.javautils.httpclient.OphHttpClient.FORM_URLENCODED;
-import static fi.vm.sade.javautils.httpclient.OphHttpClient.UTF8;
-
-import fi.vm.sade.javautils.httpclient.OphHttpClient;
-import fi.vm.sade.javautils.httpclient.OphHttpResponse;
-import fi.vm.sade.javautils.httpclient.OphRequestParameters;
-import fi.vm.sade.javautils.httpclient.apache.ApacheOphHttpClient;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.http.cookie.Cookie;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-/**
- * An example Java client to authenticate against CAS using REST services.
- * Please ensure you have followed the necessary setup found on the wiki.
- *
- * @author Antti Salonen
- * @author jesse lauren farinacci
- * @since 3.4.2
- * @Deprecated Only used by Hakuapp. To be removed
- */
-@Deprecated
-public final class CasClient {
- public static final String CAS_URL_SUFFIX = "/v1/tickets";
- public static final String SERVICE_URL_SUFFIX = "/j_spring_cas_security_check";
- private static final Logger logger = LoggerFactory.getLogger(CasClient.class);
-
- private CasClient() {
- // static-only access
- }
-
- /**
- * get cas service ticket, throws runtime exception if fails
- */
- public static String getTicket(String server, final String username, final String password, String service) {
- return getTicket(server, username, password, service, true);
- }
-
- /**
- * get cas service ticket, throws runtime exception if fails
- */
- public static String getTicket(String server, final String username, final String password, String service, boolean addSuffix) {
-
- logger.debug("getTicket for server:{}, username:{}, service::{} ", server, username, service);
-
- notNull(server, "server must not be null");
- notNull(username, "username must not be null");
- notNull(password, "password must not be null");
- notNull(service, "service must not be null");
-
- server = checkUrl(server, CAS_URL_SUFFIX);
- if (addSuffix) {
- service = checkUrl(service, SERVICE_URL_SUFFIX);
- }
-
- try (OphHttpClient client = new OphHttpClient(ApacheOphHttpClient.createCustomBuilder().
- createClosableClient().
- setDefaultConfiguration(10000, 60).build(), "CasClient")) {
- return getServiceTicket(server, username, password, service, client);
- }
- }
-
- public static Cookie initServiceSession(String casServiceSessionInitUrl, String serviceTicket, String cookieName) {
- ApacheOphHttpClient apacheClient = ApacheOphHttpClient.createCustomBuilder().createClosableClient().setDefaultConfiguration(10000, 60).build();
- try (OphHttpClient client = new OphHttpClient(apacheClient, "CasClient")) {
- return client.get(casServiceSessionInitUrl + "?" + "ticket=" + serviceTicket).skipResponseAssertions().execute(r -> {
- for (Cookie cookie : apacheClient.getCookieStore().getCookies()) {
- if (cookieName.equals(cookie.getName())) {
- return cookie;
- }
- }
- throw new RuntimeException("failed to init session to target service, response code: " + r.getStatusCode() + ", casServiceSessionInitUrl: " + casServiceSessionInitUrl + ", serviceTicket: " + serviceTicket);
- });
- }
- }
-
-
- private static String getServiceTicket(final String server, String username, String password, final String service, OphHttpClient client) {
- final String ticketGrantingTicket = getTicketGrantingTicket(server, username, password, client);
-
- logger.debug("getServiceTicket: server:'{}', ticketGrantingTicket:'{}', service:'{}'", server, ticketGrantingTicket, service);
-
- try {
- return client.post(server + "/" + ticketGrantingTicket).
- dataWriter(FORM_URLENCODED, UTF8, out -> OphHttpClient.formUrlEncodedWriter(out).param("service", service)).
- skipResponseAssertions().execute(r -> {
- final String response = r.asText();
- printTraceResponse(r, response);
- switch (r.getStatusCode()) {
- case 200:
- logger.debug("serviceTicket found: {}", response);
- return response;
- default:
- logger.warn("Invalid response code ({}) from CAS server!", r.getStatusCode());
- logger.info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
- throw new RuntimeException("failed to get CAS service ticket, response code: " + r.getStatusCode() + ", server: " + server + ", tgt: " + ticketGrantingTicket + ", service: " + service);
- }
- });
- } catch (final Exception e) {
- throw new RuntimeException("failed to get CAS service ticket, server: " + server + ", tgt: " + ticketGrantingTicket + ", service: " + service + ", cause: " + e, e);
- }
- }
-
- private static String getTicketGrantingTicket(final String server, final String username, final String password, OphHttpClient client) {
- logger.debug("getTicketGrantingTicket: server:'{}', user:'{}'", new Object[]{server, username});
-
- //username=battags&password=password&additionalParam1=paramvalue
-
- /*
- Response example:
-
- Status : 201
- URI: http://centosx/cas/v1/tickets
- Request Headers: 4
- User-Agent = Jakarta Commons-HttpClient/3.1
- Host = centosx
- Content-Length = 40
- Content-Type = application/x-www-form-urlencoded
- Response Path: /cas/v1/tickets
- Response Headers: 9
- Date = Fri, 13 Dec 2013 00:12:37 GMT
- Server = Noelios-Restlet-Engine/1.1..1
- Location = http://centosx/cas/v1/tickets/TGT-14-VW7KiAZdkqqO27ysCvd9rArUfnk0SLkXdifMzywUtlI4A7mdgg-cas.centosx
- Accept-Ranges = bytes
- Content-Type = text/html;charset=ISO-8859-1
- Content-Length = 430
- Cache-Control = max-age=0, public
- Expires = Fri, 13 Dec 2013 00:12:37 GMT
- Connection = close
- Cookies: 0
- Response Text:
-
- 201 The request has been fulfilled and resulted in a new resource being created
- TGT Created
-
-
- */
-
- try {
- return client.post(server)
- .dataWriter(FORM_URLENCODED, UTF8, out -> OphHttpClient.formUrlEncodedWriter(out)
- .param("username", username)
- .param("password", password))
- .skipResponseAssertions()
- .execute(r -> {
- switch (r.getStatusCode()) {
- case 201: {
- List locationHeaders = r.getHeaderValues("Location");
- logger.debug("locationHeader: " + locationHeaders);
- final String response = r.asText();
- printTraceResponse(r, response);
- if (locationHeaders != null && locationHeaders.size() == 1) {
- String responseLocation = locationHeaders.get(0);
- String ticket = StringUtils.substringAfterLast(responseLocation, "/");
- logger.debug("-> ticket: " + ticket);
- return ticket;
- }
- throw new RuntimeException("Successful ticket granting request, but no ticket found! server: " + server + ", user: " + username);
- }
- default: {
- throw new RuntimeException("Invalid response code from CAS server: " + r.getStatusCode() + ", server: " + server + ", user: " + username);
- }
- }
- });
- } catch (final Exception e) {
- throw new RuntimeException("error getting TGT, server: " + server + ", user: " + username + ", exception: " + e, e);
- }
- }
-
- private static void notNull(final Object object, final String message) {
- if (object == null) {
- throw new IllegalArgumentException(message);
- }
- }
-
- private static String checkUrl(String url, final String suffix) {
- logger.debug("url: " + url);
- url = url.trim();
- url = url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
- if (!url.endsWith(suffix)) {
- url += suffix;
- }
- logger.debug("-> fixed url: " + url);
- return url;
- }
-
- private static void printTraceResponse(final OphHttpResponse response, final String responseTxt) {
-
- if (!logger.isTraceEnabled()) return;
-
- OphRequestParameters requestParameters = response.getRequestParameters();
-
- logger.debug("\n");
- logger.debug("Status : " + response.getStatusCode());
- logger.debug("URI: " + requestParameters.url);
- logger.debug("Request Headers: " + requestParameters.headers.size());
-
- for (String headerName : requestParameters.headers.keySet()) {
- for (String headerValue : requestParameters.headers.get(headerName)) {
- logger.debug(" " + headerName + " = " + headerValue);
- }
- }
-
- logger.debug("Response Path: " + requestParameters.url);
- logger.debug("Response Headers: " + response.getHeaderKeys().size());
-
- for (String headerName : response.getHeaderKeys()) {
- for (String headerValue : response.getHeaderValues(headerName)) {
- logger.debug(" " + headerName + " = " + headerValue);
- }
- }
-
- logger.debug("Response Text: ");
- logger.debug(responseTxt);
- logger.debug("\n");
- }
-
-}
diff --git a/java-poi/pom.xml b/java-poi/pom.xml
deleted file mode 100644
index 1b5ca209..00000000
--- a/java-poi/pom.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
-
-
- 4.1.2
-
-
- java-poi
- 2.0.1-SNAPSHOT
-
-
- junit
- junit
- 4.13.2
- test
-
-
- org.apache.poi
- poi
- ${poi.version}
-
-
- org.apache.poi
- poi-ooxml
- ${poi.version}
-
-
- org.apache.commons
- commons-lang3
- 3.12.0
-
-
-
diff --git a/java-poi/src/main/java/fi/vm/sade/javautils/poi/OphCellStyles.java b/java-poi/src/main/java/fi/vm/sade/javautils/poi/OphCellStyles.java
deleted file mode 100644
index 8c8a1384..00000000
--- a/java-poi/src/main/java/fi/vm/sade/javautils/poi/OphCellStyles.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package fi.vm.sade.javautils.poi;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.poi.ss.usermodel.*;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.poi.ss.usermodel.CellType.*;
-
-public class OphCellStyles {
- private static final List cellTypesWithoutDangerousContent = Arrays.asList(NUMERIC, BOOLEAN, ERROR);
- private final CellStyle quotePrefixStyle;
- private final CellStyle unsafeStyle;
-
- public OphCellStyles(Workbook workbook) {
- this(workbook.createCellStyle(), workbook.createCellStyle());
- }
-
- protected OphCellStyles(CellStyle quotePrefixStyle, CellStyle unsafeStyle) {
- this.quotePrefixStyle = quotePrefixStyle;
- quotePrefixStyle.setQuotePrefixed(true);
- this.unsafeStyle = unsafeStyle;
- }
-
- public Cell apply(Cell cell) {
- if (FORMULA.equals(cell.getCellTypeEnum())) {
- throw new IllegalArgumentException("Are you sure you want to create a " + FORMULA + " cell? " + cell);
- }
- if (cellTypesWithoutDangerousContent.contains(cell.getCellTypeEnum())) {
- cell.setCellStyle(unsafeStyle);
- } else {
- String value = cell.getStringCellValue();
- if (StringUtils.startsWithAny(value, "=", "@", "-", "+")) {
- cell.setCellStyle(quotePrefixStyle);
- } else {
- cell.setCellStyle(unsafeStyle);
- }
- }
- return cell;
- }
-
- public Row apply(Row row) {
- row.setRowStyle(unsafeStyle); // This should affect only new cells when workbook is created, not override single cell styles
- return row;
- }
-
- public void visit(Consumer visitor) {
- visitor.accept(quotePrefixStyle);
- visitor.accept(unsafeStyle);
- }
-
- public CellStyle getQuotePrefixStyle() {
- return quotePrefixStyle;
- }
-
- public CellStyle getUnsafeStyle() {
- return unsafeStyle;
- }
-}
diff --git a/java-poi/src/test/java/fi/vm/sade/javautils/OphCellStylesTest.java b/java-poi/src/test/java/fi/vm/sade/javautils/OphCellStylesTest.java
deleted file mode 100644
index 4354a554..00000000
--- a/java-poi/src/test/java/fi/vm/sade/javautils/OphCellStylesTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package fi.vm.sade.javautils;
-
-import fi.vm.sade.javautils.poi.OphCellStyles;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.CellType;
-import org.junit.Assert;
-import org.junit.Test;
-
-import static org.apache.poi.ss.usermodel.HorizontalAlignment.*;
-
-public class OphCellStylesTest {
- private HSSFWorkbook workbook = new HSSFWorkbook();
- private OphCellStyles cellStyles = new OphCellStyles(workbook);
- private HSSFSheet sheet = workbook.createSheet();
- private HSSFRow row = sheet.createRow(1);
-
- @Test
- public void cellsWithDangerousContentGetQuotePrefixes() {
- HSSFCell cell = row.createCell(1);
- cell.setCellValue("=1+2");
- cellStyles.apply(cell);
- Assert.assertTrue(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellValue("@[1]");
- cellStyles.apply(cell);
- Assert.assertTrue(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellValue("+1");
- cellStyles.apply(cell);
- Assert.assertTrue(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellValue("-1");
- cellStyles.apply(cell);
- Assert.assertTrue(cell.getCellStyle().getQuotePrefixed());
- }
-
- @Test
- public void cellsWithPlainContentDoNotGetQuotePrefixes() {
- HSSFCell cell = row.createCell(1);
- cell.setCellValue("1");
- cellStyles.apply(cell);
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellValue("Dog");
- cellStyles.apply(cell);
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellValue("/hello");
- cellStyles.apply(cell);
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
- }
-
- @Test
- public void propertiesCanBeSetToBothStylesAtSameTime() {
- HSSFCell safeCell = row.createCell(2);
- safeCell.setCellValue("Hello");
- HSSFCell dangerousCell = row.createCell(3);
- dangerousCell.setCellValue("=1+2");
-
- Assert.assertEquals(GENERAL, safeCell.getCellStyle().getAlignmentEnum());
- Assert.assertEquals(GENERAL, dangerousCell.getCellStyle().getAlignmentEnum());
-
- cellStyles.visit(s -> s.setAlignment(LEFT));
-
- cellStyles.apply(safeCell);
- cellStyles.apply(dangerousCell);
-
- Assert.assertEquals(LEFT, safeCell.getCellStyle().getAlignmentEnum());
- Assert.assertEquals(LEFT, dangerousCell.getCellStyle().getAlignmentEnum());
- }
-
- @Test
- public void numericAndOtherNonTextCellsUseUnsafeStyle() {
- cellStyles.visit(s -> s.setAlignment(LEFT));
- HSSFCell cell = row.createCell(2);
-
- cell.setCellType(CellType.NUMERIC);
- cellStyles.apply(cell);
- Assert.assertEquals(LEFT, cell.getCellStyle().getAlignmentEnum());
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellType(CellType.BOOLEAN);
- cellStyles.apply(cell);
- Assert.assertEquals(LEFT, cell.getCellStyle().getAlignmentEnum());
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellType(CellType.BLANK);
- cellStyles.apply(cell);
- Assert.assertEquals(LEFT, cell.getCellStyle().getAlignmentEnum());
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
-
- cell.setCellType(CellType.ERROR);
- cellStyles.apply(cell);
- Assert.assertEquals(LEFT, cell.getCellStyle().getAlignmentEnum());
- Assert.assertFalse(cell.getCellStyle().getQuotePrefixed());
- }
-
- @Test
- public void settingRowStyleDoesNotOverrideSingleCellStyles() {
- cellStyles.visit(s -> s.setAlignment(LEFT));
- HSSFCell cell = row.createCell(2);
- cellStyles.apply(cell);
-
- OphCellStyles rowStyles = new OphCellStyles(workbook);
- rowStyles.visit(rs -> rs.setAlignment(RIGHT));
- rowStyles.apply(row);
-
- Assert.assertEquals(LEFT, cell.getCellStyle().getAlignmentEnum());
-
- HSSFCell cell2 = row.createCell(2);
- Assert.assertEquals(GENERAL, cell2.getCellStyle().getAlignmentEnum());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void creatingFormulaCellsIsNotSupported() {
- HSSFCell cell = row.createCell(2);
- cell.setCellType(CellType.FORMULA);
- cellStyles.apply(cell);
- }
-}
diff --git a/legacy-caching-rest-client/pom.xml b/legacy-caching-rest-client/pom.xml
deleted file mode 100644
index 08e895c2..00000000
--- a/legacy-caching-rest-client/pom.xml
+++ /dev/null
@@ -1,207 +0,0 @@
-
-
-
- java-utils
- fi.vm.sade.java-utils
- 0.3.0-SNAPSHOT
-
- 4.0.0
-
- legacy-caching-rest-client
- 0.6.1-SNAPSHOT
-
-
-
-
- org.apache.httpcomponents
- httpcore
- 4.4.14
-
-
- commons-httpclient
- commons-httpclient
- 3.1
-
-
- org.slf4j
- slf4j-api
- 2.0.0-alpha1
-
-
- com.google.code.gson
- gson
- 2.8.6
-
-
- commons-io
- commons-io
- 2.8.0
-
-
- commons-codec
- commons-codec
- 1.15
-
-
- commons-logging
- commons-logging
- 1.2
-
-
- org.apache.cxf
- cxf-rt-frontend-jaxrs
- 3.4.2
- test
-
-
- org.apache.cxf
- cxf-rt-rs-client
- 3.4.2
- test
-
-
- org.springframework
- spring-beans
- 5.3.5
-
-
- org.springframework
- spring-core
- 5.3.5
-
-
- org.springframework
- spring-aop
- 5.3.5
-
-
- org.springframework
- spring-web
- 5.3.5
-
-
- org.apache.cxf
- cxf-core
- 3.4.2
-
-
-
-
-
-
-
- fi.vm.sade.java-utils
- java-legacy-cas
- 0.5.1-SNAPSHOT
-
-
- org.apache.cxf
- cxf-core
-
-
- fi.vm.sade.java-utils
- legacy-cxf-cas
- 0.6.0-SNAPSHOT
-
-
- org.apache.cxf
- cxf-common-utilities
-
-
-
-
-
- org.apache.httpcomponents
- httpcore
-
-
- commons-httpclient
- commons-httpclient
-
-
- commons-io
- commons-io
-
-
- org.slf4j
- slf4j-api
-
-
- com.google.code.gson
- gson
-
-
- junit
- junit
- 4.13.2
- test
-
-
- org.apache.cxf
- cxf-rt-frontend-jaxrs
- 3.4.2
- test
-
-
- org.apache.cxf
- cxf-rt-rs-client
- 3.4.2
- test
-
-
- org.springframework
- spring-core
- 5.3.5
- test
-
-
- org.slf4j
- slf4j-log4j12
- 2.0.0-alpha1
- test
-
-
- log4j
- log4j
- 1.2.17
- test
-
-
-
- org.mortbay.jetty
- jetty
- 6.1.26
- test
-
-
- com.sun.jersey
- jersey-servlet
- 1.19.4
- test
-
-
- commons-codec
- commons-codec
- test
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
- 3.2.0
-
-
-
- test-jar
-
-
-
-
-
-
-
diff --git a/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClient.java b/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClient.java
deleted file mode 100644
index 348b224b..00000000
--- a/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClient.java
+++ /dev/null
@@ -1,764 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import static org.apache.commons.httpclient.HttpStatus.SC_BAD_REQUEST;
-import static org.apache.commons.httpclient.HttpStatus.SC_FORBIDDEN;
-import static org.apache.commons.httpclient.HttpStatus.SC_INTERNAL_SERVER_ERROR;
-import static org.apache.commons.httpclient.HttpStatus.SC_NOT_FOUND;
-import static org.apache.commons.httpclient.HttpStatus.SC_UNAUTHORIZED;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonSyntaxException;
-
-import fi.vm.sade.javautils.cas.CasClient;
-import fi.vm.sade.javautils.legacy_cxf_cas.PERA;
-import fi.vm.sade.javautils.legacy_cxf_cas.ui.portlet.security.ProxyAuthenticator;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.io.IOUtils;
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpVersion;
-import org.apache.http.ProtocolException;
-import org.apache.http.client.CookieStore;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpDelete;
-import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpPut;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.client.utils.URIBuilder;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.DefaultHttpResponseFactory;
-import org.apache.http.impl.NoConnectionReuseStrategy;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.client.DefaultRedirectStrategy;
-import org.apache.http.impl.client.RedirectLocations;
-import org.apache.http.impl.conn.PoolingClientConnectionManager;
-import org.apache.http.impl.conn.SchemeRegistryFactory;
-import org.apache.http.impl.cookie.BasicClientCookie;
-import org.apache.http.message.BasicStatusLine;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.BasicHttpContext;
-import org.apache.http.protocol.HttpContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Type;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.charset.Charset;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Simple http client, that allows doing GETs to REST-resources so that http cache headers are respected.
- * Just a lightweight wrapper on top of apache commons-http and commons-http-cache.
- * Use get -method to do requests.
- *
- * Service-as-a-user authentication: set webCasUrl/casService/username/password
- *
- * Proxy authentication: set useProxyAuthentication=true + casService
- */
-public class CachingRestClient implements HealthChecker {
-
- public static final String WAS_REDIRECTED_TO_CAS = "redirected_to_cas";
- public static final int DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5min
- private static final Charset UTF8 = Charset.forName("UTF-8");
- private static final long DEFAULT_CONNECTION_TTL_SEC = 60; // infran palomuuri katkoo monta minuuttia makaavat connectionit
- public static final String CAS_SECURITY_TICKET = "CasSecurityTicket";
- private static final String CSRF = "CachingRestClient";
- private static final String CACHE_RESPONSE_STATUS = "http.cache.response.status"; //CachingHttpClient.CACHE_RESPONSE_STATUS
- protected static Logger logger = LoggerFactory.getLogger(CachingRestClient.class);
- private static ThreadLocal df1 = new ThreadLocal(){
- protected DateFormat initialValue() {
- return new SimpleDateFormat("yyyy-MM-dd HH:mm");
- }
- };
- private static ThreadLocal df2 = new ThreadLocal(){
- @Override
- protected SimpleDateFormat initialValue() {
- return new SimpleDateFormat("yyyy-MM-dd");
- }
- };
- private boolean reuseConnections = true;
-
- private HttpClient cachingClient;
- private ThreadLocal localContext = new ThreadLocal(){
- @Override
- protected HttpContext initialValue() {
- return new BasicHttpContext();
- }
- };
- //private HttpResponse response;
- private Object cacheStatus; //used in tests
- private Gson gson;
-
- private String webCasUrl;
- private String username;
- private String password;
- private String casService;
- protected String serviceAsAUserTicket;
- private ProxyAuthenticator proxyAuthenticator;
- private boolean useProxyAuthentication = false;
- @Value("${auth.mode:cas}")
- private String proxyAuthMode;
- private String requiredVersionRegex;
- private final int timeoutMs;
- private final String callerId;
- private boolean allowUrlLogging;
- private HashMap csrfCookiesCreateForHost = new HashMap();
- private final CookieStore cookieStore;
-
- public CachingRestClient(String callerId) {
- this(callerId, DEFAULT_TIMEOUT_MS, DEFAULT_CONNECTION_TTL_SEC);
- }
-
- public CachingRestClient(String callerId, int timeoutMs) {
- this(callerId, timeoutMs, DEFAULT_CONNECTION_TTL_SEC);
- }
-
- public CachingRestClient(String callerId, int timeoutMs, long connectionTimeToLiveSec) {
- this(callerId, timeoutMs, connectionTimeToLiveSec, true);
- }
-
- public CachingRestClient(String callerId, int timeoutMs, long connectionTimeToLiveSec, boolean allowUrlLogging) {
- this.callerId = callerId;
- this.timeoutMs = timeoutMs;
- this.allowUrlLogging = allowUrlLogging;
- final DefaultHttpClient actualClient = createDefaultHttpClient(timeoutMs, connectionTimeToLiveSec);
-
- actualClient.setRedirectStrategy(new DefaultRedirectStrategy(){
- // detect redirects to cas
- @Override
- public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
- URI locationURI = super.getLocationURI(request, response, context);
- String uri = locationURI.toString();
- if (isCasUrl(uri)) {
- logger.debug("set redirected_to_cas=true, url: " + uri);
- context.setAttribute(WAS_REDIRECTED_TO_CAS, "true");
- clearRedirects();
- } else { // when redirecting back to service _from_ cas
- logger.debug("set redirected_to_cas=false, url: " + uri);
- context.removeAttribute(WAS_REDIRECTED_TO_CAS);
- }
- return locationURI;
- }
- });
-
- if (!reuseConnections) { // hidastaa?
- actualClient.setReuseStrategy(new NoConnectionReuseStrategy());
- }
-
- cookieStore = actualClient.getCookieStore();
- cachingClient = initCachingClient(actualClient);
-
- initGson();
- }
-
- public static DefaultHttpClient createDefaultHttpClient(int timeoutMs, long connectionTimeToLiveSec) {
- // multithread support + max connections
- PoolingClientConnectionManager connectionManager;
- connectionManager = new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault(), connectionTimeToLiveSec, TimeUnit.MILLISECONDS);
- connectionManager.setDefaultMaxPerRoute(100); // default 2
- connectionManager.setMaxTotal(1000); // default 20
-
- // init stuff
- final DefaultHttpClient actualClient = new DefaultHttpClient(connectionManager);
-
- HttpParams httpParams = actualClient.getParams();
- HttpConnectionParams.setConnectionTimeout(httpParams, timeoutMs);
- HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
- HttpConnectionParams.setSoKeepalive(httpParams, true); // prevent firewall to reset idle connections?
- return actualClient;
- }
-
- public static HttpClient initCachingClient(DefaultHttpClient actualClient) {
- try {
- org.apache.http.impl.client.cache.CacheConfig cacheConfig = new org.apache.http.impl.client.cache.CacheConfig();
- cacheConfig.setMaxCacheEntries(50 * 1000);
- cacheConfig.setMaxObjectSize(10 * 1024 * 1024); // 10M, eg oppilaitosnumero -koodisto is 7,5M
- return new org.apache.http.impl.client.cache.CachingHttpClient(actualClient, cacheConfig);
- } catch (Throwable e) {
- logger.error("ERROR creating CachingRestClient, httpclient-cache jar missing? falling back to non-cached http client - "+e, e);
- return actualClient;
- }
- }
-
- private void initGson() {
- GsonBuilder gsonBuilder = new GsonBuilder();
- gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new JsonDeserializer() {
-
- @Override
- public XMLGregorianCalendar deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
- throws JsonParseException {
- String string = json.getAsString();
- try {
- return parseXmlGregorianCalendar(string);
- } catch (Throwable t){
- return null;
- }
- }
-
- });
- gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() {
- @Override
- public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- return new Date(json.getAsJsonPrimitive().getAsLong());
- }
- });
- gson = gsonBuilder.create();
- }
-
- private boolean isCasUrl(String uri) {
- return uri != null && (uri.endsWith("/cas") || uri.contains("/cas/") || uri.contains("/cas?"));
- }
-
- /**
- * get REST Json resource as Java object of type resultType (deserialized with gson).
- * Returns null if error occurred while querying resource.
- */
- public T get(String url, Class extends T> resultType) throws IOException {
- InputStream is = null;
- String response = null;
- try {
- is = get(url);
- response = IOUtils.toString(is);
- T t = fromJson(resultType, response);
- return t;
- } finally {
- if(is != null) {
- is.close();
- }
- }
- }
-
- public String getAsString(String url) throws IOException {
- return IOUtils.toString(get(url));
- }
-
- private T fromJson(Class extends T> resultType, String response) throws IOException {
- try {
- return gson.fromJson(response, resultType);
- } catch (JsonSyntaxException e) {
- throw new IOException("failed to parse object from (json) response, type: "+resultType.getSimpleName()+", reason: "+e.getCause()+", response:\n"+response);
- }
- }
-
- /**
- * get REST JSON resource as string.
- */
- public InputStream get(String url) throws IOException {
- HttpGet req = new HttpGet(url);
- HttpResponse response = execute(req, null, null);
- HttpEntity responseEntity = response.getEntity();
- if (responseEntity == null) {
- logAndThrowHttpException(req, response, "request did not return any content");
- }
- return responseEntity.getContent();
- }
-
- private boolean wasRedirectedToCas() {
- return "true".equals(localContext.get().getAttribute(WAS_REDIRECTED_TO_CAS));
- }
-
- protected boolean authenticate(final HttpRequestBase req) throws IOException {
- synchronized (this) {
- if (useServiceAsAUserAuthentication()) {
- if (serviceAsAUserTicket == null) {
- checkNotNull(username, "username");
- checkNotNull(password, "password");
- checkNotNull(webCasUrl, "webCasUrl");
- checkNotNull(casService, "casService");
- serviceAsAUserTicket = obtainNewCasServiceAsAUserTicket();
- logger.info("got new serviceAsAUser ticket, service: " + casService + ", ticket: " + serviceAsAUserTicket);
- }
- req.setHeader(CAS_SECURITY_TICKET, serviceAsAUserTicket);
- PERA.setKayttajaHeaders(req, getCurrentUser(), username);
- logger.debug("set serviceAsAUser ticket to header, service: " + casService + ", ticket: " + serviceAsAUserTicket + ", currentUser: " + getCurrentUser() + ", callAsUser: " + username);
- return true;
- } else if (useProxyAuthentication) {
- checkNotNull(webCasUrl, "webCasUrl");
- checkNotNull(casService, "casService");
- if (proxyAuthenticator == null) {
- proxyAuthenticator = new ProxyAuthenticator();
- }
- final boolean[] gotNewProxyTicket = {false};
- proxyAuthenticator.proxyAuthenticate(casService, proxyAuthMode, new ProxyAuthenticator.Callback() {
- @Override
- public void setRequestHeader(String key, String value) {
- req.setHeader(key, value);
- logger.debug("set http header: " + key + "=" + value);
- }
-
- @Override
- public void gotNewTicket(Authentication authentication, String proxyTicket) {
- logger.info("got new proxy ticket, service: " + casService + ", ticket: " + proxyTicket);
- gotNewProxyTicket[0] = true;
- }
- });
- return gotNewProxyTicket[0];
- }
-
- return false;
- }
- }
-
- private void checkNotNull(String value, String name) {
- if (value == null) throw new NullPointerException("CachingRestClient."+name+" is null, and guess what, it shouldn't!");
- }
-
- /*
- private void addRequestParameter(HttpRequestBase req, String key, String value) {
- URIBuilder builder = new URIBuilder(req.getURI()).setParameter(key, value);
- try {
- req.setURI(builder.build());
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
- */
-
- private boolean useServiceAsAUserAuthentication() {
- return username != null;
- }
-
- protected String obtainNewCasServiceAsAUserTicket() throws IOException {
- return CasClient.getTicket(webCasUrl + "/v1/tickets", username, password, casService);
- }
-
- public String postForLocation(String url, String content) throws IOException {
- return postForLocation(url, "application/json", content);
- }
-
- public String postForLocation(String url, String contentType, String content) throws IOException {
- HttpRequestBase request = new HttpPost(url);
- HttpResponse response = execute(request, contentType, content);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
- return response.getFirstHeader("Location").getValue();
- } else {
- throw new RuntimeException("post didn't result in http 201 created: " + info(request, response));
- }
- }
-
- public HttpResponse post(String url, String contentType, String content) throws IOException {
- return execute(new HttpPost(url), contentType, content);
- }
-
- public HttpResponse put(String url, String contentType, String content) throws IOException {
- return execute(new HttpPut(url), contentType, content);
- }
-
- public HttpResponse delete(String url) throws IOException {
- return execute(new HttpDelete(url), null, null);
- }
-
- public HttpResponse execute(HttpRequestBase req, String contentType, String postOrPutContent) throws IOException {
- return execute(req, contentType, postOrPutContent, 0);
- }
-
- public HttpResponse execute(HttpRequestBase req, String contentType, String postOrPutContent, int retry) throws IOException {
- // prepare
- if (req.getURI().toString().startsWith("/") && casService != null) { // if relative url
- try {
- req.setURI(new URIBuilder(casService.replace("/j_spring_cas_security_check", "") + req.getURI().toString()).build());
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
- String url = req.getURI().toString();
- if (req.getURI().getHost() == null) throw new NullPointerException("CachingRestClient.execute ERROR! host is null, req.uri: "+url);
- if (contentType != null) {
- req.setHeader("Content-Type", contentType);
- }
- if(this.callerId != null) {
- req.setHeader("Caller-Id", this.callerId);
- }
- req.setHeader("CSRF",CSRF);
- ensureCSRFCookie(req);
-
- if (postOrPutContent != null && req instanceof HttpEntityEnclosingRequestBase) {
- ((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity(postOrPutContent, UTF8));
- }
-
- boolean wasJustAuthenticated = false;
- try {
- wasJustAuthenticated = authenticate(req);
- } catch (ProxyAuthenticator.CasProxyAuthenticationException e) {
- if (retry == 0) {
- logger.warn("Failed to CAS authenticate. Renewing proxy ticket.");
- logger.debug("Failed to CAS authenticate. Renewing proxy ticket.", e);
- } else {
- logger.warn("Failed second time to CAS authenticate");
- logger.debug("Failed second time to CAS authenticate", e);
- // CAS didn't likely recognise TGT (One can't be completely sure since Cas20ProxyRetriever just returns null)
- throw new HttpException(req, getEmptyHttpResponse(SC_UNAUTHORIZED), e.getMessage());
- }
- }
-
- // do actual request
- HttpResponse response = null;
- String responseString = null;
- try {
- response = cachingClient.execute(req, localContext.get());
- } catch (Exception e) {
- logger.error("error in CachingRestClient - " + info(req, response, wasJustAuthenticated, wasJustAuthenticated, wasJustAuthenticated, retry), e);
- throw new IOException("Internal error calling "+req.getMethod()+"/"+url+" (check logs): "+e.getMessage());
- } finally {
- // after request, wrap response entity so it can be accessed later, and release the connection
- if (response != null && response.getEntity() != null) {
- responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
- response.setEntity(new StringEntity(responseString, "UTF-8"));
- }
- req.releaseConnection();
- }
-
- // logging
- boolean isRedirCas = isRedirectToCas(response); // this response is 302 with location header pointing to cas
- boolean wasRedirCas = wasRedirectedToCas(); // this response is from cas after 302 redirect
- boolean isHttp401 = response.getStatusLine().getStatusCode() == SC_UNAUTHORIZED;
- if (logger.isDebugEnabled()) {
- logger.debug(info(req, response, wasJustAuthenticated, isRedirCas, wasRedirCas, retry));
- logger.debug(" responseString: {}", responseString);
- }
-
- // just got new valid ticket, but still got cas login page.. something wrong with the system, target service didn't process the request/ticket correctly?
- if (retry > 0 && wasJustAuthenticated && (isRedirCas || wasRedirCas)) {
- throw new IOException("just got new valid ticket, but still got cas login page.. something wrong with the system, target service didn't process the request/ticket correctly?\n"
- +info(req, response, wasJustAuthenticated, isRedirCas, wasRedirCas, retry));
- }
-
- // authentication: was redirected to cas OR http 401 -> get ticket and retry once (but do it only once, hence 'retry')
- if (isRedirCas || wasRedirCas || isHttp401) {
- if (retry == 0) {
- logger.warn("warn! got redirect to cas or 401 unauthorized, re-getting ticket and retrying request");
- clearTicket();
- logger.debug("set redirected_to_cas=false");
- localContext.get().removeAttribute(WAS_REDIRECTED_TO_CAS);
- return execute(req, contentType, postOrPutContent, 1);
- } else {
- clearTicket();
- logAndThrowHttpException(req, response, "Unauthorized error calling REST resource, got redirect to cas or 401 unauthorized");
- }
- }
-
- if(response.getStatusLine().getStatusCode() == SC_FORBIDDEN) {
- logAndThrowHttpException(req, response, "Access denied error calling REST resource");
- }
-
- if(response.getStatusLine().getStatusCode() >= SC_INTERNAL_SERVER_ERROR) {
- logAndThrowHttpException(req, response, "Internal error calling REST resource");
- }
-
- if(response.getStatusLine().getStatusCode() >= SC_NOT_FOUND) {
- logAndThrowHttpException(req, response, "Not found error calling REST resource");
- }
-
- if(response.getStatusLine().getStatusCode() == SC_BAD_REQUEST) {
- logAndThrowHttpException(req, response, "Bad request error calling REST resource");
- }
-
- cacheStatus = localContext.get().getAttribute(CACHE_RESPONSE_STATUS);
-
- logger.debug("{}, url: {}, contentType: {}, content: {}, status: {}, headers: {}", new Object[]{req.getMethod(), url, contentType, postOrPutContent, response.getStatusLine(), Arrays.asList(response.getAllHeaders())});
- return response;
- }
-
- private HttpResponse getEmptyHttpResponse(int statusCode) {
- return new DefaultHttpResponseFactory()
- .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, null), null);
- }
-
- private void ensureCSRFCookie(HttpRequestBase req) {
- String host = req.getURI().getHost();
- if (!csrfCookiesCreateForHost.containsKey(host)) {
- synchronized (csrfCookiesCreateForHost) {
- if (!csrfCookiesCreateForHost.containsKey(host)) {
- csrfCookiesCreateForHost.put(host, true);
- BasicClientCookie cookie = new BasicClientCookie("CSRF", CSRF);
- cookie.setDomain(host);
- cookie.setPath("/");
- cookieStore.addCookie(cookie);
- }
- }
- }
- }
-
- private void logAndThrowHttpException(HttpRequestBase req, HttpResponse response, final String msg) throws CachingRestClient.HttpException {
- String message = msg + ", " + info(req, response);
- logger.error(message);
- throw new CachingRestClient.HttpException(req, response, message);
- }
-
- private String getUserInfo(HttpUriRequest req) {
- return header(req, "current", PERA.X_KUTSUKETJU_ALOITTAJA_KAYTTAJA_TUNNUS)
- + header(req, "caller", PERA.X_PALVELUKUTSU_LAHETTAJA_KAYTTAJA_TUNNUS)
- + header(req, "proxy", PERA.X_PALVELUKUTSU_LAHETTAJA_PROXY_AUTH)
- + header(req, "ticket", CAS_SECURITY_TICKET);
- }
-
- private String header(HttpUriRequest req, String info, String name) {
- Header[] headers = req.getHeaders(name);
- StringBuilder res = new StringBuilder();
- if (headers != null && headers.length > 0) {
- res.append("|").append(info).append(":");
- for (Header header : headers) {
- res.append(header.getValue());
- }
- }
- return res.toString();
- }
-
- private String info(HttpUriRequest req, HttpResponse response) {
- return "url: " + (allowUrlLogging ? req.getURI() : "hidden")
- + ", method: " + req.getMethod()
- + ", status: " + (response != null && response.getStatusLine() != null ? response.getStatusLine().getStatusCode() : "?")
- + ", userInfo: " + getUserInfo(req)
- + ", timeoutMs: " + timeoutMs;
- }
-
- private String info(HttpUriRequest req, HttpResponse response, boolean wasJustAuthenticated, boolean isRedirCas, boolean wasRedirCas, int retry) {
- return info(req, response)
- + ", isredircas: " + isRedirCas
- + ", wasredircas: " + wasRedirCas
- + ", wasJustAuthenticated: " + wasJustAuthenticated
- + ", retry: " + retry;
- }
-
- private String getCurrentUser() {
- Authentication authentication = SecurityContextHolder.getContext() != null ? SecurityContextHolder.getContext().getAuthentication() : null;
- return authentication != null ? authentication.getName() : null;
- }
-
- /** will force to get new ticket next time */
- public void clearTicket() {
- synchronized (this) {
- serviceAsAUserTicket = null;
- if (useProxyAuthentication && proxyAuthenticator != null) {
- proxyAuthenticator.clearTicket(casService);
- }
- }
- }
-
- private void clearRedirects() {
- // clear redirects, because cas auth could cause same auth redirections again after new login/ticket. this will prevent CircularRedirectException
- localContext.get().setAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS, new RedirectLocations());
- logger.info("cleared redirects");
- }
-
- private boolean isRedirectToCas(HttpResponse response) {
- Header location = response.getFirstHeader("Location");
- return location != null && isCasUrl(location.getValue());
- }
-
- public Object getCacheStatus() {
- return cacheStatus;
- }
-
- private XMLGregorianCalendar parseXmlGregorianCalendar(String string) {
- // long t = System.currentTimeMillis();
- if (string == null || string.isEmpty()) {
- return null;
- }
-
- final boolean hasSemicolon = string.indexOf(":") != -1;
- final boolean hasDash = string.indexOf("-") != -1;
-
- try {
- if (hasSemicolon) {
- GregorianCalendar cal = new GregorianCalendar();
- cal.setTime(df1.get().parse(string));
- return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
- } else if (hasDash) {
- GregorianCalendar cal = new GregorianCalendar();
- cal.setTime(df2.get().parse(string));
- return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
- } else {
- GregorianCalendar cal = new GregorianCalendar();
- cal.setTime(new Date(Long.parseLong(string)));
- return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
-
- }
- } catch (Throwable th) {
- logger.warn("error parsing json to xmlgregoriancal: " + string);
- }
- return null;
- }
-
- public String getWebCasUrl() {
- return webCasUrl;
- }
-
- public void setWebCasUrl(String webCasUrl) {
- clearTicket();
- this.webCasUrl = webCasUrl;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- clearTicket();
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- clearTicket();
- this.password = password;
- }
-
- public String getCasService() {
- return casService;
- }
-
- public void setCasService(String casService) {
- clearTicket();
- this.casService = casService;
- }
-
- /** Check health of this rest client */
- @Override
- public Object checkHealth() throws Throwable {
- if (casService != null) {
-
- // call target service's buildversion url (if we have credentials try the secured url)
- String serviceUrl = casService.replace("/j_spring_cas_security_check", "");
- final String buildversionUrl = serviceUrl + "/buildversion.txt" + (useServiceAsAUserAuthentication() ? "?auth" : "");
- final HttpResponse result = execute(new HttpGet(buildversionUrl), null, null);
-
- LinkedHashMap map = new LinkedHashMap() {{
- put("url", buildversionUrl);
- put("user", useServiceAsAUserAuthentication() ? username : useProxyAuthentication ? "proxy" : "anonymous");
- put("status", result.getStatusLine().getStatusCode() == 200 ? "OK" : result.getStatusLine());
- // todo: kuormitusdata?
- }};
-
- // kohdepalvelun healthcheck
- try {
- Map hc = get(serviceUrl+"/healthcheck", Map.class);
- Object targetserviceStatus = hc.get("status");
- if ("OK".equals(targetserviceStatus)) {
- map.put("targetserviceHealthcheck", "OK");
- } else {
- throw new Exception("targetserviceHealthcheck error: "+targetserviceStatus);
- }
- } catch (HttpException e) {
- if (e.getStatusCode() == 404) {
- map.put("targetserviceHealthcheck", "not found");
- } else {
- throw new Exception("targetserviceHealthcheck exception: "+e.getMessage());
- }
- }
-
- // mikäli kohdepalvelu ok, mutta halutaan varmistaa vielä sen versio
- if (result.getStatusLine().getStatusCode() == 200 && requiredVersionRegex != null) {
- Properties buildversionProps = new Properties();
- buildversionProps.load(result.getEntity().getContent());
- String version = buildversionProps.getProperty("version");
- if (!version.matches(requiredVersionRegex)) {
- throw new Exception("wrong version: "+version+", required: "+ requiredVersionRegex+", service: "+casService);
- }
- map.put("version", version);
- }
-
- return map;
- } else {
- return "nothing to check, casService not configured";
- }
- }
-
- public boolean isUseProxyAuthentication() {
- return useProxyAuthentication;
- }
-
- public void setUseProxyAuthentication(boolean useProxyAuthentication) {
- this.useProxyAuthentication = useProxyAuthentication;
- }
-
- public ProxyAuthenticator getProxyAuthenticator() {
- return proxyAuthenticator;
- }
-
- public void setProxyAuthenticator(ProxyAuthenticator proxyAuthenticator) {
- this.proxyAuthenticator = proxyAuthenticator;
- }
-
- public String getRequiredVersionRegex() {
- return requiredVersionRegex;
- }
-
- public void setRequiredVersionRegex(String requiredVersionRegex) {
- this.requiredVersionRegex = requiredVersionRegex;
- }
-
- public void setReuseConnections(boolean reuseConnections) {
- this.reuseConnections = reuseConnections;
- }
-
- public static class HttpException extends IOException {
-
- private int statusCode;
- private String statusMsg;
- private String errorContent;
-
- public HttpException(HttpRequestBase req, HttpResponse response, String message) {
- super(message);
- this.statusCode = response.getStatusLine().getStatusCode();
- this.statusMsg = response.getStatusLine().getReasonPhrase();
- try {
- if (response.getEntity() != null) {
- this.errorContent = IOUtils.toString(response.getEntity().getContent());
- } else {
- this.errorContent = "no content";
- }
-
- } catch (IOException e) {
- CachingRestClient.logger.error("error reading errorContent: "+e, e);
- }
- }
-
- public int getStatusCode() {
- return statusCode;
- }
-
- public String getStatusMsg() {
- return statusMsg;
- }
-
- public String getErrorContent() {
- return errorContent;
- }
- }
-
- public CachingRestClient setAllowUrlLogging(boolean allowUrlLogging) {
- this.allowUrlLogging = allowUrlLogging;
- return this;
- }
-}
diff --git a/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/HealthChecker.java b/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/HealthChecker.java
deleted file mode 100644
index c4a04fac..00000000
--- a/legacy-caching-rest-client/src/main/java/fi/vm/sade/javautils/legacy_caching_rest_client/HealthChecker.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-/**
- * Healthcheckiin kuuluva tarkastaja, jonka roolina on tarkastaa yksi kohde healthcheckin yhteydessä.
- * SpringAwareHealthCheckServlet kutsuu spring application contextista löytyviä tämän HealthChecker -interfacen toteuttavia beaneja.
- * checkHealth -metodin palauttama objekti serialisoidaan JSON:ksi, ja liitetään healthcheckin checks -osioon kentäksi [beanName].
- * Mikäli tarkastuksessa on virhe, checkHealth -metodin tulee heittää sitä poikkeus (jonka message kuvaa virhetilannetta).
- * Tällöin poikkeuksen message liitetään healthcheck tulokseen, ja koko healthcheckin tila on ERREOR.
- *
- * Esim:
- *
- * @Component("solrIndexed")
- * public class SolrIndexedCheck implements HealthChecker {
- * Object checkHealth() throws Throwable {
- * // tarkastetaan tässä onko solr indeksoitu
- * return new LinkedHashMap(){{ put("status", "OK"); put("previouslyIndexed", timestamp); }}
- * }
- * }
- *
- * ...johtaa tällaiseen healthcheck tulokseen...
- *
- * {
- * "status": "OK",
- * "checks": {
- * "solrIndexed": {"status": "OK", "timestamp": [timestamp]}
- * }
- * }
- *
- * @see SpringAwareHealthCheckServlet (in other module)
- */
-public interface HealthChecker {
- /**
- * @return something json-serializable that describes the state of this checker
- * @throws Throwable if there is health check error
- */
- Object checkHealth() throws Throwable;
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClientTest.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClientTest.java
deleted file mode 100644
index ec7098cc..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CachingRestClientTest.java
+++ /dev/null
@@ -1,303 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import fi.vm.sade.javautils.legacy_cxf_cas.ui.portlet.security.ProxyAuthenticator;
-import junit.framework.Assert;
-import org.apache.commons.lang.StringUtils;
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.cache.CacheResponseStatus;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.security.authentication.TestingAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-import javax.ws.rs.core.MediaType;
-import javax.xml.datatype.XMLGregorianCalendar;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.List;
-
-public class CachingRestClientTest extends RestWithCasTestSupport {
-
- @Test
- public void testXmlGregorianCalendarParsing() throws Exception {
- Calendar now = new GregorianCalendar();
- assertDay(now, client.get(getUrl("/httptest/xmlgregoriancalendar1"), XMLGregorianCalendar.class));
- assertDay(now, client.get(getUrl("/httptest/xmlgregoriancalendar2"), XMLGregorianCalendar.class));
- }
-
- private void assertDay(Calendar now, XMLGregorianCalendar xmlGregorianCalendar) {
- System.out.println("CachingRestClientTest.assertDay, now: "+now+", xmlGregCal: "+xmlGregorianCalendar);
- Assert.assertEquals(now.get(Calendar.YEAR), xmlGregorianCalendar.toGregorianCalendar().get(Calendar.YEAR));
- Assert.assertEquals(now.get(Calendar.MONTH), xmlGregorianCalendar.toGregorianCalendar().get(Calendar.MONTH));
- Assert.assertEquals(now.get(Calendar.DAY_OF_MONTH), xmlGregorianCalendar.toGregorianCalendar().get(Calendar.DAY_OF_MONTH));
- }
-
- @Test
- public void testCachingWithCommonsHttpClientAndJersey() throws Exception {
- // lue resurssi, jossa cache 1 sek
- Assert.assertEquals("pong 1", get("/httptest/pingCached1sec"));
-
- // lue resurssi uudestaan, assertoi että tuli cachesta, eikä serveriltä asti
- Assert.assertEquals("pong 1", get("/httptest/pingCached1sec"));
-
- // odota 1 sek
- Thread.sleep(2000);
-
- // lue resurssi uudestaan, assertoi että haettiin serveriltä koska cache vanheni
- Assert.assertEquals("pong 2", get("/httptest/pingCached1sec"));
- }
-
- public static void assertContains(String source, String... args) {
- for(String arg: args) {
- Assert.assertTrue("could not find string '" + arg + "' from: " + source, source.indexOf(arg) > -1);
- }
- }
-
- @Test
- public void testCSRFHeaders() throws Exception {
- // lue resurssi, jossa cache 1 sek
- assertContains(get("/mirror/headers"), "CSRF: CachingRestClient", "Cookie: CSRF=CachingRestClient", "Caller-Id: RestWithCasTestSupport");
- }
-
- @Test
- public void testResourceMirroringUsingEtag() throws Exception {
- // luetaan resurssi
- Assert.assertEquals("original value 1", get("/httptest/someResource"));
- Assert.assertEquals(client.getCacheStatus(), CacheResponseStatus.CACHE_MISS);
-
- // tehdään muutos serverin resurssiin
- HttpTestResource.someResource = "changed value";
-
- // luetaan resurssi, assertoi että tulee cachesta vielä (koska expires)
- Assert.assertEquals("original value 1", get("/httptest/someResource"));
- Assert.assertEquals(client.getCacheStatus(), CacheResponseStatus.CACHE_HIT);
-
- // odotetaan että expires menee ohi
- Thread.sleep(2000);
-
- // luetaan resurssi, assertoi että tulee serveriltä, koska muuttunut etag JA expires aika mennyt
- Assert.assertEquals("changed value 2", get("/httptest/someResource"));
- Assert.assertEquals(client.getCacheStatus(), CacheResponseStatus.VALIDATED);
-
- // odotetaan että expires menee ohi
- Thread.sleep(2000);
-
- // luetaan resurssi, assertoi että tulee cachesta vaikka käy serverillä (serveri palauttaa unmodified, eikä nosta counteria, koska etag sama)
- Assert.assertEquals("changed value 2", get("/httptest/someResource"));
- Assert.assertEquals(client.getCacheStatus(), CacheResponseStatus.VALIDATED);
-
- // vielä assertoidaan että unmodified -responsen jälkeen expires toimii kuten pitää eli ei käydä serverillä vaan tulee cache_hit
- Assert.assertEquals("changed value 2", get("/httptest/someResource"));
- Assert.assertEquals(client.getCacheStatus(), CacheResponseStatus.CACHE_HIT);
- }
-
- @Test(expected = IOException.class)
- public void testErrorStatus() throws IOException {
- get("/httptest/status500");
- }
-
- @Test(expected = IOException.class)
- public void testErrorStatus400() throws IOException {
- get("/httptest/status400");
- }
-
- @Test
- public void testAuthenticationWithGetRedirect() throws Exception {
- initClientAuthentication("test");
-
- // alustava pyyntö -> CachingRestClient hankkii tiketin kutsua ennen, kutsu menee ok:sti
- Assert.assertEquals("pong 1", get("/httptest/pingSecuredRedirect/asd1"));
- assertCas(0, 1, 1, 1, 1);
-
- // simuloidaan että ollaan autentikoiduttu casiin, mutta ei kohdepalveluun vielä, joten kutsun suojattuun resurssiin pitäisi redirectoitua casiin
- TestParams.instance.userIsAlreadyAuthenticatedToCas = "asdsad";
- TestParams.instance.failNextBackendAuthentication = true;
-
- // lue suojattu resurssi -> välillä käydään cassilla, joka ohjaa takaisin ticketin kanssa (koska ollaan jo casissa sisällä)
- Assert.assertEquals("pong 2", get("/httptest/pingSecuredRedirect/asd1")); // asd? tarvitaan koska muuten apache http saattaa tulkita circular redirectiksi..
- assertCas(1, 1, 1, 3, 2);
-
- // kutsu uudestaan -> ei redirectiä koska nyt serviceenkin ollaan autentikoiduttu, ainoastaan request autentikoidaan backendissä
- Assert.assertEquals("pong 3", get("/httptest/pingSecuredRedirect/asd1"));
- assertCas(1, 1, 1, 4, 3);
-
- // invalidoi tiketti serverillä, cas sessio edelleen ok (simuloi ticket cachen tyhjäytymistä serverillä) -> redirectit resource->cas->resource tapahtuu uusiksi
- TestParams.instance.failNextBackendAuthentication = true;
- Assert.assertEquals("pong 4", get("/httptest/pingSecuredRedirect/asd1"));
- assertCas(2, 1, 1, 6, 4);
-
- // tehdään ensin onnistunut kutsu..
- Assert.assertEquals("pong 5", get("/httptest/pingSecuredRedirect/asd1"));
- assertCas(2, 1, 1, 7, 5);
- // ..sitten invalidoi tiketti ja cas sessio (simuloi cas/backend restarttia)
- // -> resurssi redirectoi cassille, mutta cas ei ohjaa takaisin koska ei olla sisällä casissa
- // -> CachingRestClient havaitsee puuttuvan authin, ja osaa hakea uuden tiketin, ja tehdä pyynnön uusiksi
- // -> redirectejä ei tämän jälkeen tapahdu, mutta tgt+ticket luodaan casiin, ja validoidaan backend resurssilla
- TestParams.instance.failNextBackendAuthentication = true;
- TestParams.instance.userIsAlreadyAuthenticatedToCas = null;
- Assert.assertEquals("pong 6", get("/httptest/pingSecuredRedirect/asd1"));
- assertCas(2, 2, 2, 9, 6);
- }
-
- @Test
- @Ignore // ei oikeastaan halutakaan tukea postien cas redirectointia, aina ennen postia pitää tehdä get!
- public void testAuthenticationWithPostRedirect() throws Exception {
- initClientAuthentication("test");
-
- // alustava pyyntö -> CachingRestClient hankkii tiketin kutsua ennen, kutsu menee ok:sti
- Assert.assertEquals("pong 1", post("/httptest/pingSecuredRedirect/asd1", "post content")); // asd? tarvitaan koska muuten apache http saattaa tulkita circular redirectiksi..
- assertCas(0, 1, 1, 1, 1);
-
- // autentikoiduttu casiin, mutta ei kohdepalveluun vielä, joten kutsun suojattuun resurssiin pitäisi redirectoitua casiin
- TestParams.instance.userIsAlreadyAuthenticatedToCas = "asdsad";
- TestParams.instance.failNextBackendAuthentication = true;
-
- // lue suojattu resurssi -> välillä käydään cassilla, joka ohjaa takaisin ticketin kanssa (koska ollaan jo casissa sisällä)
- Assert.assertEquals("pong 2", post("/httptest/pingSecuredRedirect/asd2", "post content")); // asd? tarvitaan koska muuten apache http saattaa tulkita circular redirectiksi..
- //assertCas(1, 1, 1, 3, 2); - note! ei tapahdu redirectiä, ei oikeastaan halutakaan tukea postien cas redirectointia, aina ennen postia pitää tehdä get!
- }
-
- @Test
- public void testAuthenticationWith401Unauthorized() throws Exception {
- initClientAuthentication("test");
-
- // lue suojattu resurssi joka palauttaisi 401 unauthorized, mikäli ei oltaisi autentikoiduttu -> client kuitenkin on yllä konffattu käyttämään palvelutunnuksia
- Assert.assertEquals("pong 1", get("/httptest/pingSecured401Unauthorized"));
- assertCas(0,1,1,1,1);
-
- // invalidoi serveripään tiketti -> seur kutsussa resurssi palauttaa 401, jonka jälkeen restclient osaa hakea uuden tiketin ja koittaa pyyntöä uusiksi
- TestParams.instance.failNextBackendAuthentication = true;
- Assert.assertEquals("pong 2", get("/httptest/pingSecured401Unauthorized"));
- assertCas(0,2,2,3,2);
- }
-
- @Test
- public void testIllegalUserWontGetStuckInRedirectLoopOrSthing() throws Exception {
- initClientAuthentication("illegaluser");
- try {
- get("/httptest/pingSecured401Unauthorized");
- Assert.fail("should fail");
- } catch (CachingRestClient.HttpException e) {
- Assert.assertEquals(401, e.getStatusCode());
- }
- }
-
- @Test
- public void testProxyAuthentication() throws Exception {
- // prepare & mock stuff
- final String user = "uiasdhjsadhu";
- final int[] proxyTicketCounter = {0};
- List roles = Arrays.asList((GrantedAuthority)new SimpleGrantedAuthority("testrole"));
- TestingAuthenticationToken clientAuth = new TestingAuthenticationToken(user, user, roles);
- SecurityContextHolder.getContext().setAuthentication(clientAuth);
- client.setCasService(getUrl("/httptest"));
- client.setUseProxyAuthentication(true);
- client.setProxyAuthenticator(new ProxyAuthenticator() {
- @Override
- protected String obtainNewCasProxyTicket(String casTargetService, Authentication casAuthenticationToken) {
- return "mockticket_" + user + "_" + (++proxyTicketCounter[0]);
- }
- });
-
- // lue suojattu resurssi joka palauttaisi muuten 401 unauthorized, mutta client hoitaa autentikoinnin sisäisesti ja kutsuu clientuserina
- Assert.assertEquals("pong 1", get("/httptest/pingSecured401Unauthorized"));
- Assert.assertEquals(1, proxyTicketCounter[0]);
- assertCas(0,0,0,1,1); // redir ei tehtä, tikettejä ei luoda koska client laittaa mukaan proxytiketin, tiketin validointi tehty serverillä kerran ok
-
- // invalidoi tiketti serveripäässä (esim restarttaa cas tai kohdepalvelu välissä), ja yritä uudestaan -> client pitäisi hankkia uuusi proxy ticket
- TestParams.instance.failNextBackendAuthentication = true;
- Assert.assertEquals("pong 2", get("/httptest/pingSecured401Unauthorized"));
- Assert.assertEquals(2, proxyTicketCounter[0]);
- assertCas(0,0,0,3,2);
-
- // invalidoi tiketti clientilla -> client pitäisi hankkia uuusi proxy ticket
- client.getProxyAuthenticator().clearTicket(getUrl("/httptest"));
- Assert.assertEquals("pong 3", get("/httptest/pingSecured401Unauthorized"));
- Assert.assertEquals(3, proxyTicketCounter[0]);
- assertCas(0,0,0,4,3);
- }
-
- private void initClientAuthentication(String username) {
- client.setCasService(getUrl("/httptest"));
- client.setWebCasUrl(getUrl("/mock_cas/cas"));
- client.setUsername(username);
- client.setPassword(username);
- }
-
- private String get(String url) throws IOException {
- return IOUtils.toString(client.get(getUrl(url)));
- }
-
- private String post(String url, String postContent) throws IOException {
- return IOUtils.toString(client.post(getUrl(url), "application/json", postContent).getEntity().getContent());
- }
-
- @Test
- public void testPostUTF8Encoding() throws IOException {
- final String json = "{\"test\":\"Möttönen\"}";
- final HttpResponse response = client.post(getUrl("/httptest/special-character-resource"), MediaType.APPLICATION_JSON, json);
- final String responseJson = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
- System.out.println("got response entity: " + responseJson);
- Assert.assertTrue("response should contain \"Möttönen\": "+responseJson, StringUtils.contains(responseJson, "Möttönen"));
- }
-
- @Test
- public void testPutUTF8Encoding() throws IOException {
- final String json = "{\"test\":\"Möttönen\"}";
- final HttpResponse response = client.put(getUrl("/httptest/special-character-resource"), MediaType.APPLICATION_JSON, json);
- final String responseJson = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
- System.out.println("got response entity: " + responseJson);
- Assert.assertTrue("response should contain \"Möttönen\": "+responseJson, StringUtils.contains(responseJson, "Möttönen"));
- }
-
- @Test
- public void testGotRedirectToCasBecauseSystemBroken() {
- /*
- -systeemi/konffit rikki
- -eka kutsu, juuri hankittu validi tiketti
- -silti tulee redirect cas:lle
- -clientin pitäisi osata heittää poikkeus tällöin
- */
- initClientAuthentication("test");
- try {
- String resp = get("/httptest/pingSecuredRedirect/asd1?SKIP_CAS_FILTER");
- Assert.fail("should fail, but got response: "+resp);
- } catch (Exception e) {
- Assert.assertTrue(e.toString().contains("something wrong with the system"));
- }
- }
-
- @Test
- public void testOnlyOneTicketHeader() throws IOException {
- // fix bug: fix bug: cachingrestclient 401 virheen korjaus.. cas redirect tapauksissa CasSecurityTicket-header tuli kahteen kertaan, joka aiheutti ticketin validoinnin failaamisen -> 401 unauthorized
-
- // tehdään rest kutsu
- initClientAuthentication("test");
- Assert.assertEquals("pong 1", get("/httptest/pingSecuredRedirect/asd1"));
- Assert.assertEquals(1, TestParams.prevRequestTicketHeaders.size());
- Object orgTicket = TestParams.prevRequestTicketHeaders.get(0);
-
- // invalidoidaan ticket serverillä, jotta joudutaan käymään cassilla hakemassa redirecteillä uusi
- TestParams.instance.failNextBackendAuthentication = true;
-
- // tehdään toinen kutsu
- Assert.assertEquals("pong 2", get("/httptest/pingSecuredRedirect/asd1"));
-
- // assertoidaan että kutsussa oli edelleen vain yksi ticket-header, ja se on eri kuin edellinen ticket eli ticket oikeasti haettiin uusiksi
- Assert.assertEquals(1, TestParams.prevRequestTicketHeaders.size());
- Assert.assertNotSame(orgTicket, TestParams.prevRequestTicketHeaders.get(0));
- }
-
- @Test(expected = CachingRestClient.HttpException.class)
- public void testResourceWithoutContentWillNotFail() throws IOException {
- initClientAuthentication("test");
- Assert.assertNull(get("/httptest/testResourceNoContent"));
- }
-
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CasApplicationAsAUserInterceptorTest.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CasApplicationAsAUserInterceptorTest.java
deleted file mode 100644
index bbc9a9b2..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/CasApplicationAsAUserInterceptorTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas.CasApplicationAsAUserInterceptor;
-import fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas.DefaultTicketCachePolicy;
-import fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas.TicketCachePolicy;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class CasApplicationAsAUserInterceptorTest extends RestWithCasTestSupport {
-
- private WebClient webClient;
- private CasApplicationAsAUserInterceptor appAsUserInterceptor;
- private String targetService;
- private String user;
- private String pass = "pass";
-
- @Test
- public void testCasApplicationAsAUserInterceptor() throws Exception {
- // prepare & mock the client
- webClient = createClient();
-
- // kutsutaan resurssia
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
-
- // assertoidaan: ticket haettu kerran
- assertCas(0, 1, 1, 1, 1);
-
- // kutsutaan resurssia
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
-
- // assertoidaan: ticket haettu kerran (ei autentikoida uudestaan vaan ticket cachetettu), mutta validoitu kaksi kertaa
- assertCas(0, 1, 1, 2, 2);
-
- // simuloidaan: cas restart, server ticket cache tyhjäys -> ticket ei enää validi
- TestParams.instance.failNextBackendAuthentication = true;
-
- // kutsutaan resurssia -> virhe
- Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, webClient.get().getStatus());
- assertCas(0, 1, 1, 3, 2); // autentikointi kutsuttiin kerran mutta epäonnistuneesti
-
- // simuloidaan: käyttäjä joutuu kirjautumaan uudelleen sisään, jonka jälkeen resurssi taas toimii
- appAsUserInterceptor.getTicketCachePolicy().clearTicket(targetService, user); // oikeassa ympäristössä ticket kakutettu käyttäjän http sessioon
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
-
- // assertoidaan: ticket haettu ja validoitu nyt uusiksi
- assertCas(0, 2, 2, 4, 3);
- }
-
- @Test
- public void testTicketCacheIsLoadBlocked() throws Exception {
- // prepare & mock the client
- webClient = createClient();
-
- // call X times with threads
- Thread threads[] = new Thread[2];
- final String ticketsForThreads[] = new String[threads.length];
- for (int i = 0; i < threads.length; i++) {
- final int finalI = i;
- Thread thread = threads[i] = new Thread(){
- @Override
- public void run() {
- ticketsForThreads[finalI] = appAsUserInterceptor.getTicketCachePolicy().getCachedTicket(targetService, user, new TicketCachePolicy.TicketLoader() {
- @Override
- public String loadTicket() {
- System.out.println("CasApplicationAsAUserInterceptorTest.loadTicket1");
- try {
- // ...wait 100ms when getting new ticket for threading test purposes
- Thread.sleep(100);
- System.out.println("CasApplicationAsAUserInterceptorTest.loadTicket2");
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- return "ticket_"+finalI;
- }
- });
- }
- };
- thread.start();
- }
-
- // wait for threads to complete
- for (Thread thread : threads) {
- thread.join();
- }
-
- // assert threads got the same ticket = ticket cache blocks while loading values
- for (String ticket : ticketsForThreads) {
- System.out.println("ticket: "+ticket);
- Assert.assertEquals(ticketsForThreads[0], ticket);
- }
- }
-
- @Test
- public void testGlobalTicketCacheExpires() throws Exception {
- // prepare & mock the client
- webClient = createClient();
-
- // set ttl to 1 second
- ((DefaultTicketCachePolicy)appAsUserInterceptor.getTicketCachePolicy()).setGlobalTicketsTimeToLiveSeconds(1);
-
- // call 1st time -> create ticket
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 1, 1, 1, 1);
-
- // call 2nd time -> use ticket from cache
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 1, 1, 2, 2);
-
- // wait 1,5 secs -> ticket expires
- Thread.sleep(1500);
-
- // call 3rd time -> create ticket
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 2, 2, 3, 3);
- }
-
- // todo: nämä testit kuuluisi ehkä johonkin muualle huom ticket client refaktoroinnin jälkeen
-
- @Test
- public void testSameClientForDifferentServicesAndUsers() throws Exception {
- webClient = createClient();
-
- // testataan 2 eri käyttäjällä ja 2 eri kohdepalvelulla että jokaiselle syntyy omat tgt+tiketit
-
- changeUserAndService("user1", "target1");
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 1, 1, 1, 1);
-
- changeUserAndService("user1", "target2");
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 2, 2, 2, 2);
-
- changeUserAndService("user2", "target1");
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 3, 3, 3, 3);
-
- changeUserAndService("user2", "target2");
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 4, 4, 4, 4);
-
- // tämän jälkeen käytetään cachetettua tikettiä onnistuneesti
-
- changeUserAndService("user1", "target1");
- Assert.assertEquals(HttpStatus.SC_OK, webClient.get().getStatus());
- assertCas(0, 4, 4, 5, 5);
- }
-
- private void changeUserAndService(String u, String s) {
- user = u;
- pass = "pass";
- targetService = s;
- appAsUserInterceptor.setAppClientUsername(user);
- appAsUserInterceptor.setAppClientPassword(pass);
- appAsUserInterceptor.setTargetService(targetService);
- }
-
- private WebClient createClient() {
- appAsUserInterceptor = new CasApplicationAsAUserInterceptor();
- changeUserAndService("user", "target");
- appAsUserInterceptor.setWebCasUrl(getUrl("/mock_cas/cas"));
- WebClient c = WebClient.create(getUrl("/httptest/testMethod"));
- WebClient.getConfig(c).getOutInterceptors().add(appAsUserInterceptor);
- return c;
- }
-
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/HttpTestResource.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/HttpTestResource.java
deleted file mode 100644
index 9e956513..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/HttpTestResource.java
+++ /dev/null
@@ -1,225 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import org.apache.commons.codec.binary.Hex;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.EntityTag;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.NewCookie;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-
-@Path("/httptest")
-public class HttpTestResource {
-
- public static int counter = 1;
- public static String someResource = "original value";
-
- @Path("/pingCached1sec")
- @GET
- @Produces("text/plain")
- public Response pingCached1sec() {
- System.out.println("HttpTest.pingCached1sec, counter: " + counter + ", now: " + new Date(System.currentTimeMillis()));
- return Response
- .ok("pong " + (counter++))
- .expires(date(2))
- .build();
- }
-
- @Path("/someResource")
- @GET
- @Produces("text/plain")
- public Response someResource(@Context Request request) {
- System.out.println("HttpTest.someResource: "+someResource+", counter: "+counter+", now: " + new Date(System.currentTimeMillis()));
-
- EntityTag etag = new EntityTag(Hex.encodeHexString(someResource.getBytes()));
- Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(etag);
-
- // Etag match = if resource not changed -> do nothing and return "unmodified" -http response (note also maxage-tag)
- if (responseBuilder != null) {
- System.out.println("resource has not changed..returning unmodified response code");
- return responseBuilder
- .expires(date(2))
- .build();
- }
-
- // otherwise do actual logic and tag response with etag and maxage -headers
- return Response
- .ok(someResource+" "+(counter++))
- .tag(etag)
- .expires(date(2))
- .build();
- }
-
- @Path("/cacheableAnnotatedResource")
- @GET
- @Produces("text/plain")
- public Response cacheableAnnotatedResource() {
- System.out.println("HttpTest.cacheableAnnotatedResource, counter: " + counter + ", now: " + new Date(System.currentTimeMillis()));
-
- return Response
- .ok("cacheable " + (counter++))
- .build();
- }
-
- @Path("/oneSecondResource")
- @GET
- @Produces("text/plain")
- public Response oneSecondResource() throws InterruptedException {
- Thread.sleep(1000);
- return Response.ok("OK").build();
- }
-
- @Path("/xmlgregoriancalendar1")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public String xmlgregoriancalendar1() throws InterruptedException {
- return ""+new Date().getTime();
- }
-
- @Path("/xmlgregoriancalendar2")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public String xmlgregoriancalendar2() throws InterruptedException {
- return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
- }
-
- private Date date(int dSeconds) {
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.SECOND, dSeconds); // 24h
- return calendar.getTime();
- }
-
- @Path("/status500")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response status500() {
- return Response.status(500).build();
- }
-
- @Path("/status400")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response status400() {
- return Response.status(400).build();
- }
-
- @Path("/pingSecuredRedirect/{sthing}")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response pingSecuredRedirect(@Context HttpServletRequest request) throws URISyntaxException {
- System.out.println("HttpTestResource.pingSecuredRedirect, params: "+request.getParameterMap());
- if (MockCasResource.isRequestAuthenticated(request) && request.getParameter("SKIP_CAS_FILTER")==null) {
- String s = "pong " + (counter++);
- System.out.println("HttpTestResource.pingSecuredRedirect, ok: "+s);
- return Response.ok(s).build();
- } else {
- String url = "/mock_cas/cas?service=" + request.getRequestURL();
- System.out.println("HttpTestResource.pingSecuredRedirect, redirect: "+url);
- return Response.status(302).location(new URI(url)).build();
- }
- }
-
- @Path("/pingSecuredRedirect/{sthing}")
- @POST
- @Produces(MediaType.APPLICATION_JSON)
- public Response pingSecuredRedirectPost(@Context HttpServletRequest request) throws URISyntaxException {
- return pingSecuredRedirect(request);
- }
-
- @Path("/pingSecured401Unauthorized")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response pingSecured401Unauthorized(@Context HttpServletRequest request) throws URISyntaxException {
- if (MockCasResource.isRequestAuthenticated(request)) {
- return Response.ok("pong " + (counter++)).build();
- }
- return Response.status(Response.Status.UNAUTHORIZED).build();
- }
-
- @Path("/testResourceNoContent")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response testResourceNoContent(@Context HttpServletRequest request) throws URISyntaxException {
- return Response.status(Response.Status.NOT_MODIFIED).build();
- }
-
- @Path("/testMethod")
- @GET
- public Response testMethod(@Context HttpServletRequest request) {
- if (!MockCasResource.isRequestAuthenticated(request)) {
- return Response.status(Response.Status.UNAUTHORIZED).build();
- }
- return Response.ok("testResult").build();
- }
-
- @Path("/special-character-resource")
- @POST
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response post(String json) {
- return pingBackJson(json);
- }
-
- @Path("/special-character-resource")
- @PUT
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response put(String json) {
- return pingBackJson(json);
- }
-
- private Response pingBackJson(String json) {
- System.out.println("got json: " + json);
- return Response.ok(json).build();
- }
-
- @Path("/printcookies")
- @GET
- @Produces(MediaType.TEXT_PLAIN)
- public Response printcookies(@Context HttpServletRequest request) throws URISyntaxException {
- Cookie[] cookies = request.getCookies();
- String result = "";
- for (Cookie cookie : cookies) {
- result += ""+cookie.getName()+"="+cookie.getValue()+"(" +
- "|domain:"+cookie.getDomain()+"" +
- "|path:"+cookie.getPath() +
- "|maxage:"+cookie.getMaxAge() +
- ")\n";
- }
- return Response.ok(result)
- .header("sessionid", request.getSession(true).getId())
- .build();
- }
-
- @Path("/buildversion.txt")
- @GET
- @Produces(MediaType.TEXT_PLAIN)
- public Response j_spring_cas_security_check(@Context HttpServletRequest request) throws URISyntaxException {
- String ticket = request.getParameter("ticket");
- //System.out.println("HttpTestResource.j_spring_cas_security_check, ticket: "+ ticket);
- HttpSession sess = request.getSession(true); // synnyttää JSESSIONID:n
- String ticketCookie = ticket.replaceAll(":|/", "_");
-// String ticketCookie = "asdasd";
- return Response.ok("sessionid: "+sess.getId())
- .header("sessionid", sess.getId())
- .cookie(new NewCookie("TIKETTICOOKIE", ticketCookie))
- .build();
- }
-
-
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/JettyJersey.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/JettyJersey.java
deleted file mode 100644
index 34753dc0..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/JettyJersey.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.util.Random;
-
-import org.mortbay.jetty.Server;
-import org.mortbay.jetty.servlet.Context;
-import org.mortbay.jetty.servlet.ServletHolder;
-
-/**
- * Helper class to start embedded jetty + jersey for tests.
- *
- * @author Antti Salonen
- */
-public class JettyJersey {
- static Server server;
- static int port;
-
- public static void startServer(String packageContainingJerseyRestResources, String jerseyFilterClasses) throws Exception {
-
- port = findFreeLocalPort();
-
- System.setProperty("cas_key", getUrl("testing"));
- System.setProperty("cas_service", getUrl("/httptest"));
- System.setProperty("web.url.cas", getUrl("/mock_cas/cas"));
-
- server = new Server(port);
- Context root = new Context(server, "/", Context.SESSIONS);
- ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
- servletHolder.setInitOrder(1); // have to be set so that jersey will load on startup (otherwise might cause problems in cache timeout tests..)
- servletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
- servletHolder.setInitParameter("com.sun.jersey.config.property.packages", packageContainingJerseyRestResources);
-// servletHolder.setInitParameter("com.sun.jersey.config.feature.Debug", "true");
-// servletHolder.setInitParameter("com.sun.jersey.config.feature.Trace", "true");
-// servletHolder.setInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.LoggingFilter");
- servletHolder.setInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", /*"com.sun.jersey.api.container.filter.LoggingFilter,"*/""+(jerseyFilterClasses != null ? jerseyFilterClasses : ""));
- root.addServlet(servletHolder, "/*");
- server.start();
- System.out.println("jetty started at port "+port);
- }
-
- public static void stopServer() {
- try {
- server.stop();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static int getPort() {
- return port;
- }
-
- public static String getUrl(String url) {
- return "http://localhost:"+ getPort()+url;
- }
-
- public final static boolean isFreeLocalPort(int port) {
- Socket socket = null;
- try {
- socket = new Socket("127.0.0.1", port);
- socket.close();
- } catch (IOException e) {
- return true;
- }
- return false;
- }
-
- public final static int findFreeLocalPort() {
- int port = new Random().nextInt(60000) + 1000;
- if (isFreeLocalPort(port)) {
- return port;
- } else {
- return findFreeLocalPort();
- }
- }
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MirrorMockResource.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MirrorMockResource.java
deleted file mode 100644
index 02abe925..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MirrorMockResource.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import java.io.StringWriter;
-import java.util.Enumeration;
-
-/**
- * Mock resource for mirroring request for testing purposes.
- */
-@Path("/mirror")
-public class MirrorMockResource {
-
- /**
- * Returns request headers in the response body.
- * @param request
- * @return
- */
- @Path("/headers")
- @GET
- @Produces("text/plain")
- public Response mirrorHeaders(@Context HttpServletRequest request) {
- StringWriter out = new StringWriter();
- @SuppressWarnings("unchecked")
- Enumeration headerNames = request.getHeaderNames();
- while(headerNames.hasMoreElements()) {
- String one = headerNames.nextElement();
- out.write(one + ": " + request.getHeader(one) + "\n");
- }
-
- return Response.ok(out.toString()).build();
- }
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MockCasResource.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MockCasResource.java
deleted file mode 100644
index a5267fca..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/MockCasResource.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.FormParam;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Collections;
-
-/**
- * Simple cas http mock, works with CasClient, see also HttpTestResource.
- */
-@Path("/mock_cas")
-public class MockCasResource {
-
- public static boolean isRequestAuthenticated(HttpServletRequest request) { // todo: tän voisi korvata casfiltterillä oikeastaan niin ois todellisempi
- TestParams.instance.isRequestAuthenticatedCount++;
- TestParams.prevRequestTicketHeaders = Collections.list(request.getHeaders("CasSecurityTicket"));
-
- String ticket = request.getParameter("ticket");
- if (ticket == null) ticket = request.getHeader("CasSecurityTicket"); // jos ticket headerissa
- System.out.print("isRequestAuthenticated, request: " + request.getRequestURL() + ", ticket: " + ticket + ", failNextBackendAuthentication: " + TestParams.instance.failNextBackendAuthentication);
-
- if (ticket.contains("illegaluser")) {
- System.out.println(" --> false (illegaluser)");
- return false;
- }
-
- if (TestParams.instance.failNextBackendAuthentication) {
- TestParams.instance.failNextBackendAuthentication = false;
- request.getSession().invalidate();
- System.out.println(" --> false (failNextBackendAuthentication)");
- return false;
- }
-
- // jos sessio on jo autentikoitu, ei autentikoida cassia vasten vaan luotetaan sessioon
- Object sessionTicket = request.getSession().getAttribute("authenticatedTicket");
- if (sessionTicket != null) {
- // ...paitsi ainoastaan näin mikäli sama tiketti.. jos uusi tiketti parametrina, casfilter autentikoi uusiksi
- if (sessionTicket.equals(ticket)) {
- System.out.println(" --> true (authenticatedTicket)");
- return true;
- }
- }
-
- boolean ok = ticket != null && !ticket.startsWith("invalid");
- if (ok) {
- TestParams.instance.authTicketValidatedSuccessfullyCount++;
- request.getSession().setAttribute("authenticatedTicket", ticket);
- } else {
- request.getSession().invalidate();
- }
- System.out.println(" --> "+ok);
- return ok;
- }
-
- @Path("/cas")
- @GET
- public Response casRedirectToServiceWithTicket(@Context HttpServletRequest request) throws URISyntaxException {
- String service = request.getParameter("service");
-
- if (TestParams.instance.userIsAlreadyAuthenticatedToCas != null && service != null) {
- // käyttäjällä on jo autentikoitu sessio cassiin -> redirect to target service with ticket
- TestParams.instance.authRedirects++;
- String url = service + "?ticket=REDIRECTED_FROM_CAS_" + TestParams.instance.userIsAlreadyAuthenticatedToCas + "_" + System.currentTimeMillis();
- System.out.println("MockCasResource.casRedirectToServiceWithTicket, service: "+service+" -> http 302 redir to: "+url);
- return Response.status(302).location(new URI(url)).build();
- }
-
- // mock cas auth+redirect toimii vain jos userIsAlreadyAuthenticatedToCas ja request.service annettu
- System.out.println("MockCasResource.casRedirectToServiceWithTicket, service: "+service+", user not logged in -> http 200 show login page");
- return Response.ok("this is cas login page").build();
- }
-
- @Path("/cas/v1/tickets")
- @POST
- public Response createCasTgt(@Context HttpServletRequest request, @FormParam("username") String username, @FormParam("password") String password) throws URISyntaxException {
- System.out.println("MockCasResource.cas tgt, username: "+ username);
- if (username == null) throw new NullPointerException("username param is null"); // tunnareiden "tarkastus"
- String tgt = "TEMP_TGTX_"+username+"_"+System.currentTimeMillis();
- TestParams.instance.authTgtCount++;
- return Response.created(new URI("/mock_cas/cas/v1/tickets/" + tgt + "?user=" + username)).build();
- }
-
- @Path("/cas/v1/tickets/{tgt}")
- @POST
- public Response getCasServiceTicket(@PathParam("tgt") String tgt, @FormParam("service") String service, @QueryParam("user") String user) throws URISyntaxException {
- System.out.println("MockCasResource.cas getCasServiceTicket, tgt: "+ tgt+", service: "+service+", user: "+user);
- if (tgt == null) throw new NullPointerException("tgt param is null");
- if (service == null) throw new NullPointerException("service param is null");
- String ticket = "TEMP_STX_"+(++TestParams.instance.ticketNr)+"_"+user+"_"+service+"_"+System.currentTimeMillis();
- TestParams.instance.authTicketCount++;
- return Response.ok(ticket).build();
- }
-
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/RestWithCasTestSupport.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/RestWithCasTestSupport.java
deleted file mode 100644
index 3bde8622..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/RestWithCasTestSupport.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-public class RestWithCasTestSupport {
-
- CachingRestClient client;
-
- @BeforeClass
- public static void start() throws Exception {
- JettyJersey.startServer("fi.vm.sade.javautils.legacy_caching_rest_client", null);
- }
-
- @Before
- public void init() {
- TestParams.instance = new TestParams();
- HttpTestResource.counter = 1;
- HttpTestResource.someResource = "original value";
- SecurityContextHolder.clearContext();
-// DefaultTicketCachePolicy.ticketThreadLocal.remove();
- client = new CachingRestClient("RestWithCasTestSupport");
- client.setWebCasUrl("N/A");
- }
-
- @AfterClass
- public static void stop() throws Exception {
- JettyJersey.stopServer();
- }
-
- protected String getUrl(String url) {
- return JettyJersey.getUrl(url);
- }
-
- public void assertCas(int redirects, int tgtsCreated, int ticketsCreated, int requestAuthenticationCalled, int ticketsValidatedAgainstCasSuccessfully) {
- Assert.assertEquals("error in redirects count", redirects, TestParams.instance.authRedirects);
- Assert.assertEquals("error in tgtsCreated count", tgtsCreated, TestParams.instance.authTgtCount);
- Assert.assertEquals("error in ticketsCreated count", ticketsCreated, TestParams.instance.authTicketCount);
- Assert.assertEquals("error in requestAuthenticationCalled count", requestAuthenticationCalled, TestParams.instance.isRequestAuthenticatedCount);
- Assert.assertEquals("error in ticketsValidatedAgainstCasSuccessfully count", ticketsValidatedAgainstCasSuccessfully, TestParams.instance.authTicketValidatedSuccessfullyCount);
- }
-
-}
diff --git a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/TestParams.java b/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/TestParams.java
deleted file mode 100644
index ac90ffec..00000000
--- a/legacy-caching-rest-client/src/test/java/fi/vm/sade/javautils/legacy_caching_rest_client/TestParams.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package fi.vm.sade.javautils.legacy_caching_rest_client;
-
-import java.util.ArrayList;
-
-public class TestParams {
-
- public static TestParams instance;
- public static ArrayList prevRequestTicketHeaders;
-
- //
-
- public int ticketNr = 0;
- public int authRedirects = 0;
- public int authTgtCount = 0;
- public int authTicketCount = 0;
- public int isRequestAuthenticatedCount = 0;
- public int authTicketValidatedSuccessfullyCount = 0;
- public boolean failNextBackendAuthentication = false;
- public String userIsAlreadyAuthenticatedToCas = null;
-}
diff --git a/legacy-caching-rest-client/src/test/resources/log4j.properties b/legacy-caching-rest-client/src/test/resources/log4j.properties
deleted file mode 100644
index cd1cba6a..00000000
--- a/legacy-caching-rest-client/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,11 +0,0 @@
-# Root logger option
-log4j.rootLogger=INFO, CONSOLE
-
-# Direct log messages to stdout
-log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
-log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
-# Package specific logging configurations
-log4j.logger.org.springframework=INFO
-log4j.logger.fi.vm=DEBUG
diff --git a/legacy-cxf-cas/pom.xml b/legacy-cxf-cas/pom.xml
deleted file mode 100644
index 86b59a73..00000000
--- a/legacy-cxf-cas/pom.xml
+++ /dev/null
@@ -1,105 +0,0 @@
-
-
-
- java-utils
- fi.vm.sade.java-utils
- 0.3.0-SNAPSHOT
-
- 4.0.0
-
- legacy-cxf-cas
- 0.6.0-SNAPSHOT
-
-
-
-
-
- fi.vm.sade.java-utils
- java-legacy-cas
- 0.5.1-SNAPSHOT
-
-
-
- org.springframework
- spring-beans
- 5.3.5
-
-
- org.springframework
- spring-core
- 5.3.5
-
-
- org.springframework
- spring-web
- 5.3.5
-
-
- org.springframework.security
- spring-security-core
- 5.4.5
-
-
- org.springframework.security
- spring-security-cas
- 5.4.5
-
-
- org.slf4j
- slf4j-api
- 1.7.30
-
-
- javax.validation
- validation-api
- 2.0.1.Final
-
-
- org.apache.cxf
- cxf-core
- 3.4.2
-
-
- commons-codec
- commons-codec
- 1.15
-
-
-
-
-
-
-
- fi.vm.sade.java-utils
- java-legacy-cas
-
-
-
- org.springframework
- spring-web
-
-
- org.springframework.security
- spring-security-core
-
-
- org.springframework.security
- spring-security-cas
-
-
- org.slf4j
- slf4j-api
-
-
- javax.validation
- validation-api
-
-
- org.apache.cxf
- cxf-core
-
-
-
-
diff --git a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/PERA.java b/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/PERA.java
deleted file mode 100644
index 11c61ad8..00000000
--- a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/PERA.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package fi.vm.sade.javautils.legacy_cxf_cas;
-
-import fi.vm.sade.javautils.legacy_cxf_cas.ui.portlet.security.ProxyAuthenticator;
-import org.apache.http.client.methods.HttpRequestBase;
-
-/**
- * https://liitu.hard.ware.fi/confluence/display/SPEKSI/5.+Sanomien+rakenne
- */
-public class PERA {
-
- public static final String X_KUTSUKETJU_ALOITTAJA_KAYTTAJA_TUNNUS = "X-Kutsuketju.Aloittaja.KayttajaTunnus";
- public static final String X_PALVELUKUTSU_LAHETTAJA_KAYTTAJA_TUNNUS = "X-Palvelukutsu.Lahettaja.KayttajaTunnus";
- public static final String X_PALVELUKUTSU_LAHETTAJA_PROXY_AUTH = "X-Palvelukutsu.Lahettaja.ProxyAuth"; // ei perassa
-
- public static void setKayttajaHeaders(HttpRequestBase req, String currentUser, String callAsUser) {
- req.setHeader(X_KUTSUKETJU_ALOITTAJA_KAYTTAJA_TUNNUS, currentUser);
- req.setHeader(X_PALVELUKUTSU_LAHETTAJA_KAYTTAJA_TUNNUS, callAsUser);
- }
-
- public static void setProxyKayttajaHeaders(ProxyAuthenticator.Callback callback, String currentUser) {
- callback.setRequestHeader(X_KUTSUKETJU_ALOITTAJA_KAYTTAJA_TUNNUS, currentUser);
- callback.setRequestHeader(X_PALVELUKUTSU_LAHETTAJA_KAYTTAJA_TUNNUS, currentUser);
- callback.setRequestHeader(X_PALVELUKUTSU_LAHETTAJA_PROXY_AUTH, "true");
- }
-}
diff --git a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/CasApplicationAsAUserInterceptor.java b/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/CasApplicationAsAUserInterceptor.java
deleted file mode 100644
index c208bfa0..00000000
--- a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/CasApplicationAsAUserInterceptor.java
+++ /dev/null
@@ -1,168 +0,0 @@
-package fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas;
-
-import fi.vm.sade.javautils.cas.CasClient;
-import org.apache.cxf.interceptor.Fault;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.phase.AbstractPhaseInterceptor;
-import org.apache.cxf.phase.Phase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.security.authentication.TestingAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Interceptor for outgoing SOAP calls that uses "application-as-a-user" pattern: authenticates against CAS REST API to get a service ticket.
-*/
-public class CasApplicationAsAUserInterceptor extends AbstractPhaseInterceptor {
-
- private static final Logger logger = LoggerFactory.getLogger(CasApplicationAsAUserInterceptor.class);
- private static final Integer HTTP_401_UNAUTHORIZED = Integer.valueOf(401);
-
- private String webCasUrl;
- private String targetService;
- private String appClientUsername;
- private String appClientPassword;
-
- @Value("${auth.mode:cas}")
- private String authMode;
- private TicketCachePolicy ticketCachePolicy = new DefaultTicketCachePolicy();
-
- public CasApplicationAsAUserInterceptor() {
- super(Phase.PRE_PROTOCOL);
- }
-
- private static Set buildMockAuthorities() {
- Set authorities = new HashSet();
- String org = "1.2.246.562.10.00000000001"; // root
- String apps[] = new String[] { "ANOMUSTENHALLINTA", "ORGANISAATIOHALLINTA", "HENKILONHALLINTA", "KOODISTO",
- "KOOSTEROOLIENHALLINTA", "OID", "OMATTIEDOT", "ORGANISAATIOHALLINTA", "TARJONTA", "SIJOITTELU", "VALINTAPERUSTEET", "VALINTOJENTOTEUTTAMINEN", "HAKEMUS" };
- String roles[] = new String[] { "READ", "READ_UPDATE", "CRUD" };
- for (String app : apps) {
- for (String role : roles) {
- GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_APP_" + app + "_" + role); // sama
- // rooli
- // ilman
- // oidia
- GrantedAuthority authorityOid = new SimpleGrantedAuthority("ROLE_APP_" + app + "_" + role + "_" + org);
- authorities.add(authority);
- authorities.add(authorityOid);
- }
- }
- return authorities;
- }
-
- @Override
- public void handleMessage(Message message) throws Fault {
- boolean inbound = (Boolean) message.get(Message.INBOUND_MESSAGE);
- if (inbound)
- this.handleInbound(message);
- else
- this.handleOutbound(message);
- }
-
- public void handleInbound(Message message) throws Fault {
- Integer responseCode = (Integer)message.get(Message.RESPONSE_CODE);
- if (HTTP_401_UNAUTHORIZED.equals(responseCode)) {
- logger.warn("Got response code " + responseCode + " -> removing ticket from cache");
- ticketCachePolicy.clearTicket(targetService, appClientUsername);
- }
- else {
- Map> headers = (Map>)message.get(Message.PROTOCOL_HEADERS);
- List locationHeader = headers.get("Location");
- if (locationHeader != null && locationHeader.size() > 0) {
- String location = locationHeader.get(0);
- try {
- URL url = new URL(location);
- String path = url.getPath();
- // We are only interested in CAS redirects
- if(path.startsWith("/cas/login")) {
- logger.warn("Got redirect to cas -> removing ticket from cache");
- ticketCachePolicy.clearTicket(targetService, appClientUsername);
- }
- } catch(Exception ex) {
- logger.warn("Error while parsing redirect location", ex);
- }
- }
- }
- }
-
- public void handleOutbound(Message message) throws Fault {
- String serviceTicket = ticketCachePolicy.getCachedTicket(targetService, appClientUsername, new TicketCachePolicy.TicketLoader(){
- @Override
- public String loadTicket() {
- return CasClient.getTicket(webCasUrl, appClientUsername, appClientPassword, targetService);
- }
- });
-
- HttpURLConnection httpConnection = (HttpURLConnection) message.get("http.connection");
- if (serviceTicket == null && "dev".equals(authMode)) {
- Set authorities = buildMockAuthorities();
-
- String mockUser = "1.2.246.562.24.00000000001";
- logger.warn("building mock user: " + mockUser + ", authorities: " + authorities);
- Authentication authentication = new TestingAuthenticationToken(mockUser, mockUser, new ArrayList(
- authorities));
-
- httpConnection.setRequestProperty("CasSecurityTicket", "oldDeprecatedSecurity_REMOVE");
- String user = authentication.getName();
- httpConnection.setRequestProperty("oldDeprecatedSecurity_REMOVE_username", user);
- httpConnection.setRequestProperty("oldDeprecatedSecurity_REMOVE_authorities", toString(authorities));
- logger.info("DEV Proxy ticket! user: "+ user + ", authorities: "+authorities);
- return;
- }
-
- // put service ticket to SOAP message as a http header 'CasSecurityTicket'
- httpConnection.setRequestProperty("CasSecurityTicket", serviceTicket);
-
- logger.info("CasApplicationAsAUserInterceptor, targetService: {}, endpoint: {}, serviceuser: {}, CasSecurityTicket: {}", new Object[]{
- targetService,
- message.get(Message.ENDPOINT_ADDRESS),
- appClientUsername,
- serviceTicket
- });
- }
-
- public void setWebCasUrl(String webCasUrl) {
- this.webCasUrl = webCasUrl;
- }
-
- public void setTargetService(String targetService) {
- this.targetService = targetService;
- }
-
- public void setAppClientUsername(String appClientUsername) {
- this.appClientUsername = appClientUsername;
- }
-
- public void setAppClientPassword(String appClientPassword) {
- this.appClientPassword = appClientPassword;
- }
-
- private String toString(Collection extends GrantedAuthority> authorities) {
- StringBuilder sb = new StringBuilder();
- for (GrantedAuthority authority : authorities) {
- sb.append(authority.getAuthority()).append(",");
- }
- return sb.toString();
- }
-
- public TicketCachePolicy getTicketCachePolicy() {
- return ticketCachePolicy;
- }
-
- public void setTicketCachePolicy(TicketCachePolicy ticketCachePolicy) {
- this.ticketCachePolicy = ticketCachePolicy;
- }
-}
diff --git a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/DefaultTicketCachePolicy.java b/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/DefaultTicketCachePolicy.java
deleted file mode 100644
index 0abf896f..00000000
--- a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/DefaultTicketCachePolicy.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Ticket cache policy that keeps cached ticket in user's http session context
- * (if using from spring webapp), otherwise in global (not static though) context
- * (with configurable expiration time).
- */
-public class DefaultTicketCachePolicy extends TicketCachePolicy {
-
- private static class TicketInfo {
- public final String ticket;
- public final Long loaded;
- public TicketInfo(String ticket, Long loaded) {
- this.ticket = ticket;
- this.loaded = loaded;
- }
- }
-
- private static final Logger log = LoggerFactory.getLogger(DefaultTicketCachePolicy.class);
- private int globalTicketsTimeToLiveSeconds = 10*60; // 10 min default
- private Map globalTickets = new HashMap<>();
-
- @Override
- protected String getTicketFromCache(String cacheKey) {
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- String cachedTicket = null;
- if (requestAttributes != null) {
- cachedTicket = (String) requestAttributes.getAttribute(cacheKey, RequestAttributes.SCOPE_SESSION);
- } else {
- TicketInfo ticketInfo = globalTickets.get(cacheKey);
- if (ticketInfo != null) {
- // expire?
- if (System.currentTimeMillis() - ticketInfo.loaded > globalTicketsTimeToLiveSeconds * 1000) {
- globalTickets.remove(cacheKey);
- log.info("expired ticket from global expiring cache, cacheKey: " + cacheKey);
- }
- else {
- // do not return ticket to second user before 1s in order to prevent concurrent CAS validate calls with same new ticket
- while (System.currentTimeMillis() - ticketInfo.loaded < 1000) {
- try {
- Thread.sleep(100);
- } catch (Exception ignored) {}
- }
- cachedTicket = ticketInfo.ticket;
- }
- }
- }
- return cachedTicket;
- }
-
-
- @Override
- protected void putTicketToCache(String cacheKey, String ticket) {
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- if (requestAttributes != null) {
- requestAttributes.setAttribute(cacheKey, ticket, RequestAttributes.SCOPE_SESSION);
- log.info("cached ticket to httpsession, cacheKey: "+cacheKey+", ticket: "+ticket);
- } else {
- if(ticket == null) {
- globalTickets.remove(cacheKey);
- log.info("removed ticket for cacheKey: "+cacheKey);
- } else {
- globalTickets.put(cacheKey, new TicketInfo(ticket, System.currentTimeMillis()));
- log.info("cached ticket to global expiring cache, cacheKey: "+cacheKey+", ticket: "+ticket);
- }
- }
- }
-
- public void setGlobalTicketsTimeToLiveSeconds(int globalTicketsTimeToLiveSeconds) {
- this.globalTicketsTimeToLiveSeconds = globalTicketsTimeToLiveSeconds;
- }
-}
diff --git a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/TicketCachePolicy.java b/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/TicketCachePolicy.java
deleted file mode 100644
index 9bcb8803..00000000
--- a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/authentication/cas/TicketCachePolicy.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-
-/**
- * Blocking cache for CAS tickets.
- * Blocks cache gets/loads per ticketKey.
- */
-public abstract class TicketCachePolicy {
- private static final Logger log = LoggerFactory.getLogger(TicketCachePolicy.class);
-
- protected abstract String getTicketFromCache(String cacheKey);
- protected abstract void putTicketToCache(String cacheKey, String ticket);
- public final String getCachedTicket(String targetService, Object authenticationOrUsername, TicketLoader ticketLoader) {
- Authentication auth = authenticationOrUsername instanceof Authentication ? (Authentication) authenticationOrUsername : new UsernamePasswordAuthenticationToken("" + authenticationOrUsername, null);
- String cacheKey = getCacheKey(targetService, auth.getName());
- log.debug("blocking get ticket from cache... user: " + auth.getName() + ", cacheKey: "+cacheKey+", targetService: "+targetService+", thread: "+Thread.currentThread().getName());
- synchronized (cacheKey.intern()) {
- // get from cache
- String cachedTicket = this.getTicketFromCache(cacheKey);
-
- if (cachedTicket == null) {
- // get ticket
- cachedTicket = ticketLoader.loadTicket();
- log.info("blocking loaded new ticket, user: " + auth.getName() + ", cacheKey: "+cacheKey+", ticket: " + cachedTicket+", targetService: "+targetService+", thread: "+Thread.currentThread().getName());
- if (cachedTicket == null) throw new NullPointerException("blocking loaded NULL ticket, user: " + auth.getName() + ", targetService: "+targetService);
-
- // put to cache
- this.putTicketToCache(cacheKey, cachedTicket);
- }
-
- else {
- log.debug("blocking got ticket from cache, user: " + auth.getName() + ", ticket: " + cachedTicket+", targetService: "+targetService+", thread: "+Thread.currentThread().getName());
- }
-
- return cachedTicket;
- }
- }
-
- public void clearTicket(String targetService, Object authenticationOrUsername) {
- Authentication auth = authenticationOrUsername instanceof Authentication ? (Authentication) authenticationOrUsername : new UsernamePasswordAuthenticationToken("" + authenticationOrUsername, null);
- String cacheKey = getCacheKey(targetService, auth.getName());
- synchronized (cacheKey.intern()) {
- this.putTicketToCache(cacheKey, null);
- log.info("clearTicket done, user: " + auth.getName() + ", targetService: "+targetService);
- }
- }
-
- protected String getCacheKey(String targetService, String user) {
- return "cachedTicket_" + targetService + "_"+user;
- }
-
- public static interface TicketLoader {
- String loadTicket();
- }
-
-}
-
diff --git a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/ui/portlet/security/ProxyAuthenticator.java b/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/ui/portlet/security/ProxyAuthenticator.java
deleted file mode 100644
index 613ebfe1..00000000
--- a/legacy-cxf-cas/src/main/java/fi/vm/sade/javautils/legacy_cxf_cas/ui/portlet/security/ProxyAuthenticator.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package fi.vm.sade.javautils.legacy_cxf_cas.ui.portlet.security;
-
-import fi.vm.sade.javautils.legacy_cxf_cas.PERA;
-import fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas.DefaultTicketCachePolicy;
-import fi.vm.sade.javautils.legacy_cxf_cas.authentication.cas.TicketCachePolicy;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.AnonymousAuthenticationToken;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.cas.authentication.CasAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-import javax.validation.constraints.NotNull;
-import java.util.Collection;
-
-public class ProxyAuthenticator {
-
- private static final Logger log = LoggerFactory.getLogger(ProxyAuthenticator.class);
- // private TicketCachePolicy ticketCachePolicy = new
- // SimpleTicketCachePolicy();
- private TicketCachePolicy ticketCachePolicy = new DefaultTicketCachePolicy();
-
- public void proxyAuthenticate(String casTargetService, String authMode, Callback callback) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- try {
-
- if (authentication != null && "dev".equals(authMode)) {
- proxyAuthenticateDev(callback, authentication);
- }
-
- else {
- proxyAuthenticateCas(casTargetService, callback, authentication);
- }
-
- } catch (CasProxyAuthenticationException cpae) {
- throw cpae;
- } catch (Throwable e) {
- throw new RuntimeException("Could not attach security ticket to SOAP message, user: "
- + (authentication != null ? authentication.getName() : "null") + ", authmode: " + authMode
- + ", exception: " + e, e);
- }
- }
-
- protected void proxyAuthenticateCas(String casTargetService, Callback callback, Authentication authentication) {
- String proxyTicket = getCachedProxyTicket(casTargetService, authentication, callback);
- if (proxyTicket == null) {
- throw new BadCredentialsException("got null proxyticket, cannot attach to request, casTargetService: " + casTargetService
- + ", authentication: " + authentication);
- } else {
- callback.setRequestHeader("CasSecurityTicket", proxyTicket);
- PERA.setProxyKayttajaHeaders(callback, authentication.getName());
- log.debug("attached proxyticket to request! user: " + authentication.getName() + ", ticket: " + proxyTicket);
- }
- }
-
- protected void proxyAuthenticateDev(Callback callback, Authentication authentication) {
- callback.setRequestHeader("CasSecurityTicket", "oldDeprecatedSecurity_REMOVE");
- String user = authentication.getName();
- String authorities = toString(authentication.getAuthorities());
- callback.setRequestHeader("oldDeprecatedSecurity_REMOVE_username", user);
- callback.setRequestHeader("oldDeprecatedSecurity_REMOVE_authorities", authorities);
- log.debug("DEV Proxy ticket! user: " + user + ", authorities: " + authorities);
- }
-
- public String getCachedProxyTicket(final String targetService, final Authentication authentication, final Callback callback) {
- return ticketCachePolicy.getCachedTicket(targetService, authentication, new TicketCachePolicy.TicketLoader() {
- @Override
- public String loadTicket() {
- String proxyTicket = obtainNewCasProxyTicket(targetService, authentication);
- if (callback != null) {
- callback.gotNewTicket(authentication, proxyTicket);
- }
- return proxyTicket;
- }
- });
- }
-
- public void clearTicket(String casTargetService) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- ticketCachePolicy.clearTicket(casTargetService, authentication);
- }
-
- protected String obtainNewCasProxyTicket(String casTargetService, Authentication authentication) {
- if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
- throw new RuntimeException("current user is not authenticated");
- }
- String ticket = ((CasAuthenticationToken) authentication).getAssertion().getPrincipal()
- .getProxyTicketFor(casTargetService);
- if (ticket == null) {
- throw new CasProxyAuthenticationException(
- "obtainNewCasProxyTicket got null proxyticket, there must be something wrong with cas proxy authentication -scenario! check proxy callback works etc, targetService: "
- + casTargetService + ", user: " + authentication.getName());
- }
- return ticket;
- }
-
- private String toString(Collection extends GrantedAuthority> authorities) {
- StringBuilder sb = new StringBuilder();
- for (GrantedAuthority authority : authorities) {
- sb.append(authority.getAuthority()).append(",");
- }
- return sb.toString();
- }
-
- public static interface Callback {
- void setRequestHeader(String key, String value);
-
- void gotNewTicket(Authentication authentication, String proxyTicket);
- }
-
- public void setTicketCachePolicy(TicketCachePolicy ticketCachePolicy) {
- this.ticketCachePolicy = ticketCachePolicy;
- }
-
- public static class CasProxyAuthenticationException extends RuntimeException {
- CasProxyAuthenticationException() {}
-
- CasProxyAuthenticationException(@NotNull String message) {
- super(message);
- }
- }
-}
diff --git a/opintopolku-jetty/pom.xml b/opintopolku-jetty/pom.xml
deleted file mode 100644
index e71072ff..00000000
--- a/opintopolku-jetty/pom.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
- opintopolku-jetty
- 0.3.0-SNAPSHOT
- jar
-
-
-
- org.slf4j
- slf4j-api
- 1.7.30
-
-
-
-
-
- org.eclipse.jetty
- jetty-webapp
- 11.0.1
-
-
- javax.servlet
- servlet-api
- 2.5
- provided
-
-
- org.slf4j
- slf4j-api
-
-
- ch.qos.logback
- logback-access
- 1.2.3
-
-
- junit
- junit
- 4.13.2
- test
-
-
- commons-io
- commons-io
- 2.8.0
- test
-
-
-
diff --git a/opintopolku-jetty/src/main/java/fi/vm/sade/jetty/OpintopolkuJetty.java b/opintopolku-jetty/src/main/java/fi/vm/sade/jetty/OpintopolkuJetty.java
deleted file mode 100644
index aef4b643..00000000
--- a/opintopolku-jetty/src/main/java/fi/vm/sade/jetty/OpintopolkuJetty.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package fi.vm.sade.jetty;
-
-import ch.qos.logback.access.jetty.RequestLogImpl;
-import org.eclipse.jetty.server.Connector;
-import org.eclipse.jetty.server.RequestLog;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.util.Jetty;
-import org.eclipse.jetty.util.resource.Resource;
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
-import org.eclipse.jetty.util.thread.ThreadPool;
-import org.eclipse.jetty.webapp.WebAppContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.time.Duration;
-
-public class OpintopolkuJetty {
- public static final int SERVICE_PORT_IN_ECS_CONFIGURATION = 8080;
- protected static final Logger LOG = LoggerFactory.getLogger(OpintopolkuJetty.class);
-
- public void start(String contextPath) {
- start(contextPath, SERVICE_PORT_IN_ECS_CONFIGURATION, 5, 10, Duration.ofMinutes(1), Duration.ofSeconds(4000));
- }
-
- public void start(String contextPath, int port, int minThreads, int maxThreads, Duration idleThreadTimeout, Duration connectionIdleTimeout) {
- WebAppContext webAppContext = new WebAppContext();
- webAppContext.setBaseResource(Resource.newClassPathResource("/webapp"));
- start(webAppContext, createServer(port, minThreads, maxThreads, idleThreadTimeout, connectionIdleTimeout), contextPath);
- }
-
- private Server createServer(int port, int minThreads, int maxThreads, Duration idleThreadTimeout, Duration connectionIdleTimeout) {
- int idleThreadTimeoutMs = (int) idleThreadTimeout.toMillis();
- ThreadPool threadPool = createThreadpool(minThreads, maxThreads, idleThreadTimeoutMs);
- Server server = new Server(threadPool);
- ServerConnector serverConnector = new ServerConnector(server);
- serverConnector.setPort(port);
- serverConnector.setIdleTimeout(connectionIdleTimeout.toMillis());
- server.setConnectors(new Connector[]{ serverConnector });
- return server;
- }
-
- protected ThreadPool createThreadpool(int minThreads, int maxThreads, int idleThreadTimeoutMs) {
- return new QueuedThreadPool(maxThreads, minThreads, idleThreadTimeoutMs);
- }
-
- public void start(WebAppContext webAppContext, Server server, String contextPath) {
- try {
- if (server.isStopped()) {
- webAppContext.setContextPath(contextPath);
- LOG.info(String.format("Starting Jetty %s at port %d for context %s to path %s",
- Jetty.VERSION, ((ServerConnector) server.getConnectors()[0]).getPort(), webAppContext.getWar(), webAppContext.getContextPath()));
- webAppContext.setParentLoaderPriority(true);
- server.setHandler(webAppContext);
- server.setStopAtShutdown(true);
- server.setRequestLog(createAccessLogConfiguration());
- server.start();
- }
- } catch (Throwable t) {
- throw new RuntimeException(t);
- }
- }
-
- protected RequestLog createAccessLogConfiguration() {
- RequestLogImpl requestLog = new RequestLogImpl();
- String logbackAccess = System.getProperty("logback.access");
- if (logbackAccess != null) {
- requestLog.setFileName(logbackAccess);
- } else {
- LOG.warn("Jetty access log is printed to console, use -Dlogback.access=path/to/logback-access.xml to set configuration file");
- requestLog.setResource("/logback-access-to-stdout.xml");
- }
- requestLog.start();
- return requestLog;
- }
-}
diff --git a/opintopolku-jetty/src/main/resources/logback-access-to-stdout.xml b/opintopolku-jetty/src/main/resources/logback-access-to-stdout.xml
deleted file mode 100644
index e0286ad9..00000000
--- a/opintopolku-jetty/src/main/resources/logback-access-to-stdout.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
- combined
-
-
-
-
-
diff --git a/opintopolku-jetty/src/test/java/fi/vm/sade/jetty/OpintopolkuJettyTest.java b/opintopolku-jetty/src/test/java/fi/vm/sade/jetty/OpintopolkuJettyTest.java
deleted file mode 100644
index 89e10954..00000000
--- a/opintopolku-jetty/src/test/java/fi/vm/sade/jetty/OpintopolkuJettyTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package fi.vm.sade.jetty;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-
-import org.apache.commons.io.IOUtils;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.Socket;
-import java.net.URL;
-import java.time.Duration;
-import java.util.Random;
-
-public class OpintopolkuJettyTest {
- private final OpintopolkuJetty jetty = new OpintopolkuJetty();
-
- @Test
- public void opintopolkuJettyServesContentFromGivenClasspathLocation() throws Exception {
- int port = findFreeLocalPort();
- String webappPath = "/testing";
- jetty.start(webappPath, port, 1, 5, Duration.ofSeconds(10), Duration.ofSeconds(4000));
-
- URL url = new URL(String.format("http://localhost:%d%s/hello.html", port, webappPath));
-
- String responseContent;
-
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- try (AutoCloseable conWrapper = connection::disconnect) {
- connection.setRequestMethod("GET");
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(5000);
-
- responseContent = IOUtils.toString(connection.getInputStream(), "UTF-8");
- }
-
- assertThat(responseContent, containsString("Hello, world according to OpintopolkuJetty!"));
- }
-
- public final static boolean isFreeLocalPort(int port) {
- Socket socket = null;
- try {
- socket = new Socket("127.0.0.1", port);
- socket.close();
- } catch (IOException e) {
- return true;
- }
- return false;
- }
-
- public final static int findFreeLocalPort() {
- int port = new Random().nextInt(60000) + 1000;
- if (isFreeLocalPort(port)) {
- return port;
- } else {
- return findFreeLocalPort();
- }
- }
-}
diff --git a/opintopolku-jetty/src/test/resources/webapp/hello.html b/opintopolku-jetty/src/test/resources/webapp/hello.html
deleted file mode 100644
index 91c8bbe8..00000000
--- a/opintopolku-jetty/src/test/resources/webapp/hello.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-Hello, world according to OpintopolkuJetty!
-
-
diff --git a/opintopolku-spring-security/pom.xml b/opintopolku-spring-security/pom.xml
deleted file mode 100644
index 7a11df71..00000000
--- a/opintopolku-spring-security/pom.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
-
- opintopolku-spring-security
- 0.6.0-SNAPSHOT
- jar
-
- 5.4.5
- 5.3.5
-
-
-
-
-
- org.springframework
- spring-core
- ${spring.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.springframework
- spring-aop
- ${spring.version}
-
-
- org.springframework
- spring-beans
- ${spring.version}
-
-
- org.springframework
- spring-context
- ${spring.version}
-
-
- org.springframework
- spring-expression
- ${spring.version}
-
-
- org.slf4j
- slf4j-api
- 1.7.30
-
-
- org.springframework.security
- spring-security-core
- ${spring.security.version}
-
-
- commons-httpclient
- commons-httpclient
- 3.1
-
-
- commons-logging
- commons-logging
-
-
-
-
- commons-codec
- commons-codec
- 1.15
-
-
- fi.vm.sade.java-utils
- java-auth
- 0.4.1-SNAPSHOT
-
-
- fi.vm.sade.java-utils
- java-cache
- 0.1.0-SNAPSHOT
-
-
-
-
-
-
- org.springframework
- spring-core
-
-
- org.slf4j
- slf4j-api
-
-
- org.springframework.security
- spring-security-core
-
-
- commons-httpclient
- commons-httpclient
-
-
- fi.vm.sade.java-utils
- java-auth
-
-
- fi.vm.sade.java-utils
- java-cache
-
-
-
diff --git a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/Authorizer.java b/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/Authorizer.java
deleted file mode 100644
index 26747968..00000000
--- a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/Authorizer.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package fi.vm.sade.javautils.opintopolku_spring_security;
-
-import fi.vm.sade.authorization.NotAuthorizedException;
-
-public interface Authorizer {
- void checkUserIsNotSame(String userOid) throws NotAuthorizedException;
-
- void checkOrganisationAccess(String targetOrganisationOid, String... roles) throws NotAuthorizedException;
-}
diff --git a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OidProvider.java b/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OidProvider.java
deleted file mode 100644
index 9da76ca5..00000000
--- a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OidProvider.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package fi.vm.sade.javautils.opintopolku_spring_security;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class OidProvider {
- protected final Logger log = LoggerFactory.getLogger(getClass());
-
- private final String organisaatioServiceUrl;
-
- private final String rootOrganisaatioOid;
- private final String callerId;
-
- public OidProvider(String organisaatioServiceUrl, String rootOrganisaatioOid, String callerId) {
- this.organisaatioServiceUrl = organisaatioServiceUrl;
- this.rootOrganisaatioOid = rootOrganisaatioOid;
- this.callerId = callerId;
- }
-
- public List getSelfAndParentOids(String organisaatioOid) {
- try {
- String url = organisaatioServiceUrl+"/rest/organisaatio/"+organisaatioOid+"/parentoids";
- String result = httpGet(url, 200);
- return Arrays.asList(result.split("/"));
- } catch (Exception e) {
- log.warn("failed to getSelfAndParentOids, exception: "+e+", returning only rootOrganisaatioOid and organisaatioOid");
- return Arrays.asList(rootOrganisaatioOid, organisaatioOid);
- }
- }
-
- private String httpGet(String url, int expectedStatus) {
- HttpClient client = new HttpClient();
- GetMethod get = new GetMethod(url);
- get.addRequestHeader("Caller-Id", callerId);
- try {
- client.executeMethod(get);
- final String response = get.getResponseBodyAsString();
- if (get.getStatusCode() == expectedStatus) {
- return response;
- } else {
- throw new RuntimeException("failed to call '"+url+"', invalid status: "+get.getStatusCode()+"/"+get.getStatusText());
- }
- } catch (final Exception e) {
- throw new RuntimeException("failed to call '"+url+"': "+e, e);
- } finally {
- get.releaseConnection();
- }
- }
-}
diff --git a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OrganisationHierarchyAuthorizer.java b/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OrganisationHierarchyAuthorizer.java
deleted file mode 100644
index 78371463..00000000
--- a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/OrganisationHierarchyAuthorizer.java
+++ /dev/null
@@ -1,200 +0,0 @@
-package fi.vm.sade.javautils.opintopolku_spring_security;
-
-import fi.vm.sade.authorization.NotAuthorizedException;
-import fi.vm.sade.security.SimpleCache;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-@Component
-public class OrganisationHierarchyAuthorizer { // TODO: cas todo rename?
-
- private static final Logger LOGGER = LoggerFactory.getLogger(OrganisationHierarchyAuthorizer.class);
- public static final int MAX_CACHE_SIZE = 10000;
- public static final String ANY_ROLE = "*";
-
- @Autowired
- private OidProvider oidProvider;
-
- // poor man's cache, use auth object as part of key so objects will last only one authenticated session
- //private Map> cache = new ConcurrentHashMap>();
- // not linked to user anymore, remove oldest entries instead
- // http://stackoverflow.com/questions/224868/easy-simple-to-use-lru-cache-in-java
- private static Map> cache = SimpleCache.>buildCache(MAX_CACHE_SIZE);
-
- public OrganisationHierarchyAuthorizer() {
- }
-
- public OrganisationHierarchyAuthorizer(OidProvider oidProvider) {
- this.oidProvider = oidProvider;
- }
-
- /**
- * Check if current user has at least one of given requriedRoles to target organisation or it's parents.
- *
- * @param targetOrganisationOid
- * @param requriedRoles
- * @throws NotAuthorizedException
- */
- public void checkAccess(Authentication currentUser, String targetOrganisationOid, String[] requriedRoles) throws NotAuthorizedException {
-
- // do assertions
- if (currentUser == null) {
- throw new NotAuthorizedException("checkAccess failed, currentUser is null");
- }
-
- List userRoles = toStringRoles(currentUser.getAuthorities());
- checkAccess(userRoles, targetOrganisationOid, requriedRoles);
- }
-
- /**
- * @see #checkAccess(Authentication, String, String[])
- */
- public void checkAccess(List userRoles, String targetOrganisationOid, String[] requiredRoles) throws NotAuthorizedException {
-
- List targetOrganisationAndParentsOids = getSelfAndParentOidsCached(targetOrganisationOid);
- if (targetOrganisationAndParentsOids == null || targetOrganisationAndParentsOids.size() == 0) {
- throw new NotAuthorizedException("checkAccess failed, no targetOrganisationAndParentsOids null");
- }
- if (requiredRoles == null || requiredRoles.length == 0) {
- throw new NotAuthorizedException("checkAccess failed, no requiredRoles given");
- }
-
- // do the checks
-
- // sen sijaan että tarkastettaisiin käyttäjän roolipuussa alaspäin, tarkastetaan kohde-puussa ylöspäin
- // jos käyttäjällä on rooli organisaatioon, tai johonkin sen parenttiin, pääsy sallitaan
- for (String role : requiredRoles) {
- for (String oid : targetOrganisationAndParentsOids) {
- for (String userRole : userRoles) {
- if (roleMatchesToAuthority(role, userRole) && authorityIsTargetedToOrganisation(userRole, oid)) {
- return;
- }
- }
- }
- }
- final String msg = "Not authorized! targetOrganisationAndParentsOids: " + targetOrganisationAndParentsOids + ", requiredRoles: " + Arrays.asList(requiredRoles) + ", userRoles: " + userRoles;
- throw new NotAuthorizedException(msg);
- }
-
- /**
- * Checks if the current user has at least one of given requiredRoles
- *
- * @param currentUser
- * @param requiredRoles
- * @throws NotAuthorizedException
- */
- public void checkAccess(Authentication currentUser, String[] requiredRoles) throws NotAuthorizedException {
- // do assertions
- if (currentUser == null) {
- throw new NotAuthorizedException("checkAccess failed, currentUser is null");
- }
-
- if (requiredRoles == null || requiredRoles.length == 0) {
- throw new NotAuthorizedException("checkAccess failed, no requiredRoles given");
- }
-
- for(String role: requiredRoles) {
- for(GrantedAuthority authority : currentUser.getAuthorities()) {
- if(roleMatchesToAuthority(role, authority.getAuthority())) {
- return;
- }
- }
- }
-
- final String msg = "Not authorized! currentUser: " + currentUser + ", requiredRoles: " + Arrays.asList(requiredRoles);
- throw new NotAuthorizedException(msg);
- }
-
- private List getSelfAndParentOidsCached(String targetOrganisationOid) {
- String cacheKey = targetOrganisationOid; // ei enää user-kohtaista cachea koska organisaatioparentit ei about ikinä muutu
- List cacheResult = cache.get(cacheKey);
- if (cacheResult == null) {
- cacheResult = oidProvider.getSelfAndParentOids(targetOrganisationOid);
- cache.put(cacheKey, cacheResult);
- }
- return cacheResult;
- }
-
- private static boolean roleMatchesToAuthority(String role, String authority) {
- if (ANY_ROLE.equals(role)) {
- return true;
- }
- role = stripRolePrefix(role);
- return authority.contains(role);
- }
-
- private static String stripRolePrefix(String role) {
- return role.replace("APP_", "").replace("ROLE_", "");
- }
-
- private static boolean authorityIsTargetedToOrganisation(String authority, String oid) {
- return authority.endsWith(oid);
- }
-
- /**
- * Filtteröidään käyttäjän rooleista ne, joihin käyttäjällä on haluttu oikeus, ja palautetaan kohdeorganisaatiot
- * Esim:
- *
- * // mille organisaatiolle käyttäjällä on vähintään read-oikeus koodistoon
- * String koodistoTargetOrganisaatioOid = getOrganisaatioTheUserHasPermissionTo("ROLE_APP_KOODISTO_READ", "ROLE_APP_KOODISTO_READ_UPDATE", "ROLE_APP_KOODISTO_CRUD");
- *
- * @param permissionCandidates
- * @return
- */
- public static String getOrganisaatioTheUserHasPermissionTo(String... permissionCandidates) {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- return getOrganisaatioTheUserHasPermissionTo(authentication, permissionCandidates);
- }
-
- public static String getOrganisaatioTheUserHasPermissionTo(Authentication authentication, String... permissionCandidates) {
- List userRoles = toStringRoles(authentication.getAuthorities());
- return getOrganisaatioTheUserHasPermissionTo(userRoles, permissionCandidates);
- }
-
- private static List toStringRoles(Collection extends GrantedAuthority> authorities) {
- List userRoles = new ArrayList();
- for (GrantedAuthority authority : authorities) {
- userRoles.add(authority.getAuthority());
- }
- return userRoles;
- }
-
- public static String getOrganisaatioTheUserHasPermissionTo(List userRoles, String... permissionCandidates) {
- List whatRoles = Arrays.asList(permissionCandidates);
- Set orgs = new HashSet();
- for (String userRole : userRoles) {
- if (!userRole.endsWith("READ") && !userRole.endsWith("READ_UPDATE") && !userRole.endsWith("CRUD")) { // only check user roles that end with org oid
- int x = userRole.lastIndexOf("_");
- if (x != -1) {
- String rolePart = userRole.substring(0, x);
- if (whatRoles.contains(rolePart)) {
- String orgPart = userRole.substring(x + 1);
- orgs.add(orgPart);
- }
- }
- }
- }
- if (orgs.isEmpty()) {
- LOGGER.warn("user does not have role "+whatRoles+" to any organisaatios, userRoles: "+userRoles);
- return null;
- }
- if (orgs.size() > 1) {
- throw new RuntimeException("not supported: user has role "+whatRoles+" to more than 1 organisaatios: "+orgs); // ei tuetä tämmöistä keissiä ainakaan vielä
- }
- return orgs.iterator().next();
- }
-
-}
diff --git a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/SadeBusinessException.java b/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/SadeBusinessException.java
deleted file mode 100644
index 074ced97..00000000
--- a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/SadeBusinessException.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package fi.vm.sade.javautils.opintopolku_spring_security;
-
-public abstract class SadeBusinessException extends RuntimeException {
-
- private static final long serialVersionUID = -3166133180867859097L;
-
- public SadeBusinessException() {
- super();
- }
-
- public SadeBusinessException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public SadeBusinessException(String message) {
- super(message);
- }
-
- public SadeBusinessException(Throwable cause) {
- super(cause);
- }
-
- public abstract String getErrorKey();
-}
diff --git a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/ThreadLocalAuthorizer.java b/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/ThreadLocalAuthorizer.java
deleted file mode 100644
index 6b1ad476..00000000
--- a/opintopolku-spring-security/src/main/java/fi/vm/sade/javautils/opintopolku_spring_security/ThreadLocalAuthorizer.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package fi.vm.sade.javautils.opintopolku_spring_security;
-
-import fi.vm.sade.authorization.NotAuthorizedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-
-@Component
-public class ThreadLocalAuthorizer implements fi.vm.sade.javautils.opintopolku_spring_security.Authorizer {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ThreadLocalAuthorizer.class);
-
- // @Autowired
-// private OidProvider oidProvider;
- @Autowired
- private fi.vm.sade.javautils.opintopolku_spring_security.OrganisationHierarchyAuthorizer authorizer;
-
- @Override
- public void checkOrganisationAccess(String targetOrganisationOid, String... roles) throws NotAuthorizedException {
- /*OrganisationHierarchyAuthorizer*/authorizer.checkAccess(
- SecurityContextHolder.getContext().getAuthentication(),
- /*oidProvider.getSelfAndParentOids(targetOrganisationOid),*/
- targetOrganisationOid,
- roles); // TODO: cas todo, onko oikeet roolinimet, eli ROLE_KOODISTO_CRUD, eikä esim pelkkä CRUD ???
- }
-
- @Override
- public void checkUserIsNotSame(String userOid) throws NotAuthorizedException {
- LOGGER.info("Authorizing with thread local data.");
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- LOGGER.error("Not authorized! User is null.");
- throw new NotAuthorizedException("User is not authorized for Authentication");
- }
- String user = authentication.getName();
- if (user == null) {
- LOGGER.error("Not authorized! User has no id.");
- throw new NotAuthorizedException("User is not authorized for Authentication");
- } else if (user.equals(userOid)) {
- LOGGER.error("Not authorized! User can't edit his/her own data");
- throw new NotAuthorizedException("User is not authorized for Authentication");
- }
-
- LOGGER.info("Authorized!");
- }
-
- public void setAuthorizer(fi.vm.sade.javautils.opintopolku_spring_security.OrganisationHierarchyAuthorizer authorizer) {
- this.authorizer = authorizer;
- }
-}
diff --git a/pom.xml b/pom.xml
index db16e1a3..673259da 100644
--- a/pom.xml
+++ b/pom.xml
@@ -10,21 +10,10 @@
java-properties
oid-generator
java-cas
- java-legacy-cas
- java-cxf
httpclient
- embedded-tomcat
opintopolku-cas-servlet-filter
- java-auth
java-http
- java-poi
opintopolku-user-details-service
- java-cache
- opintopolku-spring-security
- legacy-cxf-cas
- legacy-caching-rest-client
- spring-aware-health-check-servlet
- opintopolku-jetty
suomifi-valtuudet-client
diff --git a/spring-aware-health-check-servlet/pom.xml b/spring-aware-health-check-servlet/pom.xml
deleted file mode 100644
index e5956ed4..00000000
--- a/spring-aware-health-check-servlet/pom.xml
+++ /dev/null
@@ -1,144 +0,0 @@
-
-
- 4.0.0
-
- fi.vm.sade.java-utils
- java-utils
- 0.3.0-SNAPSHOT
- ..
-
- spring-aware-health-check-servlet
- 0.5.1-SNAPSHOT
- jar
-
-
-
- org.springframework
- spring-core
- 5.3.5
-
-
- org.springframework
- spring-beans
- 5.3.5
-
-
- org.springframework
- spring-context
- 5.3.5
-
-
- org.springframework
- spring-aop
- 5.3.5
-
-
- org.springframework
- spring-expression
- 5.3.5
-
-
- org.springframework
- spring-web
- 5.3.5
-
-
- org.springframework
- spring-jdbc
- 5.3.5
-
-
- org.springframework.security
- spring-security-core
- 5.4.5
-
-
- org.apache.httpcomponents
- httpcore
- 4.4.14
-
-
- javax.servlet
- javax.servlet-api
- 4.0.1
- provided
-
-
- com.google.code.gson
- gson
- 2.8.6
-
-
- fi.vm.sade.java-utils
- legacy-caching-rest-client
- 0.6.0-SNAPSHOT
-
-
- fi.vm.sade.java-utils
- java-cache
- 0.1.0-SNAPSHOT
-
-
- org.slf4j
- slf4j-api
- 1.7.30
-
-
- commons-logging
- commons-logging
- 1.2
-
-
- commons-codec
- commons-codec
- 1.15
-
-
-
-
-
- org.springframework
- spring-core
-
-
- org.springframework
- spring-beans
-
-
- org.springframework
- spring-context
-
-
- org.springframework
- spring-web
-
-
- org.springframework
- spring-jdbc
-
-
- org.springframework.security
- spring-security-core
-
-
- javax.servlet
- javax.servlet-api
-
-
- com.google.code.gson
- gson
-
-
- fi.vm.sade.java-utils
- legacy-caching-rest-client
-
-
- fi.vm.sade.java-utils
- java-cache
-
-
- org.slf4j
- slf4j-api
-
-
-
diff --git a/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/BuildVersionHealthChecker.java b/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/BuildVersionHealthChecker.java
deleted file mode 100644
index 660442d2..00000000
--- a/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/BuildVersionHealthChecker.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package fi.vm.sade.javautils.healthcheck;
-
-import fi.vm.sade.javautils.healthcheck.HealthChecker;
-
-import javax.servlet.ServletContext;
-import java.util.HashMap;
-import java.util.Properties;
-
-public class BuildVersionHealthChecker implements HealthChecker {
- private ServletContext servletContext;
-
- public BuildVersionHealthChecker(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- @Override
- public Object checkHealth() throws Throwable {
- Properties buildversionProps = new Properties();
- buildversionProps.load(servletContext.getResourceAsStream("buildversion.txt"));
- return new HashMap(buildversionProps);
- }
-}
diff --git a/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/DatabaseHealthChecker.java b/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/DatabaseHealthChecker.java
deleted file mode 100644
index cfec9cf8..00000000
--- a/spring-aware-health-check-servlet/src/main/java/fi/vm/sade/javautils/healthcheck/DatabaseHealthChecker.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package fi.vm.sade.javautils.healthcheck;
-
-import fi.vm.sade.javautils.healthcheck.HealthChecker;
-import org.springframework.jdbc.core.JdbcTemplate;
-
-import javax.sql.DataSource;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-class DatabaseHealthChecker implements HealthChecker {
-
- private DataSource dataSource;
-
- public DatabaseHealthChecker(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- @Override
- public Object checkHealth() throws Throwable {
- if (dataSource != null) {
- Map result = new LinkedHashMap();
- DatabaseMetaData dbMetaData = dataSource.getConnection().getMetaData();
- result.put("url", dbMetaData.getURL());
- ResultSet rs = dbMetaData.getTables(null, null, "DATA_STATUS", null);
- boolean dataStatusTableExists = rs.next();
- if (dataStatusTableExists) {
- JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
- List