Friday, December 30, 2011

Adding Javascripts or inline CSS to ADF page

The best way to add javascript or css to ADF page is use of af:resource. This component adds CSS or JavaScript resource to rendered HTML header. Tag af:resource is processed on the initial creation of the document.

You can point external js or css file, as shown bellow:

<af:document>
   <af:resource type="javascript" source="/js/MyJsCode.js"/>
...
</af:document>


or insert javascript / css code inside tag body:

<af:document>
   <af:resource type="javascript">

      function myJavascriptFunction(){
          alert('This is my function');
      }
   </af:resource>
...
</af:document>


The parent of a af:resource component should be af:document. There is not recommended use of af:resource inside other adf component.

Another way of adding scripts/css to ADF page is "standard" JSF way:
<af:document>
...

   <f:facet>
      <script type="text/javascript">
          function myJavascriptFunction(){
            alert('This is my function');

          }
      </script>
   </f:facet>
...
</af:document>


If you need put CSS into <f:facet> you can encounter problems when compiling. To avoid simillar problems you can wrap tags <style></style> section <![CDATA[ ]]>.

ADF: Custom Client Attributes

As Oracle say:
"The clientAttribute tag specifies the name/value for an attribute which will both be made available both on the server-side (Faces) component as well on on the client-side equivalent. This tag will be ignored for any server-rendered components, as it is only supported for the rich client. ClientAttributes are not synchronized to the server since unknown attributes from the client are not synchronized to the server."

Client attributes simply allows developers to add custom properties to an ADF Faces component instance. Next JavaScript can read custom attribute by calling the getProperty('attr_name') function on a component handle.

Use case:
  • passing to Javascript additional infromation, out of scope for the component.
  • passing to the client Context informations
  • alternative to Javascript callback

Thursday, December 29, 2011

How-to find ADF Faces Components on a Page using javascript

Search from AdfPage.PAGE
  • Search by the component ID - use findComponentByAbsoluteId function
  • Search in component that stamps its children - use findComponentByAbsoluteLocator function
 Relative Search
  •  Use findComponent function. This function searches the component clientId which can be renderer implementation specific.
 Ensure a component exists on the client before accessing it from JavaScript. To ensure client component exists (is rendered)  set clientComponent property to true.

AdfPage.PAGE.findComponentByAbsoluteLocator example:

<af:document title="Page1" id="d1">
  <af:form id="f1">
    <af:panelStretchLayout id="psl1">
      <f:facet name="center">
        <af:panelGroupLayout id="pgl1">
          <af:panelGroupLayout id="main" styleClass="AFStretchWidth" layout="vertical">
          ...
          </af:panelGroupLayout>
        </af:panelGroupLayout>
      </f:facet>
    </af:panelStretchLayout>


    <af:resource type="javascript">
      function f1(){
        var main = AdfPage.PAGE.findComponentByAbsoluteId('main');
         alert(main);
        if(main != null) {
          ActionEvent.queue(main, true);
        }
      }
    </af:resource>
    ...

Wednesday, December 28, 2011

ADF custom phase listeners

As we know developers can create and configure custom life cycle listeners to receive ADF lifecycle notifications at the beginning and the end of each phase to execute custom logic.

In Oracle ADF framework developer can use standard JSF listener or special ADF listener which supports additional ADF-specific page cycle extensions. Listeners can be used to customize the ADF Lifcycle.

Custom listener can beconfigured for the following scopes:
  • Global, when the page lifecycle listener is configured to execute for all lifecycle execution throughout the application
  • Page scope - the listener is configured in the page definition file and supports concrete page
  • Custom scope - a lifecycle listener is added programmatically from Java and remains active until it is removed or the user session is dismissed
 How to create listener?
  • Create an objects that should receive lifecycle notifications. The object must implement the PagePhaseListener interface
  • The method argument is an instance of PagePhaseEvent.
  • PhaseId returns phase identifier (int value)
  • ADF controller is requred
  • To create and configure global lifecycle listener use the adf-settings.xml configuration file. The adf-settings.xml file does not exist by default and needs to be created in the “.adf\META-INF” folder of the application. The adf-settings.xml file allows developers to define the order in which page phase listeners are invoked.
Example:
public class MyPageListener implements PagePhaseListener {

    public MyPageListener() {

        super();

    }

    public void afterPhase(PagePhaseEvent pagePhaseEvent) {

        String phaseId = pagePhaseEvent.getPhaseId();

        System.out.println("We are after "+ Lifecycle.getPhaseName(phaseId));

    }

    public void beforePhase(PagePhaseEvent pagePhaseEvent){

        String phaseId = pagePhaseEvent.getPhaseId();

        System.out.println("We are before "+ Lifecycle.getPhaseName(phaseId));

    }

}

<?xml version="1.0" encoding="US-ASCII" ?>
<adf-settings xmlns="http://xmlns.oracle.com/adf/settings">
  <adfc-controller-config xmlns="http://xmlns.oracle.com/adf/controller/config">
    <lifecycle>
      <phase-listener>
        <listener-id>MyPageListener1</listener-id>
        <class>mc.adf.listeners.MyPageListener</class>
        <before-id-set>
          <listener-id> MyPageListener2</listener-id>
        </before-id-set>
        <after-id-set>
          <listener-id>MyPageListener3</listener-id>
        </after-id-set>
     </phase-listener>
    </lifecycle>
  </adfc-controller-config>
</adf-settings> 

Friday, December 23, 2011

Java Applet java.lang.InternalError: couldn't create component peer

Sometimes our customers notice the following exception in Java console when they try to open the page with Scanner Applet and load it:

 Exception in thread "AWT-EventQueue-2" java.lang.InternalError: couldn't create component peer
    at sun.awt.windows.WComponentPeer.checkCreation(Unknown Source)
    at sun.awt.windows.WComponentPeer.<init>(Unknown Source)
    at sun.awt.windows.WCanvasPeer.<init>(Unknown Source)
    at sun.awt.windows.WPanelPeer.<init>(Unknown Source)
    at sun.awt.windows.WWindowPeer.<init>(Unknown Source)
    at sun.awt.windows.WFramePeer.<init>(Unknown Source)
    at sun.awt.windows.WEmbeddedFramePeer.<init>(Unknown Source)
    at sun.awt.windows.WToolkit.createEmbeddedFrame(Unknown Source)
    at sun.awt.windows.WEmbeddedFrame.addNotify(Unknown Source)
    at sun.plugin2.main.client.PluginEmbeddedFrame.addNotify(Unknown Source)
    at sun.awt.windows.WEmbeddedFrame.<init>(Unknown Source)
    at sun.plugin2.main.client.PluginEmbeddedFrame.<init>(Unknown Source)
    at sun.plugin2.main.client.PluginMain$StartAppletRunner.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)




Actually, it is a know problem for Oracle. Anyway, exception appears before the applet starts. Sometimes it has not an influence on the applet and it works without problem. Sometimes the applet is not loaded at all. In this case to resolve the issue you need to do the following steps:
  1. Open Java Control Panel
  2. Open Advanced tab
  3. Expand Java Plug-in item
  4. Uncheck Enable the next-generation Java Plug-in
  5. Click Apply
BUT!... Sometimes Enable the next-generation Java Plug-in checkbox is grayed out. In this situation follow the steps below to disable new java plugin via registy and see how it goes.
  1. Go to start, type regedit.exe and press Enter.
  2. Navigate to the location below:
  3. HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Plug-in
  4. Navigate to the subfolder of Java Plug-in. It should be something like:1.6.0_29
  5. Set the dword value of  "UseNewJavaPlugin" to 00000000 to disable new java plugin.
  6. Close the registry editor.
Free Web Directory - Add Your Link

Merry Christmas Everyone

Christmas greetings and all good wishes for your health and happiness in the coming year !

Friday, December 16, 2011

How to: array inversion count

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. 

Formal solution to solve is:
Given is an array A of N integers. Inversion is a pair of indexes (P, Q) such that P < Q and A[Q] < A[P].

Write a function

class Solution { public int array_inversion_count(int[] A); }

which computes the number of inversions in A, or returns -1 if such number exceeds 1,000,000,000.

Assume that:

        N is an integer within the range [0..100,000];
        each element of array A is an integer within the range [-2,147,483,648..2,147,483,647].

For example, in the following array

    A[0] = -1 A[1] = 6 A[2] = 3
    A[3] =  4 A[4] = 7 A[5] = 4

there are four inversions:

      (1,2)  (1,3)  (1,5)  (4,5)

so the function should return 4.

Complexity:

        expected worst-case time complexity is O(N*log(N));
        expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).


import java.math.*;
class Solution {
public int array_inversion_count ( int[] A ) {
// write your code here

int n = A.length;
int counter = 0;
for(int p = 0; p < n - 1; p++) 

   { 
      for(int q = p+1; q < n; q++) 
      { 
         if( A[p] > A[q] ) counter++;
      }
   }
   return counter;
  }
}

Monday, December 12, 2011

Configuring an SSL Certificate for Microsoft Active Directory

See more here: http://confluence.atlassian.com/display/CROWD/Configuring+an+SSL+Certificate+for+Microsoft+Active+Directory#ConfiguringanSSLCertificateforMicrosoftActiveDirectory-Step1InstalltheActiveDirectoryCertificateServices

Thursday, December 8, 2011

How to: creating Private Database Link to database on remote server (Oracle DB)

If you was somewhat confused about the problems with the 'ad hoc' data link to a remote database, I propose tested solution. Sometimes you can't edit TNSNAMES and you need directly put the TNSNAME entry information directly in the database link connection string. There is my example:


CREATE DATABASE LINK my_link
CONNECT TO my_schema_user IDENTIFIED BY my_password
USING '(DESCRIPTION =(ADDRESS = (PROTOCOL=TCP)(Host=my_host_ip)(Port=1521))(CONNECT_DATA=(SERVICE_NAME=my_service_name)))';

Wednesday, November 30, 2011

My old article "Building JSF custom components"

"Creating an AJAX enabled JSF (1.1 and 1.2 version) components" is my old article, still in draft version.

Article was created on the groundwork of Dr. Winston Prakash's article „Creating AJAX enabled JSF component – part 1”.
When I red Dr. Winston Prakash's article „Creating AJAX enabled JSF component – part 1” I had been verry impressed. In mine opinion
it was the best manual reffered to creating JSF components I whenever saw. There was all I wanted.
Dr. Prakash's article introduced me in exciting world of creating JSF components:).
Some time ago however I was aware of my working knowledge must be put in a good order. Then I decide to create new, but based
on Dr. Prakash's article, manual. I hope, it will be usefull for all of You. As well I hope, an author of the article I based on, perceives my
initiative with kindness and interest.

To download PDF version, please visit:


http://www.scribd.com/doc/74302797/Building-JSF-Custom-Components

Friday, November 25, 2011

How to fix "schema has already been upgraded" issue

I had similar problem when applying last oracle SOA/BPM FP.
To patch db schema I used psa tool:

%ORACLE_HOME%\bin>psa -dbType Oracle -dbConnectString  //dbhost:1521/tst -dbaUserName sys -schemaUserName MY_SOAINFRA


Psa utility threw an error but after removed cause of this error, still I could not run upgrade procedure once again. The cause was next error:


[2011-11-24T17:23:37.467+01:00] [SOAINFRA] [ERROR] [] [upgrade.SOAINFRA] [tid: 10] [ecid: 0000JFRKfjmCKu85njt1iZ1EnvBW000000,0] SOAINFRA schema has already been upgraded.


It looked like schema version was altered despite the fact that the upgrade script was not executed properly.

To check actually version of my SOA schema I used following query:


SELECT version, status FROM schema_version_registry WHERE owner='MY_SOAINFRA';


In the fact, schema version was altered from version 11.1.1.5.0 to 11.1.1.5.1.

To reset this invalid version value i used following clause:


Update SCHEMA_VERSION_REGISTRY set version='11.1.1.5.0' where comp_id='SOAINFRA' and owner='MY_SOAINFRA'

Thursday, November 17, 2011

Oracle jdbc 4.0 driver and createArrayOf issue

Problem description:

Passing an Array object to database stored procedure you can acheive as shown in oracle jdbc 4.0 documentation, eg:

Array aArray = con.createArrayOf("VARCHAR", northEastRegionnewYork);


but ... this don't work with oracle database, as I noticed today. After some googling I found following information:

The SQL standard array type is anonymous, that is the type "array of foo" does not have a name. Only the element type is named. In Oracle SQL the array type is named. In fact anonymous array types are not supported. So, the JDBC 4.0 standard factory method takes the element type as its argument and creates an instance of an anomyous array type. The Oracle JDBC drivers define an Oracle proprietary method, createArray, which takes the name of an array type and returns an instance of that named array type. This is required by the way Oracle SQL is defined. At present the Oracle database cannot support the JDBC 4.0 standard createArrayOf method.

Hmm... how to code this? This is my solution:

Connection conn;
....
ArrayDescriptor arraydesc = ArrayDescriptor.createDescriptor("NUMARRAY", conn);
ARRAY ar = new ARRAY(arraydesc, conn, di);
....
statement.setArray(1, ar);
statement.setString(2, "ble");
statement.execute();
ar.free();
...

Sunday, November 13, 2011

How to: McDialog Jsf component in JSP and facelets view

McDialog is a part of the McFaces (WshFaces) Rich Comnponents Library (JSF 2.0 version). You can find a complete sample code in project webpage: http://wshfaces.sourceforge.net.

Dialog with "static content":

            <mc:dialog id="dlg1" autoOpen="false" closeOnEscape="false" closeText="Zamknij" disabled="false" draggable="true"
                       height="300" hideEffect="none" includeCssTemplate="false" maxHeight="450" maxWidth="550" minHeight="250" minWidth="450"
                       modal="true" buttons="Yes; No; Cancel" resizable="true" title="This is McDialog demo" width="500"
                       dialogShowListener="#{dialogView.dialogShow}"
                       dialogCloseListener="#{dialogView.dialogClose}">
                <div>
                    <p>You can modify look and feel of this dialog by modyfying dialog CSS. Cause MCDialog uses JQuery.dialog pugin as a javascript frontend, you can use JQuery tools to design CSS template for your application.</p>
                    <p>dialogShowListener is called before dialog activation - please look at method mc.hqproducts.components.samples.Dialog.dialogShow to see how it works.</p>
                    <p>dialogCloseListener is called after one of buttons is clicked - please look at method mc.hqproducts.components.samples.Dialog.dialogClose to see it in action. Return value is an integer value. Last button click returns 1, next from right 2 and so on.</p>
                </div>
            </mc:dialog>




Dialog with content loaded via AJAX request:

             <mc:dialog id="dlg2" autoOpen="false" closeOnEscape="false" closeText="Zamknij" disabled="false" draggable="true"
                       height="300" hideEffect="none" includeCssTemplate="false" maxHeight="450" maxWidth="550" minHeight="250" minWidth="450"
                       modal="true" buttons="Yes; No; Cancel" resizable="true" title="This is McDialog demo" width="500" ajaxContentDelivery="true"
                       dialogShowListener="#{dialogView.dialogShow}"
                       dialogCloseListener="#{dialogView.dialogClose}"
                       >
                 <h:panelGroup id="pg2" layout="block">
                    <p>This is an exaple of Dialog with dynamically loaded content</p>
                 </h:panelGroup>
            </mc:dialog>

Thursday, November 10, 2011

How to: pass parameters to backing bean in JSF application

There is few methods to solve this task:

1. f:param - pass parameter value via f:param tag and get it back via request parameter in backing bean.

...
<h:commandbutton action="#{viewScope.documentView.handleSign}" binding="#{viewScope.documentView.pod}" partialsubmit="true" text="Sign">
   <f:param name="path" value="c:\\oracle\\middleware\\aaa">
</f:param></h:commandbutton>
...


@ManagedBean(name="documentView")
@ViewScoped
public class DocumentView{
    //...
    public String handleSign() {
        String path =     FacesContext.getExternalContext().getRequestParameterMap(.get("path");


    }
    //...
}


2. f:setPropertyActionListener - pass parameter to PropertyActionListener defined in your bean

...
<h:commandbutton actionlistener="#{viewScope.documentView.handleSign}" binding="#{viewScope.documentView.pod}" partialsubmit="true" text="Sign">
   <f:setPropertyActionListener target="#{
viewScope.documentView.podActionValue}" value="Podpisz" />
</f:param></h:commandbutton>
...


@ManagedBean(name="documentView")
@ViewScoped
public class DocumentView{
    //...

    String podActionValue;
    public void
setPodActionValue(String value) {
        String podActionvalue = value;
    }
    //...
}


3. f:atribute - Pass parameter value via f:atribute tag and get it back via action listener in backing bean.

 ...
<h:commandbutton actionlistener="#{viewScope.documentView.handleSign}" binding="#{viewScope.documentView.pod}" partialsubmit="true" text="Sign">
  
<f:param name="path" value="c:\\oracle\\middleware\\aaa">
</f:param></h:commandbutton>
...


@ManagedBean(name="documentView")
@ViewScoped
public class DocumentView{
    //...
    public void
handleSign(ActionEvent event) {
        String path = (String)event.getComponent().getAttributes().get("path");
    }
    //...
}


4. ADF way
   af:clientAttribute - You can use af:clientAttribute similar to f:attribute

   af:clientListener/serverListener - When we need add some client side processing in javascript we can pass parameter value from af:clientAttribute via af:clientListener to javascript, and next to af:serverListener tag. You can get values back in listener in backing bean. 

 ...
<af:commandbutton actionlistener="#{viewScope.documentView.handleSign}" binding="#{viewScope.documentView.pod}" partialsubmit="true" text="Sign">

   <af:clientAttribute name="path" value="c:\\oracle\\middleware\\aaa"/>
  
<af:serverListener type="customEvent" method="{viewScope.documentView.handleSign}"/>
   </
af:serverListener>
   <af:clientListener method="signButton" type="click"/>
</af:commandbutton>


<af:resource type="javascript>
function podpiszButton(evt) {
                        var src = evt.getSource();
                        var path = evt.getSource().getProperty('path');
                        component = evt.getSource();
                        AdfCustomEvent.queue(component, "customEvent", {spath:path}, true);
                        evt.cancel();
                    }

</af:resource>
...


@ManagedBean(name="documentView")
@ViewScoped
public class DocumentView{
    //...
    public void
handleSign(ClientEvent event) {
        String path = (String)event.getParameters().get("spath");
    }
    //...
}



5. MethodExpression - the simplest way available in JSF 2.0 version


...
<h:commandButton action="#{viewScope.documentView.handleSign('aaa')}" />
...


@ManagedBean(name="documentView")
@ViewScoped
public class DocumentView{
    //...

    public void handleSign(String sign) {
        this.sign = sign;
    }
    //...
}

Monday, November 7, 2011

How to: storing configuration parameters in web.xml file

Sometimes we need store application wide settings of our web application in configuration files or database. Of course one can also hardcode these parameters, but it isn't best way if we need to construct flexible, easy to maintain software.
There exists also one more, elegant and easy way to store application wide parameters: storing params in web.xml file. As you must know the web.xml file provides configuration and deployment information for the Web components that comprise a Web application. The web.xml file resides in the WEB-INF directory under the context of the hierarchy of directories that exist for a Web application. For example, if the application is myApp.war, then the web.xml file is placed in the myApp.war/WEB-INF directory.

We can store our params as shown bellow:

<?xml version = '1.0' encoding = 'UTF-8'?>
<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">
  <description>sample web.xml file for task flow</description>
  <display-name>MyApp.jws</display-name>
  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>


<context-param>
    <param-name>myParam1</param-name>
    <param-value>user@domain.com</param-value>
  </context-param>
<context-param>
    <param-name>myParam2</param-name>
    <param-value>xyz</param-value>
  </context-param>

...

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>


...

</web-app>


When we need access stored params in web application code, it can be done very easy:

String ldapUser = getServletContext().getInitParameter("myParam1");
String ldapPassword = getServletContext().getInitParameter("myParam2");


In JSF backing bean it looks simillar, by example:

ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
String ldapUser = context.getInitParameter("myParam1");
String ldapPassword = context.getInitParameter("myParam2"); 


Friday, November 4, 2011

Annouce: McFaces alpha edition released

I'm happy to announce the *alpha* edittion of McFaces, a set of JSF rich components library.
More info about the library you can find on SourceForge.

How to fix: Weblogic ServletContext.getRealPath() returns null

Weblogic Server[WLS] returns null if your code is using Servlet.getRealPath(). You can suppose that it's another weblogic server bug but it's not.

The problem is the way in which you deploy the application. If the application was deployed in exploded mode, getRealPath returns occured, valid value. But, if you deploy it as an archive having extentions like war, ear etc.  you will see "null pointer" Exception. Fortunatelly there is simple way to avoid this exception. You can fix this problem in domain level, setting weblogic Admin Console option Domain | Web Application | Archived Real Path Enabled to true, as shown below:


You can also apply fix in application level by adding the following entry to weblogic.xml file:

<container-descriptor>
    <show-archived-real-path-enabled>true</show-archived-real-path-enabled>
</container-descriptor>

You can do this by JDeveloper IDE as shown below: