Skip to content

io_nats_jparse_examples

Rick Hightower edited this page Jul 18, 2023 · 1 revision

io.nats.jparse.examples

class diagram

EmployeeDeptMain

The EmployeeDeptMain class is a public class that serves as the entry point for the employee and department management system. It provides functionality for managing employees and departments within an organization.

public static void main(String... args)

public static void main(String... args) {
    try {
        final String json = getJson();
        //final var engineeringEmployees = Path.atPath("departments[0].employees", json).asCollection().asArray();
        final File file = new File("./src/test/resources/json/depts.json");
        final RootNode rootNode = Json.toRootNode(Sources.fileSource(file));
        final ArrayNode engineeringEmployees = Path.atPath("departments[0].employees", rootNode).asCollection().asArray();
        final Node cindy = Path.atPath("[2]", engineeringEmployees);
        final Node cindyName = Path.atPath("[2].firstName", engineeringEmployees);
        final Node cindyId = Path.atPath(".id", cindy);
        final Node manager = Path.atPath("[2].manager", engineeringEmployees);
        System.out.println("      " + engineeringEmployees.toJsonString());
        System.out.println("      " + cindy.toJsonString());
        if (manager.asScalar().booleanValue()) {
            System.out.printf("This employee %s is a manager %s \n", cindyName, manager);
        }
        if (cindyName.asScalar().equalsString("Cindy")) {
            System.out.printf("The employee's name is  Cindy %s \n", cindyId);
        }
        if (cindyName instanceof CharSequence) {
            System.out.println("cirhyeName is a CharSequence");
        }
        if (cindyId instanceof Number) {
            System.out.println("cindyId is a Number");
        }
        if (engineeringEmployees instanceof List) {
            System.out.println("engineeringEmployees is a List " + engineeringEmployees.getClass().getName());
        }
        if (cindy instanceof Map) {
            System.out.println("cindy is a Map " + cindy.getClass().getName());
        }
        final Optional<ObjectNode> rick = engineeringEmployees.stream().map(node -> node.asCollection().asObject()).filter(objectNode -> objectNode.getString("firstName").equals("Rick")).findFirst();
        rick.ifPresent(node -> {
            System.out.println("Found  " + node);
            exploreNode(node);
        });
        final Optional<ObjectNode> rick2 = engineeringEmployees.findObjectNode(objectNode -> objectNode.getString("firstName").equals("Rick"));
        rick2.ifPresent(node -> {
            System.out.println("Found  " + node);
            exploreNode(node);
        });
        final List<Employee> employees = engineeringEmployees.mapObjectNode(on -> new Employee(on.getString("firstName"), on.getString("lastName"), on.getString("dob"), on.getBoolean("manager"), on.getInt("id"), on.getInt("managerId")));
        employees.forEach(System.out::println);
        final ArrayNode departmentsNode = Path.atPath("departments", json).asCollection().asArray();
        final List<Department> departments = departmentsNode.mapObjectNode(on -> new Department(on.getString("departmentName"), on.getArrayNode("employees").mapObjectNode(en -> new Employee(en.getString("firstName"), en.getString("lastName"), en.getString("dob"), en.getBoolean("manager"), en.getInt("id"), en.getInt("managerId")))));
        departments.forEach(System.out::println);
        parseBadJson();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

The main method in class io.nats.jparse.examples.EmployeeDeptMain performs the following steps:

  1. Calls the getJson() method to retrieve a JSON string.
  2. Creates a File object pointing to the JSON file located at "./src/test/resources/json/depts.json".
  3. Converts the file into a RootNode using the Json.toRootNode() method.
  4. Retrieves the "employees" array from the "departments[0]" path in the RootNode and assigns it to the engineeringEmployees variable.
  5. Retrieves the third object in the engineeringEmployees array and assigns it to the cindy variable.
  6. Retrieves the value of the "firstName" property from the cindy node and assigns it to the cindyName variable.
  7. Retrieves the value of the "id" property from the cindy node using a relative path and assigns it to the cindyId variable.
  8. Retrieves the value of the "manager" property from the engineeringEmployees array at index 2 and assigns it to the manager variable.
  9. Prints the engineeringEmployees array in JSON format.
  10. Prints the cindy node in JSON format.
  11. Checks if the manager node is a boolean value and prints a message if it is.
  12. Checks if the cindyName node is equal to the string "Cindy" and prints a message if it is.
  13. Checks if the cindyName node is an instance of CharSequence and prints a message if it is.
  14. Checks if the cindyId node is an instance of Number and prints a message if it is.
  15. Checks if the engineeringEmployees object is an instance of List and prints a message with its class name if it is.
  16. Checks if the cindy object is an instance of Map and prints a message with its class name if it is.
  17. Uses stream operations to find the first object in engineeringEmployees with "firstName" equal to "Rick" and assigns it to the rick optional object. If found, it prints the found node and calls exploreNode() method with the found node.
  18. Uses the findObjectNode() method to find the object in engineeringEmployees with "firstName" equal to "Rick".
  19. Assigns the found node to the rick2 optional object. If found, it prints the found node and calls exploreNode() method with the found node.
  20. Maps each object in engineeringEmployees to an Employee object using the corresponding properties and collects them into a list.
  21. Prints each Employee object in the employees list.
  22. Retrieves the "departments" array from the JSON string and assigns it to the departmentsNode variable.
  23. Maps each object in departmentsNode to a Department object using the corresponding properties and collects them into a list.
  24. Prints each Department object in the departments list.
  25. Calls the parseBadJson() method.
  26. Catches any exception that occurs during the execution and prints the stack trace.

sequence diagram

private static void parseBadJson()

private static void parseBadJson() {
    //RootNode rootNode = toRootNode(niceJson("'hi mom"));
    //RootNode rootNode = toRootNode(niceJson("['aabc', \n  'def', \n 123f3f.9]"));
    //RootNode rootNode = toRootNode(niceJson("{'name':'rick', \n\n\n" +
    //        " 'age':19, 'height'=10}"));
}

The method parseBadJson() defined in class io.nats.jparse.examples.EmployeeDeptMain is used to parse invalid JSON input.

Here are the steps involved in this method:

  1. Commented code: The method body contains multiple lines of commented code. These lines represent different variations of invalid JSON inputs.

  2. RootNode object creation: The commented lines instantiate a RootNode object named rootNode. However, since these lines are commented out, they do not execute.

  3. toRootNode() method: The toRootNode() method is called with an argument, niceJson(), which is used to simulate invalid JSON data. However, since these lines are commented out, the toRootNode() method is not executed.

  4. niceJson() method: The niceJson() method is not defined in the given code snippet. Therefore, it is not involved in the execution of the parseBadJson() method.

In summary, the parseBadJson() method is designed to illustrate the parsing of invalid JSON inputs. However, since all the relevant code is commented out, this method does not perform any actual JSON parsing in its current state.

sequence diagram

private static void exploreNode(ObjectNode node)

private static void exploreNode(ObjectNode node) {
    int id = node.getInt("id");
    String name = node.getString("firstName");
    String dob = node.getString("dob");
    boolean isManager = node.getBoolean("manager");
    int managerId = node.getInt("managerId");
    System.out.printf("%d %s %s %s %d \n", id, name, dob, isManager, managerId);
    final NumberNode idNode = node.getNumberNode("id");
    final StringNode nameNode = node.getStringNode("firstName");
    final StringNode dobNode = node.getStringNode("dob");
    final BooleanNode isManagerNode = node.getBooleanNode("manager");
    final NumberNode managerIdNode = node.getNumberNode("managerId");
    System.out.printf("%s %s %s %s %s \n", idNode, nameNode, dobNode, isManagerNode, managerIdNode);
    System.out.printf("%d %s %s %s %d \n", idNode.intValue(), nameNode.toString(), dobNode.toString(), isManagerNode.booleanValue(), managerIdNode.intValue());
}

The exploreNode method is defined in the EmployeeDeptMain class in the package io.nats.jparse.examples. Here is a step-by-step description of what the method does:

  1. The method takes an ObjectNode as a parameter, which is a JSON object representing an employee's details.

  2. The method extracts the values from specific fields of the JSON object using various get methods such as getInt, getString, and getBoolean. The extracted values are assigned to local variables.

  3. The method prints the extracted values using System.out.printf method call in a formatted string.

  4. The method then retrieves the same values again but this time using the getXNode methods, where X represents the type of each particular value (e.g., getNumberNode, getStringNode). The retrieved values are assigned to variables of respective types (NumberNode, StringNode, etc.).

  5. The method prints the retrieved XNode values using System.out.printf method call in a formatted string.

  6. Finally, the method prints the converted values from the XNode variables to their primitive types (e.g., intValue, toString, booleanValue) using System.out.printf method call in a formatted string.

sequence diagram

Department

The Department class is a final Class that represents a department in an organization. It provides functionality to manage and manipulate department related information.

CloudEventMain

The CloudEventMain class is a public class that serves as the entry point for processing cloud events. It contains the main method that initializes and runs the cloud event processing logic.

public static void main(String... args)

public static void main(String... args) {
    final File file = new File("./src/test/resources/cloudevents/glossaryEvent.json");
    final ObjectNode objectNode = Json.toRootNode(Sources.fileSource(file)).asObject();
    if (objectNode.getNode("subject").equalsContent("glossaryFeed")) {
        final String id = objectNode.getString("id");
        final String type = objectNode.getString("type");
        final String data = Json.serializeToString(objectNode.getNode("data"));
        System.out.printf("%s %s %s \n%s\n", "glossaryFeed", id, type, data);
    }
}

The main method in the CloudEventMain class is performing the following steps based on its body:

  1. It defines a File object with the file path "./src/test/resources/cloudevents/glossaryEvent.json".

  2. It uses the Sources.fileSource method to read the contents of the file and converts it to an ObjectNode using the Json.toRootNode method.

  3. It checks if the value of the "subject" field in the objectNode is equal to "glossaryFeed" using the equalsContent method.

  4. If the condition in step 3 is true, it retrieves the values of the "id", "type", and "data" fields from the objectNode.

  5. It serializes the value of the "data" field to a JSON string using the Json.serializeToString method.

  6. It prints the values of "glossaryFeed", "id", "type", and "data" to the console using the System.out.printf method. The values are formatted in the following format: "glossaryFeed id type data".

Please note that the actual execution of the code may have additional steps or error handling that is not mentioned in the provided code snippet.

sequence diagram

Employee

The Employee class is a final class that represents an employee. It provides various methods and attributes to manage and retrieve information about an employee.

Clone this wiki locally