Wednesday, November 25, 2026

Oracle ADF 12c: Consume a REST JSON API in a Managed Bean and Show It in af:table and dvt:lineChart

In this post I will show how to call a public REST JSON feed from an Oracle ADF 12c application, bind the result to an af:table, and plot it with a DVT line chart. The example uses the SEC EDGAR company concept API, which needs no API key but does require a User-Agent header. The same pattern works for any JSON market-data feed you want to show on a page or in a WebCenter task flow.

I have used a POJO and a managed bean rather than a REST Data Control. The data control is fine for a quick prototype, but a bean makes it easier to send a custom header, cache the response, and keep the page from calling the remote service on every PPR.

What the API returns

The company concept endpoint returns the history of one US-GAAP tag for one company. The CIK has to be 10 digits and zero-padded. Apple's assets, for example:

https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/Assets.json

A shortened payload looks like this:

{
  "cik": 320193,
  "tag": "Assets",
  "entityName": "Apple Inc.",
  "units": {
    "USD": [
      {
        "end": "2023-09-30",
        "val": 352583000000,
        "fy": 2023,
        "fp": "FY",
        "form": "10-K",
        "filed": "2023-11-03"
      }
    ]
  }
}

If you omit the User-Agent, or send a generic one with no contact email, the SEC responds with HTTP 403. Use a value like MyADFApp contact@mycompany.com. Also keep the call rate low; they ask for no more than 10 requests per second. Filing facts do not change intra-day, so a cache of a few hours is enough.

This example is written against JDeveloper / ADF 12.2.x (the DVT tag is dvt:lineChart with a dataStamp facet). On 11g the older dvt:lineGraph component is the equivalent.

Step 1: A simple POJO for each data point

Create a Java class with getters and setters. ADF can bind a List of this type directly to a table and a chart.

package com.example.sec;

public class SecFactPoint {
    private String periodEnd;
    private String form;
    private Integer fiscalYear;
    private String fiscalPeriod;
    private String filed;
    private Double value;
    private String unit;

    public String getPeriodEnd() { return periodEnd; }
    public void setPeriodEnd(String periodEnd) { this.periodEnd = periodEnd; }

    public String getForm() { return form; }
    public void setForm(String form) { this.form = form; }

    public Integer getFiscalYear() { return fiscalYear; }
    public void setFiscalYear(Integer fiscalYear) { this.fiscalYear = fiscalYear; }

    public String getFiscalPeriod() { return fiscalPeriod; }
    public void setFiscalPeriod(String fiscalPeriod) { this.fiscalPeriod = fiscalPeriod; }

    public String getFiled() { return filed; }
    public void setFiled(String filed) { this.filed = filed; }

    public Double getValue() { return value; }
    public void setValue(Double value) { this.value = value; }

    public String getUnit() { return unit; }
    public void setUnit(String unit) { this.unit = unit; }
}

Step 2: Managed bean that fetches, parses and caches

Register the bean in adfc-config.xml (or the task flow) with pageFlowScope. The HTTP call uses HttpURLConnection so you do not need an extra REST library. I parse the JSON with Jettison (org.codehaus.jettison.json), which is already on the ADF classpath. If you prefer, javax.json works on WebLogic 12.2 as well.

The ticker-to-CIK values below are only samples for a lab. In a real page you would load them from https://www.sec.gov/files/company_tickers.json or from your own table.

package com.example.sec;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

public class SecFactsBean {
    private static final String USER_AGENT = "MyADFApp contact@mycompany.com";
    private static final long CACHE_TTL_MS = 4 * 60 * 60 * 1000L; // 4 hours
    private static final ConcurrentHashMap<String, CacheEntry> CACHE =
        new ConcurrentHashMap<String, CacheEntry>();

    private String ticker = "AAPL";
    private String concept = "Assets";
    private String companyName;
    private String message;
    private List<SecFactPoint> facts = new ArrayList<SecFactPoint>();

    public void loadFactsFromButton(javax.faces.event.ActionEvent event) {
        loadFacts();
    }

    public void loadFacts() {
        message = null;
        try {
            String cik = padCik(lookupCik(ticker));
            String cacheKey = cik + "|" + concept;
            CacheEntry cached = CACHE.get(cacheKey);
            long now = System.currentTimeMillis();
            if (cached != null && now - cached.fetchedAt < CACHE_TTL_MS) {
                companyName = cached.companyName;
                facts = cached.points;
                return;
            }
            String url = "https://data.sec.gov/api/xbrl/companyconcept/CIK"
                + cik + "/us-gaap/" + concept + ".json";
            JSONObject body = new JSONObject(httpGet(url));
            companyName = body.optString("entityName", ticker);
            facts = parsePoints(body);
            CACHE.put(cacheKey, new CacheEntry(now, companyName, facts));
        } catch (Exception e) {
            facts = new ArrayList<SecFactPoint>();
            message = "Unable to load facts for " + ticker + " / " + concept
                + ": " + e.getMessage();
            e.printStackTrace();
        }
    }

    public void onPoll(oracle.adf.view.rich.event.PollEvent event) {
        loadFacts();
    }

    private List<SecFactPoint> parsePoints(JSONObject body) throws Exception {
        List<SecFactPoint> list = new ArrayList<SecFactPoint>();
        JSONObject units = body.optJSONObject("units");
        if (units == null || units.length() == 0) {
            return list;
        }
        String unitName = units.has("USD") ? "USD" : (String) units.keys().next();
        JSONArray arr = units.getJSONArray(unitName);
        for (int i = 0; i < arr.length(); i++) {
            JSONObject row = arr.getJSONObject(i);
            // Keep annual 10-K rows for the chart; leave the rest out or
            // add a filter on the page if you also want quarters.
            if (!"10-K".equals(row.optString("form")) ||
                !"FY".equals(row.optString("fp"))) {
                continue;
            }
            SecFactPoint p = new SecFactPoint();
            p.setPeriodEnd(row.optString("end", null));
            p.setForm(row.optString("form", null));
            if (row.has("fy") && !row.isNull("fy")) {
                p.setFiscalYear(row.getInt("fy"));
            }
            p.setFiscalPeriod(row.optString("fp", null));
            p.setFiled(row.optString("filed", null));
            p.setValue(row.getDouble("val"));
            p.setUnit(unitName);
            list.add(p);
        }
        return list;
    }

    private String httpGet(String urlString) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept", "application/json");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(30000);
        int status = conn.getResponseCode();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            status >= 400 ? conn.getErrorStream() : conn.getInputStream(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        conn.disconnect();
        if (status != 200) {
            throw new IllegalStateException("HTTP " + status + " " + sb.toString());
        }
        return sb.toString();
    }

    private String lookupCik(String symbol) {
        String s = symbol == null ? "" : symbol.toUpperCase();
        if ("AAPL".equals(s)) return "320193";
        if ("MSFT".equals(s)) return "789019";
        if ("GOOGL".equals(s)) return "1652044";
        throw new IllegalArgumentException("Unknown ticker in this sample: " + symbol);
    }

    private String padCik(String cik) {
        String s = cik == null ? "" : cik;
        while (s.length() < 10) {
            s = "0" + s;
        }
        return s;
    }

    public String getTicker() { return ticker; }
    public void setTicker(String ticker) { this.ticker = ticker; }
    public String getConcept() { return concept; }
    public void setConcept(String concept) { this.concept = concept; }
    public String getCompanyName() { return companyName; }
    public String getMessage() { return message; }
    public List<SecFactPoint> getFacts() { return facts; }

    private static class CacheEntry {
        private final long fetchedAt;
        private final String companyName;
        private final List<SecFactPoint> points;
        private CacheEntry(long fetchedAt, String companyName, List<SecFactPoint> points) {
            this.fetchedAt = fetchedAt;
            this.companyName = companyName;
            this.points = points;
        }
    }
}

Move the User-Agent into a JVM system property or a configuration file before you deploy. Do not check a personal email into a shared repository.

The same fetch-and-cache approach is useful anywhere you want official filing facts on a screen without calling the source on every refresh. I've been using a similar approach while building MarketCatalyst, an AI-powered market research terminal for traders and investors.

Step 3: Table, chart and a refresh button

In the page fragment, bind both components to the same list. Set clientComponent="true" if you plan to refresh them programmatically (I have covered that PPR gotcha in an earlier post). The chart uses the 12.2 dataStamp facet.

<af:panelFormLayout id="pfl1">
  <af:inputText id="itTicker" label="Ticker"
                value="#{pageFlowScope.secFactsBean.ticker}"/>
  <af:inputText id="itConcept" label="US-GAAP concept"
                value="#{pageFlowScope.secFactsBean.concept}"/>
  <af:button id="btnLoad" text="Load facts"
             actionListener="#{pageFlowScope.secFactsBean.loadFactsFromButton}"
             partialSubmit="true"/>
  <af:outputText id="otName"
                 value="#{pageFlowScope.secFactsBean.companyName}"
                 clientComponent="true"
                 partialTriggers="btnLoad poll1"/>
  <af:outputText id="otMsg"
                 value="#{pageFlowScope.secFactsBean.message}"
                 inlineStyle="color:red;"
                 clientComponent="true"
                 partialTriggers="btnLoad poll1"/>
</af:panelFormLayout>

<af:table id="tFacts"
          var="row"
          value="#{pageFlowScope.secFactsBean.facts}"
          emptyText="No facts loaded"
          partialTriggers="btnLoad poll1"
          rowBandingInterval="1">
  <af:column id="cEnd" headerText="Period end">
    <af:outputText id="otEnd" value="#{row.periodEnd}"/>
  </af:column>
  <af:column id="cFy" headerText="FY">
    <af:outputText id="otFy" value="#{row.fiscalYear}"/>
  </af:column>
  <af:column id="cForm" headerText="Form">
    <af:outputText id="otForm" value="#{row.form}"/>
  </af:column>
  <af:column id="cVal" headerText="Value">
    <af:outputText id="otVal" value="#{row.value}">
      <af:convertNumber type="number" groupingUsed="true" maxFractionDigits="0"/>
    </af:outputText>
  </af:column>
  <af:column id="cUnit" headerText="Unit">
    <af:outputText id="otUnit" value="#{row.unit}"/>
  </af:column>
</af:table>

<dvt:lineChart id="lc1"
               var="row"
               value="#{pageFlowScope.secFactsBean.facts}"
               partialTriggers="btnLoad poll1"
               inlineStyle="width:100%; height:300px;">
  <dvt:chartLegend id="cl1" rendered="true"/>
  <f:facet name="dataStamp">
    <dvt:chartDataItem id="cdi1"
                       group="#{row.periodEnd}"
                       value="#{row.value}"
                       series="#{pageFlowScope.secFactsBean.concept}"/>
  </f:facet>
</dvt:lineChart>

<!-- Optional: refresh the cache when the TTL has expired.
     Filing data does not need a short interval. -->
<af:poll id="poll1" interval="3600000"
         pollListener="#{pageFlowScope.secFactsBean.onPoll}"/>

Call loadFacts() once from the task-flow initializer (or a @PostConstruct method) so the table is not empty on the first render. The button and the poll both use partial submit, so only the table, the chart and the status text refresh.

Caching, polling and a few caveats

The static ConcurrentHashMap is shared by all users in the JVM, which is what you want here: the SEC payload is public and relatively large. Four hours is a reasonable TTL. If you put af:poll on the page, use a long interval. A 5-second poll will not get you fresher filings and may get the server blocked.

If the managed server reaches the internet through a proxy, set the usual https.proxyHost / https.proxyPort system properties, or open the connection through your standard proxy helper. If you see an SSL handshake error, check that the WebLogic trust store includes the current SEC certificate chain. Do not disable hostname verification to make a lab work.

A REST Data Control is an alternative if you want to drag and drop from the Data Controls panel. In JDeveloper: New > Business Tier > Data Controls > Web Service Data Control (REST). You will still need a way to send the User-Agent. In 12.2 that often means a custom request handler, which is why I start with a bean when the source is strict about headers.

You can drop this fragment into a bounded task flow and consume it in WebCenter Portal the same way as any other regional task flow or remote portlet. I would keep the HTTP call and the cache in the bean, and leave the portal page responsible only for layout.

If a company returns 404 for Revenues, try RevenueFromContractWithCustomerExcludingAssessedTax, or inspect the larger company facts document at /api/xbrl/companyfacts/CIK##########.json to see which US-GAAP keys that filer actually reports.

Things that usually go wrong

  • HTTP 403. The User-Agent header is missing or does not include a contact email. Check the request in a network trace from the managed server, not only from your laptop.
  • HTTP 404. The CIK is not zero-padded to 10 digits, or that filer does not report the concept name you sent.
  • The table fills but the chart is empty. Confirm the list still has rows after the 10-K / FY filter, and that value is a number, not a string.
  • The page calls the SEC on every PPR. You forgot the cache, or the cache key does not include both CIK and concept. Watch the managed server access log before you leave poll enabled.
  • actionListener does not fire. The method must take a javax.faces.event.ActionEvent. Use a no-arg method only from a task-flow initializer or action, not from actionListener.

I'm Vinay Polisetti. I used to write these ADF and WebCenter notes while building portal and Java applications, and I'm now building MarketCatalyst, an AI-powered market research terminal for traders and investors.

Tuesday, March 7, 2017

ADF Managed bean code to close the current window


import org.apache.myfaces.trinidad.util.Service;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;

    public static void closeCurrentWindow() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExtendedRenderKitService service =
            Service.getRenderKitService(facesContext,
                                        ExtendedRenderKitService.class);
        service.addScript(facesContext, "window.close();");
    }

Friday, May 6, 2016

AutoComplete feature with multiple element section in ADF

Auto suggest feature in ADF

We use the <af:autoSuggestBehavior/> tag to support the auto complete functionality in ADF - JSF screens.

Limitation with auto complete in ADF

It allows the selection of just one element. If we want multiple elements to be selected as shown below, it is not possible with ADF

Solution

We can use this JQuery add on - The link to download the JQuery is her

How to use that plugin?

JSF Code is as below

<af:inputText id="it1" rows="1" columns="50" label="To" simple="true"
styleClass="user-search-token-input" autoSubmit="true"
value="#{backingBeanScope.TestBean.sampleInput}"
binding="#{backingBeanScope.Test.sampleText}">
</af:inputText>


   <div style="display:none" data-bind="
                            tokenInput: 'REST API to get the code',
                            tokenInputSelector: '.user-search-token-input input',
                            tokenInputOptions: {
                                method: 'POST',
                                queryParam: 'query',
                                jsonContainer: 'users',
                                propertyToSearch: 'uid',
                                tokenValue: 'uid',
                                hintText: 'Please enter name or email address'
                            }"><jsp:text/></div>


Expected input to the Add on

$(document).ready(function() {
$("#user-search-token-input").tokenInput([{
"first_name": "Arthur",
"last_name": "Godfrey",
"email": "arthur_godfrey@nccu.edu",
"url": "https://default_profile_images/default_profile_2_normal.png"
},
{
"first_name": "Andre",
"last_name": "Jolly",
"email": "andre.jolly@uol.com.br",
"url": "https://default_profile_images/default_profile_2_normal.png"
},
{
"first_name": "Andre",
"last_name": "Henderson",
"email": "andre.henderson@globo.com",
"url": "https://default_profile_images/default_profile_2_normal.png"
}
 ]);
});

How to make the customization to the JQuery add on

Customize the required values in the plugin at the place shown in the below diagram.



Native transport for Oracle Service Bus with Apache Kafka

What is Apache Kafka?

Kafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.
What does all that mean?
First let's review some basic messaging terminology:
  • Kafka maintains feeds of messages in categories called topics.
  • We'll call processes that publish messages to a Kafka topic producers.
  • We'll call processes that subscribe to topics and process the feed of published messages consumers..
  • Kafka is run as a cluster comprised of one or more servers each of which is called a broker.
So, at a high level, producers send messages over the network to the Kafka cluster which in turn serves them up to consumers like this:


 


Native transport for Oracle Service Bus 

Native transport for Oracle Service Bus allows the connection and data exchange with Kafka – supporting message consumption and production to Kafka topics. This is done in a way that allows Service Bus to scale jointly with Kafka, both vertically and horizontally.

How to install and exchange the data between Oracle Service Bus and Apache Kafka Can be found here

Friday, April 29, 2016

How to create a remote portlet and consume in Webcenter portal application


In this post, we are going to discuss the way to create, deploy and consume a remote portlet

Step 1. How to create a remote portlet

Remote portlet can be anything, as simple as an ADF application.

Create an ADF application with the taskflow containing the required logic and create a portlet entry as shown as below.




Now, create a deployment profile and deploy the application as EAR (or just view controller as war) to the application server. And note down the deployment URL from the JDEV logging console as shown below



Open that link to get the WSDL to consume the created application as portlet. Choose the second URL as shown below (That give the WSDL URL of the application we just deployed and ready to be registered and consumed as portlet).



Step2 - Register the custom application as the remote portlet


Go to Tools and Services -> Portlet Producers section as shown below in the portal administration 

Click register and give the portlet name and the WSDL file of the portlet => You are all set at the producer side. The portlet is registered and is ready to be consumed.


Step 2. How to Consume a remote portlet

Go to the page on which we would like to consume the portlet and 

go to UI Components -> Portlets -> Choose your portlet as shown below.






ADFC-02013: The ADF Controller cannot find metadata for activity ...

Sometime we run into the following issue

 <Error> <oracle.webcenter.webcenterapp.internal.view.webapp> <BEA-000000> <
oracle.adf.controller.activity.ActivityLogicException: ADFC-02013: The ADF Controller cannot find metadata for activity '/extend/webcenter/doclib/view/jsf/taskf
lows/folderViewer/folderView.xml#doclib-folder-viewer@initFolderViewer'.
        at oracle.adfinternal.controller.util.Utils.createAndLogActivityLogicException(Utils.java:230)
        at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:1003)
        at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:853)
        at oracle.adfinternal.controller.engine.ControlFlowEngine.invokeTaskFlow(ControlFlowEngine.java:245)
        at oracle.adfinternal.controller.state.ChildViewPortContextImpl.invokeTaskFlow(ChildViewPortContextImpl.java:104)
        at oracle.adfinternal.controller.state.ControllerState.createChildViewPort(ControllerState.java:1519)
        at oracle.adfinternal.controller.ControllerContextImpl.createChildViewPort(ControllerContextImpl.java:88)
        at oracle.adf.controller.internal.binding.TaskFlowRegionModelViewPort.createRegionViewPortContext(TaskFlowRegionModelViewPort.java:762)
        at oracle.adf.controller.internal.binding.TaskFlowRegionModelViewPort.getViewPort(TaskFlowRegionModelViewPort.java:607)

Solution

1. Make sure that the method where the metadata is failing has the fixed outcome property set in the taskflow as shown below




2. Also there should be no errors and warnings (Yes warning should also be not there) should not be there for that method in the taskflow


Wednesday, April 13, 2016

Email Validation for af:inputText in adf

jsff code


<af:inputText styleClass="email"  label=" " id="it1" rows="1" {pageFlowScope.TestBean.userEmail}"
validator="#{pageFlowScope.TestBean.customEmailValidator}"> </af:inputText>

Java Code

    public void customEmailValidator(FacesContext facesContext,
                               UIComponent uIComponent, Object object) {
        if (object != null) {
            CharSequence inputStr = object.toString();
            Pattern pattern = Pattern.compile(PortalConstants.EMAIL_PATTERN);
            Matcher matcher = pattern.matcher(inputStr);
            if (! matcher.matches()) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                              PortalConstants.EMAIL_FORMAT_ERROR, null));
            }
        }

    }


Constants Code

public class PortalConstants {
    public static final String  EMAIL_FORMAT_ERROR = "Please enter a valid email address";
    public static final String  EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

}

Friday, April 1, 2016

How to escape the af:inputText component value in ADF managed bean

Sometimes its a requirement that the text entered by the end user has to be escaped and should be stored to not loose the values entered by the end user.

How to do it?

This can be done using the StringEscapeUtils Module

JSFF Code


af:inputText id="it3" label="message" binding="#{requestScope.MB.message}" autoSubmit="true" />

Managedbean Code


import org.apache.commons.lang.StringEscapeUtils;

//Use the StringEscapeUtils Module

String userMessage = StringEscapeUtils.escapeHtml((String)message.getValue());

Tuesday, March 29, 2016

Programmatic PPR af:outputText refresh issues - no PPR-capable ID found for elements of: RichOutputText [UIXFacesBeanImpl, id=ot05]

We sometimes see the below issue on doing a programmatic refresh of af:outputText Component

The error message

PprResponseWriter$PPRTag> <finish> no PPR-capable ID found for elements of: RichOutputText[UIXFacesBeanImpl, id=ot05]

Why do we see this issue?

By default, the framework does not generate the ids for the components unless and absolutely required to optimize the page performance but we need id to be present at the client side to do PPR and thus we see the issue in doing a programmatic PPR of af:outputText. This issue can be solved in 2 methods described below.

Solution 1

Set the clientComponent="true" for the output text, sample is as below

              <af:outputText value="Test" id="ot5" styleClass="share-error"
                             binding="#{backingBeanScope.MB.message}"
                             clientComponent="true"/>

Refer to <af:outputText> documentation for more details on the clientComponent attribute

Solution 2

Add the following in web.xml

<context-param>
    <param-name>
      oracle.adf.view.rich.SUPPRESS_IDS
    </param-name>
    <param-value>auto</param-value>
</context-param>

Tuesday, March 22, 2016

oracle.jsp.parse.JavaCodeException - Root cause and solution

Sometimes we see the following exception after doing a webcenter portal deployment

Error details

OracleJSP error: oracle.jsp.parse.JavaCodeException: Line # 13, oracle.jsp.parse.JspParseTagScriptlet@5cefd96
Error: Java code in jsp source files is not allowed in ojsp.next mode.

Solution

Make sure that the web.xml in the Deployer project is empty, it should not have any adf library references.

It should looks as below.

<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
</web-app>