/* * Example use of Advanced REST Web API interactions using Java. * AdvancedUtility.WebApi.Models.dll is available from advanced as a stand-alone reference library for use in your projects * (access the models DLL via REST URL https://webapi.yourserver.com/Content/AdvancedUtility.WebApi.Models.dll ) * Need to install one external JAR library (if using 'getHttpList'): * - org.json; */ public class WebApiRequests { public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_ERROR = "\u001B[31m"; public static final String ANSI_SUCCESS = "\u001B[32m"; public static final String ANSI_INFO = "\u001B[96m"; public static final String ANSI_PROMPT = "\u001B[34m"; private static String _webApiRootUrl; // URL Root of the REST Web API server to be used private static String _encodedUserIdPass; // CIS encoded user name and password public static void main(String[] args) { TrustCertificate.createCertificate(); // use this certificate for if making call to localhost _encodedUserIdPass = retrieveUserCredentionals(); _webApiRootUrl = retrieveHttpURL() + "/data/state"; int selection; do { System.out.println(ANSI_INFO + "\nPlease input operation number:"); System.out.println("0 - EXIT"); System.out.println("1 - run GET list request"); System.out.println("2 - run GET one request"); System.out.println("3 - run add validation for state 'ZZX' (should cause a failure)"); System.out.println("4 - run update validation for long description (should cause a failure)"); System.out.println("5 - run POST request"); System.out.println("6 - run PUT request"); System.out.println("7 - run PATCH request"); System.out.println("8 - run DELETE request"); System.out.println("9 - run all operations for testing (GET list, GET one, Validations, POST, PUT, PATCH, DELETE)"); System.out.println("10 - update url"); System.out.println("11 - update user name and password"); System.out.print(ANSI_PROMPT + "\nSelection: " + ANSI_RESET); Scanner scan = new Scanner(System.in); String selectionStr = scan.next(); try{ selection = Integer.parseInt(selectionStr); } catch (Exception e){ selection = -1; } switch (selection) { case 0: System.exit(0); case 1: getHttpList(_encodedUserIdPass, _webApiRootUrl); break; case 2: getHttpOne(_encodedUserIdPass, _webApiRootUrl); break; case 3: validateAdd(_encodedUserIdPass, _webApiRootUrl); break; case 4: validateUpdate(_encodedUserIdPass, _webApiRootUrl); break; case 5: postHttp(_encodedUserIdPass, _webApiRootUrl); break; case 6: putHttp(_encodedUserIdPass, _webApiRootUrl); break; case 7: patchHttp(_encodedUserIdPass, _webApiRootUrl); break; case 8: deleteHttp(_encodedUserIdPass, _webApiRootUrl); break; case 9: runAll(_encodedUserIdPass, _webApiRootUrl); break; case 10: _webApiRootUrl = retrieveHttpURL() + "/data/state"; break; case 11: _encodedUserIdPass = retrieveUserCredentionals(); break; default: System.out.println(ANSI_ERROR + "Unable to process selection." + ANSI_RESET); } } while (selection != 0); } public static String retrieveUserCredentionals() { Scanner scan = new Scanner(System.in); System.out.print(ANSI_PROMPT + "Please input CIS UserId: "); // CIS UserId to be used to authenticate with WebApi String webApiUser = scan.next(); System.out.print("Please input CIS password: " + ANSI_RESET); // CIS password associated with the CIS UserId above String webApiPassword = scan.next(); String webApiUserPass = webApiUser + ":" + webApiPassword; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(webApiUserPass.getBytes())); // authentication string return basicAuth; } public static String retrieveHttpURL() { System.out.print(ANSI_PROMPT + "Please input full path of REST Web API: " + ANSI_RESET); // URL Root of the REST Web API server to be used Scanner scan = new Scanner(System.in); return scan.next(); } // === HTTPS GET List // This request will retrieve a list of states, using GET request. // 1. format query string for request // eg. page=2&pagesize=5&where=code like '%N%' and o_key gt 5&order=-description&fields=* // The result should be success private static void getHttpList(String userIdAndPassword, String webApiRootUrl) { try { StringBuffer sb = new StringBuffer(webApiRootUrl); // create full URL for the request LinkedHashMap qsitems = new LinkedHashMap<>(); qsitems.put("?page=", "2"); // optional page to select - defaults to 1 qsitems.put("&pagesize=", "5"); // optional pagesize of result - defaults to 50 qsitems.put("&where=", "code%20like%20'%N%'%20and%20O_Key%20gt%205"); // optional selection filter - defaults to none qsitems.put("&order=", "-description"); // optional sort order of result - defaults to pk order qsitems.put("&fields=", "*"); // optional data shaping directive - defaults to "*" for (Map.Entry item : qsitems.entrySet()) { sb.append(item.getKey()); sb.append(item.getValue()); } URL url = new URL(sb.toString()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // creating connection con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); int responseCode = con.getResponseCode(); // trying to connect if (responseCode == 200) { // HTTP response code 200 (OK) indicates the request succeeded ListResourcesModel list = getListResourcesModelFromConnection(con); System.out.println(ANSI_SUCCESS + "Successfully retrieved list of states: Page=" + list.getCurrentPage() + ", PageSize=" + list.getPageSize() + ", TotalPages=" + list.getTotalPages() + ", TotalItems=" + list.getTotalItems()); // now find the list of states in the _embedded dictionary if (list._embedded != null && list._embedded.containsKey("_embedded") && list._embedded.get("_embedded") != null) { // JsonObject class represents an immutable JSON object value JSONObject embeddedJSON = new JSONObject(list._embedded); // get _embedded in JSON format JSONObject stateJSON = new JSONObject(embeddedJSON.getString("_embedded")); // get states in JSON format String stateString = stateJSON.getString("state"); // get states in a string format JSONArray statesArray = new JSONArray(stateString); // parse states into json array format ArrayList stateModels = new ArrayList<>(); // create and populate an array of type StateModel with states for (int i = 0, size = statesArray.length(); i < size; i++) { JSONObject objectInArray = statesArray.getJSONObject(i); stateModels.add(new StateModel(objectInArray.get("code").toString(), objectInArray.get("description").toString(), Boolean.getBoolean(objectInArray.get("disabled").toString()), objectInArray.get("o_Code").toString(), objectInArray.get("o_Description").toString(), Long.parseLong(objectInArray.get("o_Key").toString()), Long.parseLong(objectInArray.get("o_SecurityId").toString()))); } for (Iterator i = stateModels.iterator(); i.hasNext(); ) { // printing states to the console StateModel stateModel = i.next(); System.out.println("\t" + stateModel.getCode() + "\t" + stateModel.getDescription() + "\t" + stateModel.getO_Key()); } } System.out.print(ANSI_RESET); } else { System.out.println(ANSI_ERROR + "Get(list) failed with response: " + responseCode + ANSI_RESET); } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS GET One // This request will retrieve one state (NY) using GET method. // Retrieve a single resource // The result should be success private static void getHttpOne(String userIdAndPassword, String webApiRootUrl) { try { Scanner scan = new Scanner(System.in); System.out.print("Please insert value: "); String code = scan.next(); URL url = new URL(webApiRootUrl + "/" + code); // building full path HttpURLConnection con = (HttpURLConnection) url.openConnection(); // creating connection con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes int responseCode = con.getResponseCode(); // trying to connect if (responseCode == HttpURLConnection.HTTP_OK) { // success status code. Successfully retrieved single state StateModel stateModel = getStateModelFromConnection(con); System.out.println(ANSI_SUCCESS + "Successfully retrieved one resource from State Control: " + "Code: " + stateModel.getCode() + "\t" + "description: " + stateModel.getDescription() + "\t" + "o_Key: " + stateModel.getO_Key() + ANSI_RESET); } else { System.out.print(ANSI_ERROR + "Get(list) failed with response: " + responseCode + ANSI_RESET); } con.disconnect(); // === HTTPS VALIDATE // Validate a single existing resource against business rules // The result should be success HttpURLConnection conValidate = (HttpURLConnection) url.openConnection(); // creating connection conValidate.setConnectTimeout(30000); // timeout setup in 1/2 minutes conValidate.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property conValidate.setRequestProperty("X-HTTP-Method-Override", "VALIDATE"); // since Java does not support validation request, X-HTTP-Method-Override header should be used to work around conValidate.setRequestMethod("GET"); conValidate.setRequestProperty("Content-Type", "application/json"); responseCode = conValidate.getResponseCode(); // trying to connect if (responseCode == HttpURLConnection.HTTP_OK) { // Response code 200 (OK) indicates the VALIDATE was successful and there are no validation issues with the resource. System.out.println(ANSI_SUCCESS + "Successfully validated resource /data/state/" + code + ANSI_RESET); } else { System.out.println(ANSI_ERROR + " VALIDATE for changes failed with response: " + responseCode + ANSI_RESET); } conValidate.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS VALIDATE for add // This request, using post method, will ensure that business rules, existing on a server, work properly. // Code inside StateModel represents US state, which should contain 2 letters. If we will try to set more then that, it should fail. // The result of this request should be a failure private static void validateAdd(String userIdAndPassword, String webApiRootUrl) { try { StateModel stateModel = new StateModel(); stateModel.setCode("ZZQ"); stateModel.setDescription("State of Mind"); String postUrl = _webApiRootUrl + "/"; // setting up a full path URL url = new URL(postUrl); HttpURLConnection conValidate = (HttpURLConnection) url.openConnection(); conValidate.setConnectTimeout(30000); // timeout setup in 1/2 minutes conValidate.setRequestProperty("X-HTTP-Method-Override", "VALIDATE"); // since Java does not support validation request, X-HTTP-Method-Override header should be used to work around conValidate.setRequestMethod("POST"); conValidate.setDoOutput(true); conValidate.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property String stateModelRes = getStateModelInfo(stateModel); OutputStream os = conValidate.getOutputStream(); os.write(stateModelRes.getBytes()); os.flush(); os.close(); int responseCode = conValidate.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Response code 200 (OK) indicates the VALIDATE was successful and there are no validation issues with the resource. This should not be a case System.out.println(ANSI_SUCCESS + "Successfully validated new resource for add" + ANSI_RESET); } else { if(conValidate.getResponseMessage().equals("Validation failed")){ parseValidationFailed(conValidate); }else{ System.out.println(ANSI_ERROR + "VALIDATE failed with response:" + responseCode + ANSI_RESET); } } conValidate.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS VALIDATE for update // This is similar to the previous one request, will fail due to incorrect business rule (description is too long) // Validate a given resource update model for changes // The result should be a failure private static void validateUpdate(String userIdAndPassword, String webApiRootUrl) { try { StateModel stateModel = new StateModel(); stateModel.setCode("TT"); stateModel.setDescription("This is very long description, which should fail validation"); // This will cause a failure String postUrl = webApiRootUrl + "/"; URL url = new URL(postUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestProperty("X-HTTP-Method-Override", "VALIDATE"); // since Java does not support validation request, X-HTTP-Method-Override header should be used to work around con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property String stateModelRes = getStateModelInfo(stateModel); OutputStream os = con.getOutputStream(); os.write(stateModelRes.getBytes()); os.flush(); os.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Response code 200 (OK) indicates the VALIDATE was successful and there are no validation issues with the resource. System.out.println(ANSI_SUCCESS + "Successfully validated updated resource for changes" + ANSI_RESET); } else { if(con.getResponseMessage().equals("Validation failed")) { parseValidationFailed(con); }else { System.out.println(ANSI_ERROR + "VALIDATE for changes failed with response: " + responseCode + ANSI_RESET); } } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS POST // This request will add new object to the server. // Add a new resource // If the result will fail, the most common problem is that resource probably already exist on the server. Consider using delete against the resource and try again // The Result should be success private static void postHttp(String userIdAndPassword, String webApiRootUrl) { try { StateModel stateModel = new StateModel(); // creating new StateModel to pass it to the server later on Scanner scan = new Scanner(System.in); System.out.print("Insert state: "); stateModel.setCode(scan.next()); System.out.print("Insert description: "); stateModel.setDescription(scan.next()); String postUrl = webApiRootUrl + "/"; URL url = new URL(postUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property String stateModelRes = getStateModelInfo(stateModel); OutputStream os = con.getOutputStream(); os.write(stateModelRes.getBytes()); os.flush(); os.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_CREATED) { // POST response code 201 (Created) indicates success, and the new resource is returned in the response content body // the response header "Location" returns the URI of the newly created resource System.out.println(ANSI_SUCCESS + "Successfully created new state at location: " + webApiRootUrl + "/" + stateModel.getCode() + ANSI_RESET); } else { if(con.getResponseMessage().equals("Validation failed")) { parseValidationFailed(con); }else { System.out.println(ANSI_ERROR + "POST failed with response: " + responseCode + ANSI_RESET); } } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS PUT // Edit the existing resource using PUT // (PUT typically requires a GET followed by a PUT, because PUT requires the entire object to be sent, since missing properties are defaulted to "empty" values- not what you normally want) // The result should be success private static void putHttp(String userIdAndPassword, String webApiRootUrl) { try { StateModel stateModel = new StateModel(); Scanner scan = new Scanner(System.in); System.out.print("Please insert code: "); String code = scan.next(); stateModel.setCode(code); System.out.print("Please insert description: "); stateModel.setDescription(scan.next()); String postUrl = webApiRootUrl + "/" + code; URL url = new URL(postUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestMethod("PUT"); con.setDoOutput(true); con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property con.setRequestProperty("Content-Type", "application/json"); // setting up fields, which should be updated in a JSON format StringBuffer sb = new StringBuffer(); if (stateModel.getDescription() != null) sb.append("{\"description\":\"" + stateModel.getDescription() + "\","); if (stateModel.getCode() != null) sb.append("\"code\":\"" + stateModel.getCode() + "\"}"); OutputStream os = con.getOutputStream(); os.write(sb.toString().getBytes()); os.flush(); os.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // HTTP response code 200 (OK) indicates success. System.out.println(ANSI_SUCCESS + "Successfully updated state description via PUT" + ANSI_RESET); } else { if(con.getResponseMessage().equals("Validation failed")) { parseValidationFailed(con); }else { System.out.println(ANSI_ERROR + "PUT failed with response:" + responseCode + ANSI_RESET); } } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTPS PATCH // Edit the existing resource using PATCH, which allows selective operations on fields. // Refer to https://en.wikipedia.org/wiki/JSON_Patch for details on the patch document format and supported directives. // The request body should be in a particular format, eg "[{ "op": "replace", "path": "/description", "value": "ARKANSAS" }]" // op - method on the resource, path - the field on the resource for update, value - resource which should be updated // The result should be success private static void patchHttp(String userIdAndPassword, String webApiRootUrl) { try { StateModel stateModel = new StateModel(); Scanner scan = new Scanner(System.in); System.out.print("Please insert code: "); String code = scan.next(); stateModel.setCode(code); System.out.print("Please insert description: "); String description = scan.next(); stateModel.setDescription(description); System.out.print("Please insert property you want to update: "); String property = scan.next(); URL url = new URL(webApiRootUrl + "/" + code); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestProperty("X-HTTP-Method-Override", "PATCH"); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property con.setRequestProperty("Content-Type", "application/json"); StringBuffer sb = new StringBuffer(); sb.append("[{ \"op\": \"replace\", \"path\": \"/"); sb.append(property); sb.append("\", \"value\":\""); sb.append(description); sb.append("\" }]"); OutputStream os = con.getOutputStream(); os.write(sb.toString().getBytes()); os.flush(); os.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // POST response code 201 (Created) indicates success, and the new resource is returned in the response content body // the response header "Location" returns the URI of the newly created resource System.out.println(ANSI_SUCCESS + "Successfully updated state description via PATCH" + ANSI_RESET); } else { if(con.getResponseMessage().equals("Validation failed")) { parseValidationFailed(con); }else { System.out.println(ANSI_ERROR + "PATCH failed with response:" + responseCode + ANSI_RESET); } } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // === HTTP Delete // This request will delete particular resource on the server // Should be success private static void deleteHttp(String userIdAndPassword, String webApiRootUrl) { try { System.out.print("Please insert code to delete: "); Scanner scan = new Scanner(System.in); URL url = new URL(webApiRootUrl + "/" + scan.next()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(30000); // timeout setup in 1/2 minutes con.setRequestMethod("DELETE"); con.setDoOutput(true); con.setRequestProperty("Authorization", userIdAndPassword); // setting up connection property int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // POST response code 201 (Created) indicates success, and the new resource is returned in the response content body // the response header "Location" returns the URI of the newly created resource System.out.println(ANSI_SUCCESS + "Successfully deleted state " + ANSI_RESET); } else { System.out.println(ANSI_ERROR + "DELETE failed with response: " + responseCode + ANSI_RESET); } con.disconnect(); } catch (Exception e) { System.out.println(ANSI_ERROR + e + ANSI_RESET); } } // run all existing methods private static void runAll(String userIdAndPassword, String webApiRootUrl) { System.out.println("Getting list"); getHttpList(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Getting one"); getHttpOne(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("validating add"); validateAdd(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Validating update"); validateUpdate(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Post"); postHttp(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Put"); putHttp(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Patch"); patchHttp(userIdAndPassword, webApiRootUrl); System.out.println(); System.out.println("Delete"); deleteHttp(userIdAndPassword, webApiRootUrl); System.out.println(); } /** * @param stateModel the model for which string response should be generated * @return all not null value field from the model, in a format 'property=value&property2=value2...' */ private static String getStateModelInfo(StateModel stateModel) { StringBuffer sb = new StringBuffer(); sb.append("disabled=" + stateModel.getDisabled()); sb.append("&o_Key=" + stateModel.getO_Key()); sb.append("&o_SecurityId=" + stateModel.getO_SecurityId()); if (stateModel.getCode() != null) sb.append("&code=" + stateModel.getCode()); if (stateModel.getDescription() != null) sb.append("&description=" + stateModel.getDescription()); if (stateModel.getO_Code() != null) sb.append("&o_Code=" + stateModel.getO_Code()); if (stateModel.getO_Description() != null) sb.append("&o_Description=" + stateModel.getO_Description()); return sb.toString(); } /** * @param con current connection * @return StateModel */ private static StateModel getStateModelFromConnection(HttpURLConnection con) { StateModel sm = new StateModel(); try { BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); StringBuffer responseStr = new StringBuffer(); responseStr.append(in.readLine()); // reading response line by line until the end of the file sm = getStateModelFromString(responseStr.toString()); } catch (IOException e) { System.out.println(e); } return sm; } /** * @param con current connection * @return ListResourcesModel */ private static ListResourcesModel getListResourcesModelFromConnection(HttpURLConnection con){ ListResourcesModel sm = new ListResourcesModel(); try { BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); StringBuffer responseStr = new StringBuffer(); responseStr.append(in.readLine()); // reading response line by line until the end of the file sm = getListResourcesModelFromString(responseStr.toString()); } catch (IOException e) { System.out.println(e); } return sm; } /** * * @param responseString response * @return populated object ListResourcesModel */ private static ListResourcesModel getListResourcesModelFromString(String responseString){ ListResourcesModel lrm = new ListResourcesModel(); int totalItemsIndex = responseString.indexOf("totalItems"); if(totalItemsIndex != -1){ lrm.setTotalItems(Integer.parseInt(responseString.substring(totalItemsIndex+12, responseString.indexOf(',', totalItemsIndex+12)))); } int pageSizeIndex = responseString.indexOf("pageSize"); if(pageSizeIndex != -1){ lrm.setPageSize(Integer.parseInt(responseString.substring(pageSizeIndex+10, responseString.indexOf(',', pageSizeIndex+10)))); } int totalPagesIndex = responseString.indexOf("totalPages"); if(totalPagesIndex != -1){ lrm.setTotalPages(Integer.parseInt(responseString.substring(totalPagesIndex+12, responseString.indexOf(',', totalPagesIndex+12)))); } int currentPageIndex = responseString.indexOf("currentPage"); if(currentPageIndex != -1){ lrm.setCurrentPage(Integer.parseInt(responseString.substring(currentPageIndex+13, responseString.indexOf('}', currentPageIndex+13)))); } int _embeddedIndex = responseString.indexOf("_embedded"); if(_embeddedIndex != -1){ lrm._embedded.put("_embedded", responseString.substring(_embeddedIndex+11, responseString.indexOf((']'), _embeddedIndex + 11)+2)); } return lrm; } /** * * @param responseString response * @return Populated object StateModel */ private static StateModel getStateModelFromString(String responseString){ StateModel sm = new StateModel(); int DisabledIndex = responseString.indexOf("\"disabled\""); if(DisabledIndex != -1) Boolean.parseBoolean(responseString.substring(DisabledIndex + 11, responseString.indexOf('"', DisabledIndex + 11))); int O_KeyIndex = responseString.indexOf("\"o_Key\""); if(O_KeyIndex != -1) sm.setO_Key(Long.parseLong(responseString.substring(O_KeyIndex+8, responseString.indexOf(',', O_KeyIndex+8)))); int O_SecurityIdIndex = responseString.indexOf("\"o_SecurityId\""); if(O_SecurityIdIndex != -1){ sm.setO_SecurityId(Long.parseLong(responseString.substring(O_SecurityIdIndex+15, responseString.indexOf('}', O_SecurityIdIndex+15)))); } int codeIndex = responseString.indexOf("\"code\""); if(codeIndex != -1) sm.setCode(responseString.substring(codeIndex+8, responseString.indexOf('\"', codeIndex+8))); int descriptionCode = responseString.indexOf("\"description\""); if(descriptionCode != -1){ sm.setDescription(responseString.substring(descriptionCode+15, responseString.indexOf('\"', descriptionCode+15))); } int o_CodeIndex = responseString.indexOf("\"o_Code\""); if(o_CodeIndex != -1){ sm.setO_Code(responseString.substring(o_CodeIndex+10, responseString.indexOf('\"', o_CodeIndex + 10))); } int o_DescriptionIndex = responseString.indexOf("\"o_Description\""); if(o_DescriptionIndex != -1){ sm.setO_Description(responseString.substring(o_DescriptionIndex + 17, responseString.indexOf(("\""), o_DescriptionIndex + 17))); } return sm; } private static class StateModel extends ApiModelBase { private boolean disabled; private long o_Key; private long o_SecurityId; private String code; private String description; private String o_Code; private String o_Description; public StateModel(){ this.code = ""; this.description = ""; this.disabled = false; this.o_Code = ""; this.o_Description = ""; this.o_Key = 0; this.o_SecurityId = 0; } public StateModel(String code, String description, boolean disabled, String o_Code, String o_Description, long o_Key, long o_SecurityId){ this.code = code; this.description = description; this.disabled = disabled; this.o_Code = o_Code; this.o_Description = o_Description; this.o_Key = o_Key; this.o_SecurityId = o_SecurityId; } public void setCode(String code){ this.code = code; } public String getCode(){ return this.code; } public void setDescription(String description){ this.description = description; } public String getDescription(){ return this.description; } public void setDisabled(boolean disabled){ this.disabled = disabled; } public boolean getDisabled(){ return this.disabled; } public void setO_Code(String o_Code){ this.o_Code = o_Code; } public String getO_Code(){ return this.o_Code; } public void setO_Description(String o_Description){ this.o_Description = o_Description; } public String getO_Description(){ return this.o_Description; } public void setO_Key(long o_Key){ this.o_Key = o_Key; } public long getO_Key(){ return this.o_Key; } public void setO_SecurityId(long o_SecurityId){ this.o_SecurityId = o_SecurityId; } public long getO_SecurityId(){ return this.o_SecurityId; } } private static class ApiModelBase { public ApiModelBase(){} public Map _links = new HashMap(); public Map _embedded = new HashMap<>(); } private static class Hal_Link { private String href; public String getHref(){ return href; } public void setHref(String href){ this.href = href; } } public static class ListResourcesModel extends ApiModelBase { private int _totalItems; private int _pageSize; private int _totalPages; private int _currentPage; public int getTotalItems(){ return this._totalItems; } public void setTotalItems(int totalItems){ this._totalItems = totalItems; CalculateTotalPages(); } public int getPageSize(){ return this._pageSize; } public void setPageSize(int pageSize){ this._pageSize = pageSize; CalculateTotalPages(); } public int getTotalPages(){ return this._totalPages; } public void setTotalPages(int totalPages){ this._totalPages = totalPages; } public int getCurrentPage(){ return this._currentPage; } public void setCurrentPage(int currentPage){ this._currentPage = currentPage; } private void CalculateTotalPages(){ if(_pageSize > 0 && _totalItems > 0) _totalPages = (int)Math.ceil((float)_totalPages / _pageSize); else _totalPages = 0; } } // java connection needs secure certificate to access URLs. // this will create a trust manager that does not validate certificate chains // use it then server does not have secure certificate public static final class TrustCertificate { private static void createCertificate(){ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException e) {} } } private static void parseValidationFailed(HttpURLConnection conValidate){ try { BufferedReader br = new BufferedReader(new InputStreamReader(conValidate.getErrorStream())); StringBuffer responseStr = new StringBuffer(); responseStr.append(br.readLine()); // reading response line by line until the end of the file int indexOfField = responseStr.indexOf("field"); String field = responseStr.substring(indexOfField + 8, responseStr.indexOf(",") - 1); int indexOfMessage = responseStr.indexOf("message"); String message = responseStr.substring(indexOfMessage + 10, responseStr.indexOf(",", indexOfMessage) - 1); int indexOfValue = responseStr.indexOf("value"); String value = responseStr.substring(indexOfValue + 8, responseStr.indexOf(",", indexOfValue) - 1); int indexOfOptionDetail = responseStr.indexOf("optionDetail"); String optionDetail = responseStr.substring(indexOfOptionDetail + 14, responseStr.indexOf("}", indexOfOptionDetail)); System.out.println(ANSI_ERROR + "Request failed with code: " + conValidate.getResponseMessage()); System.out.println("field: " + field); System.out.println("message: " + message); System.out.println("value: " + value); System.out.println("optionDetail: " + optionDetail + ANSI_RESET); }catch (Exception e){ System.out.println("Failed reading fields on validationFailed"); } } }