Showing posts with label java/JEE. Show all posts
Showing posts with label java/JEE. Show all posts

Wednesday, 19 February 2014

Check OID connection programmatically

This snippet of code allow us to check whether the connection to an OID Identity store is available.

import oracle.security.jps.JpsContext;
import oracle.security.jps.JpsContextFactory;
import oracle.security.jps.JpsException;
import oracle.security.jps.service.idstore.IdentityStoreService;

/**
  * Method to check that I can connect to OID Server. If I can get a
  * valid Identity Store means that there is a valid connection.
  */
private boolean oidUpAndRunning() {
    logger.info("Checking that OID is up and running...");
    try {
 getStoreService().getIdmStore();
 return true;
    } catch (JpsException e) {
 e.printStackTrace();
 return false;
    }
}

/**
 * Get an Identity Store Service from the JPS Context.
 */
public IdentityStoreService getStoreService() throws JpsException {
    JpsContextFactory ctxf = JpsContextFactory.getContextFactory();
    JpsContext ctx = ctxf.getContext();
    return ctx.getServiceInstance(IdentityStoreService.class);
}

Getting data from ADF bindings programmatically

These are some useful code snippets to work with ADF bindings programmatically:

// get the binding container  
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();  
  
// get an ADF attributevalue from the ADF page definitions  
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");  
attr.setInputValue("test");  
  
// get an Action or MethodAction  
OperationBinding method = bindings.getOperationBinding("methodAction");  
method.execute();  
List errors = method.getErrors();  
  
method = bindings.getOperationBinding("methodAction");  
Map paramsMap = method.getParamsMap();  
paramsMap.put("param","value")  ;        
method.execute();  


// Get the data from an ADF tree or table  
DCBindingContainer dcBindings = 
        (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();  
  
FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding("tree");  
Row[] rows = treeData.getAllRowsInRange();  
  
// Get a attribute value of the current row of iterator  
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get("testIterator");  
String attribute = (String)iterBind.getCurrentRow().getAttribute("field1");  
  
// Get the error  
String error = iterBind.getError().getMessage();  

// refresh the iterator  
bindings.refreshControl();  
iterBind.executeQuery();  
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);  
  
// Get all the rows of a iterator  
Row[] rows = iterBind.getAllRowsInRange();  
TestData dataRow = null;  
for (Row row : rows) {  
  dataRow = (TestData)((DCDataRow)row).getDataProvider();  
}  

// Get the current row of a iterator , a different way  
FacesContext ctx = FacesContext.getCurrentInstance();  
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();  
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), 
                "#{bindings.testIter.currentRow.dataProvider}", TestHead.class);  
TestHead test = (TestHead)ve.getValue(ctx.getELContext());  

 
// get the selected rows from a table component  
RowKeySet selection = resultTable.getSelectedRowKeys();  
Object[] keys = selection.toArray();  
List receivers = new ArrayList(keys.length);  
for ( Object key : keys ) {  
  User user = modelFriends.get((Integer)key);  
}  
  
// get  selected Rows of a table 2  
for (Object facesRowKey : table.getSelectedRowKeys()) {  
 table.setRowKey(facesRowKey);  
 Object o = table.getRowData();  
 JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;  
 Row row = rowData.getRow();  
 Test testRow = (Test)((DCDataRow)row).getDataProvider() ;  
}  

Useful code snippets for ADF Security

Here are some useful code snippets related to ADF Security (thanks to Edwin Biemond blog):

// print the roles of the current user  
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {  
   System.out.println("role "+role);  
}  
  
// get the ADF security context and test if the user has the role users         
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();  
if ( sec.isUserInRole("users") ) {  
}  

// is the user valid  
public boolean isAuthenticated() {  
 return ADFContext.getCurrent().getSecurityContext().isAuthenticated();  
}
  
// return the user  
public String getCurrentUser() {  
 return ADFContext.getCurrent().getSecurityContext().getUserName();  
}  

Saturday, 5 November 2011

How to call JavaScript from a ADF Managed Bean

To run a JS function from our Managed Bean, first put the JS code in a <af:resource> component in our JSF page:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" 
           xmlns:f="http://java.sun.com/jsf/core" 
           xmlns:pe="http://xmlns.oracle.com/adf/pageeditor" 
           xmlns:cust="http://xmlns.oracle.com/adf/faces/customizable" 
           xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<af:resource type="javascript">
    function myFunc() { [ any JS code ] };
</af:resource>

In the managed bean, put the following code in the appropriate method (e.g. in a action listener if we want to execute the JS code after a commandButton or commandLink is selected):
import javax.faces.context.FacesContext;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
[…]
FacesContext facesContext = FacesContext.getCurrentInstance(); 
ExtendedRenderKitService service = (ExtendedRenderKitService) org.apache.myfaces.trinidad.util.Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
service.addScript(facesContext, "myFunc();");

Accessing an ADF Operation binding programmatically

Developing an ADF application, it sometimes comes out we need to invoke programmatically (e.g. from a Managed Bean) a method exposed as operation binding in a ADF Data Control. To do this, we need to access the current binding container:

OperationBinding searchOp = ADFUtils.findOperation("searchBusinessUnits");
The ADFUtils.findOperation() method has the following definition:
public static OperationBinding findOperation(String operationName) {
OperationBinding op = getDCBindingContainer().getOperationBinding(operationName);
if (op == null) {
throw new RuntimeException("Operation '" + operationName +"' not found");
}
return op;
}

Unfortunately, when the previous code is executed in a method action invoked at page load time through an invokeAction binding, it happens that the reference to the binding container is null at this point. In this case, we need to access the binding container in a different way, using EL:

import oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding;

[. . .]

FacesCtrlActionBinding searchOp = null;
searchOp = (FacesCtrlActionBinding)JSFUtils.resolveExpression("#{data.portal_peoplefinder_resultsPageDef.searchBusinessUnits}");
Map opParams = searchOp.getParamsMap();
opParams.put("searchTerm", searchString);
Object result = searchOp.execute();

The pageDef excerpt of the page (or page fragment) containing the binding I need to access (in this case peopleFinder_resultsPageDef.xml ):

<bindings>
[...]
<methodAction id="searchBusinessUnits" InstanceName="ContentServicesDC.dataProvider"
DataControl="ContentServicesDC" RequiresUpdateModel="true"
Action="invokeMethod" MethodName="searchBusinessUnits" IsViewObjectMethod="false"
ReturnName="data.ContentServicesDC.methodResults.searchBusinessUnits_ContentServicesDC_dataProvider_searchBusinessUnits_result"/>
[...]
</bindings>

And the line of DataBindings.cpx regarding this binding:

<page id="portal_peoplefinder_resultsPageDef"
path="oracle.webcenter.portalapp.pagefragments.peoplefinder_resultsPageDef"/>

IMPORTANT: the EL expression we are using to retrieve the binding must be comply with the following format:

[“data”] + [id of the corresponding <page> entry in DataBindings.cpx] + [name of the binding we want to retrieve]

Executing custom code at page load time via ADF Data Control

This is a very common use case: invocation of some custom code at page load time.

Thanks to ADF Data Control capability, we can incapsulate our custom code in a method of a POJO, and finally expose this as a Data Control (it's worth reminding that it complies with JSR 227 specification, so it's actually adherent to Java standards).

As we have many flavours of bindings, we are going to show in this tutorial how to achieve the same result using an attribute binding, and then using a method binding.

For this tutorial JDeveloper 11.1.1.5.0 has been used.

As a first step, let's create a new Fusion Web Application (ADF) :



In the Model project we now create a new Java class, named PageLoadDC:




and expose this class as a Data Control:


After this, the Data Controls panel is populated with the new item:

And the DataControls.dcx file is updated with the following content:



Now let's work on the ViewController project: at first we create a new JSF page, named home.jspx:




To make JDeveloper create the necessary bindings for you in the pageDef file for the new page, just drag & drop the method binding from the DataControls panel onto the page, choosing ADF Output Text as display mode for this binding:




In this way, many things happen behind the scenes:

–        a new pageDef for home.jspx page is created

–        a new binding for the method exposed in the data control is created

–        an iterator has been defined for this binding, to access the results of this method call.



The generated code in the newly created pageDef is:



Running the application gives the expected result:



An interesting observation:

Having named the DC method with a name starting with 'get' (in this case 'getContentAtPageLoad'), this is interpreted by ADF as a getter of a property 'contentAtPageLoad', so the binding definition is really an attribute binding rather than a pure method binding, and in the home.jspx page the following EL expression is used to retrieve the value:
#{bindings.contentAtPageLoad.inputValue}

Now we add a new method in the DC, this time naming it in a different name, e.g. 'buildContentAtPageLoad':



and we expose the file as a DC again:



we can now notice how a method binding is actually created.

Now in the bindings box select the Plus icon to create a new binding, the select methodAction:



In the next screen just select the DC we just created, and the method name will appear in the 'Operation' dropdown list, then press OK:



As a result, a new binding is created in the pageDef file, and it appears in the 'Bindings' box in the page overview :



Now, to make this methodAction execute when the page is loaded, we just need to create an invokeAction to actually invoke it: in the 'Executables' panel in the 'Bindings' tab for the home.jspx page just click the Plus icon and select InvokeAction:



In the 'InsertInvokeAction' select the 'buildContentAtPageLoad' method and assign it an arbitrary ID, then click OK:



Then select the newly created invokeActionBinding, and in the property inspector set the 'Refresh' dropdown to 'Always':



In the JSPX page set the EL expression for the new binding like that:



Running the page again we get the expected result:



Easy as a pie.

You can download the example JDeveloper project here (remove the .pdf extension before unpacking).

Friday, 15 April 2011

Spring 3 course and certification tips

After attending the SpringSource course last February, today I passed the Spring Core 3 certification exam, with a score of 92%. I 'm writing this article to share my experience.

My first intention was to achieve the certification without attending the VMWare course, using the so called "grandfather voucher"... unfortunately such a voucher is no more recognized by Springsource, so the only way was to attend an official SpringSource course.

Friday, 11 March 2011

Smart GWT showcase

Here is a nice website...a big Smart GWT showcase application!

http://www.smartclient.com/smartgwt/showcase/#main

Smart GWT is a GWT-based framework that allows you to not only utilize its comprehensive widget library for your application UI, but also tie these widgets in with your server-side for data management. For a quick conceptual overview of Smart GWT, read this article, or visit the official site.

Smart GWT is based on the powerful and mature SmartClient library. In addition to Smart GWT LGPL, Pro & Enterprise editions of Smart GWT are available with additional features & tools, as well as commercial support.

Thursday, 24 February 2011

JPA and Hibernate: @Version for optimistic locking

What are the possible strategies to handle multiple updates of the same record at the same time?

1. Do Nothing

2. Lock the entire record (pessimistic locking)

3. Optimistic Locking:

Optimistic locking does not use exclusive locks when reading. Instead, a check is made during the update to make sure that the record has not been changed since it was read.  It's often implemented through a single column (of type Timestamp, or Number), used for no other purpose than implementing optimistic concurrency. this column is given a value when the row is inserted. Whenever the record is read, the timestamp column is read as well. When an update is performed, the timestamp column is checked: if it has the same value at UPDATE time as it had when it was read, then the UPDATE is performed and the timestamp is updated as well. If the timestamp value is different at UPDATE time, then an error is returned to the user: they must re-read the record, re-make their changes, and try to update the record again.

Tuesday, 2 March 2010

CRUD generico con Java Reflection API, EclipseLink ed ICEFaces

Problema: abbiamo un nutrito insieme di tabelle anagrafiche con struttura simile (solitamente ID, DESCRIZIONE e pochi altri campi), e vorremmo offirire nella nostra applicazione Web le funzionalità CRUD su di esse. Quello che vogliamo assolutamente evitare è la replicazione del codice che offre queste funzionalità per ogni tabella da gestire: in sostanza, si desidera un approccio quanto più generico possibile al problema.


Voglio condividere con voi una soluzione a questo problema a mio avviso molto interessante, che fa uso estensivo delle Reflection API di Java, EJB 3.0, JPA (con EclipseLink 1.20 come persistence engine) per il backend, e IceFaces 1.8 per la parte grafica.


Tuesday, 1 December 2009

GWT: un primo approccio

Da poco mi sono imbattuto, a fini di studio e mera cultura personale, nell'oramai celebre framework Google Web Toolkit (GWT). Questo framework, in sostanza, permette lo sviluppo di applicazioni web AJAX-based in linguaggio Java (seppure con alcune restrizioni, come vedremo), che, in fase di compilazione, viene convertito in Javascript ottimizzato e compatibile con i principali browser. In sostanza, chi è particolarmente abituato a sviluppare il proprio codice in linguaggio Java può sfruttare il proprio know-how per utilizzare GWT, sfruttando allo stesso tempo i vantaggi di Javascript: velocità (il codice prodotto da GWT è altamente ottimizzato e performante) e supporto con tutti i browser, senza doversi "sporcare le mani" nello sviluppo di codice JS (per chi ci è passato, non è il linguaggio di sviluppo più semplice del mondo).


Sunday, 4 October 2009

Installazione di EclipseLink in OC4J

Dopo qualche mese di silenzio, eccovi un piccolo tutorial che ho avuto modo di creare qualche giorno fa; come accade spesso in questi ultimi tempi,  mi sono trovato a dover migrare alcune applicazioni JEE basate su motore di persistenza Toplink Essentials alla nuova versione EclipseLink su piattaforma Oracle AS 10.1.3.4 (OC4J). Al contrario di WebLogic, l'installazione di EclipseLink in OC4J è meno banale, e vale la pena riassumere gli step necessari per completarla (è stata presa come riferimento una sezione  del Wiki di EclipseLink). E' anche posssibile evitare l'installazione di EclipeLink, includendo la suddetta libreria nel file EAR della nostra applicazione: tale approccio è tuttavia sconsigliato, in quanto la bassa posizione del file eclipselink.jar sul ClassLoader impedirebbe ad altre applicazioni di poterlo utilizzare.

Download

    Innanzitutto occorre scaricare la distribuzione di EclipseLink, disponibile alla sezione downloads del sito ufficiale di EclipseLink. Una volta scaricato il file eclipselink-n.n.n.zip, estrarre da esso i due file

    - eclipselink-*\eclipselink\jlib\eclipselink.jar

    - eclipselink-*\eclipselink\jlib\jpa\javax.persistence_*.jar
    Creazione di una nuova shared-library


      In questo passo, andremo a creare una nuova shared-library versionata per EclipseLink, aggiungendo il riferimento ai file jar nei file XML di configurazione.

      In primo luogo, creare una nuova directory org.eclipse.persistence in OC4J_ROOT/shared-lib con una sottodirecotry n.n.n per questa specifica versione  - the jars will be placed and referenced here. Ad esempio:


      /opt/oc4j101n/j2ee/home/shared-lib/org.eclipse.persistence/n.n.n

      Quindi, copiare i due file jar estratti in precedenza in questa directory.

      Arrivati a questo punto, occorre modificare il file $OC4J_ROOT/config/server.xml, aggiungendovi il seguente elemento shared-library:


      <shared-library name="org.eclipse.persistence" version="1.1.0" library-compatible="true">
         <code-source path="/opt/oc4j101n/j2ee/home/shared-lib/org.eclipse.persistence/n.n.n/eclipselink.jar"/>
         <code-source path="/opt/oc4j101n/j2ee/home/shared-lib/org.eclipse.persistence/n.n.n/javax.persistence_*.jar"/>
         <import-shared-library name="oracle.jdbc"/>

      Nota: l'attributo path dell'elemento code-source prevede che TUTTO il path dei jar file venga specificato, altrimenti OC4J non troverà i file al successivo riavvio ed eliminerà la porzione di server.xml appena aggiunta (con l'ovvia conseguenza che le librerie non verranno caricate dal ClassLoader).

      Import della nuova shared library

        Adesso occorre aggiungere il seguente elemento import-shared-library nel file $OC4J_ROOT/config/system-application.xml, appena sopra le due shared library esistenti oracle.persistence e oracle.toplink.

         <imported-shared-libraries>
         <!-- new EclipseLink shared library -->
          <import-shared-library name="org.eclipse.persistence"/>
          <!-- existing shipped out-of-the-box libraries -->
          <import-shared-library name="oracle.toplink"/>
          <import-shared-library name="oracle.persistence"/>


        Infine, riavviare l'istanza OC4J per rendere effettive le modifiche.

        Nota: la procedura viene descritta per l'istanza HOME, ma è ripetibile per qualsiasi istanza <OC4J_INST>. Occorre preventivamente creare la cartella shared-lib sotto j2ee/<OC4J_INST> e copiarvi i file jar, oppure posso lasciarli nella cartella j2ee/home/shared-lib e farla puntare al file server.xml in j2ee/<OC4J_INST>/config.

        Monday, 25 May 2009

        Howto per le certificazioni SUN Java

        Condivido con voi un utile articolo di M.Marzocchi pubblicato su JavaPortal, di sicuro interesse per chi, come me, ha nella propria "TODO list" un esame di certificazione Java di SUN Microsystems (o la dobbiamo già chiamare Oracle?!?). L'articolo è di particolare utilità, vista la caoticità delle informazioni che circolano in rete sull'argomento, che rendono più complicata del dovuto la preparazione, o quantomeno l'approccio iniziale ad essa, dell'esame di certificazione.


        Tuesday, 19 May 2009

        EJB 3.1 : passi avanti verso la maturità

        Desidero condividere con voi la sintesi di un interessante articolo pubblicato su TSS di P.Moreira, riguardante la prossima release della versione 3.1 degli EJB. E' stata finalmente rilasciata la versione Proposed Final Draft, siamo ormai prossimi a una versione finale. In questa versione, vengono introdotte una serie di nuove feature, mirate a sfruttare appieno il potenziale di questa tecnologia.



        No-Interface View

        I Session Bean non sono più obbligati a implementare alcuna interfaccia. Il container EJB fornisce la reference ad una "no-interface view", che permette al client di invocare qualsiasi metodo pubblico sul bean, e assicurando che le transazioni, la sicureza e l'interception si comportino come sempre. Tutti i metodi pubblici del SB sono resi disponibili attraverso la no-interface view, e un client può ottenere la reference a questa view attraverso dependency injection o JNDI lookup (come avviene attualmente per le interfacce locali e remote). La differenza è che, a differenza delle local and remote view, in cui la reference consiste nelle rispettive interfacce locali/remote, la reference alla no-interface view è tipata come la classe stessa del SB.