Read / Parse JSON File PeopleCode Example

Let us examine how to read / parse JSON Data in PeopleCode with an example in this post. We will be using JSON.simple JAR files for this tutorial. JSON.simple is an open source library, compatible with your PeopleSoft JRE. The input JSON data will be available in a file named input.json.


1. Read / Parse JSON PeopleCode Example


We begin with a simple setup to start with.The test JSON file that will be used (across this tutorial )is provided below:

{"Planet":"Earth","ArrayData":["Item1","Item2"],"Place":"California","Counter":100,"Name":"test","ObjectArray":[{"S2":"1","S1":"1"}],"isChecked":true}

We will read 'Planet' and 'Place' information from this JSON data in PeopleCode. The example is shown below:

/* PeopleCode Program - Read / Parse JSON */

/*Use JSONParser and Parse input JSON File in PeopleCode */
Local JavaObject &parseJson = CreateJavaObject("org.json.simple.parser.JSONParser");
Local JavaObject &parseOutput = &parseJson.parseReader(CreateJavaObject("java.io.FileReader", "input.json"));

/* Read and Retrieve JSON Data */
/* Print JSON output through MessageBox */
MessageBox(0, "", 0, 0, "Place" | &parseOutput.get("Place").toString());
MessageBox(0, "", 0, 0, "Planet" | &parseOutput.get("Planet").toString());

Note that we are using a method parseReader, which returns an object of type org.json.simple.JSONObject. I have customized JSON.simple instead of using reflection techniques to get around "more than one overload matches" error. The Java Code I added to org.json.simple.parser.JSONParser is provided below. A modified version of JAR file is available for download at the end of this post.

/* New Method to Prevent Ugly Reflection Techniques in PeopleCode */
public JSONObject parseReader(Reader in) throws IOException, ParseException{
        return (JSONObject) parse(in, (ContainerFactory)null);
}

2.Parse Boolean JSON Data Type - PeopleCode Example


If you want to read Boolean data and assign it to a boolean variable, you have to do simple modifications to the PeopleCode provided earlier. This is shown below: [ You can read other data types like integer on the same approach ]
/* Read Boolean Data from JSON file to PeopleCode variable */
Local boolean &blJson = &parseOutput.get("isChecked").toString();
MessageBox(0, "", 0, 0, "Boolean Data" | &blJson);

3. Reading JSON Array in PeopleCode


We will discuss how to parse JSON Array using PeopleCode. In the input JSON File, we have a JSON Array with two elements and we will print them from PeopleCode. Again, to avoid reflection issues, we will add a new method in& org.json.simple.JSONObject, that will take the ID Element and return an object of type org.json.simple.JSONArray back. This is shown below:

/* Customization for PeopleSoft - to Return JSONArray from String */
public JSONArray getJSONArray(String aData){
        return (JSONArray) this.get(aData);
}

You can now retrieve a JSON Array, parse it and print the contents and size of the array from PeopleCode with ease. A PeopleCode snippet that does this is shown below:

/* Read JSON Array */
Local JavaObject &jsonArray = &parseOutput.getJSONArray("ArrayData");
/* Print JSON Array as String */
MessageBox(0, "", 0, 0, "JSON Array as String" | &jsonArray.toString());
/* Get Number of Elements in Array  */
MessageBox(0, "", 0, 0, "JSON Array Length" | &jsonArray.size());
/* Print individual elements in Array */
MessageBox(0, "", 0, 0, "JSON Element 1 " | &jsonArray.get(0).toString());
MessageBox(0, "", 0, 0, "JSON Element 2 " | &jsonArray.get(1).toString());

If your JSON array has mixed datatypes (boolean, integer) you can read them using same approach.


4. Parse Array of JSON Objects


Extending above example, you can also parse and read an array of JSON objects with PeopleCode. Each element in the JSONArray is an object of type JSONObject. Using the same input file, you can print the "ObjectArray" as shown below:

/* Parse Array of JSON Objects */
Local JavaObject &arrayOfJson = &parseOutput.getJSONArray("ObjectArray");
/* Get Number of JSON Objects in the Array */
MessageBox(0, "", 0, 0, "Total JSON Objects " | &arrayOfJson.size());
/* Get JSON Object of First Element */
/* Put this into a FOR LOOP to read every JSON Object line by line in the Array */
Local JavaObject &arrayObject = &arrayOfJson.getJSONObject(&arrayOfJson.get(0));
MessageBox(0, "", 0, 0, "Value of S2 " | &arrayObject.get("S2").toString());
MessageBox(0, "", 0, 0, "Value of S1 " | &arrayObject.get("S1").toString());

To get this working, add a new method in org.json.simple.JSONArray as shown below (to cast an object):
/* Get Object and Return JSONObject*/
public JSONObject getJSONObject(Object o){
                return (JSONObject)o;
}

The whole tutorial requires a bit of customization to JSON.simple, but it is worth as reading JSON from PeopleCode is greatly simplified through this approach. Finally, here are some of the artefacts that you can download for this tutorial:


Create / Write JSON File PeopleCode Example

Let us see how to write data from PeopleSoft application as a JSON File in this tutorial. This piece of code can fit into Application Engine program or even in your record peoplecode and is so simple.We will use an open source Java library JSON.simple for this purpose.You don't need to be a Java expert, as you will appreciate the easiness with which you can generate JSON data at the end of this post.

1.Write JSON From PeopleCode - Basic Example


We begin with creating a Java Object of type org.json.simple.JSONObject in PeopleCode. You can then use the put method to add JSON data. Once this is done, you can use java.io.FileWriter and write the contents in your JSONObject to file. This is the very basic approach to create JSON file and the full PeopleCode for this is shown below:

/* PeopleCode Program - Create and Write JSON File */

/* Create a JSON Object to Add Data */
Local JavaObject &myJson = CreateJavaObject("org.json.simple.JSONObject");

/* Now add some content */
&myJson.put("Name", "test");
&myJson.put("Place", "California");
&myJson.put("Planet", "Earth");

/* Create JSON Output File */
Local JavaObject &ioWriter = CreateJavaObject("java.io.FileWriter", "myJson.json");


/* Write JSON Data to File */
&ioWriter.write(&myJson.toJSONString());

/* Close File */
&ioWriter.flush();
&ioWriter.close();


The output of this program is provided below:
{"Planet":"Earth","Place":"California","Name":"test"}

This library also offers lot of additional methods using which you can write different JSON data from PeopleCode. These are shown below.

2.Write Number Data to JSON File from PeopleCode


You can easily add a line of code to the example above that can add Number data to JSON File from PeopleCode. This is shown below:
/* Add Integer Data to JSON File */
&myJson.put("Counter", CreateJavaObject("java.lang.Integer", 100));

The output JSON File data is provided below:
{"Planet":"Earth","Place":"California","Counter":100,"Name":"test"}

3. Add JSON Boolean Data from PeopleCode


On the same lines, you can easily add boolean data from PeopleCode to JSON File. A sample PeopleCode that does this is provided below:
/* Insert Boolean Data to JSON File */
&myJson.put("isChecked", CreateJavaObject("java.lang.Boolean", "true"));

The output of this code inserts boolean data to JSON File as per below:
{"Planet":"Earth","Place":"California","Counter":100,"Name":"test","isChecked":true}

4. Write JSON Array From PeopleCode


Finally, you can also add an array of JSON data using org.json.simple.JSONArray class. For the example we provided above, we can extend and add JSON array as per below:
/* Create JSON Array Object*/
Local JavaObject &myJsonArray = CreateJavaObject("org.json.simple.JSONArray");
&myJsonArray.add("Item1");
&myJsonArray.add("Item2");
/* Add Array back to Original JSON Object */
&myJson.put("ArrayData", &myJsonArray);

The output is shown below:
{"Planet":"Earth","ArrayData":["Item1","Item2"],"Place":"California","Counter":100,"Name":"test","isChecked":true}

5. Write Array of JSON Objects in PeopleCode


Finally, a JSON array can contain JSON objects and you can keep repeating the example above to add as many JSON data as required. This is shown below with an example output;
/* Add Array of JSON Objects*/
Local JavaObject &arrayObect = CreateJavaObject("org.json.simple.JSONObject");
&arrayObect.put("S1", "1");
&arrayObect.put("S2", "1");
Local JavaObject &jSonArray = CreateJavaObject("org.json.simple.JSONArray");
&jSonArray.add(&arrayObect);
/* Add object array back to original JSON */
&myJson.put("ObjectArray", &jSonArray);

/* produces an output of */
{"Planet":"Earth","ArrayData":["Item1","Item2"],"Place":"California","Counter":100,"Name":"test","ObjectArray":[{"S2":"1","S1":"1"}],"isChecked":true}

Hope this tutorial simplifies your requirement to create JSON data from PeopleSoft applications. If you have a question, you can post it in the comments section below. See you in a different tutorial next time. You can download the code used in this example here.

Download the JSON.simple JAR File and upload it to your class folder in PeopleSoft without fail. 

Read / Write CSV File PeopleCode Example

If you want to read / write comma separated file (CSV) using PeopleCode (Either in Page or Application Engine program), then this example is for you.

PeopleSoft does offer File layouts to parse CSV files in native format, but I would like to introduce you to an open source library, OpenCSV which can simplify the work for you. What's more, it is open source and you can use it on the fly with less Java knowledge.The tutorial assumes you have basic knowledge on PeopleCode. Let us get started.


1. Writing CSV File in PeopleCode


Let us assume you want to write the output of SQL query to CSV file for this example. We use CSVWriter class defined in au.com.bytecode.opencsv.CSVWriter for this purpose. Using the writeNext method on this class, you can write CSV data line by line from SQL cursor. This method takes a Java string array as input, so you have to pass an array to this suitably. The complete PeopleCode example to create CSV file is shown below:

/* Create CSV File in PeopleSoft - OpenCSV Example */

/*  Create java.io.Writer with CSV File Details */
Local JavaObject &ioWriter = CreateJavaObject("java.io.FileWriter", "PeopleSoft_CSV_File.CSV");

/* Create a CSV Writer Object Now */
Local JavaObject &CSVWriter = CreateJavaObject("au.com.bytecode.opencsv.CSVWriter", &ioWriter);

/* Write SQL Query for CSV Output */
Local SQL &dumpSQL = CreateSQL("SELECT OPRID||','||VERSION FROM SYSADM.PSOPRDEFN");

/* Fetch Data */
Local string &csvLine;

/* We create a Java Array that we can pass to CSV Writer */
Local JavaObject &Jarray = CreateJavaArray("java.lang.String[]", 1);

While &dumpSQL.Fetch(&csvLine)
   
   /* Push the input to Peoplecode Array */
   Local array of any &classListArray = CreateArrayAny();
   &classListArray.Push(&csvLine);
   /* Copy input to Java Array */
   CopyToJavaArray(&classListArray, &Jarray);
   /* Write Java Array to CSV File */
   &CSVWriter.writeNext(&Jarray);
   
End-While;
/* Close SQL Cursor */
&dumpSQL.Close();
/* Close CSV Writer */
&CSVWriter.close();

You can change the separator, SQL query, target CSV file location suitably by changing them in the program. This would be handy for AE programs.

2.Reading CSV File in PeopleCode


Reading and parsing a CSV file in PeopleCode program is a real piece of cake. No complex File Layout required. You start with a CSVReader object and pass the file name you want to parse into it. From here, you can read each line to a Java Array in PeopleCode, from there you can convert it into PeopleCode array and print on the screen or Application engine program. An example code that does this is shown below:
/* Read / Parse CSV File PeopleCode Example */

/* Read Input File through FileReader Object */
Local JavaObject &ioReader = CreateJavaObject("java.io.FileReader", "PeopleSoft_CSV_File.CSV");

/* Create a CSV Reader Object Now */
Local JavaObject &CSVReader = CreateJavaObject("au.com.bytecode.opencsv.CSVReader", &ioReader);

/* Create Java String Array that can read CSV Data */
Local JavaObject &Jarray;


/* Read File line by line now */
While True
   
   &Jarray = &CSVReader.readNext();
   
   /* You have the line in a Java Array now */
   
   /* You can now use CopyFromJavaArray and take it to PeopleCode Array */
   
   
End-While;
&CSVReader.close();

As an activity for you, I have left the last two parts blank - you just have to apply the reverse of write method that we saw above to get the file data into PeopleCode. Give a try and post us a comment if you are stuck.

Setup:
Just download openCSV and copy the JAR file to your classpath.

Read / Write Metadata - Excel POI Example

We have seen so much on working with actual data in POI so far. In this post, I would like to touch a bit on the metadata. A document is never complete without adding suitable metadata and Apache POI offers a plethora of options to set metadata against a document. We will discuss how to read and write metadata into Excel workbooks using Apache POI in Java with simple working examples in this post. We will focus on XLSX document types. For Office 97 – 2003 formats, we will provide another post that would explain how metadata can be extracted / written.

Metadata in Excel spreadsheets can be classified into three major categories;

Core Properties:  These are defined in org.apache.poi.POIXMLProperties.CoreProperties and include the following properties that you can read / set against:

  • Category – Category of the document
  • Content Status – Status of the content
  • Content Type – Type of Content
  • Document Created TimeStamp
  • Description of the Document
  • Identifiers
  • Keywords in the document
  • Last printed date
  • Modified Date
  • Revision
  • Subject of the document
  • Title of the document

Extended Properties: Extended properties are applicable across all Office files and defined in org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties class. Some of the properties that you can set through this class in Apache POI is provided below:

  • Company
  • Manager
  • Hyperlink Base
Custom Properties: On top of core and extended properties, you can also add custom properties as name value pairs. You can add your own or choose from a list that is already provided as a part of Office. 

These include the following – Checked By, Client, Date Completed, Department, Destination, Disposition, Division, Document Number, Editor, Forward to, Group, Language, Mailstop, Matter, Office, Owner, Project, Publisher, Purpose, Received From, Recorded By, Reference, Source, Status, Telephone Number and Typist. You can set a type against such custom properties which can be Text, Date, Number or Yes /No. Finally you can also provide a value for such properties.

With this bit of theory, let us now write a simple Java program that will help us to set all these properties against an Excel Spreadsheet.

Excel File: Write Metadata Using Apache POI – Java Example Program


 import java.io.FileOutputStream;
 import java.io.IOException;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.poi.xssf.usermodel.*;
 import org.apache.poi.POIXMLProperties;
 import org.apache.poi.POIXMLProperties.*;
 import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties;
 public class setMetadata
 {
   public static void main(String[] args)
     throws IOException
   {
     /* Start with a workbook object to write comments into */
     XSSFWorkbook xlsxSetMetadata = new XSSFWorkbook();
     xlsxSetMetadata.createSheet("Write Metadata");
     POIXMLProperties props = xlsxSetMetadata.getProperties();
     
     /* Let us set some core properties now*/
     POIXMLProperties.CoreProperties coreProp=props.getCoreProperties();
     coreProp.setCreator("Thinktibits"); //set document creator
     coreProp.setDescription("set Metadata using Apache POI / Java"); //set Description
     coreProp.setKeywords("Apache POI, Metadata, Java, Example Program, XLSX "); //set keywords
     coreProp.setTitle("XLSX Metadata Example Apache POI "); //Title of the document
     coreProp.setSubjectProperty("Code"); //Subject
     coreProp.setCategory("Programming"); //category
     
     /* We can now set some extended properties */
     POIXMLProperties.ExtendedProperties extProp=props.getExtendedProperties();
     extProp.getUnderlyingProperties().setCompany("Apache Software Foundation");
     extProp.getUnderlyingProperties().setTemplate("XSSF");
     extProp.getUnderlyingProperties().setManager("Manager Name");
     
     /* Finally, we can set some custom Properies */
     POIXMLProperties.CustomProperties custProp = props.getCustomProperties();
     custProp.addProperty("Author", "Thinktibits");// String
     custProp.addProperty("Year", 2014);     // Number Property
     custProp.addProperty("Published", true); //Yes No Property
     custProp.addProperty("Typist", "tika");
     
     /* Write all these metadata into workbook and Close Document */
     
     String fname = "Metadata.xlsx";
     FileOutputStream out = new FileOutputStream(fname);
     xlsxSetMetadata.write(out);
     out.close();
   }
 }

The output of this program is shown below (2 screens : One for Core/ Extended Metadata, Another for Custom Metadata)

Apache POI - Add Custom Metadata in Excel - Example Output
Apache POI - Add Custom Metadata in Excel - Example Output

Java: Add Core / Extended Metadata to Excel Using POI - Output
Java: Add Core / Extended Metadata to Excel Using POI - Output
Like how you can write metadata information into Excel Files, Apache POI also provides rich set of methods to read them and use them for various purposes – there are different getter methods available to read different types of properties. As an example, let us read the same document that we created in the step earlier, and print the metadata information out in the console. Here is a program that does that with the output;

Excel File: Read Metadata with Apache POI – Example Code


 import java.io.FileInputStream;
 import java.io.*;
 import java.util.List;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.poi.xssf.usermodel.*;
 import org.apache.poi.POIXMLProperties;
 import org.apache.poi.POIXMLProperties.*;
 import org.openxmlformats.schemas.officeDocument.x2006.customProperties.*;
 public class getMetadata
 {
   public static void main(String[] args)
     throws IOException
   {
     FileInputStream input_document = new FileInputStream(new File("Metadata.xlsx")); //Read XLSX document - Office 2007, 2010 format     
     XSSFWorkbook readMetadata = new XSSFWorkbook(input_document); //Read the Excel Workbook in a instance object    

     POIXMLProperties props = readMetadata.getProperties();
     
     
     POIXMLProperties.CoreProperties coreProp=props.getCoreProperties();
     /* Read and print core properties as SOP */
     System.out.println("Document Creator :" + coreProp.getCreator()); 
     System.out.println("Description :" + coreProp.getDescription());
     System.out.println("Keywords :" + coreProp.getKeywords());
     System.out.println("Title :" + coreProp.getTitle());
     System.out.println("Subject :" + coreProp.getSubject());
     System.out.println("Category :" + coreProp.getCategory());
     
     
     /* Read and print extended properties */
     POIXMLProperties.ExtendedProperties extProp=props.getExtendedProperties();
     System.out.println("Company :" + extProp.getUnderlyingProperties().getCompany());
     System.out.println("Template :" + extProp.getUnderlyingProperties().getTemplate());
     System.out.println("Manager Name :" + extProp.getUnderlyingProperties().getManager());
     
     
     /* Finally, we can retrieve some custom Properies */
     POIXMLProperties.CustomProperties custProp = props.getCustomProperties();
     List<CTProperty> my1=custProp.getUnderlyingProperties().getPropertyList();
     System.out.println("Size :" + my1.size());
     for (int i = 0; i < my1.size(); i++) {
            CTProperty pItem = my1.get(i);
            System.out.println(""+pItem.getPid());
            System.out.println(""+pItem.getFmtid());
            System.out.println(""+pItem.getName());
            System.out.println(""+pItem.getLpwstr());
            
     }
 
   }
 }

This programs prints the metadata information and the output is shown below:

Document Creator :Thinktibits
Description :set Metadata using Apache POI / Java
Keywords :Apache POI, Metadata, Java, Example Program, XLSX
Title :XLSX Metadata Example Apache POI
Subject :Code
Category :Programming
Company :Apache Software Foundation
Template :XSSF
Manager Name :Manager Name
Size :4
2
{D5CDD505-2E9C-101B-9397-08002B2CF9AE}
Author
Thinktibits
3
{D5CDD505-2E9C-101B-9397-08002B2CF9AE}
Year
null
4
{D5CDD505-2E9C-101B-9397-08002B2CF9AE}
Published
null
5
{D5CDD505-2E9C-101B-9397-08002B2CF9AE}
Typist
tika

If you notice the custom properties section output, you are able to get the output for properties that are of type “string”. You need to use different methods to get if you use a Yes/No or number type of custom property. I would like leave this for you to give a try – post a comment here if you are stuck. The examples presented in this post are tested with POIv3.8. You can modify the code provided above to update metadata on existing Excel documents, if you have such a requirement.