Showing posts with label PeopleCode. Show all posts
Showing posts with label PeopleCode. Show all posts

Wednesday, August 05, 2026

SaveEdit, SavePreChange, SavePostChange... Which Event Should I Use?


When a user presses the Save button on a PeopleSoft component, PeopleSoft triggers three PeopleCode events in sequence:

  • SaveEdit
  • SavePreChange
  • SavePostChange

These events allow us to write specialized logic to:

  1. Validate data before saving,
  2. Update other fields within the component, and
  3. Trigger additional business logic, such as synchronizing systems through integration or launching an approval process.

Each scenario uses a different event. Let's review scenario #1: data validation.

  • A page has two fields: start date and end date. We must confirm that the start date precedes the end date.
Which event would you use?
  • SaveEdit
  • SavePreChange
  • SavePostChange

Let's review the behavior of each event to help us determine the best fit. Specifically, we want an event that can stop Save Processing if validation fails. This will keep us from sending invalid content to the database.

  • SaveEdit: Cancelable event.
  • SavePreChange: Cancelable event.
  • SavePostChange: Not cancelable because the data is already in the database.

This leaves two cancelable events: SaveEdit and SavePreChange. But what does PeopleBooks say?

"Important! Never use an Error or Warning statement in any save processing event other than SaveEdit. Perform all component data validation in SaveEdit." (emphasis added.)

Why? Why is it so important that we handle validation in SaveEdit and not SavePreChange?

Let's say we ignore PeopleBooks' advice, and we put data validation in SavePreChange rather than SaveEdit. How many SavePreChange events exist per component? The number is infinite. There is at least one per field associated with the component (Record/Field), as well as at least one per record in the component (Component/Record). We reach infinity when considering Event Mapping, because there is no limit on the number of Application Classes that may be associated with a component's SavePreChange possibilities.

Next, imagine that some of those SavePreChange events assume validation is complete and make changes to the component buffer. But if we put validation logic in one of those SavePreChange events, and that validation fails, what happens to all of those other SavePreChange component buffer updates? Nothing. There is no automatic reset. What if one of those handlers disabled the field that failed validation? How would the user correct the issue? This is why it is so important that we follow PeopleBooks' advice in this case and only validate in SaveEdit.

By the time the component processor reaches SavePreChange, all validation should be complete.

In summary, here is how you should use each Save event:

  • SaveEdit: Cross-field validation. Do not update data or change field properties from this event.
  • SavePreChange: Update data within the component buffer and apply field property changes, but do not perform validation.
  • SavePostChange: Perform any non-component, post-database work: Integrations, Notifications, Workflow, non-component data updates, etc.

At JSMpros, we teach PeopleCode tips daily! Check out our live virtual events calendar and on-demand offerings to enroll in your next course. Interested in learning more about PeopleCode specifically? Then check out these two classes:

Both are available live, live virtual, and on-demand. Contact us, and let's get you scheduled!

Monday, July 13, 2026

PeopleTools 8.62 is Missing a Critical Code Enabler... Now What?


PeopleCode is fantastic, but it has limitations. With GetJavaClass and CreateJavaObject PeopleCode functions, Java is the perfect language to bust through that capability wall. Need a regular expression processor? Java has you covered. Base64 encoding Unicode characters? Java can handle that too.

But there is one challenge: Java supports a feature called "overloading." An overloaded method is defined multiple times, each with a differing parameter type or number. Unfortunately, PeopleCode can't natively map between the various Java types, so it can't determine which overloaded method to invoke. This forces us into a complicated, illegible combination of PeopleCode and Java reflection.

This is where JavaScript enters the story. JavaScript provides a convenient way to bridge PeopleCode and Java. Here is a simple PeopleCode example that uses Java to invoke JavaScript:

Local JavaObject &manager =  CreateJavaObject("javax.script.ScriptEngineManager");
Local JavaObject &engine =  &manager.getEngineByName("JavaScript");

REM ** Evaluate a simple JavaScript;
&engine.eval("var result = Math.random();");

REM ** Access the value of the JavaScript variable named result;
Local string &result_text =  &engine.get("result").toString();

This code ran flawlessly on PeopleTools 8.61, 8.60, 8.59, and many earlier releases. But that is not the case with new releases. Java used to bundle the Nashorn JavaScript Engine, but discontinued this practice in Java 15 (PeopleTools 8.61 bundled Java 11 LTS). So what are some alternatives?

  • Move your code into Java.
  • Leverage Java through PeopleCode and Reflection.
  • Install a JavaScript script engine.

Move Your Code into Java

Chapter 11 of our PeopleSoft PeopleTools Tips and Techniques book shows you how to write and deploy your own custom Java to a PeopleSoft instance to be run on the App Server or Process Scheduler Server (App Engine). Java written for PeopleSoft has full access to the PeopleCode API, including classes and functions through the PeopleCode.jar file. Because your Java application is running on the App Server (or App Engine), it has full access to the database via SQLExec, Rowsets, etc.

Note: Once the Java Runtime Environment (JRE) loads a class into memory, you must restart the JRE to deploy changes. Since development is often an iterative process, this means you will need to restart the JRE each time you deploy updated Java class files to your App or Process Scheduler server. For an App Server, restarting the JRE means restarting the App Server. So while this compiled Java alternative may seem better architecturally, constant App Server restarts during development significantly increase development time (not to mention the annoyance factor).

Leverage Java through PeopleCode and Reflection

Java's overloaded syntax is challenging in PeopleCode, so we must invoke overloaded methods and constructors via the Java Reflection API. While certainly possible, the code is just as challenging to read as it is to write. You may find several examples of Java Reflection in PeopleCode on our blog.

Install a JavaScript Script Engine

What makes this approach appealing is its flexibility in deployment and its simple code. Unlike compiled Java code, JavaScript does not require a server restart. And just like Java code, JavaScript running in the App Server (or Process Scheduler) has full access to the Java API, PeopleCode, and your database.

You may expose any JSR 223 compatible script engine (JavaScript, Groovy, Jython, JRuby, etc.) by including the appropriate jar file in the PeopleSoft CLASSPATH. There are several documented ways to extend the PeopleSoft CLASSPATH, but the most common is to add your jar file locations to the Add to CLASSPATH property in your app and process scheduler configuration files.

Nashorn

Nashorn is the JavaScript engine included with Java 11 LTS (PeopleTools 8.61). If you have scripts and PeopleCode written for earlier versions of PeopleTools (such as 8.61), this may be your fastest path to compatibility.

The standalone Nashorn JavaScript engine requires the ASM library to compile JavaScript dynamically. As of this writing, a working deployment would include:

  • asm-util-9.10.1.jar
  • nashorn-core-15.7.jar


To deploy Nashorn, you would:

  1. Download the latest version of asm-util and nashorn-core,
  2. Place them in a folder available to your app server, and
  3. List them in the Add to CLASSPATH variable of your app server configuration file.

Other JavaScript engines include Rhino and GraalVM/GraalJS, with Oracle recommending GraalVM. If you choose to move forward with GraalVM, be sure to check out org.graalvm.polyglot.Context, which is recommended over the JSR 223 ScriptEngineManager approach.


The other day, we needed to receive a large amount of data from a cloud provider. To avoid crashing the server, we chose stream processing. Unfortunately, this is not an Integration Broker-supported feature, so we chose to use the Jakarta and Apache HttpClient libraries included with PeopleTools. You can read more about this solution in our post Consuming Enormous Datasets with PeopleSoft. To avoid Java Reflection, we chose JavaScript on the app server.

How about you? Have you experienced situations where you hit the PeopleCode capability limit? If so, what strategy did you use to deliver a solution?

At JSMpros, we teach PeopleTools tips like this daily. Visit our live virtual events calendar to schedule your next class.

Our classes are available live, live virtual, and on-demand. Want to learn more? Contact us, and let's get you scheduled.

Monday, June 15, 2026

Parameterized Landing Page Section Templates

Dynamic Sections are a powerful feature of PeopleSoft’s modern Landing Pages that use App Classes to render data-driven results. Many sections, such as My Direct Reports, My Queries, My Expense Reports, and My Advisees, require no parameters, with each having its own App Class. But what if you want to leverage the same business logic across multiple sections? How would you pass parameters to your Dynamic Sections?

For example, imagine you are an Integration Broker administrator responsible for ensuring smooth operations across your PeopleSoft environment. You know how challenging it can be to keep track of integration queues, especially when operations get stuck in New status. Wouldn’t it be helpful to have a dynamic landing page section that automatically lists these problematic operations, complete with links to investigate each one?


Note: A dynamic section such as this one is perfect for an Integration Administrator Dashboard, but may not be a candidate for a consolidated Landing Page.

Here is a screenshot of my section configuration:



But just as important as messages stuck in New status are messages in Error status. It was while creating the "Messages in Error Status" dynamic section that I noticed the similarities. The code for the Messages Stuck in New Status and Messages in Error Status classes is nearly identical. In keeping with best practices, I applied the D.R.Y (Don't Repeat Yourself) principle and refactored that shared logic into a common base class. Here is what my class hierarchy looks like:




The base class declares an abstract property, and each implementation provides a value for that property. This is the beauty of object-oriented programming: shared logic and multiple implementations. But do you know what else we have? Multiple configurations. Each App Class will have its own section configuration. If we create Landing Page Section Templates, then we would have one template for each App Class.

Is there a way to parameterize the App Class or Section template so we can use just one App Class (IBMsgStatusLoader) and have it derive the desired status from a parameter? Yes, in fact, there is! At the bottom of a Section configuration, you will find Section Attributes:


We use Section Attributes to identify stylesheets and style classes. The delivered Landing Page API exposes these two specific attributes as section properties. But what about other Section Attributes? Can you define your own attribute keys? We traced it and discovered that Section Attributes are stored in the PSPTHPAGATTR table. We can access a section's attributes through the SQL:

SELECT PORTAL_ATTR_VAL
  FROM PSPTHPAGATTR
 WHERE PORTAL_NAME = :1
   AND PORTAL_OBJNAME = :2
   AND PORTAL_OBJNAME_PGT = :3
   AND PORTAL_ATTR_NAM = :4

We can extract a section parameter, therefore, using the following PeopleCode:

SQLExec(SQL.TRN_LP_SCTN_ATTR_VAL, &portalName, &tabName, &sectionName, &attributeKey, &attributeValue);

The Portal name, tab name, and section name are available in the Loader constructor through the &oTab and &oSection variables:

&m_portalName = &oTab.PortalName;
&m_tabName = &oTab.TabName;
&m_sectionName = &oSection.SectionName;

You may find a copy of our Parameterized Section Loader base class in our PeopleCode Templates GitHub repository.

What section templates would you like to parameterize? Leave us a comment to let us know!

At JSMpros, we regularly teach best practices for Fluid, PeopleCode, and Landing Page. Check out our online events calendar to see what course we are offering next! Prefer on-demand? Check out our Course Catalog for a variety of PeopleTools courses covering Fluid, Landing Pages, Application Classes, and much more!

Tuesday, February 10, 2026

Is GenerateComponentPortalURL Still Relevant?

Let's say you need to link from one PeopleSoft component to another. How would you generate the link? Perhaps FieldChange PeopleCode on a button or hyperlink? If so, what PeopleCode function would you use? GenerateComponentPortalUrl? PeopleCode includes functions such as GenerateComponentPortalUrl for generating URLs. But are these functions the best approach?

The URL generation functions create a URL to any menu/component combination. Provide these functions with PeopleTools metadata, and they will craft a URL. But here is the problem:

They have no regard for the Portal Registry.

Many Oracle-delivered Fluid solutions use framework components, such as PT_AGSTARTPAGE_NUI (Activity Guides and Navigation Collections) and PT_FLDASHBOARD (Dashboards). These framework components use Query String attributes, such as CONTEXTIDPARAMS. With Framework components, it is not enough to just create a menu/component/market URL with a function like GenerateComponentPortalURL. We must also consider the additional Portal Registry attributes.

Here is an alternative: Use the Portal Registry API. Instead of using GenerateComponentPortalURL, leverage the Portal Registry metadata. Here is a PeopleCode fragment to get you started:

method getCrefAbsoluteContentUrl
   /+ &crefId as String +/
   /+ Returns String +/
   Local ApiObject &PTPortal = %Session.GetPortalRegistry();
   Local ApiObject &CREF;
   
   If &PTPortal.Open(%Portal) Then
      &CREF = &PTPortal.FindCRefByName(&crefId);
      &PTPortal.close();
      Return &CREF.AbsoluteContentURL;
   Else
      Return "";
   End-If;
end-method;

I would place this code in a common, reusable container for future use. Now, what do you think, should we put this code in an Application Class or a Function Library?

Use generation functions, such as GenerateComponentPortalUrl, when you don't have a Content Reference. Otherwise, consider using the Portal Registry.

At JSMpros, we teach PeopleCode tips every week! Check out our live virtual events calendar to schedule your next class. Interested in learning more about PeopleCode specifically? Then check out these two classes:

Both are available live, live virtual, and on-demand. Want to learn more? Contact us, and let's get you scheduled!

Wednesday, January 14, 2026

App Classes Versus Function Libraries

If you were to create a reusable code fragment, would you use an App Class or a Function Library? We asked our LinkedIn audience, and this was the result:

Bar chart showing 9 out of 10 developers prefer Application Classes

Do these results surprise you? Here are some insightful comments from the poll participants:

"Application Classes... For so many reasons:
  1. Application Classes hold state across method calls
  2. You get maintenance savings from classes
  3. Application Packages can bundle related code
  4. Classes give you public, protected, and private methods
  5. Encapsulation and state
  6. Clear Namespaces"
"I have always preferred application classes over function libraries because I find the discoverability of functions to be severely lacking. They can be placed just anywhere in any field in any record. And I can never remember the format for the declare statement."
"Don't forget about the variable declarations and type checking, which can avoid lots of problems at Runtime. That is on top of a clear inventory of available methods at the top of the class."
"Hands down application class..."
"My personal problems with functions:
  1. Keep forgetting library records 
  2. Can’t group code without creating a new library
  3. Can't use them for configuration such as IB Handlers"
"I haven't willingly created a new function library in years.
  • Application classes are much neater
  • Nicer to implement
  • Like the OO[P] reference
  • Not nested in other code"
"A bonus of using Application Classes is being able to test any of your code from a delivered component in the PIA with the Application Class Tester. Navigation: Enterprise Components > Component Configurations > Application Class Tester. One of the best development tools that Peoplesoft delivers!"

Let's do a side-by-side comparison of the differences identified in the comments:

App Classes Function Libraries
All variables must be declared
Stateful
Testability
PeopleCode-specific container
Dynamic execution
Object-oriented concepts such as Inheritance and Composition
May be used by frameworks (IB, etc.)
Stateless

While the App Class column has the most checkmarks, is it the right answer for every situation?

All Variables Must Be Declared

Function libraries allow us to use variables without declaring them. An undeclared variable becomes implicitly declared as a generic data type upon first use. The problem with implicitly defined variables is that they support typos. It is really easy to mistype a variable name, which then becomes a new implicitly defined variable.

Application Classes will not compile and save unless you declare every variable. This avoids implicit typos.

At JSMpros, we teach that all variables should be defined at all times. The compilation output window, therefore, becomes a worklist. If a variable appears in the list, either declare or fix it. At the end of the day, anything in the list is a typo.

State

Application Classes are stateful, whereas Function Libraries are stateless. Both have their place. Application Classes must be instantiated prior to use. There are times when I have a code fragment that doesn't require state. Instantiating an object to perform a stateless operation seems like a waste. If the logic does not require state, then Application Classes may be overkill.

Testability

With Oracle-delivered solutions, such as the Application Class Tester, and community projects, such as PSUnit, it may seem that Application Classes are easier to test. But testability has more to do with coding practices than the container. For example, code you plan to test should avoid context-aware functions and variables. Whether you are testing App Classes or PeopleCode functions, you will write test case PeopleCode, which can be as simple as an App Designer-run App Engine.

PeopleCode-specific Container

Function Libraries are PeopleCode functions attached to events in Record Field PeopleCode. This can be challenging to manage. Having a PeopleCode-specific Container, such as an App Class makes a lot of sense. I do wish Function Libraries were stored in their own container. This doesn't impact their functionality, but it does affect lifecycle management and reuse.

Dynamic Execution

As noted in the comments, function libraries must be declared before they are invoked. We could argue that Application Classes have the same requirement in the form of import statements, but that's not exactly the case. One of the most powerful features of Application Classes is that we can instantiate objects, invoke methods, and set properties at runtime without knowing the implementing class at design time. We do this through the PeopleCode functions CreateObject, ObjectDoMethod, and ObjectSetProperty. These three functions allow for fully dynamic PeopleCode. In short, Application Classes don't need to be declared. It is this characteristic that allows PeopleSoft to build frameworks, such as Approval Workflow Engine, Event Mapping, and Integration Broker.

Object-Oriented Concepts Such as Inheritance and Composition

This is a key component to making Dynamic Execution work. We can create frameworks that code to interfaces and abstract base classes, and then use dynamic functions to instantiate full implementations at runtime.

Overall, object-oriented programming is not considered better or worse; it's just different. Poorly designed inheritance hierarchies can cause more problems than they fix. Perhaps what makes them challenging is that a solution is not static. We might create an amazing hierarchical design for the first build, but over time, that design becomes corrupted through changes. Composition is an Object-oriented concept that attempts to overcome the challenges of Inheritance.

May be used by frameworks (IB, etc.)

This feature brought to you by Dynamic Execution. Because we can code to an interface, we don't need implementation details until runtime. This makes App Classes perfect for AWE, IB, Event Mapping, PSUnit, Landing Pages, and much more!


In conclusion, each strategy has its place. Choose Function Libraries in the following situations:

  • There are times when you must use Function Libraries. Signon PeopleCode is a great example.
  • I also choose Function Libraries for stateless routines. If your reusable code fragment is stateless, then the overhead of App Classes may be overkill.

Choose App Classes:

  • If you are building a framework, such as AWE, and want to register future event handlers, Application Classes are the right tool. You, the framework builder, would code to an interface, and later implementations provide the runtime details.


Which do you prefer? Let us know in the comments.

We teach both topics in our on-demand PeopleCode course. Already familiar with Function Libraries and want more information on Application Classes? Enroll in our on-demand course or join us for our next live virtual session!

Monday, December 08, 2025

Branding System Options for Fluid

 The PeopleTools Branding System Options component allows a developer to inject custom CSS and custom JavaScript globally. This is fantastic, but it only applies to Classic/Classic+ (see Oracle Support document 2827970.1). Wouldn't it be nice to have the same functionality for Fluid? Now you can! PeopleTools 8.60 included Global Event Mapping, a feature that allows us to attach JavaScript and CSS to all Fluid components at once! We published a video a couple of years ago describing this PeopleTools feature. You may want to watch the video before continuing with this post:



Let's apply what we learned in the video to our scenario:

1. Create an Event Mapping Service App Class

In Application Designer, let's create a Global Event Mapping App Class. A Global Event Mapping App Class is just like any other Event Mapping App Class. They all start with the same PeopleCode. You may download our Event Mapping PeopleCode template from our GitHub repository. Here is a PeopleCode template to get you started:

import PT_RCF:ServiceInterface;

class FluidBrandingSystemOptions extends PT_RCF:ServiceInterface
   method execute();
end-class;

method execute
   /+ Extends/implements PT_RCF:ServiceInterface.execute +/
   
   If (IsFluidMode()) Then
      REM ** Insert JavaScripts;
      REM AddJavaScript(HTML.ABC123);
      
      REM ** Insert Stylesheets;
      REM AddStylesheet(Stylesheet.DEF456);
   End-If;
end-method;

2. Create an Event Mapping Service Definition

Every Event Mapping solution requires a Related Content Service Definition. As of PeopleTools 8.59, we can use a dedicated page for Event Mapping, but we don't have to. We can create our Global Event Mapping service definition the same way we have always created Related Content Service Definitions. Here is a screenshot of my service definition:



3. Run PeopleCode to Apply Global Event Mapping

Since there is no user interface to manage Global Event Mapping, we must invoke a few lines of PeopleCode to register our Global Event Mapping solution. I like to use App Engines for this, because I can run them directly from App Designer. Here is the PeopleCode I placed in my App Engine:

import PTCS_GLOBALEVENTMAPPING:*;

Local PTCS_GLOBALEVENTMAPPING:GlobalEventMapping &gem = create PTCS_GLOBALEVENTMAPPING:GlobalEventMapping();
Local boolean &bstatus = &gem.CreateGlobalEventMappingConfig("JSM_GBL_BRAND", "JSM_GBL_FL_BRAND");

4. Refactor Your Solution into a Table-Driven Framework (Optional)

Fantastic! We can now add or remove CSS and JavaScript globally by adding and removing lines from our App Class PeopleCode. Alternatively, would you like to maintain your list of assets through an online configuration page? The solution requires a bit more effort, but would involve the following:

  • A table to store JavaScript and Stylesheet names,
  • A page for configuring (likely with grids for JavaScript and Stylesheet assets), and
  • An online component.

I'll leave this final step to you. Personally, I prefer the static code listing, as it performs better (critical for Global Event Mapping), and my list of Stylesheet and JavaScript resources doesn't change very often. I also like the change control required by PeopleCode that would not exist if I had an online configuration table.

As noted in the video, be careful not to break Global Event Mapping. One misstep and your entire system is broken! As also noted in the video, correcting an error is trivial. Just comment out the offending code.


Are you interested in learning more about Event Mapping? Check out our Event Mapping on-demand course, just one of many on-demand classes included with our subscription service.

Tuesday, December 02, 2025

When AI Writes PeopleCode... Fact or Fiction?

I just asked Gemini the following question:

"Is there a PeopleCode variable to detect Fluid Mode vs Classic mode?"

Gemini responded with, "Yes!" I thought, "FANTASTIC!"

Here is the code snippet Gemini suggested:

If %Component.IsFluid Then
    /* Logic specific to Fluid Mode */
    MessageBox(0, "", 0, 0, "Running in Fluid Mode");
Else
    /* Logic specific to Classic Mode */
    MessageBox(0, "", 0, 0, "Running in Classic Mode");
End-If;

Wow! That is some fantastic PeopleCode! But AI is known to hallucinate. Before trusting this code, we have to ask: Fact or Fiction?

Let's start with line 1:

If %Component.IsFluid Then
It appears Gemini thinks %Component is an object. What does PeopleBooks say?
%Component returns an uppercase character string containing the name of the current component, as set in the component definition.
To confirm, let's try compiling it in Application Designer. The following is a screenshot of the compilation result:

Verdict: Fiction.

%Component contains a primitive string, not an object. Since a primitive string does not have methods. The IsFluid method would be invalid.

I followed up with Gemini by asking:

"Can you share your reference for %Component?"

Instead of sharing a bibliography of cited sources, Gemini shared what appeared to be very legitimate documentation that describes Gemini's understanding of %Component. I attached a screenshot for your reference:




I circled the last statement, because it was the only part of this listing that was true:

"Gemini can make mistakes, so double-check it"

But I have to ask: Where did Gemini get its information? 🤔 Like a crack reporter, Gemini would not reveal its sources.

The good news is that Gemini is a fast learner! I fed Gemini a few authoritative PeopleBooks, such as a reference to PeopleCode System Variables, and Gemini generated a new response. This version is clever, but does it work?

Local ContentReference &oCRef;
Local boolean &isFluidMode;

/* Get the ContentReference object for the currently running content.
This object holds the metadata for the component's setup.
*/
&oCRef = %Session.GetContentReference();

If (&oCRef <> Null) Then
    /* Check the IsFluid property on the ContentReference object */
    &isFluidMode = &oCRef.IsFluid;
End-If;

If &isFluidMode Then
    /* Execute PeopleCode specific to Fluid UI */
    /* ... */
Else
    /* Execute PeopleCode specific to Classic UI */
    /* ... */
End-If;

What do you think? Fact or Fiction?

Let's start with the first line:

Local ContentReference &oCRef;

Unfortunately, ContentReference is not a built-in PeopleCode data type. What about this line?

&oCRef = %Session.GetContentReference();

Strike 2! GetContentReference is not a documented method of the Session object.

Verdict: Fiction.

But Gemini is on to something! The Fluid Mode attribute is visible in Structure and Content, so with a bit of PortalRegistry PeopleCode and the new %CRef system variable, you could write a lot of PeopleCode to determine if the current component is using Fluid mode.

I wanted to spend a few more minutes helping Gemini find the correct answer, so I fed Gemini several more PeopleBooks entries, hoping it would derive the correct answer. Each time, Gemini gave me a new, seemingly authoritative but entirely fictitious response, inventing new App classes and creating new functions.

After a few iterations, I decided to share the correct answer with Gemini. PeopleCode has a built-in function to determine Classic from Fluid: IsFluidMode. Here is Gemini's reply:


"This built-in function provides the clean separation of logic needed when supporting the same component in both Fluid and Classic modes (emphasis added)..."

Should we tell Gemini that a single component cannot be both Fluid and Classic?

This was a fun exercise. It was like a PeopleCode puzzle: find the hidden AI hallucination, and solve the puzzle.

How about you? Do you have interesting stories about AI and PeopleSoft? If so, please share them in the comments. We love hearing your stories!

Today, there is no substitute for experience and a strong personal understanding of PeopleCode. Want to become a PeopleSoft development expert so you can better determine fact from fiction? Enroll in the JSMpros All-access training pass and start learning!

Monday, September 08, 2025

Parsing JSON Arrays with PeopleCode

PeopleCode includes built-in support for parsing JSON through a native object called the JsonParser. Let's review a couple of JSON strings and then see how the JsonParser interprets them. First, let's review a JsonObject:

{
  "course": "PT1",
  "description": "PeopleTools",
  "courseType": "T",
  "duration": 4
}

Assuming that the JSON text is in the string variable &jsonStr, then we might parse it with code similar to:

Local JsonParser &p = CreateJsonParser();

If (&p.Parse(&jsonStr)) Then
  REM ** Woo Hoo! It parsed!;
End-If;

Parsing means the JsonParser created an in-memory structure. To leverage the JSON, we need to access that in-memory structure. The JsonParser includes one documented method to access the JSON Structure: GetRootObject(). The GetRootObject method returns a JsonObject. According to the documentation, the following PeopleCode should give us the value of the description attribute from the JSON above:

Local JsonObject &course = &p.GetRootObject();
Local string &descr; = &course.GetString("description");

What about a JSON Array? Here is my concern: There is no GetRootArray method. What if the "root object" is not an "object," but an Array? Here is what a valid JSON Array might look like:

[{
  "course": "PT1",
  "description": "PeopleTools",
  "courseType": "T",
  "duration": 4
}, {
  "course": "PC",
  "description": "PeopleCode",
  "courseType": "T",
  "duration": 5
}]

We would parse it using the same code as above. But how would you access the Array? Since the Parser has a GetRootObject method, let's invoke it, and then ToString the root object to see its JSON output. Here is the PeopleCode:

MessageBox(0, "", 0, 0, "%1", &p.GetRootObject().ToString());

... and here is the JSON:

{[
    {
        "course": "PT1",
        "description": "PeopleTools",
        "courseType": "T",
        "duration": 4
    },
    {
        "course": "PC",
        "description": "PeopleCode",
        "courseType": "T",
        "duration": 5
    }
]}

Do you notice anything unusual about that JSON? Notice the extra curly braces ({}). The "root" object is a JSON object. But here is where it gets interesting. The printed JSON is not valid. An object must have an attribute. The array should be assigned to an attribute. Now, does this matter? I think Oracle is allowed to internally represent JSON any way they desire. You might say that what we did was unexpected. We asked PeopleSoft to print an internal representation, not a true, expected JSON Object. But my question is the same: How do you access the Array that is now inside the root object? Here is the answer:

&p.GetRootObject().GetJsonArray("");

The GetJsonArray method expects an attribute name. We don't have one. So we don't give it one. Just use a zero-length string.

Want hands-on experience with REST services and PeopleCode parsing techniques? Join us on Tuesday, September 23, for two hands-on, live virtual workshops focused on integration! Details for the entire September series are available online.

We teach PeopleTools tips like this every week. Check out our website to see what we are offering next. Prefer to learn at your own pace? Our entire catalog is available online.

Tuesday, May 06, 2025

Which Technology Would You Use for JSON?

We asked our LinkedIn audience:

Which Technology Would You Use to Process JSON?

And they replied:


These answers are fantastic! Based on performance testing and research, PeopleCode native JSON objects, such as JsonObject and JsonArray, perform much faster than the Documents module or external Java libraries. However, there are times when I might choose an alternative.

Java Libraries

PeopleCode leverages the Java Native Interface to provide bidirectional access to Java. Java classes can interact with PeopleCode functions and objects, and vice versa. In addition to the delivered Java API, PeopleSoft provides several key Java libraries, including the Jakarta JSON library. Jakarta stream processing enables us to process enormous datasets. This stands in contrast to native DOM-based JSON parsing, which is limited by the amount of system memory available.

Documents

A document structure may generate either XML or JSON, which might simplify solution development when creating APIs that support multiple output types. Likewise, a document structure is required when creating a REST URI template.

Additional Resources


How about you? What technology would you choose? What are some reasons you might choose an alternative to the native JsonObject and JsonArray?

At JSMpros, we teach JSON processing techniques regularly through our Integration Tools Update course. Check out our online schedule to see what we are offering next! Alternatively, subscribe to gain access to all of our on-demand courses!

Monday, April 21, 2025

Consuming Enormous Datasets with PeopleSoft

Integration Broker is built on the DOM concept, which means it parses data into an in-memory structured document before transforming, processing, or transmitting it. This is fantastic for small and incremental integrations designed to keep two systems synchronized on a per-transaction basis. However, it fails when processing datasets that exceed the amount of available system memory.

An alternative is to use a SAX or stream-based parser that emits events. This type of parser only consumes the memory necessary to emit the next event. Stream-based parsers are highly efficient for one-way, one-time reads through large datasets. Unfortunately, Integration Broker does not support stream-based processing.

While reviewing PeopleSoft's Java class path, I noticed the Jakarta JSON stream-processing Java library. You can find a simple PeopleCode example of processing a JSON file using Jakarta JSON streams in our blog post JSON Stream Processing with PeopleCode. Now that we know how to use Jakarta's stream processing, the next challenge is reading an input stream from an external service. Since Integration Broker does not support streams, we need alternatives. Here are a few Java-based alternatives that readily integrate with PeopleCode through delivered APIs:

  • Java Sockets
  • Java HttpURLConnection
  • Apache HttpClient

Although PeopleCode offers incredible support for Java, the real challenge lies with method and constructor overloading. PeopleCode identifies target Java methods and constructors through parameter count, not parameter type. Java overloading doesn't play well with PeopleCode. The solution I use to overcome method overloading is to leverage Java's support for JavaScript as a translation layer or a "glue." PeopleSoft exposes all functions and objects to Java. Therefore, all PeopleCode functions and objects are also available to JavaScript.

The following is a sample JavaScript that can run from PeopleCode to stream load data into a PeopleSoft table. It uses Jakarta for stream processing and Apache HttpClient to connect to the external service. Both of these external libraries are included with PeopleTools. Notice the use of PeopleCode functions, such as CreateSQL, as well as Java objects such as HttpGet.

I use PeopleCode similar to the following to run JavaScript from PeopleCode. You can find several examples of using Java's ScriptEngineManager on our blog.

Local JavaObject &manager = CreateJavaObject("javax.script.ScriptEngineManager");
Local JavaObject &engine = &manager.getEngineByName("JavaScript");
Local String &script = "JavaScript goes here";
Local Any &result;

&engine.eval(&script);

&result = &engine.get("result");

At JSMpros, we teach PeopleTools and PeopleCode tips like this in every class. Check out our online schedule to see what we're offering next. Would you prefer to learn at your own pace? Purchase a subscription to access all of our on-demand content at discounted rates!

Wednesday, February 26, 2025

Function Library or Application Class?

When we discover redundancies while writing code, the DRY principle (Don't Repeat Yourself) encourages us to refactor our code into reusable definitions. Reasons cited for writing DRY code include:

  • Code that is easier to maintain,
  • Code that scales better as system load increases, and
  • Reduced redundancies in process logic.

With PeopleCode, we have two reusable options:

  • Function Libraries
  • Application Classes

We asked our LinkedIn audience which option they would choose.


The poll results show that 76% would choose Application Classes! Wow! 76% will defer to Object-oriented programming. This is one of those questions that has no right or wrong answer. Both are effective. But is there a more correct answer? Is there a time when using one over the other is more appropriate?

Let's consider App Classes first. Every App Class involves object creation overhead, which means using objects has a cost. But there are two features App Classes contain that set them apart from Function Libraries:

  • State: App Classes have an internal state. App Classes have private, internal variables that persist beyond method invocation.
  • Dynamic Execution: At runtime, we can create objects, set properties, and invoke methods that didn't exist during design time. Function libraries can't do this.

If I know that my solution will require internal state or dynamic execution, I choose App Classes; function libraries are not an option.

Here are a few other reasons people choose Application Classes over Function Libraries:

  • To leverage dynamic testing frameworks such as PSUnit.
  • Extensible framework development through inheritance and composition.

Is there a place for function libraries in modern PeopleCode? This is an interesting question that I think Oracle answers for us. If you look through Oracle's Fluid-specific PeopleCode, you will see a lot of references to Fluid-specific Function Libraries. Why? If you don't need internal state or dynamic execution, then a Function Library may be the fastest, lightweight option.

Consider the following example (adapted from Base64 Encoding with Emoji):

/****
 * You may find a subset of supported character sets in the Javadoc:
 * https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html
 */
Function base64_encode(&textToEncode as string, &charSet as string) returns string
   Local JavaObject &encoder = GetJavaClass("java.util.Base64").getEncoder();
   Local JavaObject &bytes = CreateJavaObject("java.lang.String", &textToEncode).getBytes(&charSet);

   return &encoder.encodeToString(&bytes);
End-Function;

Does it make more sense to expose this reusable algorithm as a Function Library or Application Class method? What do you think? If you choose App Classes, why? If you prefer Function Libraries, we would love to hear your reasons!

At JSMpros, we teach PeopleTools and PeopleCode tips like this in every class. Check out our online schedule to see what we're offering next. Would you prefer to learn at your own pace? Purchase a subscription to access all of our on-demand content at discounted rates!

Tuesday, January 07, 2025

Five Ways to Consume a REST Service with PeopleSoft

PeopleSoft includes facilities for providing and consuming REST. A service provider is a listener. A provider waits for requests and responds accordingly. To provide web services, we must register metadata with Integration Broker. The process is pretty well fixed. Consumption, on the other hand, is much more flexible. Consuming a REST service means invoking (or calling) someone else's listener. The consumer initiates the conversation. In a consumption scenario, we might be sending data, receiving data, or both.

Here are five ways a PeopleSoft developer might invoke a REST service:

1. Metadata

This is the traditional PeopleSoft approach and follows the same pattern as providing services through Integration Broker. Here are a few of the metadata items a developer would create:

  • Documents,
  • Messages,
  • Service, and
  • Service Operation.
After creating and registering somewhat reusable metadata, the developer would then write PeopleCode to:
  • Create Document structures,
  • Invoke the service, and
  • Parse the response.

Even though this approach requires the most effort and offers the least reuse, it takes full advantage of Integration Broker's capabilities, including logging, security, etc.

Metadata, in general, offers the following benefits:

  • Reuse (ability to use the same definition multiple times),
  • Documentation (describes an object),
  • Reporting (query and analysis), and
  • Transformation (ability to upgrade and transform based on architecture changes).

Pure code solutions are much harder to query and transform. Metadata is what allowed PeopleSoft to switch from a Windows-based Client/Server solution to its Pure Internet Architecture in (mostly) one release. Metadata is what allowed Integration Broker to transform from an XML-focused solution into an SOA solution in one release (the 8.48 transform). If these benefits sound appealing, then metadata may be the right choice for you.

2. Application Services Framework

Created initially as a REST provider to support digital assistants, the Application Services Framework can now consume REST services. The Application Services Framework is a developer-friendly configuration layer tightly integrated with Integration Broker metadata. Rather than directly working with SOA-oriented metadata, the Application Services Framework allows developers to create solutions using REST terminology and REST patterns.

To use the Application Services Framework for consumption, a developer would:

  • Register the target service with the Application Services Framework, which includes describing the URL, parameters, headers, and payload (both request and response).
  • Write PeopleCode to invoke the endpoint service.
This is one of the most important chapters in our updated Integration Tools curriculum. You may find basic information (including code samples) on consuming a REST service in PeopleBooks.

3. %IntBroker.ConnectorRequestURL

If your request is a simple URL with no special headers (request or response headers) and any parameters may be passed through the URL, then this is the most straightforward approach:

Local string &response = %IntBroker.ConnectorRequestURL("http://rest.example.com/endpoint");

Unfortunately, this solution offers no logging, header control, or any typical Integration Broker or integration features. It is strictly for the simplest GET requests. Nevertheless, by using URL definitions, this alternative may be one of the better alternatives for cross-environment migrations.

4. Code-only

The challenge with the first option, Metadata, is that it requires creating, migrating, and maintaining a significant number of definitions that provide little (if any) value for REST. For example, the URL of a PeopleSoft REST consumer service becomes part of the metadata. If you have different targets between DEV, TEST, and PROD, then you must modify the metadata after every migration. Implementing a true PeopleSoft Metadata-focused solution (such as option 1) may require you to violate development best practices by making changes after each migration.

Since all approaches require PeopleCode, why not skip the Integration Broker metadata in favor of your own reusable best practice-based metadata? You may find an example of this approach in our blog post Simple Code-only REST Request. With this approach, you are responsible for managing URLs, Credentials, etc., but you may store them in a manner that allows for reuse and better migration management. For example, you might create URL definitions that point to different endpoints in DEV, TEST, and PROD.

It is important to note that this approach DOES use metadata, but it reuses generic PeopleTools-delivered definitions, so we don't have to create new definitions.

As mentioned earlier, code doesn't report or transform well, so this alternative may miss out on future automated transforms, such as the 8.48 automated transform. Likewise, integrations launched in this manner won't log details in the Synchronous Service Operation Monitor. Nevertheless, this approach is becoming one of our favorite alternatives to overly complicated metadata.

5. Java

Using Java allows a PeopleSoft developer to bypass Integration Broker altogether. We put this option last because it should be the choice of last resort. However, it is probably the most flexible option available, allowing for everything from simple low-level sockets to convenient libraries, such as Apache's HttpClient (now included with PeopleTools).

There are many reasons to choose this option, but here are the two most common:

  • Processing binary data: Integration Broker is pretty much an XML workhorse. Everything passing through Integration Broker is wrapped in XML at some point. Unfortunately, that might not work well with binary data. Therefore, skipping Integration Broker may be appropriate.
  • Processing large amounts of data: Integration Broker works with DOM. It requires all data to be loaded in memory at one time. This makes it a poor choice for handling large datasets. An alternative is to use stream processing with an event-based parser, such as a SAX parser. With Java, you can read bytes, process them through an event-based processor, and then discard the processed bytes.
The challenge with using Java directly from PeopleCode is that many Java methods and constructors use overloading. As a workaround, we devised a strategy for invoking Java through JavaScript from PeopleCode. With a small PeopleCode fragment, we can invoke a JavaScript, and JavaScript handles Java really well. Details about this strategy are available in our Blog Post JavaScript on the App Server: Scripting PeopleCode.

The following is a sample JavaScript we used at Reconnect 2024 to stream-processed a large amount of JSON data from a REST service.


At JSMpros, we teach all five options in our Integration Tools and Integration Tools Update courses. Check out our website for on-demand and live course offerings. Alternatively, subscribe to gain access to all of our on-demand courses.

Thursday, December 19, 2024

How Well Do You Know the PeopleCode Language?

 I was reading through some forum threads and saw an interesting question. Let me summarize:

How do I convert from a number to a string so that I get the integer portion of the number? I have 1234 in a number, but when I put it in a string field, I get 1234.00.

This is a great question! There are many PeopleCode "casting" functions, such as Number and String. Reading through the thread, I saw some interesting answers. One of them that I liked used Java to do the conversion. What I liked about this idea was the out-of-the-box thinking. But is it necessary? Can you do this with PeopleCode? The answer is YES using the functions NumberToString and NumberToDisplayString. Is there anything wrong with using Java instead? No. I love PeopleCode's ability to leverage the JRE. But there is a cost in context switching, JRE overhead, etc.

Keeping with the number and string scenario, do you really need to "cast" a number to a string? Consider the following code listing:

Local number &anInteger = 1234;

MessageBox(0,"",0,0, &anInteger);

This code would fail because the fifth parameter to MessageBox must be a string. Therefore, it seems we need casting functions. Or do we? Consider the following alternative (notice the string concatenation in the MessageBox function):

Local number &anInteger = 1234;

MessageBox(0,"",0,0, "" | &anInteger);

When we concatenate a number to a string, PeopleCode applies an implicit cast. Interestingly, it only applies an implicit cast if we trick it with a zero-length string. As a side note, the above implicit cast returns the integer portion 1234 without decimals because 1234 has no decimals (which was the original request).

What about conditional logic? Here is one of my favorite examples:

If(PER_ORG_ASGN.POI_TYPE = "00002") Then
   JOB.COMPRATE.Visible = False;
Else
   JOB.COMPRATE.Visible = True;
End-If;

The above conditional code could be rewritten as:

JOB.COMPRATE.Visible = (PER_ORG_ASGN.POI_TYPE = "00002");

With an understanding of the PeopleCode language, we have reduced five lines of code into a single line. This might be considered the Spartan Programming approach. While I love the concept, Spartan Programming claims it "is not directly concerned with readability." Therefore, I prefer a slightly modified, possibly more human-readable alternative:

Local boolean &isVisible = (PER_ORG_ASGN.POI_TYPE = "00002");

JOB.COMPRATE.Visible = &isVisible;

Here is another piece of code I found several years ago:

Local Array of String &arr;

...

REM ** delete all elements from an array;
For &i = 1 to &arr.Len
   &arr.pop();
End-For;

If you look through PeopleBooks, you will see the Array has no clearemptydeleteAll, or any other method for emptying all elements from an array. So I can see why the author wrote the code above. But the reason the Array object has no method for emptying an array is because it doesn't need one. The Array length is writable. The easiest way to empty an array is:

&arr.Len = 0;

How well do you know the PeopleCode language? Time for a refresher? Check out our on-demand PeopleCode course and advanced PeopleCode Application Classes courses and experience a new side of PeopleCode!

Tuesday, November 19, 2024

Generating Activity Guide URLs

Creating Activity Guide navigation is challenging for two reasons:

  1. Simple Fluid Activity Guides all use the same component. This means we can't use a simple content reference. To use security to show or hide an Activity Guide content reference, we must use the URL type of PeopleSoft Generic URL. We must type a PeopleSoft URL fragment rather than leverage the traditional Content Reference fields (menu, component, market).
  2. Activity Guides with Runtime Context require dynamically generated URLs. These Activity Guides cannot leverage simple content references.

My PeopleCode for launching Activity Guides with Runtime Context usually starts with a GenerateComponentPortalURL to generate the base Activity Guide framework URL and then a bit of URL concatenation to assemble the Runtime context attributes. Here is an App Class I put together to make this easier.



Here is how you would use it:

import JSM_URL_UTIL:ActivityGuideURL;   
   
Local JSM_URL_UTIL:ActivityGuideURL &urlBuilder = create JSM_URL_UTIL:ActivityGuideURL("JSM_AWE_AG");
Local string &url;

&urlBuilder.addContextItem(Field.EOAWPRCS_ID, "FacilityAccessRequest");
&urlBuilder.addContextItem(Field.DESCR, "Facility Access Request");

&url = &urlBuilder.generateFluidURL();

The addContextItem method takes a key/value pair, both of which are strings (they will become part of the URL string). Since context IDs (keys) are fields, then using Field.FIELDNAME syntax is preferred so Edit | Find Definition References will locate your field usage.

We added one more convenience method: generateGenericPeopleSoftFluidURL(). Use this method to help you craft a PeopleSoft Generic URL to a static Activity Guide. This is a one-time-use method you would call at design time to create that static URL fragment required by a Content Reference. If you have a simple, static Activity Guide with no context, then you may want to create a Content Reference. However, typing all of the parameters correctly can be a challenge. Use this helper method to generate the full Generic PeopleSoft URL for you. We invoke this method from a design-time App Engine, but you may want to create a page for it instead.

Are you interested in learning more about PeopleCode Application Classes? Check out our two-day course available live virtual or on-demand!

Thursday, June 27, 2024

PeopleSoft Data Masking Options

PeopleSoft customers have several Data Masking options:

Let's compare the various options.

Event Mapping

Event Mapping is the most flexible option, allowing us to use any masking character, from alpha-numeric to emoji. In fact, you may even combine the space character with custom CSS to leverage any character, including custom Fonts, such as FontAwesome. Relevant PeopleCode functions and methods include:

Field.SetDisplayMask
Field.AddFFClass
AddStylesheet

Check out this video to learn more about Event Mapping for Data Masking:


Page and Field Configurator

Page and Field Configurator is less flexible but easier to apply than Event Mapping. Page and Field Configurator offers a point-click interface to configure masking against page fields. Masking characters are limited to * and x (although this is configurable through masking profiles).

App-specific masking

The HCM team built its own registry of sensitive fields with a masking utility. You can learn more about this feature in the Quest blog post Maintaining Data Privacy in PeopleSoft HCM. What makes this option compelling is:

  1. The HCM team wrote all the code. All we have to do is choose our sensitive fields, components, and roles.
  2. If anything breaks, we file a ticket for the HCM team to fix. This is in contrast to Page and Field Configurator and Event Mapping, which are site-specific isolated customizations and, therefore, the customer's responsibility to fix.
  3. This solution has broad coverage. If we choose to mask a sensitive field, such as birth date, then all HCM pages and components should mask that field. Event Mapping and Page and Field Configurator, on the other hand, only mask one component. If we used either of those solutions to mask the birth date field, we would need to apply that masking to all components ourselves.

Data Privacy Framework

The Data Privacy Framework allows us to apply masking to query results. This is not mutually exclusive. You may choose to apply the Data Privacy Framework along with any of the other options.

Bolt-on Solutions

My favorite data masking solution is Pathlock's Security Solution for PeopleSoft. Besides the basics of masking, Pathlock's solution also allows us to unmask using a variety of techniques, including:

  • Click-to-view (a loggable event) and
  • MFA-to-view (also loggable but requiring a second factor to confirm your identity).

Interested in learning more? We teach PeopleTools Tips like this every week at JSMpros! Check out our online schedule to see what we are offering next! Or do you have a specific topic you want to study? Subscribe to gain access to all of our on-demand content at a fraction of the cost!

Thursday, April 25, 2024

HOWTO Override Fluid Component Event Handlers

Oracle's delivered Fluid components use an interesting pattern: App Class Event Handlers. This isn't required. It's just a design decision. Here is how it works: a Fluid page's Component PreBuild usually initializes a component-scoped App Class variable and every subsequent event delegates to a custom App Class method. If done properly, this design decision has the following potential benefits:

  • Reusable,
  • Unit testable,
  • Extensible, and
  • It eliminates the "Data Integrity Error" when making changes to Component-specific PeopleCode while a component transaction is in progress.

Unfortunately, to be reusable and testable, App Class code must be context-agnostic. That means it can't leverage component buffer-specific functions, such as GetLevel0, GetRow, and GetRowset; it can't use context-specific variables, such as %Component; and it can't use bare references, such as RECORD.FIELD references.

We discuss these design concepts regularly in our PeopleCode Application Classes two-day course, and we wrote about the extensibility idea in this blog post. In the blog post, we noted that Oracle would need to change the way they load their App Classes in Component PreBuild to make event handlers extensible. But do we need to wait? We came up with an idea that allows us to implement this idea now: we can use Event Mapping to replace Component PreBuild so we can load our own App Class. As long as our new App Class extends the Oracle-delivered App class, all other event PeopleCode will delegate properly. In other words, PeopleSoft will use our code in all other events. What's interesting about this idea is that it may allow you to apply just one Event Mapping service to a component rather than one per event.

As an example, let's extend Direct Deposit by subclassing (overriding) one of its App Classes. Components that apply the event delegation pattern instantiate App Classes in PreBuild. Within the PreBuild of the Direct Deposit component (PY_IC_DIR_DEP_FL), we see the App Class PY_DD_SELFSERVICE:Utilities. That class includes several important methods, including one appropriately named PageActivate. Our goal is to use the PageActivate event to hide the Pay Statement Print Options box. We will accomplish this goal by using Event Mapping to replace PY_DD_SELFSERVICE:Utilities with our own Utilities subclass. Here is the code for the Utilities subclass:

import PY_DD_SELFSERVICE:Utilities;

class CustomUtilities extends PY_DD_SELFSERVICE:Utilities;
   method pageactivate();
   REM ** Add more methods to override mor functionality;
end-class;

method pageactivate
   /+ Extends/implements PY_DD_SELFSERVICE:Utilities.pageactivate +/
   REM ** invoke original pageactivate method since we are just extending, not replacing;
   %Super.pageactivate();
   REM ** The following line doesn't work because later Oracle-delivered code overrides it;
   REM PY_IC_WRK2.PRINT_OPTN.Visible = False
   PY_IC_WRK2.PRINT_OPTN.AddFFClass("psc_hidden");
end-method;

The next step is to apply Event Mapping to override Component PreBuild. Here is our sample code:

import PT_RCF:ServiceInterface;
import PY_DD_SELFSERVICE:Utilities;
import TRN_PY_IC_DIR_DEP_FL_OVRD:CustomUtilities;

class PreBuild extends PT_RCF:ServiceInterface
   method execute();
end-class;

Component PY_DD_SELFSERVICE:Utilities &DDUltities;

method execute
   /+ Extends/implements PT_RCF:ServiceInterface.execute +/
   
   &DDUltities = create TRN_PY_IC_DIR_DEP_FL_OVRD:CustomUtilities();
end-method;



After applying Event Mapping, the delivered Direct Deposit component will now pass all Utilities requests through our subclass. The standard, delivered &DDUtilities.pageactivate call that is in the middle of the delivered PageActiviate PeopleCode will now invoke our pageactivate method instead.

Summary

This was an interesting academic exercise with some benefits over Event Mapping:

  • This approach allowed me to indirectly inject code into the middle of an Oracle-delivered code listing. The delivered PageActivate event invokes &DDUtilities.pageactivate in the middle. Event Mapping would have required my change to appear at the end or beginning, but not in the middle.
  • I only had to configure one Event Mapping, not one for each event I desired to extend.

I also found some challenges that this approach could not solve:

  • I wanted to run code at the end of PageActivate, not in the middle. My CustomUtilities code triggers too soon. As you can see from the first code listing, I run Oracle's code through %Super, and then mine. But the actual event code listing has more code that overrides my code. Event Mapping is the only way to make sure your code runs last.
  • I would like to mask the routing number within the rows of the Direct Deposit grid. I would use RowInit to apply this masking. The delivered Direct Deposit component does not have code in RowInit. I would, therefore, have to use Event Mapping to apply RowInit code.

This is a pattern I'm going to keep in my toolbox. For this scenario specifically, Event Mapping without overriding was a better solution. But there are times where subclassing a backing App Class may make more sense.

Are you interested in learning more about PeopleTools and PeopleCode? Check out our live virtual and on-demand courses. Or even better, subscribe and get access to all of our content for a full year!

Thursday, January 18, 2024

Generating LARGE JSON Files

The PeopleCode native JsonObject and JsonArray classes allow us to create JSON structures as in-memory representations. But what if you need to generate a really LARGE JSON structure? An in-memory JSON Array may consume more memory than you can reasonably allow. Fortunately, PeopleTools includes the Jakarta JSON library, which allows us to write a JSON structure to a stream during construction.

The following code snippet demonstrates creating 10 million JSON objects in an array without any change in memory consumption. The generated file was 2.5 GB in size, but my memory utilization didn't change the entire time the program ran.

Local JavaObject &Json = GetJavaClass("jakarta.json.Json");
Local JavaObject &writer = CreateJavaObject("java.io.FileWriter", "C:\temp\users-big.json");

Local JavaObject &gen = &Json.createGenerator(&writer);

Local number &iteration = 1;

REM ** 10 million iterations;
Local number &maxIterations = 10000000;

&gen.writeStartArray();

For &iteration = 1 To &maxIterations
   
   REM ** start person/user object;
   &gen.writeStartObject();
   &gen.write("id", "" | &iteration);
   &gen.write("firstName", "John");
   &gen.write("lastName", "Smith");
   
   REM ** start child address object;
   &gen.writeStartObject("address");
   &gen.write("streetAddress", "21 2nd Street");
   &gen.write("city", "New York");
   &gen.write("state", "NY");
   &gen.write("postalCode", "10021");
   &gen.writeEnd();
   
   REM ** start phone number array;
   &gen.writeStartArray("phoneNumber");
   
   REM ** start home phone object;
   &gen.writeStartObject();
   &gen.write("type", "home");
   &gen.write("number", "212 555-1234");
   &gen.writeEnd();
   
   REM ** start fax number object;
   &gen.writeStartObject();
   &gen.write("type", "fax");
   &gen.write("number", "646 555-4567");
   &gen.writeEnd();
   
   REM ** end array of phone numbers;
   &gen.writeEnd();
   
   REM ** end person/user object;
   &gen.writeEnd();
End-For;


REM ** end array;
&gen.writeEnd();

REM ** cleanup to flush buffers;
&gen.close();
&writer.close();

The hard-coded values come directly from the Jakarta generator API documentation. In real life, you would replace these values with database data. I converted numbers to strings to simplify the example to avoid Java Reflection.

Are you interested in parsing rather than generating large JSON files? Check out our post on JSON Stream Parsing.

We teach PeopleTools and PeopleCode tips like this every week! Check out our upcoming course schedule to see what we are offering next! We would love to have you join us. Want to learn at your own pace? Check out our subscriptions and on-demand offerings as well. Or do you have a group you would like to train? Contact us for group and quantity discounts.

Monday, December 18, 2023

JSON Stream Processing with PeopleCode

Our Integration Tools courses emphasize the importance of utilizing PeopleSoft's native JSON support to parse and process JSON. This feature provides excellent functionality for most scenarios, as PeopleSoft's native JsonObject and JsonArray offer fast and efficient JSON processing. They are particularly useful for generating small integration responses or handling tasks like JWT (JSON Web Token) generation.

It's important to note that PeopleSoft's native JSON definitions employ a DOM-based parser, which builds an in-memory JSON structure. While this is effective in many cases, it does require your server to have enough memory to accommodate the entire JSON document without impacting its normal workload. Large files, therefore, can be problematic.

Stream-based parsing provides an alternative approach. With a stream-based parser, events are emitted as they occur, enabling immediate processing of data identified by these events. Once processed, the parser discards the data and proceeds to the next event. For instance, let's consider a scenario where you have a massive array of users. A DOM parser would load the entire array into memory, whereas a stream-based parser would only load one user at a time, allowing you to process the user and then discard it. Stream-based parsers are often more efficient in terms of resource utilization, as they process and discard data right away instead of constructing a traversable in-memory document.

Although PeopleCode itself doesn't include a stream-based parser, it does include the Java Jakarta stream-based JSON parser, which we can leverage through PeopleSoft's built-in Java support. Let me share an example with you. For testing purposes, I obtained a sample JSON file from https://jsonplaceholder.typicode.com/users. This file is small and perfect for testing. I then incorporated the following PeopleCode into an App Engine step, which you can run locally through App Designer:

REM ** JavaDoc: https://jakarta.ee/specifications/jsonp/2.0/apidocs/jakarta.json/jakarta/json/stream/jsonparser;
REM ** Data: https://jsonplaceholder.typicode.com/users;
Local JavaObject &Json = GetJavaClass("jakarta.json.Json");
Local JavaObject &reader = CreateJavaObject("java.io.FileReader", "C:\temp\users.json");
Local JavaObject &parser = &Json.createParser(&reader);

Local string &email;

While (&parser.hasNext())
   Local JavaObject &next = &parser.next();
   
   If (&next.equals(&next.START_OBJECT)) Then
      
      Local JavaObject &user = &parser.getObject();
      
      REM ** do something with the object;
      &email = &user.getString("email");
      MessageBox(0, "", 0, 0, "email: %1", &email);
   End-If;
End-While;

Here is some sample output generated by this short App Engine program:

email: Sincere@april.biz (0,0)
 Message Set Number: 0
 Message Number: 0
 Message Reason: email: Sincere@april.biz (0,0) (0,0)

email: Shanna@melissa.tv (0,0)
 Message Set Number: 0
 Message Number: 0
 Message Reason: email: Shanna@melissa.tv (0,0) (0,0)

email: Nathan@yesenia.net (0,0)
 Message Set Number: 0
 Message Number: 0
 Message Reason: email: Nathan@yesenia.net (0,0) (0,0)

email: Julianne.OConner@kory.org (0,0)
 Message Set Number: 0
 Message Number: 0
 Message Reason: email: Julianne.OConner@kory.org (0,0) (0,0)

Are you interested in learning more about PeopleSoft Integration, PeopleTools, Or PeopleCode? If so, check out our subscriptions, on-demand, and upcoming course schedule. We would love to have you join us!