diff --git a/.idea/artifacts/soapClient_jar.xml b/.idea/artifacts/soapClient_jar.xml index 893c068..483a99e 100644 --- a/.idea/artifacts/soapClient_jar.xml +++ b/.idea/artifacts/soapClient_jar.xml @@ -3,7 +3,6 @@ $PROJECT_DIR$/out/artifacts/soapClient_jar - \ No newline at end of file diff --git a/.idea/libraries/jcommander_1_27.xml b/.idea/libraries/jcommander_1_27.xml deleted file mode 100644 index 435c5f6..0000000 --- a/.idea/libraries/jcommander_1_27.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 03f397c..1c2e834 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/lib/jcommander-1.27.jar b/lib/jcommander-1.27.jar deleted file mode 100644 index f949090..0000000 Binary files a/lib/jcommander-1.27.jar and /dev/null differ diff --git a/soapClient.iml b/soapClient.iml index a406ea3..49589a4 100644 --- a/soapClient.iml +++ b/soapClient.iml @@ -7,6 +7,41 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/META-INF/MANIFEST.MF b/src/META-INF/MANIFEST.MF index 3375b0c..afb4ab7 100644 --- a/src/META-INF/MANIFEST.MF +++ b/src/META-INF/MANIFEST.MF @@ -1,3 +1,3 @@ Manifest-Version: 1.0 -Main-Class: com.belkast.soap.Webservice +Main-Class: com.belkast.soap.webService diff --git a/src/com/belkast/soap/Base64.java b/src/com/belkast/soap/Base64.java deleted file mode 100644 index 8c820de..0000000 --- a/src/com/belkast/soap/Base64.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.belkast.soap; - -/** - * - * @author Keith - */ -public class Base64 { - - -//The line separator string of the operating system. - -private static final String systemLineSeparator = System.getProperty("line.separator"); - - - -//Mapping table from 6-bit nibbles to Base64 characters. - -private static char[] map1 = new char[64]; - -static { - - int i=0; - - for (char c='A'; c<='Z'; c++) map1[i++] = c; - - for (char c='a'; c<='z'; c++) map1[i++] = c; - - for (char c='0'; c<='9'; c++) map1[i++] = c; - - map1[i++] = '+'; map1[i++] = '/'; } - - - -//Mapping table from Base64 characters to 6-bit nibbles. - -private static byte[] map2 = new byte[128]; - -static { - - for (int i=0; isun.misc.BASE64Encoder.encodeBuffer(byte[]). - -* @param in An array containing the data bytes to be encoded. - -* @return A String containing the Base64 encoded data, broken into lines. - -*/ - -public static String encodeLines (byte[] in) { - -return encodeLines(in, 0, in.length, 76, systemLineSeparator); } - - - -/** - -* Encodes a byte array into Base 64 format and breaks the output into lines. - -* @param in An array containing the data bytes to be encoded. - -* @param iOff Offset of the first byte in in to be processed. - -* @param iLen Number of bytes to be processed in in, starting at iOff. - -* @param lineLen Line length for the output data. Should be a multiple of 4. - -* @param lineSeparator The line separator to be used to separate the output lines. - -* @return A String containing the Base64 encoded data, broken into lines. - -*/ - -public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { - -int blockLen = (lineLen*3) / 4; - -if (blockLen <= 0) throw new IllegalArgumentException(); - -int lines = (iLen+blockLen-1) / blockLen; - -int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length(); - -StringBuilder buf = new StringBuilder(bufLen); - -int ip = 0; - -while (ip < iLen) { - - int l = Math.min(iLen-ip, blockLen); - - buf.append (encode(in, iOff+ip, l)); - - buf.append (lineSeparator); - - ip += l; } - -return buf.toString(); } - - - -/** - -* Encodes a byte array into Base64 format. - -* No blanks or line breaks are inserted in the output. - -* @param in An array containing the data bytes to be encoded. - -* @return A character array containing the Base64 encoded data. - -*/ - -public static char[] encode (byte[] in) { - -return encode(in, 0, in.length); } - - - -/** - -* Encodes a byte array into Base64 format. - -* No blanks or line breaks are inserted in the output. - -* @param in An array containing the data bytes to be encoded. - -* @param iLen Number of bytes to process in in. - -* @return A character array containing the Base64 encoded data. - -*/ - -public static char[] encode (byte[] in, int iLen) { - -return encode(in, 0, iLen); } - - - -/** - -* Encodes a byte array into Base64 format. - -* No blanks or line breaks are inserted in the output. - -* @param in An array containing the data bytes to be encoded. - -* @param iOff Offset of the first byte in in to be processed. - -* @param iLen Number of bytes to process in in, starting at iOff. - -* @return A character array containing the Base64 encoded data. - -*/ - -public static char[] encode (byte[] in, int iOff, int iLen) { - -int oDataLen = (iLen*4+2)/3; // output length without padding - -int oLen = ((iLen+2)/3)*4; // output length including padding - -char[] out = new char[oLen]; - -int ip = iOff; - -int iEnd = iOff + iLen; - -int op = 0; - -while (ip < iEnd) { - - int i0 = in[ip++] & 0xff; - - int i1 = ip < iEnd ? in[ip++] & 0xff : 0; - - int i2 = ip < iEnd ? in[ip++] & 0xff : 0; - - int o0 = i0 >>> 2; - - int o1 = ((i0 & 3) << 4) | (i1 >>> 4); - - int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); - - int o3 = i2 & 0x3F; - - out[op++] = map1[o0]; - - out[op++] = map1[o1]; - - out[op] = op < oDataLen ? map1[o2] : '='; op++; - - out[op] = op < oDataLen ? map1[o3] : '='; op++; } - -return out; } - - - -/** - -* Decodes a string from Base64 format. - -* No blanks or line breaks are allowed within the Base64 encoded input data. - -* @param s A Base64 String to be decoded. - -* @return A String containing the decoded data. - -* @throws IllegalArgumentException If the input is not valid Base64 encoded data. - -*/ - -public static String decodeString (String s) { - -return new String(decode(s)); } - - - -/** - -* Decodes a byte array from Base64 format and ignores line separators, tabs and blanks. - -* CR, LF, Tab and Space characters are ignored in the input data. - -* This method is compatible with sun.misc.BASE64Decoder.decodeBuffer(String). - -* @param s A Base64 String to be decoded. - -* @return An array containing the decoded data bytes. - -* @throws IllegalArgumentException If the input is not valid Base64 encoded data. - -*/ - -public static byte[] decodeLines (String s) { - -char[] buf = new char[s.length()]; - -int p = 0; - -for (int ip = 0; ip < s.length(); ip++) { - - char c = s.charAt(ip); - - if (c != ' ' && c != '\r' && c != '\n' && c != '\t') - - buf[p++] = c; } - -return decode(buf, 0, p); } - - - -/** - -* Decodes a byte array from Base64 format. - -* No blanks or line breaks are allowed within the Base64 encoded input data. - -* @param s A Base64 String to be decoded. - -* @return An array containing the decoded data bytes. - -* @throws IllegalArgumentException If the input is not valid Base64 encoded data. - -*/ - -public static byte[] decode (String s) { - -return decode(s.toCharArray()); } - - - -/** - -* Decodes a byte array from Base64 format. - -* No blanks or line breaks are allowed within the Base64 encoded input data. - -* @param in A character array containing the Base64 encoded data. - -* @return An array containing the decoded data bytes. - -* @throws IllegalArgumentException If the input is not valid Base64 encoded data. - -*/ - -public static byte[] decode (char[] in) { - -return decode(in, 0, in.length); } - - - -/** - -* Decodes a byte array from Base64 format. - -* No blanks or line breaks are allowed within the Base64 encoded input data. - -* @param in A character array containing the Base64 encoded data. - -* @param iOff Offset of the first character in in to be processed. - -* @param iLen Number of characters to process in in, starting at iOff. - -* @return An array containing the decoded data bytes. - -* @throws IllegalArgumentException If the input is not valid Base64 encoded data. - -*/ - -public static byte[] decode (char[] in, int iOff, int iLen) { - -if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); - -while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--; - -int oLen = (iLen*3) / 4; - -byte[] out = new byte[oLen]; - -int ip = iOff; - -int iEnd = iOff + iLen; - -int op = 0; - -while (ip < iEnd) { - - int i0 = in[ip++]; - - int i1 = in[ip++]; - - int i2 = ip < iEnd ? in[ip++] : 'A'; - - int i3 = ip < iEnd ? in[ip++] : 'A'; - - if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) - - throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); - - int b0 = map2[i0]; - - int b1 = map2[i1]; - - int b2 = map2[i2]; - - int b3 = map2[i3]; - - if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) - - throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); - - int o0 = ( b0 <<2) | (b1>>>4); - - int o1 = ((b1 & 0xf)<<4) | (b2>>>2); - - int o2 = ((b2 & 3)<<6) | b3; - - out[op++] = (byte)o0; - - if (op parameters = new ArrayList(); - - @Parameter(names = "--props" , description = "Location of the Properties file") - public String varPropertiesFile; - - @Parameter(names = "--key" , description = "Key used for encryption", required = true) - public String varKey; - - @Parameter(names = "--encrypt", description = "Encrypt this value using the Key") - public String varEncrypt; - - @Parameter(names = "--replace", description = "Tokens for which to search", variableArity = true, splitter = SpaceParameterSplitter.class) - public List varTokens = new ArrayList(); - - @Parameter(names = "--help", description = "print this message", help = true) - public boolean help; - - @Parameter(names = "--debug", description = "Used to debug the program") - public String debug; -} diff --git a/src/com/belkast/soap/Protector.java b/src/com/belkast/soap/Protector.java deleted file mode 100644 index d4df7c5..0000000 --- a/src/com/belkast/soap/Protector.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.belkast.soap; - -import java.security.Key; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - -public class Protector - { - private static final String ALGORITHM = "AES"; - - public static char[] encrypt(byte[] varKey, String valueToEnc) throws Exception - { - System.out.println("## Encrypting password ##"); - Key key = generateKey(varKey); - Cipher c = Cipher.getInstance("AES"); - c.init(1, key); - byte[] encValue = c.doFinal(valueToEnc.getBytes()); - char[] encryptedValue = Base64.encode(encValue); - return encryptedValue; - } - - public static String decrypt(byte[] varKey, String encryptedValue) throws Exception - { - System.out.println("## Decrypting password ##"); - Key key = generateKey(varKey); - Cipher c = Cipher.getInstance("AES"); - c.init(2, key); - byte[] decordedValue = Base64.decode(encryptedValue); - byte[] decValue = c.doFinal(decordedValue); - String decryptedValue = new String(decValue); - return decryptedValue; - } - - private static Key generateKey(byte[] varKey) throws Exception - { - Key key = new SecretKeySpec(varKey, "AES"); - return key; - } - } \ No newline at end of file diff --git a/src/com/belkast/soap/Webservice.java b/src/com/belkast/soap/Webservice.java deleted file mode 100644 index 8362c76..0000000 --- a/src/com/belkast/soap/Webservice.java +++ /dev/null @@ -1,386 +0,0 @@ - package com.belkast.soap; - - import java.io.BufferedReader; - import java.io.ByteArrayOutputStream; - import java.io.File; - import java.io.FileInputStream; - import java.io.FileReader; - import java.io.IOException; - import java.io.InputStreamReader; - import java.io.OutputStream; - import java.io.PrintStream; - import java.io.BufferedWriter; - import java.io.FileWriter; - import java.net.HttpURLConnection; - import java.net.URL; - import java.net.URLConnection; - import java.text.SimpleDateFormat; - import java.util.*; - import java.util.Map.Entry; - import javax.net.ssl.HostnameVerifier; - import javax.net.ssl.HttpsURLConnection; - import javax.net.ssl.SSLSession; - - import com.beust.jcommander.*; - - public class Webservice - { - private static Boolean varDebug; - - private static String varDebugToFile = "false"; - - private static String varPassword; - private static String programStatus; - - private static String NEW_STATUS = null; - - public static void main(String[] args) throws Exception - { - try - { - soapResponse(args); - } - catch(Exception ex) - { - throw new RuntimeException(ex); - } - } - - public static String soapResponse(String[] args) throws Exception - { - - SimpleDateFormat varFormat = new SimpleDateFormat("HH:mm:ss.SSS"); - - Date dateStart = new Date(); - - System.out.println("\nStart Time: " + varFormat.format(dateStart) + ""); - - Parser commandLine = new Parser(); - JCommander jct = new JCommander (commandLine); - File configFilePath = new File(""); - try - { - jct.parse(args); - } - catch (ParameterException ex) - { - System.out.println(ex.getMessage()); - jct.usage(); - } - - if (commandLine.varKey != null && commandLine.varEncrypt != null) - { - varPassword = encryptPassword(commandLine.varKey, commandLine.varEncrypt); - return ""; - } - - if (commandLine.varPropertiesFile == null) - { - programStatus = "Properties file not valid"; - return programStatus; - } - - varDebug = Boolean.parseBoolean(commandLine.debug); - - System.out.println("Debug is: " + varDebug.toString() + ""); - - try - { - configFilePath = new File(commandLine.varPropertiesFile); - FileReader fileReader = new FileReader(configFilePath); - } - catch (IOException e) - { - programStatus = e.toString(); - return programStatus; - } - - String varDelimiter = readProperty(varDebug, configFilePath, "ARGUMENT_DELIMITER"); - varDebugToFile = readProperty(varDebug, configFilePath, "DEBUG_TO_FILE"); - - debugMessage(varDebug, "==================== START ====================", varDebugToFile); - debugMessage(varDebug, "Start Time: " + varFormat.format(dateStart), varDebugToFile); - - HashMap hashMap = generateHashMap(commandLine.varTokens.size(), varDelimiter, commandLine.varTokens); - - System.out.println(); - String varURL = readProperty(varDebug, configFilePath, "SHIM_URL"); - String varInputFile = readProperty(varDebug, configFilePath, "INPUT_FILE"); - String varUsername = readProperty(varDebug, configFilePath, "USERNAME"); - String varPasswordTemp = readProperty(varDebug, configFilePath, "PASSWORD"); - - String varUseSSL = readProperty(varDebug, configFilePath, "SSL"); - - String varKeystore_LOC = readProperty(varDebug, configFilePath, "JAVA_KS_LOCATION"); - String varKeystore_PW = readProperty(varDebug, configFilePath, "JAVA_KS_PASSWORD"); - - try - { - varPassword = Protector.decrypt(commandLine.varKey.getBytes(), varPasswordTemp); - } - catch (Exception e) - { - programStatus = e.toString(); - return programStatus; - } - - if ((varURL.equalsIgnoreCase("")) || (varInputFile.equalsIgnoreCase(""))) - { - programStatus = "Properties file " + configFilePath.toString() + " is not valid"; - return programStatus; - } - - System.out.println(); - - String varDocument = readTextFile(varInputFile, hashMap); - if (varDocument.length() > 0) - { - String response = writeMessage(varUsername, varPassword, varURL, varInputFile, varUseSSL, varKeystore_LOC, varKeystore_PW, hashMap, varDocument.getBytes()); - System.out.println(); - System.out.println("SOAP Document received: " + response + ""); - - debugMessage(varDebug, "SOAP Document received: " + response, varDebugToFile); - - Date dateEnd = new Date(); - - System.out.println("\nEnd Time: " + varFormat.format(dateEnd) + ""); - debugMessage(varDebug, "End Time: " + varFormat.format(dateEnd), varDebugToFile); - debugMessage(varDebug, "==================== FINISH ====================", varDebugToFile); - - if (programStatus == null) - { - return "WS response: " + response; - } - } - - return programStatus; - - } - - private static String debugMessage(Boolean varLevel, String varMessage, String varDebugToFile) - { -// System.out.println("I AM HERE [" + varMessage + "]"); - - if (varLevel.booleanValue() == true) - { - System.out.println(varMessage); - } - - if (varDebugToFile.equalsIgnoreCase("true")) - { - File file = new File("debug.log"); - try - { - //if file doesnt exists, then create it - if (!file.exists()) - { - System.out.println("Creating a new file!"); - file.createNewFile(); - } - - BufferedWriter bw = null; - bw = new BufferedWriter(new FileWriter(file, true)); - bw.write(varMessage); - bw.newLine(); - bw.flush(); - bw.close(); - } - catch (IOException e) - { - return programStatus; - } - } - - return "OK"; - } - - private static HashMap generateHashMap(Integer size, String delimiter, List tokens) throws Exception - { - - System.out.println("\n## Generating a HashMap based on " + tokens.toString() + " ##"); - String[] argumentsArray = new String[size]; - HashMap hashMap = new HashMap(); - - System.out.println("Token size " + size.toString() + ""); - - - for (int i = 0; i < size; i++) - { - argumentsArray[i] = tokens.get(i); - System.out.println("Token [" + i + "]: " + argumentsArray[i] + ""); - - String words[] = argumentsArray[i].split(delimiter); - - if (words.length != 2) - continue; - System.out.println("hashMap: " + words[0] + " and " + words[1] + ""); - hashMap.put(words[0], words[1]); - } - debugMessage(varDebug, "Array Size " + argumentsArray.length + "", varDebugToFile); - debugMessage(varDebug, "HashMap contains " + hashMap.size() + " key value pairs", varDebugToFile); - - return hashMap; - } - - private static String encryptPassword(String tempKey, String varPassword) throws Exception - { - char[] varPasswordIn = new char[0]; - Integer validKeyLength = 15; - - System.out.println("\n## Generating an encrypted password ##"); - try - { - tempKey.charAt(validKeyLength); - byte[] thisKey = tempKey.getBytes(); - System.out.println("Key to use: " + new String(thisKey)); - System.out.println("Value to encrypt: " + varPassword); - varPasswordIn = Protector.encrypt(thisKey, varPassword); - System.out.println("Encrypted value: " + new String(varPasswordIn)); - String varPasswordOut = Protector.decrypt(thisKey, new String(varPasswordIn)); - System.out.println("Test Decrypted value: " + varPasswordOut); - } - catch(Exception e) - { - e.printStackTrace(); - } - - return varPasswordIn.toString(); - } - - public static String readProperty(Boolean varDebug, File MyFile, String varProperty) throws Exception - { - Properties props = new Properties(); - String propertyValue = ""; - - if (varProperty.equals("SHOW_DEBUG")) - { - varDebug = true; - } - try - { - props.load(new FileInputStream(MyFile)); - propertyValue = props.getProperty(varProperty); - if (propertyValue == null) - { - propertyValue = ""; - } - debugMessage(varDebug, "Reading properties file for " + varProperty + ", got " + propertyValue + "", varDebugToFile); - } - catch (Exception e) - { - e.printStackTrace(); - } - return propertyValue; - } - - public static String readTextFile(String fullPathFilename, HashMap hashMap) throws IOException - { - System.out.println("## Preparing the SOAP document ##"); - StringBuilder sb = new StringBuilder(43); - try - { - File myFile = new File(fullPathFilename); - FileReader fileReader = new FileReader(myFile); - BufferedReader reader = new BufferedReader(fileReader); - String line; - while ((line = reader.readLine()) != null) - { - sb.append(line); - } - reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - return (""); - } - - String returnString = sb.toString(); - - Set set = hashMap.entrySet(); - Iterator i = set.iterator(); - while (i.hasNext()) - { - Map.Entry me = (Map.Entry)i.next(); - System.out.println("Replacing " + me.getKey().toString() + " with " + me.getValue().toString() + ""); - - debugMessage(varDebug, "Replacing " + me.getKey().toString() + " with " + me.getValue().toString(), varDebugToFile); - - returnString = returnString.replaceAll(me.getKey().toString(), me.getValue().toString()); - } - - System.out.println("SOAP Document to send: " + returnString + ""); - - debugMessage(varDebug, "SOAP Document to send: " + returnString, varDebugToFile); - - return returnString; - } - - public static String writeMessage(String username, String password, String varURL, String varInputFile, String varUseSSL, String thisKeystore, String thisPassword, HashMap hashMap, byte[] document) throws Exception - { - programStatus = NEW_STATUS; - - StringBuilder response = new StringBuilder(500); - String login = username + ":" + password; - String encoding = Base64.encodeString(login); - - URL url = new URL(varURL); - - try { - System.out.println("\n## Sending SOAP Document ##"); - - if ( Boolean.parseBoolean(varUseSSL) ) - { - System.setProperty("javax.net.ssl.trustStore", thisKeystore); - System.setProperty("javax.net.ssl.trustStorePassword", thisPassword); - } - - URLConnection connection = url.openConnection(); - connection.setRequestProperty("Authorization", "Basic " + encoding); - HttpURLConnection httpConn = (HttpURLConnection)connection; - ByteArrayOutputStream outstr = new ByteArrayOutputStream(); - - httpConn.setRequestProperty("Content-Length", String.valueOf(document.length)); - httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); - httpConn.setRequestMethod("POST"); - httpConn.setDoOutput(true); - httpConn.setDoInput(true); - - OutputStream out = httpConn.getOutputStream(); - out.write(document); - out.close(); - - InputStreamReader ireader = new InputStreamReader(httpConn.getInputStream()); - - BufferedReader in = new BufferedReader(ireader); - String inputLine; - while ((inputLine = in.readLine()) != null) - { - response.append(inputLine); - } - - in.close(); - httpConn.disconnect(); - } - catch (Exception e) - { - e.printStackTrace(); - programStatus = e.toString(); - return programStatus; - } - - return response.toString(); - } - - static - { - HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() - { - public boolean verify(String hostname, SSLSession sslSession) - { - System.out.println("Hostname: " + hostname + ""); - return true; - } - }); - } -} \ No newline at end of file diff --git a/src/com/belkast/soap/debugProcessor.java b/src/com/belkast/soap/debugProcessor.java new file mode 100644 index 0000000..b91b4bf --- /dev/null +++ b/src/com/belkast/soap/debugProcessor.java @@ -0,0 +1,34 @@ +package com.belkast.soap; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public class debugProcessor { + + public static void writer(Boolean toScreen, String varMessage) + { + if (toScreen) + { + System.out.println(varMessage); + } + + File file = new File("debug.log"); + try + { + if (!file.exists()) + { + boolean success = file.createNewFile(); + } + + BufferedWriter bw = null; + bw = new BufferedWriter(new FileWriter(file, true)); + bw.write(varMessage); + bw.newLine(); + bw.flush(); + bw.close(); + } + catch (IOException e) {} + } +} diff --git a/src/com/belkast/soap/fileProcessor.java b/src/com/belkast/soap/fileProcessor.java new file mode 100644 index 0000000..42dabef --- /dev/null +++ b/src/com/belkast/soap/fileProcessor.java @@ -0,0 +1,74 @@ +package com.belkast.soap; + +import java.io.*; +import java.util.*; + +public class fileProcessor { + + public static String readFirstLine(String thisFile) throws Exception { + File file = new File(thisFile); + if (file.exists()) { + FileReader fr = new FileReader(file); + LineNumberReader ln = new LineNumberReader(fr); + while (ln.getLineNumber() == 0) { + String s = ln.readLine(); + return s; + } + } + return null; + } + + public static Boolean getFile (String myFile) + { + if (myFile == null) + { + return false; + } + + File thisFile = new File(myFile); + if (thisFile.exists()) + { + return true; + } + + return false; + } + + public static String replaceInFile (String myFile, Map hashMap) + { + File thisFile = new File(myFile); + if (!thisFile.exists()) + { + return null; + } + StringBuilder sb = new StringBuilder(); + try + { + FileReader fileReader = new FileReader(myFile); + BufferedReader reader = new BufferedReader(fileReader); + String line; + while ((line = reader.readLine()) != null) + { + sb.append(line); + } + reader.close(); + } + catch (IOException e) + { + e.printStackTrace(); + return null; + } + + String returnString = sb.toString(); + + Set set = hashMap.entrySet(); + Iterator i = set.iterator(); + while (i.hasNext()) + { + Map.Entry me = (Map.Entry)i.next(); + returnString = returnString.replaceAll(me.getKey().toString(), me.getValue().toString()); + } + + return returnString; + } +} \ No newline at end of file diff --git a/src/com/belkast/soap/jCommanderArgs.java b/src/com/belkast/soap/jCommanderArgs.java new file mode 100644 index 0000000..b4af093 --- /dev/null +++ b/src/com/belkast/soap/jCommanderArgs.java @@ -0,0 +1,18 @@ +package com.belkast.soap; + +import com.beust.jcommander.Parameter; + +public class jCommanderArgs { + + @Parameter(names = "--props" , description = "Location of the properties file", validateWith = jCommanderVerifyFile.class) + public String props; + + @Parameter(names = "--key", description = "Encryption Key (must be 16 characters in length)", required = true, password = true, validateWith = jCommanderVerifyKey.class) + public String key; + + @Parameter(names = "--encrypt", description = "Value to encrypt using the Encryption Key") + public String encrypt; + + @Parameter(names = "--debug", description = "Display debug information on the screen") + public String debug; +} diff --git a/src/com/belkast/soap/jCommanderVerifyFile.java b/src/com/belkast/soap/jCommanderVerifyFile.java new file mode 100644 index 0000000..05a1aee --- /dev/null +++ b/src/com/belkast/soap/jCommanderVerifyFile.java @@ -0,0 +1,22 @@ +package com.belkast.soap; + +import com.beust.jcommander.IParameterValidator; +import com.beust.jcommander.ParameterException; + +import java.io.File; + +public class jCommanderVerifyFile implements IParameterValidator +{ + public void validate(String name, String value) throws ParameterException + { + File file = new File (value); + boolean isThere = file.exists(); + + if (!isThere) + { + System.out.println(); + System.out.println("Parameter value " + name + " points to a file that does not exist!"); + throw new ParameterException("Parameter value " + name + " points to a file that does not exist!"); + } + } +} diff --git a/src/com/belkast/soap/jCommanderVerifyKey.java b/src/com/belkast/soap/jCommanderVerifyKey.java new file mode 100644 index 0000000..8a7b8c0 --- /dev/null +++ b/src/com/belkast/soap/jCommanderVerifyKey.java @@ -0,0 +1,17 @@ +package com.belkast.soap; + +import com.beust.jcommander.IParameterValidator; +import com.beust.jcommander.ParameterException; + +public class jCommanderVerifyKey implements IParameterValidator { + + public void validate(String name, String value) throws ParameterException + { + int n = value.length(); + if (n != 16) { + System.out.println(); + System.out.println("Parameter value " + name + " must have a length of 16 characters!"); + throw new ParameterException("Parameter value " + name + " must have a length of 16 characters!"); + } + } + } diff --git a/src/com/belkast/soap/propertyProcessor.java b/src/com/belkast/soap/propertyProcessor.java new file mode 100644 index 0000000..798fbb8 --- /dev/null +++ b/src/com/belkast/soap/propertyProcessor.java @@ -0,0 +1,29 @@ +package com.belkast.soap; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +public class propertyProcessor +{ + public static String getProperty(File MyFile, String varProperty) throws Exception + { + Properties props = new Properties(); + String propertyValue = ""; + + try + { + props.load(new FileInputStream(MyFile)); + propertyValue = props.getProperty(varProperty); + if (propertyValue == null) + { + propertyValue = ""; + } + } + catch (Exception e) + { + e.printStackTrace(); + } + return propertyValue; + } +} diff --git a/src/com/belkast/soap/soapProcessor.java b/src/com/belkast/soap/soapProcessor.java new file mode 100644 index 0000000..0dc62a1 --- /dev/null +++ b/src/com/belkast/soap/soapProcessor.java @@ -0,0 +1,98 @@ +package com.belkast.soap; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.util.Base64; +import java.util.Map; + +public class soapProcessor { + + public static String getCredentials(String username, String password) throws Exception + { + String login = username + ":" + password; + String credentials = Base64.getEncoder().encodeToString(login.getBytes()); + return credentials; + } + + public static Boolean closeConnection(HttpURLConnection thisConn) throws Exception + { + thisConn.disconnect(); + return true; + } + public static HttpURLConnection getConnection(String thisCredentials, String thisURL, Boolean thisSSL, String thisKeystore, String thisPassword) throws Exception + { + URL url = new URL(thisURL); + if (thisSSL) + { + System.setProperty("javax.net.ssl.trustStore", thisKeystore); + System.setProperty("javax.net.ssl.trustStorePassword", thisPassword); + } + try + { + URLConnection connection = url.openConnection(); + connection.setRequestProperty("Authorization", "Basic " + thisCredentials); + HttpURLConnection httpConn = (HttpURLConnection)connection; + return httpConn; + } + catch (Exception ex) + { + System.out.println(ex.toString()); + return null; + } + } + + public static String send(HttpURLConnection thisConn, String varInputFile, Map hashMap, byte[] document) throws Exception + { + StringBuilder response = new StringBuilder(500); + + try { + ByteArrayOutputStream outstr = new ByteArrayOutputStream(); + thisConn.setRequestProperty("Content-Length", String.valueOf(document.length)); + thisConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); + thisConn.setRequestMethod("POST"); + thisConn.setDoOutput(true); + thisConn.setDoInput(true); + + OutputStream out = thisConn.getOutputStream(); + out.write(document); + out.close(); + + InputStreamReader ireader = new InputStreamReader(thisConn.getInputStream()); + + BufferedReader in = new BufferedReader(ireader); + String inputLine; + while ((inputLine = in.readLine()) != null) + { + response.append(inputLine); + } + + in.close(); + } + catch (Exception ex) + { + System.out.println(ex.toString()); + return ex.toString(); + } + + return response.toString(); + } + + static + { + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() + { + public boolean verify(String hostname, SSLSession sslSession) + { + return true; + } + }); + } +} diff --git a/src/com/belkast/soap/userVerify.java b/src/com/belkast/soap/userVerify.java new file mode 100644 index 0000000..9a8b69e --- /dev/null +++ b/src/com/belkast/soap/userVerify.java @@ -0,0 +1,130 @@ +package com.belkast.soap; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; + +import java.io.File; +import java.io.FileReader; +import java.io.Reader; +import java.util.*; + +public class userVerify +{ + public static void main (String[] args) { + System.out.println(); + Scanner myObj = new Scanner(System.in); // Create a Scanner object + System.out.print("Enter the name of the file to verify : "); + + String varFileName = myObj.nextLine(); // Read user input + File thisFile = new File(varFileName); + if (!thisFile.exists()) { + System.out.println("The file " + varFileName + " does not exist. Please enter a valid filename!"); + System.exit(0); + } + System.out.println(); + System.out.println("CSV input file : " + varFileName); + ArrayList thisCSV = readCSV(varFileName, true); + System.out.println(); + + Iterator mapper1 = thisCSV.iterator(); + int varIter = 0; + while (mapper1.hasNext()) + { + varIter++; + Map thisMap = mapper1.next(); + Iterator> it = thisMap.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry pair = it.next(); + System.out.println("record " + varIter + " key : " + pair.getKey()); + System.out.println("record " + varIter + " val : " + pair.getValue()); + } + System.out.println(); + } + boolean validfile = (thisCSV.isEmpty()); + System.out.println("CSV file records : " + varIter); + System.out.println("CSV file is valid : " + validfile); + System.out.println(); + } + + public static ArrayList readCSV (String thisFile, boolean fromUser) + { + int readNum = 0; + int invalidNum = 0; + ArrayList finalArray = new ArrayList(); + File varFile = new File (thisFile); + if (!varFile.exists()) { + System.out.println(varFile + " does not exist. Please enter a valid filename!"); + System.exit(0); + } + + try { + Reader in = new FileReader(varFile); + String varHeader = fileProcessor.readFirstLine(thisFile); + + System.out.println(varHeader); + if (varHeader.length() == 0) + { + System.out.println("The " + thisFile + " file appears to be missing a valid header!"); + return finalArray; + } + + CSVFormat csvFormat = CSVFormat.RFC4180.builder() + .setHeader(varHeader.split(",")) + .setSkipHeaderRecord(true) + .setIgnoreEmptyLines(true) + .setIgnoreSurroundingSpaces(true) + .setTrim(true) + .build(); + + int headerLen = csvFormat.getHeader().length; + Iterable records = csvFormat.parse(in); + + if (fromUser) + { + System.out.println("CSV token count : " + headerLen); + System.out.println("CSV token list : " + varHeader); + System.out.println(); + } + + for (CSVRecord record : records) + { + readNum++; + long lineNum = record.getParser().getCurrentLineNumber(); + boolean isValid = record.isConsistent(); + + if (isValid) { + finalArray.add(record.toMap()); + if (fromUser) + { + System.out.println("PASSED => CSV line : " + lineNum); + } + } + else + { + invalidNum++; + if (fromUser) + { + System.out.println("FAILED => CSV line : " + lineNum); + System.out.println("FAILED => Contents : " + lineNum + " is " + record.toMap().toString()); + } + } + } + } catch (Exception e) { + } + + if (fromUser) + { + System.out.println(); + System.out.println("CSV lines passed : " + String.valueOf(readNum - invalidNum)); + System.out.println("CSV lines failed : " + invalidNum); + } + + if (invalidNum > 0) + { + finalArray = new ArrayList(); + } + + return finalArray; + } +} diff --git a/src/com/belkast/soap/webService.java b/src/com/belkast/soap/webService.java new file mode 100644 index 0000000..15cdf16 --- /dev/null +++ b/src/com/belkast/soap/webService.java @@ -0,0 +1,180 @@ +package com.belkast.soap; + +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.*; + +import java.io.File; +import java.net.HttpURLConnection; +import java.text.SimpleDateFormat; +import java.util.*; + +public class webService { + static Date dateStart = new Date(); + static SimpleDateFormat varFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + static Boolean varDebug = false; + static String varKey; + + public static void main(String... argv) throws Exception { + +// @Parameter(names = "--props", +// description = "Location of the Properties file") + +// @Parameter(names = "--key", +// description = "Encryption Key (length of 16)") + +// @Parameter(names = "--encrypt", +// description = "Encrypt this value using the Key") + +// @Parameter(names = "--debug", +// description = "Write details to the screen") + + jCommanderArgs args = new jCommanderArgs(); + JCommander jct = new JCommander(args); + + try { + jct.parse(argv); + } catch (ParameterException ex) { + System.out.println(); + jct.usage(); + System.exit(0); + } + + System.out.println(); + + varDebug = Boolean.valueOf(args.debug); + varKey = args.key; + String varToEncrypt = args.encrypt; + + if (varToEncrypt != null && varToEncrypt.length() > 0) + { + String varToStore = secretProcessor.encode(secretProcessor.encrypt(varKey, varToEncrypt)); + String varChecked = secretProcessor.decrypt(varKey, secretProcessor.decode(varToStore)); + System.out.println("Clear Text Password : " + varToEncrypt); + System.out.println("Encryption Key : " + varKey); + System.out.println("Encrypted / Encoded : " + varToStore); + System.out.println("Decoded / Decrypted : " + varChecked); + System.out.println(); + System.exit(0); + } + + String varProps = args.props; + if (varProps == null && varToEncrypt == null) + { + debugProcessor.writer(true, "Check your parameters. There is simply nothing to see here!"); + System.out.println(); + jct.usage(); + System.exit(0); + } + + if (!fileProcessor.getFile(varProps)) { + debugProcessor.writer(true, "Please supply a valid properties file for --props"); + System.exit(0); + } + + doSoap(new File(varProps)); + System.exit(0); + } + + private static String doSoap(File thisProps) throws Exception { + String varPassword = new String(); + String varDelimiter = propertyProcessor.getProperty(thisProps, "ARGUMENT_DELIMITER"); + + debugProcessor.writer(true, "============ START ============"); + + debugProcessor.writer(true, "Start Time: " + varFormat.format(dateStart)); + debugProcessor.writer(varDebug, "Debug is set to : " + varDebug); + + System.out.println(); + String varURL = propertyProcessor.getProperty(thisProps, "SHIM_URL"); + String varRoleFile = propertyProcessor.getProperty(thisProps, "INPUT_FILE"); + String varInputFile = propertyProcessor.getProperty(thisProps, "XML_FILE"); + String varUsername = propertyProcessor.getProperty(thisProps, "USERNAME"); + String varPasswordTemp = propertyProcessor.getProperty(thisProps, "PASSWORD"); + + String varUseSSL = propertyProcessor.getProperty(thisProps, "SSL"); + + String varKeystore_LOC = propertyProcessor.getProperty(thisProps, "JAVA_KS_LOCATION"); + String varKeystore_PW = propertyProcessor.getProperty(thisProps, "JAVA_KS_PASSWORD"); + + debugProcessor.writer(varDebug, thisProps + " => SOAP URL : " + varURL); + debugProcessor.writer(varDebug, thisProps + " => Username : " + varUsername); + debugProcessor.writer(varDebug, thisProps + " => Use SSL : " + varUseSSL); + debugProcessor.writer(varDebug, thisProps + " => JAVA Keystore : " + varKeystore_LOC); + debugProcessor.writer(varDebug, thisProps + " => JAVA Keystore password : " + varKeystore_PW); + debugProcessor.writer(varDebug, thisProps + " => Input File : " + varRoleFile); + debugProcessor.writer(varDebug, thisProps + " => XML File : " + varInputFile); + + File checkInput = new File (varInputFile); + if (!checkInput.exists()) + { + debugProcessor.writer(varDebug, "The XML_FILE file specified in " + thisProps + " does not exist!"); + System.exit(0); + } + + File checkRole = new File (varRoleFile); + if (!checkRole.exists()) + { + debugProcessor.writer(varDebug, "The INPUT_FILE specified in " + thisProps + " does not exist!"); + System.exit(0); + } + + try { + byte[] varDecoded = secretProcessor.decode(varPasswordTemp); + varPassword = secretProcessor.decrypt(varKey, varDecoded); + } catch (Exception e) { + debugProcessor.writer(varDebug, "The supplied password could not be decrypted. Please check the password!"); + System.exit(0); + } + + ArrayList thisCSV = userVerify.readCSV(varRoleFile, false); + + boolean validfile = (thisCSV.size() > 0); + debugProcessor.writer(true, varRoleFile + " : CSV file is valid => " + validfile); + debugProcessor.writer(true, varRoleFile + " : records to process => " + thisCSV.size()); + + if (!validfile) + { + debugProcessor.writer(true, varRoleFile + " : verify the file with com.belkast.soap.userVerify"); + } + int varCount = 0; + Iterator mapper1 = thisCSV.iterator(); + while (mapper1.hasNext()) { + varCount++; + debugProcessor.writer(false, ""); + debugProcessor.writer(true, "Processing record " + varCount); + + Map hashMap = mapper1.next(); + debugProcessor.writer(varDebug, "Record " + varCount + " : " + hashMap.values().toString()); + + Iterator> it = hashMap.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry pair = it.next(); + debugProcessor.writer(varDebug, "Record " + varCount + " : " + pair.getKey() + " => " + pair.getValue()); + } + + String varDocument = fileProcessor.replaceInFile(varInputFile, hashMap); + + if (varDocument.length() > 0) ; + { + String varCredentials = soapProcessor.getCredentials(varUsername, varPassword); + Boolean isSSL = Boolean.parseBoolean(varUseSSL); + + debugProcessor.writer(varDebug, "Connecting to URL : " + varURL); + HttpURLConnection varConn = soapProcessor.getConnection(varCredentials, varURL, isSSL, varKeystore_LOC, varKeystore_PW); + + debugProcessor.writer(varDebug, "Sending document : " + varDocument); + String response = soapProcessor.send(varConn, varInputFile, hashMap, varDocument.getBytes()); + + debugProcessor.writer(varDebug, "Response received : " + response); + soapProcessor.closeConnection(varConn); + } + } + Date dateEnd = new Date(); + System.out.println(); + debugProcessor.writer(true, "Finish Time: " + varFormat.format(dateEnd)); + debugProcessor.writer(true, "============ FINISH ============"); + return new String(); + } +} \ No newline at end of file