From cb3bdff3abf7df19c8c1e836136e7992a14fb408 Mon Sep 17 00:00:00 2001 From: Brad Nicholes Date: Fri, 4 Feb 2022 16:09:54 -0700 Subject: [PATCH 1/2] Implement the SPS streaming request --- .../ISafeguardSessionsConnection.java | 7 ++ .../SafeguardSessionsConnection.java | 108 ++++++++++-------- 2 files changed, 66 insertions(+), 49 deletions(-) diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java index b582a87..9dd0ecb 100644 --- a/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java @@ -42,4 +42,11 @@ String InvokeMethod(Method method, String relativeUrl, String body) FullResponse InvokeMethodFull(Method method, String relativeUrl, String body) throws ObjectDisposedException, SafeguardForJavaException, ArgumentException; + /** + * Provides support for HTTP streaming requests + * + * @return returns ISpsStreamingRequest + * @throws com.oneidentity.safeguard.safeguardjava.exceptions.ObjectDisposedException + */ + ISpsStreamingRequest getStream() throws ObjectDisposedException; } diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java index 07c4473..657124f 100644 --- a/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java @@ -15,131 +15,141 @@ import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import org.apache.http.Header; -import org.apache.http.HeaderElement; import org.apache.http.client.methods.CloseableHttpResponse; /** - * This is the reusable connection interface that can be used to call SPS API. + * This is the reusable connection interface that can be used to call SPS API. */ class SafeguardSessionsConnection implements ISafeguardSessionsConnection { private boolean disposed; - - private RestClient _client; - private Header _authCookie = null; - + + private RestClient client; + private final Header authCookie = null; + public SafeguardSessionsConnection(String networkAddress, String username, - char[] password, boolean ignoreSsl, HostnameVerifier validationCallback) + char[] password, boolean ignoreSsl, HostnameVerifier validationCallback) throws SafeguardForJavaException { - + String spsApiUrl = String.format("https://%s/api", networkAddress); - _client = new RestClient(spsApiUrl, username, password, ignoreSsl, validationCallback); + client = new RestClient(spsApiUrl, username, password, ignoreSsl, validationCallback); - Map headers = new HashMap<>(); + Map headers = new HashMap<>(); Logger.getLogger(SafeguardSessionsConnection.class.getName()).log(Level.FINEST, "Starting authentication."); - logRequestDetails(Method.Get, _client.getBaseURL() + "/" + "authentication", null, null); + logRequestDetails(Method.Get, client.getBaseURL() + "/" + "authentication", null, null); + + CloseableHttpResponse response = client.execGET("authentication", null, null, null); - CloseableHttpResponse response = _client.execGET("authentication", null, null, null); - if (response == null) { throw new SafeguardForJavaException(String.format("Unable to authenticate to SPS %s", networkAddress)); } String reply = Utils.getResponse(response); - + if (!Utils.isSuccessful(response.getStatusLine().getStatusCode())) { throw new SafeguardForJavaException("Error returned from Safeguard API, Error: " + String.format("%d %s", response.getStatusLine().getStatusCode(), reply)); } - + Header authCookie = response.getFirstHeader("Set-Cookie"); if (authCookie != null) { - _client.addSessionId(authCookie.getValue()); + client.addSessionId(authCookie.getValue()); } - + Logger.getLogger(SafeguardSessionsConnection.class.getName()).log(Level.FINEST, String.format("Response content: $s", reply)); } @Override - public String InvokeMethod(Method method, String relativeUrl, String body) + public String InvokeMethod(Method method, String relativeUrl, String body) throws ObjectDisposedException, SafeguardForJavaException, ArgumentException { - + return InvokeMethodFull(method, relativeUrl, body).getBody(); } /** - * Call a SafeguardForPrivilegedSessions API method and get a detailed response with status code, headers, - * and body. If there is a failure a SafeguardDotNetException will be thrown. + * Call a SafeguardForPrivilegedSessions API method and get a detailed + * response with status code, headers, and body. If there is a failure a + * SafeguardDotNetException will be thrown. + * + * @param method HTTP method type to use. + * @param relativeUrl The url. + * @param body Request body to pass to the method. * - * @param method HTTP method type to use. - * @param relativeUrl The url. - * @param body Request body to pass to the method. - * - * @return Response with status code, headers, and body as string. - */ + * @return Response with status code, headers, and body as string. + */ @Override //TODO: This API should have an additionalHeaders parameter //TODO: This API should have an parameters parameter //TODO: This API should have an timeout parameter - public FullResponse InvokeMethodFull(Method method, String relativeUrl, String body) + public FullResponse InvokeMethodFull(Method method, String relativeUrl, String body) throws ObjectDisposedException, SafeguardForJavaException, ArgumentException { - + if (disposed) { throw new ObjectDisposedException("SafeguardSessionsConnection"); } - if (Utils.isNullOrEmpty(relativeUrl)) + if (Utils.isNullOrEmpty(relativeUrl)) { throw new ArgumentException("Parameter relativeUrl may not be null or empty"); - + } + Logger.getLogger(SafeguardSessionsConnection.class.getName()).log(Level.FINEST, String.format("Invoking method on sps: $s", relativeUrl)); CloseableHttpResponse response = null; - logRequestDetails(method, _client.getBaseURL() + "/" + relativeUrl, null, null); - + logRequestDetails(method, client.getBaseURL() + "/" + relativeUrl, null, null); + switch (method) { case Get: - response = _client.execGET(relativeUrl, null, null, null); + response = client.execGET(relativeUrl, null, null, null); break; case Post: - response = _client.execPOST(relativeUrl, null, null, null, new JsonBody(body)); + response = client.execPOST(relativeUrl, null, null, null, new JsonBody(body)); break; case Put: - response = _client.execPUT(relativeUrl, null, null, null, new JsonBody(body)); + response = client.execPUT(relativeUrl, null, null, null, new JsonBody(body)); break; case Delete: - response = _client.execDELETE(relativeUrl, null, null, null); + response = client.execDELETE(relativeUrl, null, null, null); break; } - + if (response == null) { - throw new SafeguardForJavaException(String.format("Unable to connect to web service %s", _client.getBaseURL())); + throw new SafeguardForJavaException(String.format("Unable to connect to web service %s", client.getBaseURL())); } - + String reply = Utils.getResponse(response); - + if (!Utils.isSuccessful(response.getStatusLine().getStatusCode())) { throw new SafeguardForJavaException("Error returned from Safeguard API, Error: " + String.format("%d %s", response.getStatusLine().getStatusCode(), reply)); } Logger.getLogger(SafeguardSessionsConnection.class.getName()).log(Level.FINEST, String.format("Invoking method finished: $s", reply)); - + FullResponse fullResponse = new FullResponse(response.getStatusLine().getStatusCode(), response.getAllHeaders(), reply); - + logResponseDetails(fullResponse); - + return fullResponse; } - + + @Override + public ISpsStreamingRequest getStream() throws ObjectDisposedException { + if (disposed) { + throw new ObjectDisposedException("SafeguardSessionsConnection"); + } + + return (ISpsStreamingRequest) new SpsStreamingRequest(this.client); + } + boolean isDisposed() { return disposed; } - public void dispose() - { - if (_client != null) - _client = null; + public void dispose() { + if (client != null) { + client = null; + } disposed = true; } From e3ce148804ede5137c2c62e10bb594bc84c4c416 Mon Sep 17 00:00:00 2001 From: Brad Nicholes Date: Tue, 8 Feb 2022 14:03:15 -0700 Subject: [PATCH 2/2] Finishing implementing the SPS file streaming upload functions. Two streaming upload functions. One that takes a byte array and another than takes a file. The file version uses multipart/form-data. --- pom.xml | 5 + .../ISafeguardSessionsConnection.java | 2 +- .../safeguardjava/ISpsStreamingRequest.java | 49 ++++++++++ .../SafeguardSessionsConnection.java | 4 +- .../safeguardjava/SpsStreamingRequest.java | 91 +++++++++++++++++++ .../safeguardjava/restclient/RestClient.java | 78 +++++++++++++++- .../safeguardclient/SafeguardJavaClient.java | 24 ++++- .../safeguardclient/SafeguardTests.java | 59 +++++++++++- 8 files changed, 302 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/oneidentity/safeguard/safeguardjava/ISpsStreamingRequest.java create mode 100644 src/main/java/com/oneidentity/safeguard/safeguardjava/SpsStreamingRequest.java diff --git a/pom.xml b/pom.xml index 6e8bedf..c0e40ec 100644 --- a/pom.xml +++ b/pom.xml @@ -54,6 +54,11 @@ httpclient 4.5.13 + + org.apache.httpcomponents + httpmime + 4.5.13 + com.fasterxml.jackson.core jackson-databind diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java index 9dd0ecb..9fa0c1b 100644 --- a/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISafeguardSessionsConnection.java @@ -48,5 +48,5 @@ FullResponse InvokeMethodFull(Method method, String relativeUrl, String body) * @return returns ISpsStreamingRequest * @throws com.oneidentity.safeguard.safeguardjava.exceptions.ObjectDisposedException */ - ISpsStreamingRequest getStream() throws ObjectDisposedException; + ISpsStreamingRequest getStreamingRequest() throws ObjectDisposedException; } diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/ISpsStreamingRequest.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISpsStreamingRequest.java new file mode 100644 index 0000000..0615ff4 --- /dev/null +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/ISpsStreamingRequest.java @@ -0,0 +1,49 @@ +package com.oneidentity.safeguard.safeguardjava; + +import com.oneidentity.safeguard.safeguardjava.exceptions.ArgumentException; +import com.oneidentity.safeguard.safeguardjava.exceptions.SafeguardForJavaException; +import java.util.Map; + +/** + * SPS streaming request methods + */ +public interface ISpsStreamingRequest { + + /** + * Call a Safeguard Sps POST API providing a stream as request content. If + * there is a failure a SafeguardDotNetException will be thrown. + * + * @param relativeUrl Relative URL of the service to use. + * @param stream Stream to upload as request content. + * @param progressCallback Optionally report upload progress. + * @param parameters Additional parameters to add to the URL. + * @param additionalHeaders Additional headers to add to the request. + * @return Response body as a string. + * @throws + * com.oneidentity.safeguard.safeguardjava.exceptions.SafeguardForJavaException + * @throws + * com.oneidentity.safeguard.safeguardjava.exceptions.ArgumentException + */ + String uploadStream(String relativeUrl, byte[] stream, IProgressCallback progressCallback, + Map parameters, Map additionalHeaders) + throws SafeguardForJavaException, ArgumentException; + + /** + * Call a Safeguard Sps POST API providing a file as request content. If + * there is a failure a SafeguardDotNetException will be thrown. + * + * @param relativeUrl Relative URL of the service to use. + * @param fileName File to upload as request content. + * @param parameters Additional parameters to add to the URL. + * @param additionalHeaders Additional headers to add to the request. + * @return Response body as a string. + * @throws + * com.oneidentity.safeguard.safeguardjava.exceptions.SafeguardForJavaException + * @throws + * com.oneidentity.safeguard.safeguardjava.exceptions.ArgumentException + */ + String uploadStream(String relativeUrl, String fileName, + Map parameters, Map additionalHeaders) + throws SafeguardForJavaException, ArgumentException; + +} diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java index 657124f..cf3d751 100644 --- a/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/SafeguardSessionsConnection.java @@ -134,12 +134,12 @@ public FullResponse InvokeMethodFull(Method method, String relativeUrl, String b } @Override - public ISpsStreamingRequest getStream() throws ObjectDisposedException { + public ISpsStreamingRequest getStreamingRequest() throws ObjectDisposedException { if (disposed) { throw new ObjectDisposedException("SafeguardSessionsConnection"); } - return (ISpsStreamingRequest) new SpsStreamingRequest(this.client); + return new SpsStreamingRequest(this.client); } boolean isDisposed() { diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/SpsStreamingRequest.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/SpsStreamingRequest.java new file mode 100644 index 0000000..88887ef --- /dev/null +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/SpsStreamingRequest.java @@ -0,0 +1,91 @@ +package com.oneidentity.safeguard.safeguardjava; + +import com.oneidentity.safeguard.safeguardjava.data.FullResponse; +import com.oneidentity.safeguard.safeguardjava.data.Method; +import com.oneidentity.safeguard.safeguardjava.exceptions.ArgumentException; +import com.oneidentity.safeguard.safeguardjava.exceptions.SafeguardForJavaException; +import com.oneidentity.safeguard.safeguardjava.restclient.RestClient; +import java.util.Map; +import org.apache.http.client.methods.CloseableHttpResponse; + +class SpsStreamingRequest implements ISpsStreamingRequest { + + private RestClient client; + + SpsStreamingRequest(RestClient client) { + this.client = client; + } + + @Override + public String uploadStream(String relativeUrl, byte[] stream, IProgressCallback progressCallback, + Map parameters, Map additionalHeaders) + throws SafeguardForJavaException, ArgumentException { + + if (Utils.isNullOrEmpty(relativeUrl)) { + throw new ArgumentException("Parameter relativeUrl cannot be null or empty"); + } + if (client == null) { + throw new ArgumentException("Invalid or unauthenticated SPS connection"); + } + + CloseableHttpResponse response = null; + + SafeguardConnection.logRequestDetails(Method.Post, client.getBaseURL() + "/" + relativeUrl, parameters, additionalHeaders); + + response = client.execPOSTBytes(relativeUrl, parameters, additionalHeaders, null, stream, progressCallback); + + if (response == null) { + throw new SafeguardForJavaException(String.format("Unable to connect to SPS service %s", client.getBaseURL())); + } + + String reply = Utils.getResponse(response); + + if (!Utils.isSuccessful(response.getStatusLine().getStatusCode())) { + throw new SafeguardForJavaException("Error returned from SPS API, Error: " + + String.format("%d %s", response.getStatusLine().getStatusCode(), reply)); + } + + FullResponse fullResponse = new FullResponse(response.getStatusLine().getStatusCode(), response.getAllHeaders(), reply); + + SafeguardConnection.logResponseDetails(fullResponse); + + return fullResponse.getBody(); + } + + @Override + public String uploadStream(String relativeUrl, String fileName, + Map parameters, Map additionalHeaders) + throws SafeguardForJavaException, ArgumentException { + + if (Utils.isNullOrEmpty(relativeUrl)) { + throw new ArgumentException("Parameter relativeUrl cannot be null or empty"); + } + if (client == null) { + throw new ArgumentException("Invalid or unauthenticated SPS connection"); + } + + CloseableHttpResponse response = null; + + SafeguardConnection.logRequestDetails(Method.Post, client.getBaseURL() + "/" + relativeUrl, parameters, additionalHeaders); + + response = client.execPOSTFile(relativeUrl, parameters, additionalHeaders, null, fileName); + + if (response == null) { + throw new SafeguardForJavaException(String.format("Unable to connect to SPS service %s", client.getBaseURL())); + } + + String reply = Utils.getResponse(response); + + if (!Utils.isSuccessful(response.getStatusLine().getStatusCode())) { + throw new SafeguardForJavaException("Error returned from SPS API, Error: " + + String.format("%d %s", response.getStatusLine().getStatusCode(), reply)); + } + + FullResponse fullResponse = new FullResponse(response.getStatusLine().getStatusCode(), response.getAllHeaders(), reply); + + SafeguardConnection.logResponseDetails(fullResponse); + + return fullResponse.getBody(); + } + +} diff --git a/src/main/java/com/oneidentity/safeguard/safeguardjava/restclient/RestClient.java b/src/main/java/com/oneidentity/safeguard/safeguardjava/restclient/RestClient.java index eec42c8..9c64c87 100644 --- a/src/main/java/com/oneidentity/safeguard/safeguardjava/restclient/RestClient.java +++ b/src/main/java/com/oneidentity/safeguard/safeguardjava/restclient/RestClient.java @@ -5,13 +5,16 @@ import com.oneidentity.safeguard.safeguardjava.data.CertificateContext; import com.oneidentity.safeguard.safeguardjava.data.JsonObject; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.net.MalformedURLException; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; +import java.net.URL; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -40,10 +43,12 @@ import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; +import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.RequestBuilder; @@ -52,11 +57,13 @@ import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.cookie.Cookie; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; @@ -69,6 +76,7 @@ public class RestClient { private BasicCookieStore cookieStore = new BasicCookieStore(); private String serverUrl = null; + private String hostDomain = null; private boolean ignoreSsl = false; private HostnameVerifier validationCallback = null; @@ -86,7 +94,12 @@ public RestClient(String connectionAddr, String userName, char[] password, boole CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, new String(password))); - client = builder.setDefaultCredentialsProvider(provider).setDefaultCookieStore(cookieStore).disableCookieManagement().build(); + RequestConfig customizedRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); + + client = builder.setDefaultCredentialsProvider(provider) + .setDefaultRequestConfig(customizedRequestConfig) + .setDefaultCookieStore(cookieStore) + .build(); } private HttpClientBuilder createClientBuilder(String connectionAddr, boolean ignoreSsl, HostnameVerifier validationCallback) { @@ -102,6 +115,13 @@ private HttpClientBuilder createClientBuilder(String connectionAddr, boolean ign this.ignoreSsl = ignoreSsl; this.serverUrl = connectionAddr; + + try { + URL aUrl = new URL(connectionAddr); + this.hostDomain = aUrl.getHost(); + } catch (MalformedURLException ex) { + Logger.getLogger(RestClient.class.getName()).log(Level.SEVERE, "Invalid URL", ex); + } SSLConnectionSocketFactory sslsf = null; if (ignoreSsl) { @@ -174,6 +194,10 @@ public void addSessionId(String cookieValue) { cookie.setPath(path); } + if (this.hostDomain != null) { + cookie.setDomain(this.hostDomain); + } + String secure = keyValues.get("Secure"); if (secure != null) { cookie.setSecure(true); @@ -345,6 +369,54 @@ public CloseableHttpResponse execPOSTBytes(String path, Map quer return null; } + public CloseableHttpResponse execPOSTFile(String path, Map queryParams, Map headers, Integer timeout, String fileName) { + + File file = new File(fileName); + + HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) + .addBinaryBody("firmware", file, ContentType.MULTIPART_FORM_DATA, file.getName()).build(); + + if (headers == null || !headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers = headers == null ? new HashMap() : headers; + } + RequestBuilder rb = prepareRequest(RequestBuilder.post(getBaseURI(path)), queryParams, headers, timeout); + + try { + rb.setEntity(data); + CloseableHttpResponse r = client.execute(rb.build()); + return r; + } catch (IOException ex) { + return null; + } + } + + public CloseableHttpResponse execPOSTFile(String path, Map queryParams, Map headers, Integer timeout, + String fileName, CertificateContext certificateContext) { + + CloseableHttpClient certClient = getClientWithCertificate(certificateContext); + + if (certClient != null) { + File file = new File(fileName); + HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) + .addBinaryBody("firmware", file, ContentType.MULTIPART_FORM_DATA, file.getName()).build(); + + if (headers == null || !headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers = headers == null ? new HashMap() : headers; + } + RequestBuilder rb = prepareRequest(RequestBuilder.post(getBaseURI(path)), queryParams, headers, timeout); + + try { + rb.setEntity(data); + CloseableHttpResponse r = client.execute(rb.build()); + return r; + } catch (IOException ex) { + return null; + } + } + return null; + } + public CloseableHttpResponse execDELETE(String path, Map queryParams, Map headers, Integer timeout) { RequestBuilder rb = prepareRequest(RequestBuilder.delete(getBaseURI(path)), queryParams, headers, timeout); @@ -416,7 +488,7 @@ private RequestBuilder prepareRequest(RequestBuilder rb, Map que rb.addHeader(HttpHeaders.ACCEPT, "application/json"); if (headers == null || !headers.containsKey(HttpHeaders.CONTENT_TYPE)) rb.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - + if (headers != null) { for (Map.Entry entry : headers.entrySet()) { rb.addHeader(entry.getKey(), entry.getValue()); diff --git a/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardJavaClient.java b/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardJavaClient.java index 99a3ebd..11f3947 100644 --- a/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardJavaClient.java +++ b/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardJavaClient.java @@ -27,6 +27,16 @@ public static void main(String[] args) { boolean done = false; SafeguardTests tests = new SafeguardTests(); + // Uncomment the lines below to enable console debug logging of the http requests + //System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog"); + //System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); + //System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "DEBUG"); + + //System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.impl.conn", "DEBUG"); + //System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.impl.client", "DEBUG"); + //System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.client", "DEBUG"); + //System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "DEBUG"); + while (!done) { Integer selection = displayMenu(); @@ -101,9 +111,15 @@ public static void main(String[] args) { tests.safeguardSessionsApi(sessionConnection); break; case 24: - tests.safeguardTestManagementConnection(connection); + tests.safeguardSessionsFileUpload(sessionConnection); break; case 25: + tests.safeguardSessionsStreamUpload(sessionConnection); + break; + case 26: + tests.safeguardTestManagementConnection(connection); + break; + case 27: tests.safeguardTestAnonymousConnection(connection); break; default: @@ -141,8 +157,10 @@ private static Integer displayMenu() { System.out.println ("\t21. Test Upload Backup File"); System.out.println ("\t22. Test SPS Connection"); System.out.println ("\t23. Test SPS API"); - System.out.println ("\t24. Test Management Interface API"); - System.out.println ("\t25. Test Anonymous Connection"); + System.out.println ("\t24. Test SPS Firmware Upload"); + System.out.println ("\t25. Test Stream Upload"); + System.out.println ("\t26. Test Management Interface API"); + System.out.println ("\t27. Test Anonymous Connection"); System.out.println ("\t99. Exit"); diff --git a/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardTests.java b/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardTests.java index f86e88e..6e867b1 100644 --- a/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardTests.java +++ b/tests/safeguardjavaclient/src/main/java/com/oneidentity/safeguard/safeguardclient/SafeguardTests.java @@ -612,7 +612,7 @@ void safeguardSessionsApi(ISafeguardSessionsConnection connection) { } try { - FullResponse fullResponse = connection.InvokeMethodFull(Method.Get, "firmware", null); + FullResponse fullResponse = connection.InvokeMethodFull(Method.Get, "configuration/network/naming", null); System.out.println(String.format("\t\\Users full response:")); logResponseDetails(fullResponse); @@ -621,6 +621,63 @@ void safeguardSessionsApi(ISafeguardSessionsConnection connection) { } } + public void safeguardSessionsFileUpload(ISafeguardSessionsConnection connection) { + + if (connection == null) { + System.out.println(String.format("Safeguard not connected")); + return; + } + + String patchFileName = readLine("SPS Firmware File Name: ", null); + + if (patchFileName == null) { + System.out.println(String.format("file name")); + return; + } + + try { + Path filePath = Paths.get(patchFileName).toAbsolutePath(); + System.out.println(String.format("\tFile path: %s", filePath.toAbsolutePath())); + + connection.getStreamingRequest().uploadStream("upload/firmware", filePath.toString(), null, null); + System.out.println(String.format("\tUploaded file: %s", patchFileName)); + } catch (ObjectDisposedException | SafeguardForJavaException ex) { + System.out.println("\t[ERROR]Test SPS firmware upload failed: " + ex.getMessage()); + } catch (Exception ex) { + System.out.println("\t[ERROR]Test SPS firmware upload failed: " + ex.getMessage()); + } + } + + public void safeguardSessionsStreamUpload(ISafeguardSessionsConnection connection) { + + if (connection == null) { + System.out.println(String.format("Safeguard not connected")); + return; + } + + String patchFileName = readLine("SPS Firmware File Name: ", null); + boolean withProgress = readLine("With Progress Notification(y/n): ", "n").equalsIgnoreCase("y"); + + if (patchFileName == null) { + System.out.println(String.format("file name")); + return; + } + + try { + Path filePath = Paths.get(patchFileName).toAbsolutePath(); + IProgressCallback progressCallback = withProgress ? new ProgressNotification() : null; + byte[] fileContent = Files.readAllBytes(filePath); + System.out.println(String.format("\tFile path: %s", filePath.toAbsolutePath())); + + connection.getStreamingRequest().uploadStream("upload/firmware", fileContent, progressCallback, null, null); + System.out.println(String.format("\tUploaded file: %s", patchFileName)); + } catch (ObjectDisposedException | SafeguardForJavaException ex) { + System.out.println("\t[ERROR]Test SPS firmware upload failed: " + ex.getMessage()); + } catch (Exception ex) { + System.out.println("\t[ERROR]Test SPS firmware upload failed: " + ex.getMessage()); + } + } + void safeguardTestManagementConnection(ISafeguardConnection connection) { if (connection == null) { System.out.println(String.format("Safeguard not connected. This test requires an annonymous connection."));