Thursday, December 12, 2013

ADF : Insert a row at the end of a ViewObject

public String onRowCreate() {

 BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
 //access the name of the iterator the table is bound to. Its "allDepartmentsIterator"
 //in this sample
 DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("allDepartmentsIterator");
 //access the underlying RowSetIterator
 RowSetIterator rsi = dciter.getRowSetIterator();
 //get handle to the last row
 Row lastRow = rsi.last();
 //obtain the index of the last row
 int lastRowIndex = rsi.getRangeIndexOf(lastRow);
 //create a new row
 Row newRow = rsi.createRow();
 //initialize the row
 newRow.setNewRowState(Row.STATUS_INITIALIZED);
 //add row to last index + 1 so it becomes last in the range set
 rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
 //make row the current row so it is displayed correctly
 rsi.setCurrentRow(newRow);                        
 return null;
}

Friday, July 05, 2013

ADF MDS : Use MDS API to remove Customizations and/or merge Documents

import java.io.StringReader;


import java.io.StringWriter;

import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import oracle.adf.share.ADFContext;
import oracle.adf.share.config.UserCC;

import oracle.apps.fnd.applcore.log.AppsLogger;

import oracle.mds.config.CustConfig;
import oracle.mds.core.ConcurrentMOChangeException;
import oracle.mds.core.MDSInstance;
import oracle.mds.core.MDSSession;
import oracle.mds.core.MOReference;
import oracle.mds.core.MetadataNotFoundException;
import oracle.mds.core.MetadataObject;
import oracle.mds.core.RestrictedSession;
import oracle.mds.core.SessionOptions;
import oracle.mds.core.ValidationException;
import oracle.mds.core.ValidationType;
import oracle.mds.cust.CacheHint;
import oracle.mds.cust.CustClassList;
import oracle.mds.cust.CustomizationClass;
import oracle.mds.exception.UnsupportedUpdateException;
import oracle.mds.internal.query.NameQueryImpl;
import oracle.mds.naming.ReferenceException;
import oracle.mds.persistence.MDSIOException;
import oracle.mds.query.ConditionFactory;
import oracle.mds.query.QueryResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;


import org.xml.sax.InputSource;

public class MDSOperations {

    public MDSOperations() {
        super();
    }

    public void removeCustomizations() {
        MDSSession mdsReadSession =
            (MDSSession)ADFContext.getCurrent().getMDSSessionAsObject();
        MDSInstance mdsInstance =
            (MDSInstance)ADFContext.getCurrent().getMDSInstanceAsObject();
        MDSSession mdsWriteSession =
            mdsInstance.createSession(new SessionOptions(null, null,
                                                         CustConfig.NO_CUSTOMIZATIONS),
                                      null);
        String appUserFromDoc =
            ADFContext.getCurrent().getSecurityContext().getUserName();
        NameQueryImpl query =
            new NameQueryImpl(mdsReadSession, ConditionFactory.createNameCondition("/mypackage/mdssys/cust/User/"+appUserFromDoc,
                                                                                   "%ParamaterViewDef.xml.xml",
                                                                                   true));
        Iterator<QueryResult> result = query.execute();
        while (result.hasNext()) {
            try {
                QueryResult qr = result.next();
                String mdsDocFullName = qr.getAbsoluteName();
                String mdsDocName = qr.getResourceName().getLocalName();
                mdsReadSession.flushChanges(false,
                                             new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
             
                mdsReadSession.flushChanges(false,
                                             new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
             
                if (mdsDocFullName.startsWith("/mypackage/mdssys/cust/User/" +
                                              appUserFromDoc)) {
                 
                    String baseDocFilePath =
                        "/mypackage/" +
                        mdsDocName.substring(0, mdsDocName.lastIndexOf("."));
                 
                    CustomizationClass[] custClass =
                        new CustomizationClass[] { new MyUserCC("User",
                                                                 appUserFromDoc) };
                    CustClassList custCCList = new CustClassList(custClass);

                    MetadataObject mo11 =
                        mdsReadSession.getMetadataObject(baseDocFilePath,
                                                         custCCList, null);

                    Document mergedDoc = mo11.getDocument(true);
                    String mergedXMLStr = getXMLAsString(mergedDoc);                  

                    MOReference baseDocRef =
                        mdsWriteSession.getMOReference(baseDocFilePath);
                    MetadataObject baseMO =
                        mdsWriteSession.getMutableMO(baseDocRef);
                    Document baseDoc = baseMO.getDocument();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder;
                    builder = factory.newDocumentBuilder();
                    baseDoc = builder.parse(new InputSource(new StringReader(mergedXMLStr)));
                 
                    mdsWriteSession.deleteAllCustomizations(baseDocRef);
                    mdsWriteSession.deleteMetadataObject(baseDocRef);
                    mdsWriteSession.createMetadataObject(baseDocFilePath, baseDoc);

                    mdsWriteSession.flushChanges(false,
                                                 new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });

                 
                    MetadataObject baseMO1 =
                        mdsReadSession.getMetadataObject(baseDocFilePath);
                    baseDoc = baseMO1.getDocument();
                 
                    mdsWriteSession.deleteAllCustomizations(baseDocRef);
                    mdsWriteSession.flushChanges(false,
                                                 new ValidationType[] { ValidationType.RELATIONSHIP_VALIDATION });
                }
            } catch (MetadataNotFoundException mnfe) {
            } catch (UnsupportedUpdateException uue) {
            } catch (MDSIOException mdsioe) {
            } catch (ReferenceException re) {
            } catch (ConcurrentMOChangeException cmoce) {
            } catch (DOMException dome) {
            } catch (ValidationException ve) {
            } catch (Exception e) {
            }
        }
    }
 
    private static String getXMLAsString(Document document) throws Exception{
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        String xmlString = null;
        try {
            DOMSource source = new DOMSource(document);
            transformer.transform(source, result);
            xmlString = result.getWriter().toString();
         
        } catch (TransformerException te) {
        } catch (Exception e) {
             
        } finally {
            result.getWriter().close();
        }
        return xmlString;          
    }
}
/**
 *  Customization class for the User Layer only required at runtime.
 */
class MyUserCC extends UserCC {
    String layerName = "User";
    String layerValue = null;

    /**
     * Public Constructor
     */
    public MyUserCC() {
        super();
    }

    public MyUserCC(String layerName, String layerValue) {
        super();
        this.layerName = layerName;
        this.layerValue = layerValue;
    }

    /**
     * Getter method for CacheHint.
     * @return CacheHint.
     */
    public CacheHint getCacheHint() {
        return CacheHint.USER;
    }

    /**
     * Getter method for Name.
     * @return String Name
     */
    public String getName() {
        return "User";
    }

    /**
     * Getter method for value.
     * @param sess RestrictedSession
     * @param mo MetadataObject
     * @return String[] value.
     */
    public String[] getValue(RestrictedSession sess, MetadataObject mo) {
        return new String[] { this.layerValue };
    }

    /**
     * This method is used by level picker functionality to set the value for the level.
     *
     * @param value
     */
    public void setValue(String value) {
        // not required for constant value.
    }

}

Wednesday, May 08, 2013

WebApp-Collecting Page load time Statistics in Browser

window.performance.timing is a new DOM Object introduced by most of the new version of Browsers such as IE 8+, Safari 5+, Firefox 3.6+ & Chrome.

Here is a sample Code snippet which can be used in ADF JSPX/JSFF pages through a JavaScript function.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"></meta>
    <title>PageLoadStatsTestPage</title>
    <script  language="javascript">
        function processTiming()
        {
        var navTimeAvailable, performanceTiming;
        navTimeAvailable = window.performance || window.msPerformance || window.webkitPerformance || window.mozPerformance;
        if(navTimeAvailable && navTimeAvailable.timing && navTimeAvailable.navigation) {
            performanceTiming = window.performance.timing;
                        connectEnd = performanceTiming.connectEnd;
                        connectStart = performanceTiming.connectStart;
                        domComplete = performanceTiming.domComplete;
                        domContentLoadedEventEnd = performanceTiming.domContentLoadedEventStart;
                        domContentLoadedEventStart = performanceTiming.domContentLoadedEventStart;
                        domInteractive = performanceTiming.domInteractive;
                        domLoading  =   performanceTiming.domLoading;
                        domainLookupEnd =   performanceTiming.domainLookupEnd;
                        domainLookupStart   =   performanceTiming.domainLookupStart;
                        fetchStart  =   performanceTiming.fetchStart;
                        loadEventEnd    =   performanceTiming.unloadEventEnd;
                        loadEventStart  =   performanceTiming.unloadEventStart;
                        navigationStart =   performanceTiming.navigationStart;
                        redirectEnd =   performanceTiming.redirectEnd;
                        redirectStart   =   performanceTiming.redirectStart;
                        requestStart    =  performanceTiming.requestStart;
                        responseEnd =   performanceTiming.responseEnd;
                        responseStart   =   performanceTiming.responseStart;
                        secureConnectionStart   =   performanceTiming.secureConnectionStart;
                        unloadEventEnd  =   performanceTiming.unloadEventEnd;
                        unloadEventStart    =   performanceTiming.unloadEventStart;
                }

            var timeStats = "connectEnd="+connectEnd+"\n"+"connectStart="+connectStart+"\n"+"domComplete="+domComplete+"\n"+"domContentLoadedEventEnd="+domContentLoadedEventEnd+"\n"+
                            "domContentLoadedEventStart="+domContentLoadedEventStart+"\n"+"domInteractive="+domInteractive+"\n"+"domLoading="+domLoading+"\n"+"domainLookupEnd="+domainLookupEnd+"\n"+
                            "domainLookupStart="+domainLookupStart+"\n"+"fetchStart="+fetchStart+"\n"+"loadEventEnd="+loadEventEnd+"\n"+"loadEventStart="+loadEventStart+"\n"+
                            "navigationStart="+navigationStart+"\n"+"redirectEnd="+redirectEnd+"\n"+"redirectStart="+redirectStart+"\n"+"requestStart="+requestStart+"\n"+
                            "responseEnd="+responseEnd+"\n"+"responseStart="+responseStart+"\n"+"secureConnectionStart="+secureConnectionStart+"\n"+"unloadEventEnd="+unloadEventEnd+"\n"+
                            "unloadEventStart="+unloadEventStart+"\n"+
                            "";
            alert(timeStats);
        }
    </script>
  </head>
  <body onload="processTiming();"></body>
</html>

Sunday, March 24, 2013

WLST sample commands for MDS docs



  • $MW_HOME/oracle_common/common/bin/wlst.sh (AdminServer HostPort)
  • exportMetadata(application='',server='', toLocation='/tmp',  docs='/oracle/apps/atk/homePage/**') ;
  • deleteMetadata(application='',server='', docs='/oracle/apps/atk/homePage/fuse/**');


Monday, February 18, 2013

JDev..SSLException .. Certificate Error ... Hostname Verification

Sometimes, in JDEV, during development, when we access any HTTPS URL for some feature(e.g. Accessing a REST Webservice URL or accessing an SSL enabled URL using java.net.HttpURLConnection Object), we come  across

SSLException .. Certificate Error ... Hostname Verification

This is NOT any error, this is desired.

To solve this in JDEV(Note, in Standalone WLS, you need to run the KeyTool.exe from MW_HOME)

  • Tools->Preferences->Credentials
  • Credential Names  Dropdown->Select "HTTPS Credential"
  • In the field, "Client Trusted Certificate KeyStore", browse and give the full path to
  • $MW_HOME/jdk160_24/jre/lib/security/cacerts

Save and re-run the App(You need to restart Integrated server)

Thursday, December 13, 2012

ADF and Implicit Peristance with MDS


The RichClient API method "setDontPersist(String[] dontPersist)" will not persist only if  org.apache.myfaces.trinidad.CHANGE_PERSISTENCE param value in web.xml is 'oracle.adf.view.page.editor.change.ComposerChangeManager'.

With org.apache.myfaces.trinidad.CHANGE_PERSISTENCE  param value as 'oracle.adf.view.rich.change.MDSDocumentChangeManager'.

This method still persists the Attributes to MDS.

Monday, September 24, 2012

ADF: Preventing user actions on UI when a process is running

There are often requirements when we want users not to click here and there on a JSFF page, when an important process is running.

ADF out of the box provides a way to achieve the same


af:resource type="JavaScript"
                  function preventOperation(event){
                      event.preventUserInput();
                  }

Use this JS method in the clientListener of your UI components on which you want Users to prevent clicking.

CSS: Gradient class for all browsers


@agent ie{

  .application-container {
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000');
  }
}

@agent webkit{
  .application-container {
    background-image: -webkit-gradient(linear, left top, left bottom, from(RED), to(GREEN)); /* for webkit browsers */
  }
}

@agent gecko{
  .application-container {
    background-image: -moz-linear-gradient(top,  YELLOW,  BLUE); /* for firefox 3.6+ */
  }
}

MDS ChangeManager code for af:carousel

When your ADF application is MDS enabled,you may see the MDS persistence behaviour across user sessions.
Here is a piece of code to avoid the same.


    public void spinEvent(CarouselSpinEvent carouselSpinEvent) {

        // Add event code here...
        try {
            ChangeManager cm =
                RequestContext.getCurrentInstance().getChangeManager();
            System.out.println(this.getCarouselComp().getCurrentItemKey().getClass());
            ComponentChange change =
                new AttributeComponentChange("currentItemKey", null);
            if (cm != null)
                cm.addComponentChange(FacesContext.getCurrentInstance(),
                                      getCarouselComp(), change);
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }      
    }

JSTL:Print Java List Size in JSFF

#{fn:length(DemoBean.testList)}

Tuesday, September 11, 2012

Execute an expensive VO Iterator after page Load happens(using af:poll)-1

We may have scenario where we want the ADF Page to be loaded as soon as possible without waiting for all the PageDef iterators to be executed, hence reducing the page load time.

A possible solution is using a polling component.When the page loads, the UI component with the expensive SQL wont get rendered.After the page loads, the af:poll gets fired after (t) time, say 5 seconds, execute the VO Iterator and make the UI component "visible= true".

Here are the code snippets we need to use

Page.jsff


    <af:panelBox text="Announcements" id="pb1">

        <f:facet name="toolbar">
            <af:poll id="p1" interval="5000"
                     pollListener="#{DemoBean.refreshAnnouncements}"/>
        </f:facet>
        <af:panelFormLayout id="pfl1" partialTriggers="p1" visible="false"
                            binding="#{DemoBean.announcementForm}">
            <af:panelLabelAndMessage label="#{bindings.Subject.hints.label}"
                                     id="plam2">
                <af:outputText value="#{bindings.Subject.inputValue}" id="ot2"/>
            </af:panelLabelAndMessage>
            <af:panelLabelAndMessage label="#{bindings.Description.hints.label}"
                                     id="plam1">
                <af:outputText value="#{bindings.Description.inputValue}"
                               id="ot1"/>
            </af:panelLabelAndMessage>
            <f:facet name="footer">
                <af:panelGroupLayout layout="horizontal" id="pgl1">
                    <af:commandButton actionListener="#{bindings.Previous.execute}"
                                      text="Previous"
                                      partialSubmit="true" id="cb2"/>
                    <af:commandButton actionListener="#{bindings.Next.execute}"
                                      text="Next"
                                      partialSubmit="true" id="cb1"/>
                </af:panelGroupLayout>
            </f:facet>
        </af:panelFormLayout>
    </af:panelBox>

PageDef.xml(Note the refresh property of iterator = never, so that on page load, the SQL doesnt get executed)

    <iterator Binds="AtkHpAnnouncementsVO1" RangeSize="25"
              DataControl="AnnouncementAMDataControl"
              id="AtkHpAnnouncementsVO1Iterator" ChangeEventPolicy="ppr"
              Refresh="never"/>

ManagedBean code for af:poll pollListener code

import oracle.adf.model.BindingContext;


import oracle.adf.view.rich.component.rich.RichPoll;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;

import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.BindingContainer;

import oracle.binding.OperationBinding;

import org.apache.myfaces.trinidad.event.PollEvent;

public class DemoBean {
    private RichPanelFormLayout announcementForm;

    public DemoBean() {
    }

    public void refreshAnnouncements(PollEvent pollEvent) {
        // Add event code here...
         BindingContainer bindings =   BindingContext.getCurrent().getCurrentBindingsEntry();
         OperationBinding operationBinding = bindings.getOperationBinding("Execute");
         Object result = operationBinding.execute();  
         System.out.println(result);
         this.getAnnouncementForm().setVisible(true);
         AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAnnouncementForm());
         RichPoll pollComp = (RichPoll)pollEvent.getComponent();
         pollComp.setInterval(-1);//Disable the polling now
         AdfFacesContext.getCurrentInstance().addPartialTarget(pollComp);
    }

    public void setAnnouncementForm(RichPanelFormLayout announcementForm) {
        this.announcementForm = announcementForm;
    }

    public RichPanelFormLayout getAnnouncementForm() {
        return announcementForm;
    }
}

Monday, September 03, 2012

SharedAM Examples

SharedAM VOs can be refreshed using 2 mechanisms.

DataBase Change Notification

SharedAM test(DB Change Notification=>AutoRefresh = true)
  • Make Default AM configuration to Shared
  • grant change notification to fusion
  • Model->Project properties->ApplicationModeul->Shuttle to Application Level
  • For the Shared VO autorefresh=true
  • Create a ViewAccessor of the SharedVO and expose in Client Interface
  • From DataControl Pallete, use 
<af:forEach items="#{bindings.return.attributeDefs}" var="def">
            <af:column headerText="#{bindings.return.labels[def.name]}"
                       sortable="true" sortProperty="#{def.name}" id="c1">
              <af:outputText value="#{row[def.name]}" id="ot1"/>
            </af:column>


  • In DataBindings.cpx->AM DatAControl->Use Configuration=Shared
  • For the VA Iterator in pagedef, set ChangeEventPolicy=ppr

TimeOut Feature for refreshing the Query Collection

  • jbo.ampool.timetolive="86400000" jbo.qcpool.maxinactiveage="86400000"
Maintains the SharedAM VO cache for 24 hours and then invalidates.

Tuesday, June 26, 2012

Applying multiple VCs to a ViewObject


  1. EmployeesVO.
  2. Two Design Time VCs
  3. findByName->( (UPPER(Employees.FIRST_NAME) LIKE UPPER('%' || :bName || '%') ) )
  4. findByEmail -> ( (UPPER(Employees.Email) LIKE UPPER('%' || :bEmail || '%') ) )
  5. Apply these 2 VCs programmatically with an AND Condition.




    public void applyMultipleVCs(String bName, String bEmail) {
        ViewObjectImpl viewObj = getEmployeesVO1();
        if (viewObj != null) {
            ViewCriteria vc =
                viewObj.getViewCriteria("findByName");
            viewObj.setNamedWhereClauseParam("bName", bName);
            ViewCriteria vc1 =
                viewObj.getViewCriteria("findByEmail");
            viewObj.setNamedWhereClauseParam("bEmail", bEmail);
            viewObj.applyViewCriteria(vc,true);
            viewObj.executeQuery();
           
            viewObj.applyViewCriteria(vc1,true);
            viewObj.executeQuery();
            viewObj.removeApplyViewCriteriaName("findByName");
            viewObj.removeApplyViewCriteriaName("findByEmail");
            viewObj.setRangeSize(-1);
            Row[] allRows = viewObj.getAllRowsInRange();
            for(Row row : allRows){
                String firstName = (String)row.getAttribute("FirstName");
                String email = (String)row.getAttribute("Email");
                System.err.println("-->"+firstName+"        ---->"+email);
            }
               
        }
    }

Tuesday, February 28, 2012

ADF:Deleting MDS document


        MDSInstance mdsi =  (MDSInstance)ADFContext.getCurrent().getMDSInstanceAsObject();
        MDSSession mdss = (MDSSession)ADFContext.getCurrent().getMDSSessionAsObject();
        MetadataObject mo;
        try {
            mo = mdss.getMetadataObject("/sessiondef/oracle/apps/atk/ess/MyJobDefintion6AtkEssParamaterViewDef.xml");
            MOReference mr = mo.getReference();
            mdss.deleteMetadataObject(mr);
        } catch (Exception e) {
            e.printStackTrace();
        } 

Wednesday, November 30, 2011

JSON-P an example

Say, you have an HTML page in 1 domain and a servlet running in another domain.
For cross domain communication from your HTML and Servlet you can take advantage of the JSONP.

HTML File in Server 1



<html>
  <head>
    <script type="text/javascript">
      function callTheJsonp() {
          // the url of the script where we send the asynchronous call
          //var url = "http://rws65594fwks.us.oracle.com:7001/GoogleAppInsideFireWall/osmservlet?callback=parseRequest";
          var currentPageURL = document.location.href;
          alert(currentPageURL);
          var url = "http://127.0.0.1:7101/GoogleAppInsideFireWall/osmservlet?callback=parseRequest&calledPageUrl="+currentPageURL;//For My JDev testing
          // create a new script element
          var script = document.createElement('script');
          // set the src attribute to that url
          script.setAttribute('src', url);
          // insert the script in out page
          document.getElementsByTagName('head')[0].appendChild(script);
      }

      // this function should parse responses.. you can do anything you need..
      // you can make it general so it would parse all the responses the page receives based on a response field
      function parseRequest(response) {
          try // try to output this to the javascript console
          {
              alert('in callback--Response from OSM ');
              //console.log(response);
              alert('product id ' + response.itemId + ': quantity = ' + response.quantity + ' & price = ' + response.price);
          }
          catch (an_exception)// alert for the users that don't have a javascript console
          {
              alert('product id ' + response.itemId + ': quantity = ' + response.quantity + ' & price = ' + response.price);
          }
      }
    </script>
  </head>
  <body>
    <form>
      <p>
        <b>AMulya Mishra Test-&gt;</b>
         is a simulation of Buzzient UI hosted in 
        <b>Google Apps</b>.Clicking this button will invoke Ravi's WLS ADF App
                          which is inside Oracle Firewall.
      </p>
      <p>Access this page without VPN or without Proxy.. Before clicking this
         button, set proxy or connect to VPN and click to access the ADF App
         running in Ravi's WLS.</p>
      <p>
        1)-See the java script code written in this HTML using view source.<br>
        2)-Clicking 'Create Service Request' button calls a JavaScript method called callTheJsonp().<br>
        3)-Here we add a dynamic script tag with attribute src pointing to a servlet in different WLS.<br>
        4)-The servlet has a method to generate a JSON object and send it back as response to This page.<br>
        5)-Then it invokes function parseRequest(response) which takes this JSON object and prints in javascript console.<br>
      </p>
      <input type="button" name="Create Fusion Apps Service Request"
             value="Create Fusion Apps Service Request"
             onclick="callTheJsonp();"/>
          </form>
  </body>
</html>



Servlet code in Server 2


package view.oracle.apps.atf.osm.hadoopTest;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Map;

import java.util.Random;

import javax.servlet.*;
import javax.servlet.http.*;

import oracle.apps.OSMPojo;

public class OSMServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        System.out.println("--->Here in GET");
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        Map params = request.getParameterMap(); 
        if(params != null && params.containsKey("callback")){
            String jsonData = this.getJSONData();
            String output = request.getParameter("callback") + "(" + jsonData + ");";
            out.println(output);
        }
        out.close();
    }

    private String getJSONData() {
        Gson gson = new Gson();
        OSMPojo pojo = new OSMPojo();
        pojo.setItemId(new Long(new Random().nextLong()).toString());
        pojo.setPrice(new Long(new Random().nextLong()).toString());
        pojo.setQuantity(new Long(new Random().nextLong()).toString());
        String json = gson.toJson(pojo);
        return json;
    }    
}

Thursday, November 24, 2011

Creating your first J2EE Google App and Host in Google Apps Engine.

This is for people who just want to know how to build an app and upload to Google Apps Engine so that you dont have to worry about Server and Hosting mechanism.

If you have an J2EE WebApp and you want to host it in Google Apps Engine, here are the steps.
Assumption, you have a Google/GMAIL account.

Step 1: Go to https://appengine.google.com/ and create a new application.
If you have never used App Engine before, you might be asked to verify your mobile phone number before you can create a new app.

Step 2: Give your application a name – it should be unique and may only include lowercase alphabets and digits.
For this example, our app identifier is “amulsmmtest”. (http://amulsmmtest.appspot.com)
Application Title-> SMM Test For ATK -AMulya

Step3: http://code.google.com/appengine/downloads.html
Download appengine-java-sdk-1.6.0.zip
Unzip to a dir called D:\Downloads\appengine-java-sdk-1.6.0\appengine-java-sdk-1.6.0\

Step4:Create an J2EE WebApp having a servlet/jsp/HTML.
Step5:In the WebApp,under WEB-INF dir(where web.xml resides),create a new XML file called appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>amulsmmtest</application>
<version>1</version>
</appengine-web-app>


Step6:From JDeveloper, right click and deploy the War file to a directory, say D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp.war

Step7: Unzip this war to D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp

Step8:You are done now to upload the App to Google Apps Engine, to your own domain, you have created in Step2.

Step9: Go to your Command Prompt and make sure, your %JAVA_HOME%/bin is in classpath
Step10:
Execute the following Java command to upload the WebApp

D:\Downloads\appengine-java-sdk-1.6.0\appengine-java-sdk-1.6.0\bin\appcfg.cmd -p www-proxy.uk.oracle.com:80 update D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp


Thats it, now access the HTML page in your webapp using this URL
http://amulsmmtest.appspot.com/GoogleAppMainPage.html

Where amulsmmtest.appspot.com is your domain and GoogleAppMainPage.html is the HTML page inside your webapp's WEB-INF dir.

Thursday, November 17, 2011

Viewing SOAPMessage in console

Add -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true

Saturday, November 12, 2011

Invoking Secured Webservice client proxy code

Few setups needed to be done in WLS domain, to enable GPA.
Securing a Webservice producer
Save the below file in name gpa.py under $MW_HOME/oracle_common/common/bin

connect('weblogic','weblogic1','t3://localhost:7101')
beginRepositorySession()
createPolicySet('default-domain-ws-DefaultDomain','ws-service','Domain("*")')
attachPolicySetPolicy('oracle/wss_saml_or_username_token_service_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-client-DefaultDomain','ws-client','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-connection-DefaultDomain','ws-connection','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-callback-DefaultDomain','ws-callback','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('soa-domain-sca-reference-fusion_domain','sca-reference','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('soa-domain-sca-service-fusion_domain','sca-service','Domain("*")')
attachPolicySetPolicy('oracle/wss_saml_or_username_token_service_policy')
validatePolicySet()
commitRepositorySession()


Execute this gpa.py

$MW_HOME/oracle_common/common/bin/wlst.sh gpa.py


$MW_HOME/oracle_common/common/bin/wlst.sh
connect('weblogic','weblogic1','t3://localhost:7101')
createCred(map="oracle.wsm.security", key="keystore-csf-key", user="owsm", password="welcome1", desc="Keystore key")
createCred(map="oracle.wsm.security", key="enc-csf-key", user="orakey", password="welcome1", desc="Encryption key")
createCred(map="oracle.wsm.security", key="sign-csf-key", user="orakey", password="welcome1", desc="Signing key")
createCred(map="oracle.wsm.security", key="basic.credentials", user="weblogic", password="weblogic1", desc="User")


Assumming the Webservice producer App name is "ProducerApp"

$MW_HOME/oracle_common/common/bin/wlst.sh
connect('weblogic','weblogic1','t3://localhost:7101')
grantPermission(codeBaseURL="file:${common.components.home}/modules/oracle.wsm.agent.common_11.1.1/wsm-agent-core.jar",permClass="oracle.wsm.security.WSIdentityPermission",permTarget="resource=ProducerApp",permActions="assert")


Configuration from Client Side
create the Webservice client.(OSMGateWayAMService_Service)
2)-Add the policy "policy:oracle/wss10_saml_token_client_policy" to this client.
3)-Then , they have to create the ProxyClient,i.e oSMGateWayProxy

ProducerService_Service producer_Service =
new ProducerService_Service(new URL(wsdlUrl),
new QName(producer
producer));
SecurityPolicyFeature[] securityFeature = new SecurityPolicyFeature[] { new SecurityPolicyFeature("policy:oracle/wss10_saml_token_client_policy")};
ProducerService producerServiceProxy = producer_Service.getProducerServiceHttpPort(securityFeature);

5)-If you WONT attach this Client Policy, then while invocation, you get "SAML Indentity Assertion Error".

Thursday, September 29, 2011

WebLogic WorkManager for Multi-threading

WebLogic's WorkManager provides a self-tuned ThreadPool to enable Multi-Threading.

Define a WorkManager either in WLS console or in web.xml as below.

<resource-ref>
<res-ref-name>wm/MyWorkManager</res-ref-name>
<res-type>commonj.work.WorkManager</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>


In weblogic-application.xml, you can configure the ThreadPool Size

  <work-manager>
<name>wm/MyWorkManager</name>
<max-threads-constraint>
<name>a</name>
<count>5</count>
</max-threads-constraint>
</work-manager>
<work-manager>


Java Code

        try {
InitialContext ic = new InitialContext();
WorkManager workManager = (WorkManager)ic.lookup("java:comp/env/wm/MyWorkManager");
List workItemList=new ArrayList();

for(int i=0;i<10;i++){
WorkItem workItem1 = startWorkItem(my,i,"OSMM");
workItemList.add(workItem1);
}



//run the work items in parallel; don't wait
//workManager.waitForAll(workItemList, WorkManager.IMMEDIATE);


    public WorkItem startWorkItem(WorkManager workManager, final int count, final String wmName) throws Exception{
WorkItem workItem10 = workManager.schedule(new Work() {
public void run() {
try {
System.out.println("Current Count ["+count+"] : wmName ["+wmName+"]ThreadName Is: "+Thread.currentThread().getName()+"##Priroty="+Thread.currentThread().getPriority());
} catch (Exception e) {
e.printStackTrace();
}
}

public void release() {
}

public boolean isDaemon() {
return false;
}
}); //End of Schedule
return workItem10;

}

PLSQL:Encryption Decryption DBMS_CRYPTO

set serveroutput on

DECLARE
LC$Source VARCHAR2(19) := 'Music is the best!';
LR$Source RAW(128) := utl_raw.cast_to_raw(LC$Source);
LR$Key RAW(128) := utl_raw.cast_to_raw('FrankZappa');
LR$Crypted RAW(2048);
LR$Decrypted RAW(2048);

BEGIN

dbms_output.put_line('Source string : ' || LC$Source);

LR$Crypted := dbms_crypto.encrypt(LR$Source,
dbms_crypto.des_cbc_pkcs5, LR$Key);

dbms_output.put_line('Encrypted raw : ' ||
RAWTOHEX(utl_raw.cast_to_raw(LR$Crypted)));

LR$Decrypted := dbms_crypto.decrypt(src => LR$Crypted,
typ => dbms_crypto.des_cbc_pkcs5, key => LR$Key);

dbms_output.put_line('Decrypted string : ' ||
utl_raw.cast_to_varchar2(LR$Decrypted));
END;
/

Tuesday, August 02, 2011

Raising Business Event from AMImpl

ADFbc EO gives a declarative way of raising Business Event.But in cases, when you need the Business Events to be raised from somewhere else than EO, how will you do.

Libraries needed

  • Add SOA Runtime Lib to the JPR.
  • Make sure, you have "oracle.soa.workflow.wc" lib deployed and targeted to DefaultServer in your WLS.
  • Add below Lib Reference to the weblogic-application.xml file
<library-ref>
<library-name>oracle.soa.workflow.wc</library-name>
</library-ref>




DataSource Configuration

Business Event internally uses Oracle AQ.It needs the "ENDSource" or "EDNDataSource" to be configured in WLS.

Diagnostic messages which comes from Business Event classes are as below(If you dont setup the Above Data Source)

INFO: Looking for BusinessEventConnectionFactory
INFO: Looking for EDN-DB JNDI configuration to create SAQRemoteBusinessEventConnectionFactory.
INFO: Unable to create SAQRemoteBusinessEventConnectionFactory: [jdbc/EDNSource or jdbc/EDNDataSource] undefined.
INFO: Looking for EDN-JMS JNDI configuration to create JMSRemoteBusinessEventConnectionFactory.
INFO: Unable to create JMSRemoteBusinessEventConnectionFactory: [java:comp/UserTransaction] undefined.
INFO: Unable to create JMSRemoteBusinessEventConnectionFactory: [jms/fabric/EDNConnectionFactory] undefined.
INFO: Failed to get ConnectionFactory instance.

Verifying the PayLoad gets Saved to the DB after you publish the event

Once you publish the event, the data goes into the AQ table called "AQ$EDN_EVENT_QUEUE_TABLE" which is inside schema "soa_infra/soa_infra".

  • From ADF App, raise a Business Event
  • connect to your DB as soa_infra/soa_infra
  • select * from AQ$EDN_EVENT_QUEUE_TABLE
  • You can see the row gets populated
  • AQ$EDN_EVENT_QUEUE_TABLE.USER_DATA EDN_EVENT_DATA()
    desc EDN_EVENT_DATA
    user type definition
    -----------------------------------
    type edn_event_data as object (
    event edn_business_event,
    publish_impl char,
    subject_info varchar2(256),
    target varchar2(1024));

Sample Java Code

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import oracle.fabric.blocks.event.BusinessEventConnection;
import oracle.fabric.blocks.event.BusinessEventConnectionFactory;

import oracle.fabric.blocks.event.BusinessEventSubscriptionManager;

import oracle.fabric.common.BusinessEvent;

import oracle.integration.platform.blocks.event.BusinessEventBuilder;
import oracle.integration.platform.blocks.event.BusinessEventConnectionFactorySupport;

import oracle.integration.platform.blocks.event.EDNFacadeImpl;
import oracle.integration.platform.blocks.event.SubscriptionInfo;

import oracle.soa.management.facade.LocatorFactory;
import oracle.soa.management.internal.facade.edn.Event;
import oracle.soa.management.internal.facade.edn.Subscription;

import oracle.xml.parser.v2.XMLDocument;

import org.w3c.dom.Element;

    private static final String eventName = MyNotification;
private static final String eventNamespace = "http://schemas.oracle.com/events/edl/EventDefinition";
private static final String schemaNamespace = "http://xmlns.oracle.com/events/edl/EventDefinition";
public void raiseBusinessEvent() {
try {
// Get event connection, make sure the following entry exists in weblogic-application.xml
/*
*
*
oracle.soa.workflow.wc

*/
BusinessEventConnectionFactory cf =
BusinessEventConnectionFactorySupport.findRelevantBusinessEventConnectionFactory(true);

if (cf != null) {
BusinessEventConnection conn =
cf.createBusinessEventConnection();

// Build event
BusinessEventBuilder builder =
BusinessEventBuilder.newInstance();

// Specify the event name and namespace. In this prototype, they are constants, eventNamespace, eventName
builder.setEventName(new QName(eventNamespace, eventName));

// Specify the event payload. In this prototype, the getXMLPayload custom method constructs the payload

builder.setBody(getXMLPayload().getDocumentElement());
BusinessEvent event = builder.createEvent();

// Publish event
conn.publishEvent(event, 5);
conn.close();

// Event was sent sucessfully;
} else {
// For debug only
//cf is null
}
} catch (Exception exp) {
// For debug only
// Failed sending event: " + exp.getMessage();
exp.printStackTrace();
}
}

private XMLDocument getXMLPayload() {
Element masterElem, childElem1, childElem2, childElem3, childElem4, childElem5;
XMLDocument document = new XMLDocument();

String userName = "row.getUsername()";

masterElem =
document.createElementNS(schemaNamespace, "MyNotification");
document.appendChild(masterElem);

childElem1 = document.createElementNS(schemaNamespace, "userName");
childElem1.appendChild(document.createTextNode(userName));
masterElem.appendChild(childElem1);

childElem2 =
document.createElementNS(schemaNamespace, "distBudgetIssueVal");

childElem2.appendChild(document.createTextNode("getPublishRecallVal"));
masterElem.appendChild(childElem2);

childElem3 = document.createElementNS(schemaNamespace, "comment");

childElem3.appendChild(document.createTextNode("getNotificationComment()"));
masterElem.appendChild(childElem3);

childElem4 =
document.createElementNS(schemaNamespace, "moduleIdentifier");

childElem4.appendChild(document.createTextNode("BudgetNotification"));
masterElem.appendChild(childElem4);

return document;
}

Wednesday, July 27, 2011

Manipulating MDS Customizations In Java

In ADF,we have various Customization layers such as RolesCC,SiteCC,UserCC etc defined in adf-config.xml.This decides in which TIP layer the customization would go.

      <cust-config>
<match path="/">
<customization-class name="oracle.adf.share.config.SiteCC"/>
<customization-class name="oracle.adf.share.config.ADFRolesCC"/>
<customization-class name="oracle.adf.share.config.ADFUserCC"/>
</match>
</cust-config>


But there are scenarios, when we want a particular customization should be in base only, not specific to any TIP layer.

Here is how you can achieve the same.This example is to apply NO_CUSTOMIZATIONS at runtime.

Create a class that implements oracle.adf.share.mds.SessionOptionsFactory interface.
import java.util.List;

import oracle.adf.share.ADFContext;
import oracle.adf.share.mds.SessionOptionsFactory;

import oracle.mds.config.CustClassListMapping;
import oracle.mds.config.CustConfig;
import oracle.mds.config.MDSConfigurationException;
import oracle.mds.core.MDSInstance;
import oracle.mds.core.SessionOptions;
import oracle.mds.cust.CustClassList;
import oracle.mds.cust.CustomizationClass;
import oracle.mds.exception.InvalidNamespaceException;
import oracle.mds.naming.InvalidReferenceException;
import oracle.mds.naming.InvalidReferenceTypeException;
import oracle.mds.naming.Namespace;
import oracle.mds.naming.NamespaceRestriction;
import oracle.mds.naming.PackageName;
import oracle.mds.persistence.PManager;
import oracle.mds.sandbox.IncompatibleSandboxException;
import oracle.mds.sandbox.SandboxHelper;
import oracle.mds.sandbox.SandboxNotFoundException;
import oracle.mds.sandbox.SandboxNotSupportedException;
import oracle.mds.sandbox.SandboxUsage;
import oracle.mds.versioning.LabelNotFoundException;
import oracle.mds.versioning.MultipleLabelsException;
import oracle.mds.versioning.VersionContext;
import oracle.mds.versioning.VersioningNotSupportedException;

/**
* A factory that subtitute the <code>CustConfig</code> object with
* <code>CustConfig.NO_CUSTOMIZATIONS</code> in the default
* <code>SessionOptions</code> object.
*/
public class MyADFSessionOptionsFactory implements SessionOptionsFactory
{

/**
* Gets the instance of the factory for creating base documents.
*
* @return the instance of the factory for creating base documents
*/
public static ModelerSessionOptionsFactory getBaseInstance()
{
return _INSTANCE;
}

private static final ModelerSessionOptionsFactory _INSTANCE =
new ModelerSessionOptionsFactory(CustConfig.NO_CUSTOMIZATIONS, null);
}


Use this class in your AMImpl or somewhere the session starts

    ConfigUtils.setSessionOptionsFactory(_currentContext,
ModelerSessionOptionsFactory.getBaseInstance());

Tuesday, July 26, 2011

Creating a ViewDef Programmatically

Make sure you have an adf-config.xml entry as below, where the ViewDef XML file will be persisted in MDS.

          <mds:namespace metadata-store-usage="globalStore-by-adfconfigfilter"
path="/sessiondef"/>

<mds:metadata-store-usage default-cust-store="true"
deploy-target="true"
id="globalStore-by-adfconfigfilter">
<mds:metadata-store class-name="oracle.mds.persistence.stores.db.DBMetadataStore">
<mds:property value="mds-ApplicationMDSDB"
name="repository-name"/>
<mds:property value="FAGlobal" name="partition-name"/>
<mds:property value="jdbc/mds/mds-ApplicationMDSDBDS"
name="jndi-datasource"/>
</mds:metadata-store>
</mds:metadata-store-usage>



Java Code
    public String writeSessionDefViewDefintion(){
String PACKAGE_NAME = "oracle.apps.atk.ess";
String voName = "MyViewName";
String viewDefFullName = "sessiondef."+PACKAGE_NAME+"."+voName+"MyViewDef";

ViewDefImpl viewDef = new ViewDefImpl(ViewDefImpl.DEF_SCOPE_SESSION,
voName + "MyViewDef");
viewDef.setFullName(viewDef.getBasePackage() + "." + PACKAGE_NAME +
"." + viewDef.getName());*/

AttributeDefImpl attrDef = viewDef.addViewAttribute("id", null, java.sql.Date.class);

Calendar cal = Calendar.getInstance();

// set Date portion to January 1, 1970
cal.set(cal.YEAR, 2011);
cal.set(cal.MONTH, cal.JULY);
cal.set(cal.DATE, 21);

cal.set(cal.HOUR_OF_DAY, 0);
cal.set(cal.MINUTE, 0);
cal.set(cal.SECOND, 0);
cal.set(cal.MILLISECOND, 0);

java.sql.Date defaultDate = new java.sql.Date(cal.getTime().getTime());
attrDef.setDefaultValue(defaultDate);
attrDef.setProperty(AttributeDefImpl.FMT_FORMAT,"MM-dd-yyyy");
attrDef.setProperty(AttributeDefImpl.FMT_FORMATTER,"oracle.jbo.format.DefaultDateFormatter");


// viewDef.setFullSql(true);
viewDef.resolveDefObject();
viewDef.registerDefObject();
viewDef.writeXMLContents();
viewDef.saveXMLContents();
viewDef.setDirty(true);
String viewInstanceName ="MyViewName" + "MyViewDef";
ViewObject dynamicVO =
this.findViewObject(viewInstanceName);

if (dynamicVO != null) {
dynamicVO.remove();
}
dynamicVO = createViewObject(viewInstanceName, viewDefFullName);
String VOName = dynamicVO.getDefFullName();
System.out.println("###VOName="+VOName);
this.setEssParamVOName(VOName);
return VOName;
}

Monday, July 25, 2011

Deriving and Binding WSLD URL at runtime for ADF Application

There are scenario when developers tend to use an exposed WSDL URL and consume it in their ADF Application.
Say, developer is trying to generate Java client proxy classes and use them to build the Application by invoking the Webservice methods.

When you generate the proxies, the WSDL URL gets hardcoded in the Service.java class.
Something like this
        wsdlLocationURL =
SMMPostCrawlerService_Service.class.getResource("http://10.176.87.233:7101/app/CrawlerServicePort?WSDL");



When you deploy the application or the Webservice deployment changes from server to server, then its hard to change in the java class, then redeploy the Ear altogether.

A simple solution IMO is,
  • Define a WSDL URL Connection in connections.xml.("MyWSDLConnection")
  • In your Client Proxy,read this WSDL URL Connection from connections.xml programmatically and use Bindingprovider to bind the URL at runtime to your proxy.
Connections.xml entry
   <Reference name="MyWSDLConnection" className="oracle.adf.model.connection.url.HttpURLConnection" xmlns="">
<Factory className="oracle.adf.model.connection.url.URLConnectionFactory"/>
<RefAddresses>
<XmlRefAddr addrType="MyWSDLConnection">
<Contents>
<urlconnection name="MyWSDLConnection" url="http://myServer:7002/app/CrawlerServicePort?WSDL"/>
</Contents>
</XmlRefAddr>
</RefAddresses>
</Reference>



This eliminates the changes to the java class and avoids redeployment.

    public String readURLFromConnectionsXML() {
String wsdlURL = null;
try {
URLConnectionProxy wsConnection =
(URLConnectionProxy)ADFContext.getCurrent().getConnectionsContext().lookup("MyWSDLConnection");
wsdlURL= wsConnection.getURL().toExternalForm();
} catch (Exception e) {
e.printStackTrace();
}
return wsdlURL;
}



Use this WSDL URL to bind at runtime to your Webservice java client proxy code.
In your ServicePortClient.java class

  @WebServiceRef
private static CrawlerService_Service crawlerService_Service;

public static void main(String [] args)
{

crawlerService_Service = new CrawlerService_Service();
CrawlerService_Service crawlerService_Service = crawlerService_Service.getCrawlerServicePort();


BindingProvider bp = (BindingProvider)sMMPostCrawlerService;
String CrawlerServiceWSDL = readURLFromConnectionsXML();
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, CrawlerServiceWSDL);
}

Oracle AQ programmatic Solution(Example)

This article demonstrates a Sample Oracle AQJMS program to send & receive Object Messages between two Clients.

Setups Needed in DataBase side

Grant AQ Permission to the DB Schema User.(Say HR)
connect system/manager as sysdba;

grant aq_administrator_role to <schema>;
grant execute on dbms_aqadm to <schema>;
grant execute on dbms_aq to <schema>;
grant execute on dbms_aqin to <schema>;
grant execute on dbms_aqjms to <schema>;


Database Objects Needed to be created(Comments are self Explanatory)

We need to create an AQ Table,AQ Queue and Start the Queue(s)

set serveroutput on

declare
begin
dbms_aqadm.stop_queue(queue_name => 'SMM_AQ_FACEBOOK_Q');
dbms_aqadm.stop_queue(queue_name => 'SMM_AQ_TWITTER_Q');
dbms_aqadm.stop_queue(queue_name => 'SMM_AQ_RSS_Q');
dbms_aqadm.drop_queue(queue_name => 'SMM_AQ_FACEBOOK_Q');
dbms_aqadm.drop_queue(queue_name => 'SMM_AQ_TWITTER_Q');
dbms_aqadm.drop_queue(queue_name => 'SMM_AQ_RSS_Q');
dbms_aqadm.drop_queue_table(queue_table => 'SMM_AQ_QT');
exception
WHEN OTHERS THEN
dbms_output.put_line (SQLCODE||' Drop Queue Objects ' || SUBSTR(SQLERRM, 1, 256));
END;
/

set serveroutput on
DECLARE
BEGIN
dbms_output.put_line ('Creating Queue Table SMM_AQ_QT.');
dbms_aqadm.CREATE_queue_table( queue_table => 'SMM_AQ_QT', queue_payload_type => 'SYS.AQ$_JMS_OBJECT_MESSAGE', sort_list=> 'ENQ_TIME,PRIORITY', multiple_consumers => FALSE, message_grouping=> DBMS_AQADM.NONE, primary_instance=> '0', secondary_instance=> '0', COMMENT => 'Creating Queue Table SMM_AQ_RSS_QT');
dbms_output.put_line ('Created Queue Table SMM_AQ_QT.');


EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line (SQLCODE||' Create Queue Table ' || SUBSTR(SQLERRM, 1, 256));
END;
/



DECLARE
BEGIN
dbms_output.put_line ('Creating Queue SMM_AQ_RSS_Q...');
dbms_aqadm.CREATE_queue( queue_name => 'SMM_AQ_RSS_Q', queue_table => 'SMM_AQ_QT', queue_type=> DBMS_AQADM.NORMAL_QUEUE, max_retries=> '5', retry_delay=> '0', retention_time=> '0', COMMENT => 'Resource Registration Queue');
dbms_output.put_line ('Created Queue SMM_AQ_RSS_Q.');

dbms_output.put_line ('Creating Queue SMM_AQ_FACEBOOK_Q...');
dbms_aqadm.CREATE_queue( queue_name => 'SMM_AQ_FACEBOOK_Q', queue_table => 'SMM_AQ_QT', queue_type=> DBMS_AQADM.NORMAL_QUEUE, max_retries=> '5', retry_delay=> '0', retention_time=> '0', COMMENT => 'Resource Registration Queue');
dbms_output.put_line ('Created Queue SMM_AQ_FACEBOOK_Q.');

dbms_output.put_line ('Creating Queue SMM_AQ_TWITTER_Q...');
dbms_aqadm.CREATE_queue( queue_name => 'SMM_AQ_TWITTER_Q', queue_table => 'SMM_AQ_QT', queue_type=> DBMS_AQADM.NORMAL_QUEUE, max_retries=> '5', retry_delay=> '0', retention_time=> '0', COMMENT => 'Resource Registration Queue');
dbms_output.put_line ('Created Queue SMM_AQ_TWITTER_Q.');


EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLCODE|| ' Create Queue ' || SUBSTR(SQLERRM, 1, 256));
END;
/


DECLARE
BEGIN
dbms_output.put_line('starting queue SMM_AQ_RSS_Q...');
dbms_aqadm.start_queue( queue_name => 'SMM_AQ_RSS_Q');
dbms_output.put_line ('Started Queue SMM_AQ_RSS_Q.');

dbms_output.put_line('starting queue SMM_AQ_FACEBOOK_Q...');
dbms_aqadm.start_queue( queue_name => 'SMM_AQ_FACEBOOK_Q');
dbms_output.put_line ('Started Queue SMM_AQ_FACEBOOK_Q.');

dbms_output.put_line('starting queue SMM_AQ_TWITTER_Q...');
dbms_aqadm.start_queue( queue_name => 'SMM_AQ_TWITTER_Q');
dbms_output.put_line ('Started Queue SMM_AQ_TWITTER_Q.');

EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line (SQLCODE || ' Start Queue ' || SUBSTR(SQLERRM, 1, 256));
END;
/

grant all on SYSTEM.SMM_AQ_QT to <schema>;
/

Serialized POJO Object to send and receive from Oracle AQ
import java.io.Serializable;

public class SmmPojo implements Serializable{
private String name;
private Long rollnumber;
public SmmPojo() {
super();
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setRollnumber(Long rollnumber) {
this.rollnumber = rollnumber;
}

public Long getRollnumber() {
return rollnumber;
}
}


JMS Client programs with Send and Receive code


Below is a Managed bean code.You can create a very simple ADF WebApplication with a DB DataSource called "SmmApp" in the WLS.

In the JSPX page, create 2 buttons and associate them with the 2 ActionEvents shown below[sendMessage() and ReceiveMessage()]


import javax.faces.event.ActionEvent;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;

import javax.naming.Context;
import javax.naming.InitialContext;

import oracle.apps.atk.ess.view.SmmPojo;

import oracle.jms.AQjmsFactory;
import oracle.jms.AQjmsSession;
import oracle.jms.AQjmsTextMessage;
import oracle.jms.AQjmsObject;

public class DemoBean {
public DemoBean() {
}

public void sendMessage(ActionEvent actionEvent) {
// Add event code here...
QSendFunction();
}

public void QSendFunction() {
QueueConnection qc = null;
try {
Context jndiContext = new InitialContext();
javax.sql.DataSource smmAppDS
= (javax.sql.DataSource) jndiContext.lookup ("jdbc/SmmAppDS");

QueueConnectionFactory qcf =
AQjmsFactory.getQueueConnectionFactory(smmAppDS);
qc = qcf.createQueueConnection();

//Message delivery does not begin until you start the connection you created by calling the start method
qc.start();

//session is not transacted
QueueSession m_queueSess =
qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);


// Destination is Queue created in database
Queue m_queue =
((AQjmsSession)m_queueSess).getQueue("", "SMM_AQ_TWITTER_Q");

QueueSender m_sender = m_queueSess.createSender(m_queue);

SmmPojo smmMessagePojo = new SmmPojo();
smmMessagePojo.setName("AMulya Mishra");
smmMessagePojo.setRollnumber(931L);
ObjectMessage objectMessage = m_queueSess.createObjectMessage();
objectMessage.setObject(smmMessagePojo);

//Message mesg = m_queueSess.createTextMessage("Test Message");

m_sender.send(objectMessage);

System.out.println("Message Sent->");

} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
qc.stop();
qc.close();
} catch (JMSException e1) {
}
}
}

public void ReceiveMessage(ActionEvent actionEvent) {
// Add event code here...
QRecvFunction();
}

public void QRecvFunction() {
QueueConnection qc = null;
try {

// QueueConnectionFactory is the preconfigured JMS Object set by administrator.
Context jndiContext = new InitialContext();
javax.sql.DataSource smmAppDS
= (javax.sql.DataSource) jndiContext.lookup ("jdbc/SmmAppDS");

QueueConnectionFactory qcf =
AQjmsFactory.getQueueConnectionFactory(smmAppDS);

// Does not created Destination, there is no look to JNDI that holds QF and Destination by JMS Client (this program)
// we are directly using JMS Client to make JMS Provider
// QueueConnection to JMS Provider ( database with JMS Services demon is the service provider )
// User can create one more connections to QF

qc = qcf.createQueueConnection();
// Start the Connection
//Message delivery does not begin until you start the connection you created by calling the start method
qc.start();

//A session is a single-threaded context for producing and consuming messages
//QueueSession m_queueSess = qc.createQueueSession(true, 0);

QueueSession m_queueSess =
qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue m_queue =
((AQjmsSession)m_queueSess).getQueue("", "SMM_AQ_TWITTER_Q");

//Once you have created a message consumer, it becomes active, and you can use it to receive messages
//a session and is used for receiving messages sent to a destination.
//A message consumer allows a JMS client to register interest in a destination with a JMS provider.
//The JMS provider manages the delivery of messages

QueueReceiver m_receiver = m_queueSess.createReceiver(m_queue);

// Synchronous messaging
//A receiver explicitly fetches the message from the destination by calling the receive method.
// The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit
//if you do not want your program to consume system resources unnecessarily, use a timed synchronous receive ex:- receive(1000) timeout 1000ms
ObjectMessage objectMessage = (ObjectMessage)m_receiver.receive(5000);
//Message mesg = m_receiver.receive(5000);
//System.out.println(((AQjmsTextMessage)mesg).getText());
if (objectMessage != null){
oracle.jms.AQjmsObjectMessage aqjmsObjectMessage = (oracle.jms.AQjmsObjectMessage)objectMessage;
SmmPojo smmMessagePojo = (SmmPojo)objectMessage.getObject();
System.out.println(smmMessagePojo.getName()+"--->"+smmMessagePojo.getRollnumber());
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
qc.stop();
qc.close();
} catch (JMSException e1) {
}
}
}
}

ADFbc:Inserting and retreiving java.util.List object to anf from Database

CREATE TABLE java_objects
(
object_id NUMBER,
object_name VARCHAR(128),
object_value BLOB DEFAULT empty_blob(),
PRIMARY KEY (object_id)
);

CREATE SEQUENCE java_objects_S1 MINVALUE 1 INCREMENT BY 1 START WITH 1000 CACHE 1000
/



Create an EO,VO and AM on this table.

AMImpl code

    public void insertData(){
List<Object> modules = new ArrayList<Object>();
modules.add("This is a short string.");
modules.add(new Integer(1234));
modules.add(new java.util.Date());

ViewObjectImpl vo = getJavaObjectsVO1();
Row row = vo.createRow();
row.setAttribute("ObjectName", "AMulya");
try{
BlobDomain blob = new BlobDomain();
OutputStream os = blob.getBinaryOutputStream();
ObjectOutputStream oop = new ObjectOutputStream(os);
oop.writeObject(modules);
oop.flush();
oop.close();
os.close();
row.setAttribute("ObjectValue", blob);
}catch(Exception e){
e.printStackTrace();
}

vo.insertRow(row);
this.getDBTransaction().commit();
}

public void readData(){
ViewObjectImpl vo = getJavaObjectsVO1();
Row row = vo.first();
BlobDomain blob = (BlobDomain)row.getAttribute("ObjectValue");
try{
InputStream is = blob.getBinaryStream();
ObjectInputStream oip = new ObjectInputStream(is);
Object object = oip.readObject();
String className = object.getClass().getName();
System.out.println(className);
oip.close();
is.close();
// de-serialize list a java object from a given objectID
List listFromDatabase = (List) object;
System.out.println("[After De-Serialization] list=" + listFromDatabase);
}catch(Exception e){
e.printStackTrace();
}

}