Search in sources :

Example 1 with AutomationException

use of exceptions.AutomationException in project cvs-auto-svc by dvsa.

the class TestResultsClient method postTestResultsFieldChange.

public Response postTestResultsFieldChange(TestResults testResults, String propertyField, String value, ToTypeConvertor toType, TestResultsLevel testResultsLevel) {
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode node = objectMapper.valueToTree(testResults);
    JsonNode nodeToUpdate;
    for (Field field : TestResultsGet.class.getDeclaredFields()) {
        node.remove(field.getName());
    }
    for (Field field : TestTypesGet.class.getDeclaredFields()) {
        nodeToUpdate = node.get("testTypes").get(0);
        ((ObjectNode) nodeToUpdate).remove(field.getName());
    }
    switch(testResultsLevel) {
        case MAIN_LEVEL:
            nodeToUpdate = node;
            break;
        case VEHICLE_CLASS:
            nodeToUpdate = node.get("vehicleClass");
            break;
        case TEST_TYPES:
            nodeToUpdate = node.get("testTypes").get(0);
            break;
        case DEFECTS:
            nodeToUpdate = node.get("testTypes").get(0).get("defects").get(0);
            break;
        case ADDITIONAL_INFORMATION:
            nodeToUpdate = node.get("testTypes").get(0).get("defects").get(0).get("additionalInformation");
            break;
        case LOCATION:
            nodeToUpdate = node.get("testTypes").get(0).get("defects").get(0).get("additionalInformation").get("location");
            break;
        case ITEM:
            nodeToUpdate = node.get("testTypes").get(0).get("defects").get(0).get("item");
            break;
        case DEFICIENCY:
            nodeToUpdate = node.get("testTypes").get(0).get("defects").get(0).get("item").get("deficiency");
            break;
        default:
            throw new AutomationException("Level not recognized");
    }
    switch(toType) {
        case INTEGER:
            ((ObjectNode) nodeToUpdate).put(propertyField, Integer.valueOf(value));
            break;
        case STRING:
            ((ObjectNode) nodeToUpdate).put(propertyField, value);
            break;
        case INTEGER_ARRAY:
            ((ObjectNode) nodeToUpdate).putArray(propertyField).add(Integer.valueOf(value));
            break;
        case NULL:
            ((ObjectNode) nodeToUpdate).putNull(propertyField);
            break;
        case NULL_ARRAY:
            ((ObjectNode) nodeToUpdate).putArray(propertyField).addNull();
            break;
        case EMPTY_ARRAY:
            ((ObjectNode) nodeToUpdate).putArray(propertyField);
            break;
        case MISSING:
            ((ObjectNode) nodeToUpdate).remove(propertyField);
            break;
        default:
            throw new AutomationException("Convert type not supported");
    }
    Response response = callPostTestResults(node);
    if (response.getStatusCode() == 401 || response.getStatusCode() == 403) {
        saveUtils();
        response = callPostTestResults(node);
    }
    return response;
}
Also used : Response(io.restassured.response.Response) Field(java.lang.reflect.Field) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) AutomationException(exceptions.AutomationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with AutomationException

use of exceptions.AutomationException in project cvs-auto-svc by dvsa.

the class GenericData method getRestrictions.

public static JSONObject getRestrictions(String testCode) {
    String testTypeProperties;
    if (testCode.lastIndexOf("_") != -1) {
        testTypeProperties = GenericData.readJsonValueFromFile("test-type.json", "$..[?(@.defaultTestCode == '" + testCode.split("_")[0] + "' && @.forVehicleType == '" + testCode.split("_")[1] + "')]");
    } else {
        if (testCode.contentEquals("lcp")) {
            testTypeProperties = GenericData.readJsonValueFromFile("test-type.json", "$..[?(@.linkedTestCode == '" + testCode + "')]");
        } else {
            testTypeProperties = GenericData.readJsonValueFromFile("test-type.json", "$..[?(@.defaultTestCode == '" + testCode + "')]");
        }
    }
    String restrictions = GenericData.getJsonObjectInPath(testTypeProperties, "$[0]");
    JSONObject jsonObject;
    try {
        jsonObject = new JSONObject(restrictions);
    } catch (JSONException err) {
        throw new AutomationException("'" + restrictions + "' is not a valid JSON string");
    }
    Iterator keys = jsonObject.keys();
    JSONObject actualRestrictions = new JSONObject();
    while (keys.hasNext()) {
        String key = keys.next().toString();
        if (!(key.contentEquals("defaultTestCode")) && !(key.contentEquals("linkedTestCode"))) {
            try {
                if (!jsonObject.get(key).toString().contentEquals("null")) {
                    switch(key) {
                        case "forVehicleType":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("vehicleType", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("vehicleType", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleSize":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("vehicleSize", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("vehicleSize", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleConfiguration":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("vehicleConfiguration", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("vehicleConfiguration", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleAxles":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.Integer"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("noOfAxles", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("noOfAxles", jsonObject.get(key));
                            }
                            break;
                        case "forEuVehicleCategory":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("euVehicleCategory", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("euVehicleCategory", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleClass":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("vehicleClass", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("vehicleClass", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleSubclass":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.String"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                actualRestrictions.put("vehicleSubclass", array);
                            } else {
                                actualRestrictions.put("vehicleSubclass", jsonObject.get(key));
                            }
                            break;
                        case "forVehicleWheels":
                            if (!(jsonObject.get(key).getClass().getName().contentEquals("java.lang.Integer"))) {
                                JSONArray array = (JSONArray) jsonObject.get(key);
                                Random r = new Random();
                                int randomNumber = r.nextInt(array.length());
                                actualRestrictions.put("numberOfWheelsDriven", array.get(randomNumber));
                            } else {
                                actualRestrictions.put("numberOfWheelsDriven", jsonObject.get(key));
                            }
                            break;
                    }
                } else {
                    if ((key.contentEquals("forVehicleConfiguration")) && (jsonObject.get("forVehicleType").getClass().getName().contentEquals("java.lang.String")) && (jsonObject.get("forVehicleType").toString().contentEquals("psv"))) {
                        String[] configurations = { "rigid", "articulated" };
                        Random r = new Random();
                        int randomNumber = r.nextInt(configurations.length);
                        actualRestrictions.put("vehicleConfiguration", configurations[randomNumber]);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return actualRestrictions;
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AutomationException(exceptions.AutomationException)

Example 3 with AutomationException

use of exceptions.AutomationException in project cvs-auto-svc by dvsa.

the class VehicleTechnicalRecordsClient method createTechRecord.

public Map<String, Object> createTechRecord(JSONObject restrictions) {
    List<JsonPathAlteration> techRecordAlterations = new ArrayList<>();
    String vehicleType = "";
    try {
        int length = restrictions.length();
        if (length != 0) {
            Iterator iterator = restrictions.keys();
            Object[] names = new Object[length];
            int i = 0;
            while (iterator.hasNext()) {
                names[i] = iterator.next();
                if (names[i].toString().contentEquals("vehicleType")) {
                    vehicleType = restrictions.get(names[i].toString()).toString();
                }
                if (names[i].toString().contentEquals("vehicleClass")) {
                    String vehicleClassFields = "";
                    for (VehicleClass vehicleClass : VehicleClass.values()) {
                        if (vehicleClass.getCode().contentEquals(restrictions.get(names[i].toString()).toString())) {
                            vehicleClassFields = "{\"description\":\"" + vehicleClass.getDescription(restrictions.get(names[i].toString()).toString()) + "\"}";
                            break;
                        }
                    }
                    // add tech record alteration for each restriction set on the test type to be created
                    JsonPathAlteration additionalTechRecordAlteration = new JsonPathAlteration("$.techRecord[0]." + names[i].toString(), vehicleClassFields, "", "REPLACE");
                    techRecordAlterations.add(additionalTechRecordAlteration);
                } else {
                    // add tech record alteration for each restriction set on the test type to be created
                    JsonPathAlteration additionalTechRecordAlteration = new JsonPathAlteration("$.techRecord[0]." + names[i].toString(), restrictions.get(names[i].toString()), "", "REPLACE");
                    techRecordAlterations.add(additionalTechRecordAlteration);
                }
                i += 1;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String techRecordPayloadFile = "technical-records_" + vehicleType + ".json";
    // CREATE TECH RECORD
    Map<String, Object> testResultAttributes = new HashMap<>();
    // generate random Vin
    String randomVin = GenericData.generateRandomVin();
    // generate random Vrm
    String randomVrm = GenericData.generateRandomVrm();
    if (!(vehicleType.contentEquals("hgv") || vehicleType.contentEquals("psv") || vehicleType.contentEquals("trl") || vehicleType.contentEquals("lgv") || vehicleType.contentEquals("car") || vehicleType.contentEquals("motorcycle"))) {
        throw new AutomationException("Invalid vehicle type");
    }
    // read post request body from file
    String postTechRecordBody = GenericData.readJsonValueFromFile(techRecordPayloadFile, "$");
    // create alteration to change Vin in the request body with the random generated Vin
    JsonPathAlteration alterationVin = new JsonPathAlteration("$.vin", randomVin, "", "REPLACE");
    // create alteration to change primary vrm in the request body with the random generated primary vrm
    JsonPathAlteration alterationVrm = new JsonPathAlteration("$.primaryVrm", randomVrm, "", "REPLACE");
    // additional alterations for tech record
    techRecordAlterations.add(alterationVin);
    techRecordAlterations.add(alterationVrm);
    Response postTechRecordsResponse = postVehicleTechnicalRecordsWithAlterations(postTechRecordBody, techRecordAlterations);
    postTechRecordsResponse.prettyPrint();
    if (postTechRecordsResponse.statusCode() != 201) {
        postTechRecordsResponse.prettyPrint();
        throw new AutomationException("The post tech records request was not successful, status code was " + postTechRecordsResponse.statusCode());
    }
    Response getTechRecordsResponse = getVehicleTechnicalRecords(randomVin);
    getTechRecordsResponse.prettyPrint();
    if (getTechRecordsResponse.statusCode() != 200) {
        postTechRecordsResponse.prettyPrint();
        throw new AutomationException("The get tech records request was not successful, status code was " + getTechRecordsResponse.statusCode());
    }
    String systemNumber = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].systemNumber");
    String trailerId;
    String firstUseDate;
    if (vehicleType.equals("trl")) {
        trailerId = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].trailerId");
        firstUseDate = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].firstUseDate");
    } else {
        trailerId = null;
        firstUseDate = null;
    }
    int noOfAxles = GenericData.extractIntegerValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].noOfAxles");
    String vehicleClassCode = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].vehicleClass.code");
    String vehicleClassDescription = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].vehicleClass.description");
    JSONArray vehicleSubclass;
    if (vehicleType.contentEquals("car") || vehicleType.contentEquals("lgv")) {
        try {
            vehicleSubclass = new JSONArray(GenericData.extractArrayListStringFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].vehicleSubclass").toString());
        } catch (JSONException e) {
            throw new AutomationException(e.getMessage());
        }
    } else {
        vehicleSubclass = null;
    }
    String vehicleConfiguration;
    if (!(vehicleType.contentEquals("car") || vehicleType.contentEquals("motorcycle") || vehicleType.contentEquals("lgv"))) {
        vehicleConfiguration = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].vehicleConfiguration");
    } else {
        vehicleConfiguration = null;
    }
    String vehicleSize;
    if (vehicleType.contentEquals("psv")) {
        vehicleSize = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].vehicleSize");
    } else {
        vehicleSize = null;
    }
    String euVehicleCategory = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].euVehicleCategory");
    String regnDate;
    if (!vehicleType.contentEquals("trl")) {
        regnDate = GenericData.extractStringValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].regnDate");
    } else {
        regnDate = null;
    }
    int numberOfWheelsDriven;
    if (vehicleType.contentEquals("psv") || vehicleType.contentEquals("hgv") || vehicleType.contentEquals("motorcycle")) {
        numberOfWheelsDriven = GenericData.extractIntegerValueFromJsonString(getTechRecordsResponse.prettyPrint(), "$[0].techRecord[0].numberOfWheelsDriven");
    } else {
        numberOfWheelsDriven = -1;
    }
    // add in map all attributes that we need to change in the test results payload so they match the values on the
    // newly created tech record
    testResultAttributes.put("vin", randomVin);
    testResultAttributes.put("vrm", randomVrm);
    testResultAttributes.put("systemNumber", systemNumber);
    if (trailerId != null) {
        testResultAttributes.put("trailerId", trailerId);
    }
    testResultAttributes.put("noOfAxles", noOfAxles);
    testResultAttributes.put("vehicleClass.code", vehicleClassCode);
    testResultAttributes.put("vehicleClass.description", vehicleClassDescription);
    if (vehicleSubclass != null) {
        testResultAttributes.put("vehicleSubclass", vehicleSubclass);
    }
    if (vehicleConfiguration != null) {
        testResultAttributes.put("vehicleConfiguration", vehicleConfiguration);
    }
    if (vehicleSize != null) {
        testResultAttributes.put("vehicleSize", vehicleSize);
    }
    testResultAttributes.put("euVehicleCategory", euVehicleCategory);
    if (firstUseDate != null) {
        testResultAttributes.put("firstUseDate", firstUseDate);
    }
    if (regnDate != null) {
        testResultAttributes.put("regnDate", regnDate);
    }
    if (numberOfWheelsDriven != -1) {
        testResultAttributes.put("numberOfWheelsDriven", numberOfWheelsDriven);
    }
    testResultAttributes.put("vehicleType", vehicleType);
    return testResultAttributes;
}
Also used : JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AutomationException(exceptions.AutomationException) VehicleClass(clients.model.VehicleClass) Response(io.restassured.response.Response) JSONObject(org.json.JSONObject)

Example 4 with AutomationException

use of exceptions.AutomationException in project cvs-auto-svc by dvsa.

the class DataMapper method getNotExistingTestTypeById.

public static TestTypeById getNotExistingTestTypeById(String testTypeClassification, String forVehicleType, String forVehicleSize, String forVehicleConfiguration, String forVehicleAxles) {
    TestTypeById testTypeByIdReturned = null;
    ClassLoader classLoader = new DataMapper().getClass().getClassLoader();
    try {
        ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        TestTypeById[] node = objectMapper.readValue(readFromInputStream(classLoader.getResourceAsStream("loader/" + BaseData.getDataLocation() + "/test-type-by-id.json")), TestTypeById[].class);
        List<TestTypeById> list = Arrays.asList(node);
        testTypeByIdReturned = findNotExistingTestType(list, testTypeClassification, forVehicleType, forVehicleSize, forVehicleConfiguration, forVehicleAxles);
    } catch (IOException e) {
        throw new AutomationException("Error: " + e.getMessage());
    }
    if (testTypeByIdReturned == null) {
        throw new AutomationException("Error finding test type by id. Check file contents: test-type-by-id.json");
    }
    return testTypeByIdReturned;
}
Also used : TestTypeById(model.testtypeid.TestTypeById) AutomationException(exceptions.AutomationException) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with AutomationException

use of exceptions.AutomationException in project cvs-auto-svc by dvsa.

the class AwsUtil method getNextSystemNumberInSequence.

public static String getNextSystemNumberInSequence() {
    Regions clientRegion = Regions.EU_WEST_1;
    AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard().withRegion(clientRegion).build();
    String uuid = String.valueOf(UUID.randomUUID());
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(System.getProperty("AWS_ROLE")).withDurationSeconds(3600).withRoleSessionName(uuid);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken());
    AmazonDynamoDBClient client = new AmazonDynamoDBClient(temporaryCredentials);
    client.setRegion(Region.getRegion(clientRegion));
    DynamoDB dynamoDB = new DynamoDB(client);
    String tableName = "cvs-" + loader.getBranchName() + "-test-number";
    Table table = dynamoDB.getTable(tableName);
    ItemCollection<ScanOutcome> items = // FilterExpression
    table.scan(// FilterExpression
    "attribute_exists(systemNumber)", // ProjectionExpression
    "systemNumber", // ExpressionAttributeNames - not used in this example
    null, // ExpressionAttributeValues - not used in this example
    null);
    System.out.println("Scan of " + tableName + " for items with systemNumber not null");
    Iterator<Item> iterator = items.iterator();
    String lastSystemNumberUsed = null;
    while (iterator.hasNext()) {
        lastSystemNumberUsed = GenericData.getValueFromJsonPath(iterator.next().toJSONPretty(), "$.systemNumber");
    }
    if (lastSystemNumberUsed != null) {
        int nextSystemNumberInSequence = Integer.parseInt(lastSystemNumberUsed) + 1;
        return Integer.toString(nextSystemNumberInSequence);
    } else {
        throw new AutomationException("No value found for last used systemNumber");
    }
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) BasicSessionCredentials(com.amazonaws.auth.BasicSessionCredentials) Regions(com.amazonaws.regions.Regions) AutomationException(exceptions.AutomationException) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) AmazonDynamoDBClient(com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient) AWSSecurityTokenService(com.amazonaws.services.securitytoken.AWSSecurityTokenService)

Aggregations

AutomationException (exceptions.AutomationException)17 Response (io.restassured.response.Response)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 JSONObject (org.json.JSONObject)4 JSONArray (org.json.JSONArray)3 JSONException (org.json.JSONException)3 FluentWait (org.openqa.selenium.support.ui.FluentWait)3 BasicSessionCredentials (com.amazonaws.auth.BasicSessionCredentials)2 Regions (com.amazonaws.regions.Regions)2 AmazonDynamoDBClient (com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient)2 AWSSecurityTokenService (com.amazonaws.services.securitytoken.AWSSecurityTokenService)2 AssumeRoleRequest (com.amazonaws.services.securitytoken.model.AssumeRoleRequest)2 AssumeRoleResult (com.amazonaws.services.securitytoken.model.AssumeRoleResult)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 IOException (java.io.IOException)2 Field (java.lang.reflect.Field)2 TestTypeById (model.testtypeid.TestTypeById)2 WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait)2 TestTypeField (clients.model.TestTypeField)1 TestTypes (clients.model.TestTypes)1