Wednesday, April 26, 2017

FDMEE and PBJ, together hand in hand

Do you know Jason Jones? I guess you do but in case you don't, I'm sure you may have been playing around with any of his developments.

Personally, I've been following Jason since years. I remember what I thought when I went to one his presentations in Kscope: "This guy really knows what he says and has put lot of effort helping the EPM community. Definitely an EPM Rock star."

One day, I found something quite interesting in his blog: PBJ. I thought it could be very useful to improve and simplify something that I had already built using a different solution. Why not then using something he was offering to the community as open-source? It was good to me and also good to him. I guess that seeing something you've built is useful for others, must make you proud.
When I told him that I was going to integrate FDMEE on-prem with PBCS using PBJ, he was very enthusiastic. The library was not fully tested so I made sure I was providing continuous feedback. Some days ago he published about our "joint venture". Now it's time for me.

FDMEE Hybrid Integrations
We have already covered Hybrid integrations in some posts.
In a few words, FDMEE on-prem PSU200+ can be used to extract/load data from Oracle EPM Cloud Services (E/PBCS, FCCS so far).

I suggest you also visit John's blog to know more about hybrid integrations in FDMEE:
PBJ - The Java Library for PBCS
REST Web Services, what's that? I  let you google and read about it. For us, REST is how EPM Cloud Services open to the external world. Oracle provides different REST APIs for the different EPM CS.

Luckily, Jason has gone one step further. He built a Java Library to use the REST API for PBCS:

PBJ is a Java library for working with the Planning and Budgeting Cloud Service (PBCS) REST API. It is open source software.

Why would we need PBJ in our solutions? Currently hybrid integrations have some missing functionality like working with metadata among others. For example, we recently built a solution in FDMEE to load exchange rates from HFM into PBCS.

FDMEE was offering seamless extracts from HFM. Rates are data in HFM but not in PBCS. They are treated as metadata. We used REST APIs for PBCS from FDMEE scripts which was working perfectly. However, we built the code using modules available in Jython 2.5.1. That gave rise to much head-scratching... Working with HTTP requests and JSON was not an easy task.
We noticed everything was much easier from Python 2.7 (Jython 2.7) but nothing we could do here as we were stick to what FDMEE can use :-(

TBH, we had a further ace up our sleeve: building our own Java library but we delayed this development for different reasons. It was then that PBJ appeared :-)

Why reinventing the wheel? PBJ is open-source and makes coding easier. We can collaborate with Jason in GIT and he is quite receptive for feedback given.

Using PBJ from FDMEE Scripts
When I first started testing it, I noticed that there were multiple JAR dependencies which had to be added to the sys.path in my FDMEE script. That was causing some conflicts with other Jars used by FDMEE so Jason came up with an uber-JAR:

uber-JAR—also known as a fat JAR or JAR with dependencies—is a JAR file that contains not only a Java program, but embeds its dependencies as well. This means that the JAR functions as an "all-in-one" distribution of the software, without needing any other Java code. (You still need a Java run-time, and an underlying operating system, of course.)

One of my concerns was the fact that FDMEE uses Java 1.6. That's usually a problem when using external Jars from FDMEE scripts. Luckily, PBJ is also built using Java 1.6 so the current versions of FDMEE and PBJ are good friends.

Before using any PBJ class we have to add the Jar to the sys.path which contains a list of strings that specifies the search path for modules:


# -------------------------------------------------------------------
# Add library path to sys.path
# -------------------------------------------------------------------
import sys
import os.path as osPath

# list of jar files
listPBJdep = ["pbj-pbcs-client-1.0.3-SNAPSHOT.jar"]

# Add jars
pbjDepPath = r"E:\PBJ\uber_jar"
# Debug
fdmAPI.logInfo("Adding PBJ dependencies from %s" % pbjDepPath)
for jar in listPBJdep:
    pbjPathJar = osPath.join(pbjDepPath, jar)
    if pbjPathJar not in sys.path:
        sys.path.append(pbjPathJar)
        fdmAPI.logDebug("PBJ dependency appended to sys path: %s" % jar)


Once the Jar file is added to the path we can import the different classes we want to use:


# -------------------------------------------------------------------
# Import section
# -------------------------------------------------------------------
from com.jasonwjones.pbcs.client.impl import PbcsConnectionImpl
from com.jasonwjones.pbcs import PbcsClientFactory
from com.jasonwjones.pbcs.client.exceptions import PbcsClientException
import time


We are now ready to connect to our PBCS instance.

Example: loading new Cost Centers into PBCS
I have created a custom script in FDMEE to keep it simple. The script is basically performing the following actions:
  1. Import PBJ Jar file
  2. Connect to PBCS
  3. Upload a CSV file with new Cost Centers
  4. Execute a Job to add new Cost Centers
Our CSV file with new metadata is simple, just three new members:
PBJ has class PbcsClientException to capture and handle exceptions. You can use this class in addition to Python's one:


try:
    # Your code...    
except PbcsClientException, exPBJ:
    fdmAPI.logInfo("Error in PBJ: %s" % exPBJ)
except Exception, exPy:
    fdmAPI.logInfo("Error: %s" % exPy)


Connecting to PBCS
We just need 4 parameters to create a PBCS connection:


# -------------------------------------------------------------------
# Credentials
# -------------------------------------------------------------------
server = "fishingwithfdmee.pbcs.em2.oraclecloud.com"
identityDomain = "fishingwithfdmee"
username = "franciscoamores@fishingwithfdmee.com"
password = "LongliveOnPrem"


Note: just working with Jason to use encrypted password instead of hard-coded one. I'll update this post soon.

Creating the PBJ Client (PbcsClient)
PBJ can be seen as a PBCS client built in Java so next step is to create the Client object:



# Create client
clientFactory = PbcsClientFactory()
fdmAPI.logInfo("PbcsClientFactory object created")
client = clientFactory.createClient(connection) # PbcsClient
fdmAPI.logInfo("PbcsClient object created")  


With the client object we can upload the file with new metadata to the PBCS Inbox/Outbox folder. This is done with uploadFile method:

 
# Upload metadata file to PBCS Inbox
csvFilepath = r"E:\FDMEE_CC\FDMEE_CostCenter.csv"
client.uploadFile(csvFilepath)
fdmAPI.logInfo("File successfully uploaded to PBCS Inbox")


The file is then uploaded to PBCS so the Job can process it:


Creating the Application object (PbcsApplication) 
Once file file is uploaded we need to create an application object to import new metadata. In my case, my PBCS application is DPEU.


# Set PBCS application
appName = "DPEU"
app = client.getApplication(appName) # PbcsApplication


Executing the Job and Checking Job Status
I have created a Job in PBCS to upload new cost centers from a CSV file (PBJ also supports zip files):

One thing you need to know about REST API is that they are called asynchronously. In other words, we need to check the job status until it is completed (or predefined timeout is reached).

So we first execute the job by calling method importMethod and then check job status with method getJobStatus. The status will be checked every 10 seconds while the job is running.

In order to check the job status we need to know the job id. This is done with getJobId method:


# Execute Job to import new metadata (Cost Center)
result = app.importMetadata("FDMEE_Import_CC") # PbcsJobLaunchResult
fdmAPI.logInfo("Result: %s " % result)
        
# Check Job Status and loop while executing (may add timeout)
jobStatus = app.getJobStatus(result.getJobId()) # PbcsJobStatus
fdmAPI.logInfo("Job status: %s " % jobStatus)
statusCode = jobStatus.getStatus()
while (statusCode == -1):
    time.sleep(10) # sleep 10 seconds
    jobStatus = app.getJobStatus(result.getJobId()) # PbcsJobStatus
    fdmAPI.logInfo("Job status: %s " % jobStatus)
    statusCode = jobStatus.getStatus()
        
# Show Message
if statusCode == 0:
    fdmAPI.showCustomMessage("New Cost Centers added!")
else:
    fdmAPI.showCustomMessage("Some errors happened! %s" % jobStatus)


Once the job is completed we can see the results in the PBCS Job console:
Job was executed with no errors. By navigating to the Cost Center dimension we can see the new hierarchy added:
I have also added some code to write debug entries in the FDMEE process log. This is always useful and can help you to find and fix issues easily:

Conclusion and Feedback
In this post, my main goal has been to show you how to use PBJ library in FDMEE. I'm sure this can be very useful to implement different requirements for hybrid integrations.

Jason did a great job and the ball is now in our court. The best way of contributing is to keep testing PBJ and provide feedback.
Let me highlight that PBJ is not his only project. There are few others that you can check in his site.

Enjoy FDMEE and PBJ together hand in hand!

Friday, April 7, 2017

Replacing source files on the fly - Playing around with XML files

The following post came up after seeing that lot of people in the FDMEE community were asking "how can we manipulate the source file and replace by new one on the fly?"
In other words, how we can replace the source file selected by end user with a new file we create during the import process... or let's be clear... how can we cheat on FDMEE? :-)

I thought it was good idea to share with you a real case study we had from a customer. Their ERP system had a built-in process which was extracting data in XML format. Hold on, but can FDMEE import XML files? Not out the box, Yes with some imagination and scripting.

The Requirement
As stated above, FDMEE does not support all kind of formats out of the box. We usually have to ask our ERP admin (or IT) to create a file in a format that FDMEE can easily read, mainly delimited files such as CSV.

But what about Web Services like SOAP or REST? they mainly return XML or JSON responses. We need to be prepared for that in case we want our FDMEE integration to consume a WS. This is quite useful in FDMEE on-premise as I guess Data Management for the Cloud will include "some kind of JSON adapter" sooner or later in order to integrate with non-Oracle web services.

And what about any other integration where source files are in another format than fixed/delimited?

Luckily I had that one... we get an XML file from our IT and we need to convert to CSV so we can import through FDMEE.

High Level Solution
The main idea is to convert the XML file selected to a CSV file that FDMEE can understand. Now the questions are Where and How?

  • Where? It makes sense that we do the conversion before the actual import happens. BefImport event script?
  • How? FDMEE will be expecting a CSV file, how do we convert the XML to CSV? There are multiple methods: Python modules, Java libraries for XPath... I will show one of them.
The XML File
Image below doesn't show the real XML (confidentiality) but a basic one:
As you can see data is enclosed in <data> tag an lines are enclosed in <dataRow> tags. Besides, each dimension has a different tag. 
As an extra for this post, just to let you know that I usually use Notepad++ plugin XML Tools which allows me to perform multiple operations including XPath queries:
Before we move into more details. What do you think it would happen if we try to import the XML file with no customization? 
FDMEE rejects all records in the file. What were you thinking then? That's the reason I'm blogging about this (lol)

Import Format, Location and DLR for the CSV File
In this case, our source type is File. However, I usually define instances of File when I want FDMEE admins/users to see the real source system (this is optional):
The Import Format (IF)  has been defined to import a semicolon delimited file having numeric data only (you can use any delimiter):
I'm going to keep it simple. One-to-one mapping between XML dimension tags and HFM dimensions:
The Data Load Rule is using the IF we just defined. As you may know, we can have one location with multiple DLRs using different IFs when source is File.

BefImport Event Script
The conversion will done in the BefImport event script which is triggered before FDMEE imports the file the end-user selected when running the DLR.

We can split this script into two main steps:
  1. Create the new CSV file in the location's inbox folder
  2. Update database tables to replace the original file selected with the new one created in step 1
The final solution could be more sophisticated (create the CSV based on IF definition, parse null values, etc.). Today we will go for the simple one.

Let's dive into details.

Converting XML to CSV
There are multiple ways of converting an XML to CSV. To simplify, we could group them as:
  • Method A: parses the entire XML and convert to CSV
  • Method B: converts nodes into CSV lines as we iterate them
Method A would be good for small files. It's also quite useful if our XML structure is complex. However, if we have big files we may want to avoid loading file into memory before converting which is more efficient. Therefore, I have decided to implement Method B. Within all different options we have, I will show the event-style method using xml Python module.

Which Python modules I'm using?
  • xml module to iterate the XML nodes (iterparse)
  • csv module to create the CSV file
  • os to build the file paths
Let's import the modules:

# Import Section
try:
    from xml.etree.ElementTree import iterparse
    import csv
    import os
    fdmAPI.logInfo("Modules successfully imported")
except ImportError, err:
    fdmAPI.logFatal("Error importing libraries: " % err)

Then we need to build the different paths for the XML and CSV files. We will also create a file object for the CSV file. This object will be used to create the csv writer.
The XML file is automatically uploaded to the location's inbox folder when import begins. The CSV file will be created in the same folder.

# Get Context details
inboxDir = fdmContext["INBOXDIR"]
locName = fdmContext["LOCNAME"]
fileName = fdmContext["FILENAME"]
loadId = fdmContext["LOADID"]

# XML File
xmlFile = os.path.join(inboxDir, locName, fileName)
fdmAPI.logInfo("Source XML file: %s" % xmlFile)

# CSV file will be created in the inbox folder
csvFilename = fileName.replace(".xml", ".csv")
csvFilepath = os.path.join(inboxDir, locName, csvFilename)

# To avoid blank lines in between lines: csv file 
# must be opened with the "b" flag on platforms where 
# that makes a difference (like windows)
csvFile = open(csvFilepath, "wb")
fdmAPI.logInfo("New CSV file: %s" % csvFilepath)

The writer object for the CSV file must use semicolon as delimiter so it matches with our IF definition. We have also enclosed non-numeric values in quotes to avoid issues in case you define your import format as comma delimited:

try:
    # Writer
    writer = csv.writer(csvFile, delimiter=';', quoting=csv.QUOTE_NONNUMERIC)
except Exception, err:
    fdmAPI.logDebug("Error creting the writer: %s" % err)

Once the writer is ready, it's time to iterate the nodes and building our CSV. Before seeing the code, I'd like to highlight some points:
  • We just want to capture start tags so we only capture start event in iterparse
  • We can include event in the for statement for debugging purposes (we can print how the XML file is read)
  • Property tag returns the XML node name (<entity>...)
  • Property text returns the XML node text (<entity>EastSales</entity>) 
  • We know amount is the last XML tag so we will write the CSV line when it's found
  • The CSV writer generates the delimited line from list of node texts (row)
try: 
    # Iterate the XML file to build lines for CSV file
    for (event, node) in iterparse(xmlFile, events=['start']):
        
        # Ignore anything not being dimension tags
        if node.tag in ["data", "dataRow"]:            
            continue

        # For other nodes, get node value based on tag
        if node.tag == "entity":
            entity = node.text
        elif node.tag == "account":
            account = node.text
        elif node.tag == "icp":
            icp = node.text
        elif node.tag == "custom1":
            c1 = node.text
        elif node.tag == "custom2":
            c2 = node.text
        elif node.tag == "custom3":
            c3 = node.text
        elif node.tag == "custom4":
            c4 = node.text        
        elif node.tag == "amount":
            amount = node.text 
        
        # Build CSV row as a list (only when amount is reached)
        if node.tag == "amount":
            row = [entity, account, icp, c1, c2, c3, c4, amount] 
            fdmAPI.logInfo("Row parsed: %s" % ";".join(row))        
            # Output a data row
            writer.writerow(row)
        
except Exception, err:
    fdmAPI.logDebug("Error parsing the XML file: %s" % err)

The result of this step is the CSV file created in the same folder as the XML one:
If we open the file, we can see the 3 lines generated from the 3 XML dataRows:
Cool, first challenged completed. Now we need to make FDMEE to import the new file. Let's move forward.

Replacing the Source File on the fly
FDMEE stores the file name to be imported in several tables. It took to me some time and several tests to get which tables I had to update. Finally I got them:
  • AIF_PROCESS_DETAILS: to show the new file name in Process Details page
  • AIF_BAL_RULE_LOADS: to set the new file name for the current process
  • AIF_PROCESS_PERIODS: the file name is also used in the table where FDMEE stores periods processed by the current process
To update the tables we need 2 parameters: CSV file name and current Load Id (Process Id)

# ********************************************************************
# Replace source file in FDMEE tables
# ********************************************************************

# Table AIF_PROCESS_DETAILS
sql = "UPDATE AIF_PROCESS_DETAILS SET ENTITY_NAME = ? WHERE PROCESS_ID = ?"
params = [csvFilename, loadId]
fdmAPI.executeDML(sql, params, True)

# Table AIF_BAL_RULE_LOADS
sql = "UPDATE AIF_BAL_RULE_LOADS SET FILE_NAME_STATIC = ? WHERE LOADID = ?"
params = [csvFilename, loadId]
fdmAPI.executeDML(sql, params, True)

# Table AIF_PROCESS_PERIODS
sql = "UPDATE AIF_PROCESS_PERIODS SET IMP_ENTITY_NAME = ? WHERE PROCESS_ID = ?"
params = [csvFilename, loadId]
fdmAPI.executeDML(sql, params, True)

# ********************************************************************
# Close CSV File
# ********************************************************************
csvFile.close()

Let's have a look to the tables after they have been updated:
  • AIF_BAL_RULE_LOADS
  •  AIF_PROCESS_DETAILS
  •  AIF_PROCESS_PERIODS
At this point, FDMEE doesn't know anything about the original XML file. Maybe some references in the process log, but nothing important.

Let's give a try!
Ready to go. FDMEE user selects the XML file when running the DLR:
Import is happening... and... data imported! XML with 3 dataRows = 3 lines imported
Process details show the new file (although it's not mandatory to change it if you don't want to)

I'm going to leave it here for today. Processing XML files can be something very useful, not only when we have to import data but in other scenarios. For example, I'm sure some of you had some solutions in mind where the Intersection Check Report (FDMEE generates an XML file which is converted to PDF) had to be processed...

I hope you enjoy this post and find it useful for your current or future requirements.

Have a good weekend!