From 53ae84e6e13760e564b40967d9866090e1a0d778 Mon Sep 17 00:00:00 2001 From: Dustin Jenkins Date: Thu, 21 Nov 2024 21:37:14 +0000 Subject: [PATCH] ci: spotless changes --- build.gradle | 63 ++++++++++++++++- .../ApplicationConfiguration.java | 69 ++++++++++--------- .../SciencePortalAuthAction.java | 56 ++++++++------- .../SciencePortalAuthGetAction.java | 14 ++-- .../scienceportal/context/GetAction.java | 5 +- .../scienceportal/image/GetAction.java | 5 +- .../oidc/callback/GetAction.java | 32 ++++----- .../scienceportal/oidc/login/GetAction.java | 3 +- .../scienceportal/repository/GetAction.java | 5 +- .../scienceportal/session/DeleteAction.java | 12 ++-- .../scienceportal/session/GetAction.java | 5 +- .../scienceportal/session/PostAction.java | 23 ++++--- .../scienceportal/userinfo/GetAction.java | 23 +++---- .../scienceportal/session/PostActionTest.java | 39 ++++++++--- 14 files changed, 214 insertions(+), 140 deletions(-) diff --git a/build.gradle b/build.gradle index dc01619..4c6f4aa 100644 --- a/build.gradle +++ b/build.gradle @@ -3,10 +3,12 @@ import org.apache.tools.ant.filters.ReplaceTokens plugins { id 'war' id "com.github.node-gradle.node" version "3.0.1" - id 'com.diffplug.spotless' version '6.25.0' + id 'com.diffplug.spotless' version '6.13.0' // IntelliJ IDEA plugin here to allow integration tests to appear properly in IDEs. id 'idea' + id 'jacoco' + id 'org.jetbrains.dokka' version '1.6.0' } node { @@ -72,3 +74,62 @@ processResources.dependsOn 'buildReactApp' assemble.dependsOn 'copyDevToDist' clean.delete << file('src/main/webapp/dist') + +spotless { + java { + // Use the default importOrder configuration + importOrder() + // Remove unused imports + removeUnusedImports() + // Google Java Format, Android Open Source Project style which uses 4 spaces for indentation + palantirJavaFormat() + // Format annotations on a single line + formatAnnotations() + } + format 'misc', { + target '*.gradle' + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } +} +check.dependsOn spotlessCheck + +// Create Java Code Coverage Reports +jacocoTestReport { + reports { + xml.enabled true + html.enabled true + } +} +check.dependsOn jacocoTestReport + +// Create JavaDoc +javadoc { + destinationDir = file("${buildDir}/docs/javadoc") +} + +// Create Java Documentation using Dokka for Github Markdown and HTML +tasks.dokkaGfm.configure { + outputDirectory.set(file("${buildDir}/docs/dokka/gfm")) + dokkaSourceSets { + register("main") { + sourceRoots.from(file("src/main/java")) + } + } +} +tasks.dokkaHtml.configure { + outputDirectory.set(file("${buildDir}/docs/dokka/html")) + dokkaSourceSets { + register("main") { + sourceRoots.from(file("src/main/java")) + } + configureEach { + jdkVersion.set(11) + sourceLink { + localDirectory.set(file("src/main/java")) + remoteUrl.set("https://github.com/opencadc/science-portal/tree/main/src/main/java") + } + } + } +} diff --git a/src/main/java/org/opencadc/scienceportal/ApplicationConfiguration.java b/src/main/java/org/opencadc/scienceportal/ApplicationConfiguration.java index aa38de0..97ace0a 100644 --- a/src/main/java/org/opencadc/scienceportal/ApplicationConfiguration.java +++ b/src/main/java/org/opencadc/scienceportal/ApplicationConfiguration.java @@ -1,11 +1,17 @@ package org.opencadc.scienceportal; - import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.LocalAuthority; import ca.nrc.cadc.reg.client.RegistryClient; import ca.nrc.cadc.util.StringUtil; +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.util.Arrays; +import java.util.Date; +import java.util.NoSuchElementException; +import java.util.Set; import org.apache.commons.configuration2.CombinedConfiguration; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; @@ -18,28 +24,18 @@ import org.json.JSONObject; import org.opencadc.token.Client; -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.util.Arrays; -import java.util.Date; -import java.util.NoSuchElementException; -import java.util.Set; - - public class ApplicationConfiguration { // Included in the JSP public static final long BUILD_TIME_MS = new Date().getTime(); public static final String FIRST_PARTY_COOKIE_NAME = "__Host-science-portal-auth"; - public static final String DEFAULT_CONFIG_FILE_PATH = System.getProperty("user.home") - + "/config/org.opencadc.science-portal.properties"; + public static final String DEFAULT_CONFIG_FILE_PATH = + System.getProperty("user.home") + "/config/org.opencadc.science-portal.properties"; private static final Logger LOGGER = Logger.getLogger(ApplicationConfiguration.class); private final Configuration configuration; private final String filePath; - public ApplicationConfiguration() { this.filePath = ApplicationConfiguration.DEFAULT_CONFIG_FILE_PATH; @@ -49,9 +45,9 @@ public ApplicationConfiguration() { combinedConfiguration.addConfiguration(new SystemConfiguration()); final Parameters parameters = new Parameters(); - final FileBasedConfigurationBuilder builder = - new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure( - parameters.properties().setFileName(filePath)); + final FileBasedConfigurationBuilder builder = new FileBasedConfigurationBuilder<>( + PropertiesConfiguration.class) + .configure(parameters.properties().setFileName(filePath)); try { combinedConfiguration.addConfiguration(builder.getConfiguration()); @@ -89,11 +85,14 @@ public String getTokenCacheURLString() { * @return String array, never null. */ public String[] getTabLabels() { - final String[] tabLabelArray = Arrays.stream(configuration.getString(ConfigurationKey.TAB_LABELS.propertyName).split(",")) - .map(String::trim) - .toArray(String[]::new); + final String[] tabLabelArray = Arrays.stream(configuration + .getString(ConfigurationKey.TAB_LABELS.propertyName) + .split(",")) + .map(String::trim) + .toArray(String[]::new); if (tabLabelArray.length == 0) { - throw new IllegalStateException("Configuration property " + ConfigurationKey.TAB_LABELS.propertyName + " is missing" + this.filePath); + throw new IllegalStateException("Configuration property " + ConfigurationKey.TAB_LABELS.propertyName + + " is missing" + this.filePath); } return tabLabelArray; @@ -110,9 +109,9 @@ public JSONObject getHeaderURLs() { Arrays.stream(ApplicationStandards.values()).forEach(applicationStandard -> { try { - jsonObject.put(applicationStandard.standardID.toString(), - registryClient.getAccessURL(RegistryClient.Query.APPLICATIONS, - applicationStandard.standardID)); + jsonObject.put( + applicationStandard.standardID.toString(), + registryClient.getAccessURL(RegistryClient.Query.APPLICATIONS, applicationStandard.standardID)); } catch (Exception e) { LOGGER.warn("Unable to get Applications URL for " + applicationStandard.standardID, e); } @@ -123,7 +122,8 @@ public JSONObject getHeaderURLs() { final Set credEndpoints = localAuthority.getServiceURIs(Standards.CRED_PROXY_10); if (!credEndpoints.isEmpty()) { final URI credServiceID = credEndpoints.stream().findFirst().orElseThrow(IllegalStateException::new); - final URL credServiceURL = registryClient.getServiceURL(credServiceID, Standards.CRED_PROXY_10, AuthMethod.CERT); + final URL credServiceURL = + registryClient.getServiceURL(credServiceID, Standards.CRED_PROXY_10, AuthMethod.CERT); if (credServiceURL != null) { jsonObject.put("ivo://cadc.nrc.ca/cred", credServiceURL.toExternalForm()); @@ -140,8 +140,8 @@ String getStringValue(final String key, final boolean required) { final String val = this.configuration.getString(key); if (required && !StringUtil.hasText(val)) { - throw new IllegalStateException("Configuration property " + key + " is missing or invalid at " - + this.filePath); + throw new IllegalStateException( + "Configuration property " + key + " is missing or invalid at " + this.filePath); } else { return val; } @@ -172,18 +172,23 @@ public String getOIDCScope() { } public boolean isOIDCConfigured() { - return StringUtil.hasText(getOIDCClientID()) && StringUtil.hasText(getOIDCClientSecret()) - && StringUtil.hasText(getOIDCCallbackURI()) && StringUtil.hasText(getOIDCScope()) + return StringUtil.hasText(getOIDCClientID()) + && StringUtil.hasText(getOIDCClientSecret()) + && StringUtil.hasText(getOIDCCallbackURI()) + && StringUtil.hasText(getOIDCScope()) && StringUtil.hasText(getTokenCacheURLString()); } public Client getOIDCClient() throws IOException { - return new Client(getOIDCClientID(), getOIDCClientSecret(), - new URL(getOIDCCallbackURI()), new URL(getOIDCRedirectURI()), - getOIDCScope().split(" "), getTokenCacheURLString()); + return new Client( + getOIDCClientID(), + getOIDCClientSecret(), + new URL(getOIDCCallbackURI()), + new URL(getOIDCRedirectURI()), + getOIDCScope().split(" "), + getTokenCacheURLString()); } - private enum ApplicationStandards { PASSWORD_CHANGE(URI.create("ivo://cadc.nrc.ca/passchg")), PASSWORD_RESET(URI.create("ivo://cadc.nrc.ca/passreset")), diff --git a/src/main/java/org/opencadc/scienceportal/SciencePortalAuthAction.java b/src/main/java/org/opencadc/scienceportal/SciencePortalAuthAction.java index a161d51..603fc3d 100644 --- a/src/main/java/org/opencadc/scienceportal/SciencePortalAuthAction.java +++ b/src/main/java/org/opencadc/scienceportal/SciencePortalAuthAction.java @@ -76,19 +76,17 @@ import ca.nrc.cadc.rest.InlineContentHandler; import ca.nrc.cadc.rest.RestAction; import ca.nrc.cadc.util.StringUtil; +import java.io.IOException; import java.net.URL; +import java.util.Arrays; +import java.util.Collections; +import java.util.NoSuchElementException; import java.util.Set; +import javax.security.auth.Subject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opencadc.token.Client; -import javax.security.auth.Subject; -import java.io.IOException; -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; -import java.util.NoSuchElementException; - /** * Base class to support storing the OIDC Access Token in a cookie. * This should be replaced with a (BFF), but this @@ -112,27 +110,28 @@ protected Subject getCurrentSubject(final URL targetURL) throws Exception { final Subject subject = AuthenticationUtil.getCurrentSubject(); if (StringUtil.hasText(rawCookieHeader)) { - final String[] firstPartyCookies = - Arrays.stream(rawCookieHeader.split(";")) - .map(String::trim) - .filter(cookieString -> cookieString.startsWith( - ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME)) - .toArray(String[]::new); + final String[] firstPartyCookies = Arrays.stream(rawCookieHeader.split(";")) + .map(String::trim) + .filter(cookieString -> cookieString.startsWith(ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME)) + .toArray(String[]::new); if (firstPartyCookies.length > 0 && applicationConfiguration.isOIDCConfigured()) { for (final String cookie : firstPartyCookies) { // Only split on the first "=" symbol, and trim any wrapping double quotes - final String encryptedCookieValue = - cookie.split("=", 2)[1].replaceAll("\"", ""); + final String encryptedCookieValue = cookie.split("=", 2)[1].replaceAll("\"", ""); try { final String accessToken = getOIDCClient().getAccessToken(encryptedCookieValue); - subject.getPrincipals().add(new AuthorizationTokenPrincipal(AuthenticationUtil.AUTHORIZATION_HEADER, - AuthenticationUtil.CHALLENGE_TYPE_BEARER - + " " + accessToken)); - subject.getPublicCredentials().add(new AuthorizationToken(AuthenticationUtil.CHALLENGE_TYPE_BEARER, accessToken, - Collections.singletonList(targetURL.getHost()))); + subject.getPrincipals() + .add(new AuthorizationTokenPrincipal( + AuthenticationUtil.AUTHORIZATION_HEADER, + AuthenticationUtil.CHALLENGE_TYPE_BEARER + " " + accessToken)); + subject.getPublicCredentials() + .add(new AuthorizationToken( + AuthenticationUtil.CHALLENGE_TYPE_BEARER, + accessToken, + Collections.singletonList(targetURL.getHost()))); } catch (NoSuchElementException noTokenForKeyInCacheException) { LOGGER.warn("Cookie found and decrypted but no value in cache. Ignoring cookie..."); } @@ -140,16 +139,21 @@ protected Subject getCurrentSubject(final URL targetURL) throws Exception { if (!subject.getPrincipals(AuthorizationTokenPrincipal.class).isEmpty()) { // Ensure it's clean first. - subject.getPublicCredentials(AuthMethod.class) - .forEach(authMethod -> subject.getPublicCredentials().remove(authMethod)); + subject.getPublicCredentials(AuthMethod.class).forEach(authMethod -> subject.getPublicCredentials() + .remove(authMethod)); subject.getPublicCredentials().add(AuthMethod.TOKEN); } } else if (AuthenticationUtil.getAuthMethod(subject) == AuthMethod.COOKIE) { - final Set publicCookieCredentials = subject.getPublicCredentials(SSOCookieCredential.class); + final Set publicCookieCredentials = + subject.getPublicCredentials(SSOCookieCredential.class); if (!publicCookieCredentials.isEmpty()) { - final SSOCookieCredential publicCookieCredential = publicCookieCredentials.toArray(new SSOCookieCredential[0])[0]; - subject.getPublicCredentials().add(new SSOCookieCredential(publicCookieCredential.getSsoCookieValue(), targetURL.getHost(), - publicCookieCredential.getExpiryDate())); + final SSOCookieCredential publicCookieCredential = + publicCookieCredentials.toArray(new SSOCookieCredential[0])[0]; + subject.getPublicCredentials() + .add(new SSOCookieCredential( + publicCookieCredential.getSsoCookieValue(), + targetURL.getHost(), + publicCookieCredential.getExpiryDate())); } } } diff --git a/src/main/java/org/opencadc/scienceportal/SciencePortalAuthGetAction.java b/src/main/java/org/opencadc/scienceportal/SciencePortalAuthGetAction.java index 454f970..0440f98 100644 --- a/src/main/java/org/opencadc/scienceportal/SciencePortalAuthGetAction.java +++ b/src/main/java/org/opencadc/scienceportal/SciencePortalAuthGetAction.java @@ -68,19 +68,15 @@ package org.opencadc.scienceportal; -import ca.nrc.cadc.auth.AuthenticationUtil; import ca.nrc.cadc.net.HttpGet; -import ca.nrc.cadc.rest.InlineContentHandler; -import ca.nrc.cadc.rest.RestAction; import ca.nrc.cadc.util.StringUtil; - -import javax.security.auth.Subject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.PrivilegedExceptionAction; import java.util.stream.Collectors; +import javax.security.auth.Subject; public abstract class SciencePortalAuthGetAction extends SciencePortalAuthAction { @@ -99,16 +95,14 @@ public void doAction() throws Exception { if (!syncInput.getParameterNames().isEmpty()) { query = (StringUtil.hasText(apiEndpointURL.getQuery()) ? "&" : "?") + syncInput.getParameterNames().stream() - .map(k -> k + "=" + this.syncInput.getParameter(k)) - .collect(Collectors.joining("&")); + .map(k -> k + "=" + this.syncInput.getParameter(k)) + .collect(Collectors.joining("&")); } else { query = ""; } Subject.doAs(subject, (PrivilegedExceptionAction) () -> { - final HttpGet httpGet = - new HttpGet(new URL(apiEndpoint + query), - true); + final HttpGet httpGet = new HttpGet(new URL(apiEndpoint + query), true); httpGet.setRequestProperty("accept", "application/json"); httpGet.prepare(); diff --git a/src/main/java/org/opencadc/scienceportal/context/GetAction.java b/src/main/java/org/opencadc/scienceportal/context/GetAction.java index 76c8fb1..df0dab9 100644 --- a/src/main/java/org/opencadc/scienceportal/context/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/context/GetAction.java @@ -71,11 +71,10 @@ import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthGetAction; - import java.net.URI; import java.net.URL; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthGetAction; public class GetAction extends SciencePortalAuthGetAction { private static final String CONTEXT_ENDPOINT = "/context"; diff --git a/src/main/java/org/opencadc/scienceportal/image/GetAction.java b/src/main/java/org/opencadc/scienceportal/image/GetAction.java index 209ccf9..beb240d 100644 --- a/src/main/java/org/opencadc/scienceportal/image/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/image/GetAction.java @@ -71,11 +71,10 @@ import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthGetAction; - import java.net.URI; import java.net.URL; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthGetAction; public class GetAction extends SciencePortalAuthGetAction { private static final String IMAGE_ENDPOINT = "/image"; diff --git a/src/main/java/org/opencadc/scienceportal/oidc/callback/GetAction.java b/src/main/java/org/opencadc/scienceportal/oidc/callback/GetAction.java index f4eeb6c..12411de 100644 --- a/src/main/java/org/opencadc/scienceportal/oidc/callback/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/oidc/callback/GetAction.java @@ -69,19 +69,17 @@ package org.opencadc.scienceportal.oidc.callback; import ca.nrc.cadc.util.StringUtil; -import org.opencadc.token.Client; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthAction; - -import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; - +import javax.servlet.http.HttpServletResponse; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthAction; +import org.opencadc.token.Client; public class GetAction extends SciencePortalAuthAction { - private static final String COOKIE_FORMAT = ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME - + "=%s; Path=/; Secure; HttpOnly"; + private static final String COOKIE_FORMAT = + ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME + "=%s; Path=/; Secure; HttpOnly"; @Override public void doAction() throws Exception { @@ -93,20 +91,18 @@ public void doAction() throws Exception { } void setCookie(final byte[] encryptedAssetsKey) { - syncOutput.setHeader("set-cookie", String.format(GetAction.COOKIE_FORMAT, - new String(encryptedAssetsKey, - StandardCharsets.ISO_8859_1))); + syncOutput.setHeader( + "set-cookie", + String.format(GetAction.COOKIE_FORMAT, new String(encryptedAssetsKey, StandardCharsets.ISO_8859_1))); } URI getRequestURI() { final String requestSchemeHostPath = this.syncInput.getRequestURI(); - final String requestQueryString = - this.syncInput.getParameterNames().stream() - .map(parameterName -> String.format("%s=%s", parameterName, - this.syncInput.getParameter(parameterName))) - .collect(Collectors.joining("&")); - return URI.create(requestSchemeHostPath + (StringUtil.hasText(requestQueryString) - ? "?" + requestQueryString : "")); + final String requestQueryString = this.syncInput.getParameterNames().stream() + .map(parameterName -> String.format("%s=%s", parameterName, this.syncInput.getParameter(parameterName))) + .collect(Collectors.joining("&")); + return URI.create( + requestSchemeHostPath + (StringUtil.hasText(requestQueryString) ? "?" + requestQueryString : "")); } void redirectToCallback(final Client oidcClient) { diff --git a/src/main/java/org/opencadc/scienceportal/oidc/login/GetAction.java b/src/main/java/org/opencadc/scienceportal/oidc/login/GetAction.java index 5614731..b8eea9f 100644 --- a/src/main/java/org/opencadc/scienceportal/oidc/login/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/oidc/login/GetAction.java @@ -68,9 +68,8 @@ package org.opencadc.scienceportal.oidc.login; -import org.opencadc.scienceportal.SciencePortalAuthAction; - import javax.servlet.http.HttpServletResponse; +import org.opencadc.scienceportal.SciencePortalAuthAction; public class GetAction extends SciencePortalAuthAction { @Override diff --git a/src/main/java/org/opencadc/scienceportal/repository/GetAction.java b/src/main/java/org/opencadc/scienceportal/repository/GetAction.java index de9ef79..2ddffa2 100644 --- a/src/main/java/org/opencadc/scienceportal/repository/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/repository/GetAction.java @@ -71,11 +71,10 @@ import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthGetAction; - import java.net.URI; import java.net.URL; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthGetAction; public class GetAction extends SciencePortalAuthGetAction { private static final String REGISTRY_ENDPOINT = "/repository"; diff --git a/src/main/java/org/opencadc/scienceportal/session/DeleteAction.java b/src/main/java/org/opencadc/scienceportal/session/DeleteAction.java index 62e4b0a..db92528 100644 --- a/src/main/java/org/opencadc/scienceportal/session/DeleteAction.java +++ b/src/main/java/org/opencadc/scienceportal/session/DeleteAction.java @@ -72,20 +72,20 @@ import ca.nrc.cadc.net.HttpDelete; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; -import ca.nrc.cadc.rest.InlineContentHandler; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthAction; - -import javax.security.auth.Subject; import java.net.URI; import java.net.URL; import java.security.PrivilegedExceptionAction; +import javax.security.auth.Subject; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthAction; public class DeleteAction extends SciencePortalAuthAction { @Override public void doAction() throws Exception { final URL apiURL = new URL(getAPIURL().toExternalForm() - + syncInput.getRequestPath().substring(syncInput.getContextPath().length())); + + syncInput + .getRequestPath() + .substring(syncInput.getContextPath().length())); final Subject authenticatedUser = getCurrentSubject(apiURL); diff --git a/src/main/java/org/opencadc/scienceportal/session/GetAction.java b/src/main/java/org/opencadc/scienceportal/session/GetAction.java index 987c152..597dfc4 100644 --- a/src/main/java/org/opencadc/scienceportal/session/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/session/GetAction.java @@ -72,11 +72,10 @@ import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; import ca.nrc.cadc.util.StringUtil; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthGetAction; - import java.net.URI; import java.net.URL; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthGetAction; public class GetAction extends SciencePortalAuthGetAction { private static final String SESSION_ENDPOINT = "/session"; diff --git a/src/main/java/org/opencadc/scienceportal/session/PostAction.java b/src/main/java/org/opencadc/scienceportal/session/PostAction.java index e914e40..a168641 100644 --- a/src/main/java/org/opencadc/scienceportal/session/PostAction.java +++ b/src/main/java/org/opencadc/scienceportal/session/PostAction.java @@ -75,10 +75,6 @@ import ca.nrc.cadc.rest.SyncInput; import ca.nrc.cadc.util.Base64; import ca.nrc.cadc.util.StringUtil; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthAction; - -import javax.security.auth.Subject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -92,6 +88,9 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; +import javax.security.auth.Subject; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthAction; public class PostAction extends SciencePortalAuthAction { static final String SECRET_REQUEST_HEADER_NAME_TO_SKAHA = "x-skaha-registry-auth"; @@ -131,9 +130,11 @@ public void doAction() throws Exception { HttpPost createPostRequest(final URL apiURL) { final Map payload = new HashMap<>(); payload.putAll(syncInput.getParameterNames().stream() - .collect(Collectors.toMap(key -> key, - key -> syncInput.getParameter(key) == null - ? "" : syncInput.getParameter(key).trim()))); + .collect(Collectors.toMap( + key -> key, + key -> syncInput.getParameter(key) == null + ? "" + : syncInput.getParameter(key).trim()))); final HttpPost httpPost = new HttpPost(apiURL, payload, false); @@ -142,8 +143,9 @@ HttpPost createPostRequest(final URL apiURL) { if (StringUtil.hasText(repositorySecret)) { if (StringUtil.hasText(repositoryUsername)) { - httpPost.setRequestProperty(PostAction.SECRET_REQUEST_HEADER_NAME_TO_SKAHA, - Base64.encodeString(repositoryUsername + ":" + repositorySecret)); + httpPost.setRequestProperty( + PostAction.SECRET_REQUEST_HEADER_NAME_TO_SKAHA, + Base64.encodeString(repositoryUsername + ":" + repositorySecret)); } else { throw new IllegalArgumentException("Secret specified but no username provided."); } @@ -155,7 +157,8 @@ HttpPost createPostRequest(final URL apiURL) { } URL buildAPIURL() throws MalformedURLException { - final StringBuilder apiURLBuilder = new StringBuilder(lookupAPIEndpoint().toExternalForm() + PostAction.SESSION_ENDPOINT); + final StringBuilder apiURLBuilder = + new StringBuilder(lookupAPIEndpoint().toExternalForm() + PostAction.SESSION_ENDPOINT); // Preserve path items. final String path = this.syncInput.getPath(); diff --git a/src/main/java/org/opencadc/scienceportal/userinfo/GetAction.java b/src/main/java/org/opencadc/scienceportal/userinfo/GetAction.java index a8fc10e..abe1c8d 100644 --- a/src/main/java/org/opencadc/scienceportal/userinfo/GetAction.java +++ b/src/main/java/org/opencadc/scienceportal/userinfo/GetAction.java @@ -74,18 +74,16 @@ import ca.nrc.cadc.net.HttpGet; import ca.nrc.cadc.reg.Standards; import ca.nrc.cadc.reg.client.RegistryClient; -import org.json.JSONObject; -import org.opencadc.scienceportal.ApplicationConfiguration; -import org.opencadc.scienceportal.SciencePortalAuthAction; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.PrivilegedExceptionAction; - +import javax.security.auth.Subject; +import javax.servlet.http.HttpServletResponse; +import org.json.JSONObject; +import org.opencadc.scienceportal.ApplicationConfiguration; +import org.opencadc.scienceportal.SciencePortalAuthAction; public class GetAction extends SciencePortalAuthAction { @Override @@ -104,14 +102,15 @@ public void doAction() throws Exception { syncOutput.setHeader("content-type", "application/json"); final JSONObject jsonObject = new JSONObject(); final Subject validatedSubject = AuthenticationUtil.validateSubject(subjectFromCookie); - jsonObject.put("name", AuthenticationUtil.getIdentityManager().toDisplayString(validatedSubject)); + jsonObject.put( + "name", AuthenticationUtil.getIdentityManager().toDisplayString(validatedSubject)); syncOutput.getOutputStream().write(jsonObject.toString().getBytes(StandardCharsets.UTF_8)); syncOutput.getOutputStream().flush(); } } catch (RuntimeException runtimeException) { // The Skaha API throws a RuntimeException when looking up the capabilities with an old Token. if ((runtimeException.getCause() instanceof IOException) - && (runtimeException.getCause().getCause() instanceof NotAuthenticatedException)) { + && (runtimeException.getCause().getCause() instanceof NotAuthenticatedException)) { syncOutput.setCode(HttpServletResponse.SC_UNAUTHORIZED); return null; } @@ -131,11 +130,11 @@ private URL getSessionsURL() throws IOException { final ApplicationConfiguration applicationConfiguration = new ApplicationConfiguration(); final URI apiServiceURI = URI.create(applicationConfiguration.getResourceID()); final RegistryClient registryClient = new RegistryClient(); - final URL registryServiceBaseURL = registryClient.getServiceURL(apiServiceURI, Standards.PROC_SESSIONS_10, - AuthMethod.TOKEN); + final URL registryServiceBaseURL = + registryClient.getServiceURL(apiServiceURI, Standards.PROC_SESSIONS_10, AuthMethod.TOKEN); if (registryServiceBaseURL == null) { throw new IOException("The Skaha web service is not configured in the Registry. Please ensure that " - + apiServiceURI + " exists."); + + apiServiceURI + " exists."); } return new URL(registryServiceBaseURL.toExternalForm() + "/session"); diff --git a/src/test/java/org/opencadc/scienceportal/session/PostActionTest.java b/src/test/java/org/opencadc/scienceportal/session/PostActionTest.java index 072edd7..448ad02 100644 --- a/src/test/java/org/opencadc/scienceportal/session/PostActionTest.java +++ b/src/test/java/org/opencadc/scienceportal/session/PostActionTest.java @@ -4,7 +4,6 @@ import ca.nrc.cadc.net.HttpRequestProperty; import ca.nrc.cadc.rest.SyncInput; import ca.nrc.cadc.util.Base64; - import java.net.URL; import java.util.HashSet; import java.util.List; @@ -19,8 +18,10 @@ public class PostActionTest { public void createPostRequestMissingUsername() throws Exception { final SyncInput mockSyncInput = Mockito.mock(SyncInput.class); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)).thenReturn("mysecret"); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)).thenReturn(null); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)) + .thenReturn("mysecret"); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)) + .thenReturn(null); final Set parameterNames = new HashSet<>(); parameterNames.add("param1"); @@ -35,7 +36,10 @@ public void createPostRequestMissingUsername() throws Exception { testSubject.createPostRequest(postURL); Assert.fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException illegalArgumentException) { - Assert.assertEquals("Wrong exception message", "Secret specified but no username provided.", illegalArgumentException.getMessage()); + Assert.assertEquals( + "Wrong exception message", + "Secret specified but no username provided.", + illegalArgumentException.getMessage()); } Mockito.verify(mockSyncInput, Mockito.times(1)).getParameterNames(); @@ -46,8 +50,10 @@ public void createPostRequestMissingUsername() throws Exception { public void createPostRequestMissingSecret() throws Exception { final SyncInput mockSyncInput = Mockito.mock(SyncInput.class); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)).thenReturn(null); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)).thenReturn("username1"); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)) + .thenReturn(null); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)) + .thenReturn("username1"); final Set parameterNames = new HashSet<>(); parameterNames.add("param1"); @@ -62,7 +68,10 @@ public void createPostRequestMissingSecret() throws Exception { testSubject.createPostRequest(postURL); Assert.fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException illegalArgumentException) { - Assert.assertEquals("Wrong exception message", "Username specified but no secret provided.", illegalArgumentException.getMessage()); + Assert.assertEquals( + "Wrong exception message", + "Username specified but no secret provided.", + illegalArgumentException.getMessage()); } Mockito.verify(mockSyncInput, Mockito.times(1)).getParameterNames(); @@ -73,8 +82,10 @@ public void createPostRequestMissingSecret() throws Exception { public void createPostRequestPrivate() throws Exception { final SyncInput mockSyncInput = Mockito.mock(SyncInput.class); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)).thenReturn("secret1"); - Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)).thenReturn("username1"); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_SECRET_FROM_BROWSER)) + .thenReturn("secret1"); + Mockito.when(mockSyncInput.getHeader(PostAction.REPOSITORY_AUTH_USERNAME_FROM_BROWSER)) + .thenReturn("username1"); final Set parameterNames = new HashSet<>(); parameterNames.add("param1"); @@ -97,8 +108,14 @@ public void createPostRequestPrivate() throws Exception { Assert.assertEquals("Wrong value2", "value2", postParameters.get("param2")); final List postProperties = httpPost.getRequestProperties(); - Assert.assertEquals("Wrong auth header", PostAction.SECRET_REQUEST_HEADER_NAME_TO_SKAHA, postProperties.get(0).getProperty()); - Assert.assertEquals("Wrong auth header value", Base64.encodeString("username1:secret1"), postProperties.get(0).getValue()); + Assert.assertEquals( + "Wrong auth header", + PostAction.SECRET_REQUEST_HEADER_NAME_TO_SKAHA, + postProperties.get(0).getProperty()); + Assert.assertEquals( + "Wrong auth header value", + Base64.encodeString("username1:secret1"), + postProperties.get(0).getValue()); Mockito.verify(mockSyncInput, Mockito.times(1)).getParameterNames(); Mockito.verify(mockSyncInput, Mockito.times(2)).getParameter("param1");