-
Notifications
You must be signed in to change notification settings - Fork 0
io_nats_jparse_examples

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) {
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:
- Calls the
getJson()method to retrieve a JSON string. - Creates a
Fileobject pointing to the JSON file located at "./src/test/resources/json/depts.json". - Converts the file into a
RootNodeusing theJson.toRootNode()method. - Retrieves the "employees" array from the "departments[0]" path in the
RootNodeand assigns it to theengineeringEmployeesvariable. - Retrieves the third object in the
engineeringEmployeesarray and assigns it to thecindyvariable. - Retrieves the value of the "firstName" property from the
cindynode and assigns it to thecindyNamevariable. - Retrieves the value of the "id" property from the
cindynode using a relative path and assigns it to thecindyIdvariable. - Retrieves the value of the "manager" property from the
engineeringEmployeesarray at index 2 and assigns it to themanagervariable. - Prints the
engineeringEmployeesarray in JSON format. - Prints the
cindynode in JSON format. - Checks if the
managernode is a boolean value and prints a message if it is. - Checks if the
cindyNamenode is equal to the string "Cindy" and prints a message if it is. - Checks if the
cindyNamenode is an instance ofCharSequenceand prints a message if it is. - Checks if the
cindyIdnode is an instance ofNumberand prints a message if it is. - Checks if the
engineeringEmployeesobject is an instance ofListand prints a message with its class name if it is. - Checks if the
cindyobject is an instance ofMapand prints a message with its class name if it is. - Uses stream operations to find the first object in
engineeringEmployeeswith "firstName" equal to "Rick" and assigns it to therickoptional object. If found, it prints the found node and callsexploreNode()method with the found node. - Uses the
findObjectNode()method to find the object inengineeringEmployeeswith "firstName" equal to "Rick". - Assigns the found node to the
rick2optional object. If found, it prints the found node and callsexploreNode()method with the found node. - Maps each object in
engineeringEmployeesto anEmployeeobject using the corresponding properties and collects them into a list. - Prints each
Employeeobject in theemployeeslist. - Retrieves the "departments" array from the JSON string and assigns it to the
departmentsNodevariable. - Maps each object in
departmentsNodeto aDepartmentobject using the corresponding properties and collects them into a list. - Prints each
Departmentobject in thedepartmentslist. - Calls the
parseBadJson()method. - Catches any exception that occurs during the execution and prints the stack trace.

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:
-
Commented code: The method body contains multiple lines of commented code. These lines represent different variations of invalid JSON inputs.
-
RootNode object creation: The commented lines instantiate a
RootNodeobject namedrootNode. However, since these lines are commented out, they do not execute. -
toRootNode()method: ThetoRootNode()method is called with an argument,niceJson(), which is used to simulate invalid JSON data. However, since these lines are commented out, thetoRootNode()method is not executed. -
niceJson()method: TheniceJson()method is not defined in the given code snippet. Therefore, it is not involved in the execution of theparseBadJson()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.

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:
-
The method takes an
ObjectNodeas a parameter, which is a JSON object representing an employee's details. -
The method extracts the values from specific fields of the JSON object using various
getmethods such asgetInt,getString, andgetBoolean. The extracted values are assigned to local variables. -
The method prints the extracted values using
System.out.printfmethod call in a formatted string. -
The method then retrieves the same values again but this time using the
getXNodemethods, whereXrepresents the type of each particular value (e.g.,getNumberNode,getStringNode). The retrieved values are assigned to variables of respective types (NumberNode,StringNode, etc.). -
The method prints the retrieved
XNodevalues usingSystem.out.printfmethod call in a formatted string. -
Finally, the method prints the converted values from the
XNodevariables to their primitive types (e.g.,intValue,toString,booleanValue) usingSystem.out.printfmethod call in a formatted string.

The Department class is a final Class that represents a department in an organization. It provides functionality to manage and manipulate department related information.
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) {
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:
-
It defines a
Fileobject with the file path "./src/test/resources/cloudevents/glossaryEvent.json". -
It uses the
Sources.fileSourcemethod to read the contents of the file and converts it to anObjectNodeusing theJson.toRootNodemethod. -
It checks if the value of the "subject" field in the
objectNodeis equal to "glossaryFeed" using theequalsContentmethod. -
If the condition in step 3 is true, it retrieves the values of the "id", "type", and "data" fields from the
objectNode. -
It serializes the value of the "data" field to a JSON string using the
Json.serializeToStringmethod. -
It prints the values of "glossaryFeed", "id", "type", and "data" to the console using the
System.out.printfmethod. 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.

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.
- Java Open AI Client
- Using ChatGpt embeddings and hyde to improve search results
- Anthropics Claude Chatbot Gets Upgrade
- Elon Musks XAi new frontier for artificial intelligence
- Using Mockito to test JAI Java Open AI Client
- Fine tuning journey with Open AI API
- Using Open AI to create callback functions, the basis for plugins
- Using Java Open AI Client Async
- Fastest Java JSON Parser
- Java Open AI API Client on Github
- Medium: Introducing Java Open AI Client
- Medium: Using ChatGPT, Embeddings, and HyDE to Improve Search Results