Tuesday, February 2, 2016

Hibernate 5.0.2 - Specifying Schema Causes AssertionFailure in JoinedSubclassEntityPersister

After migrate to Wildfly 10, my web application based on JPA and Hibernate cannot be deployed due to the following error:

Caused by: org.hibernate.AssertionFailure: Table xxx.XXX not found
    at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5107)
    at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
    at sun.reflect.GeneratedConstructorAccessor89.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    ... 13 more

I tested against Hibernate 5.0.1, up to 5.0.7 which is bundled in WildFly 10. It turns out until Hibernate 5.0.1, my application works just fine. From Hibernate 5.0.2 and higher, it's broken.

It seems the <schema> elements in my ORM mapping file for those entities in the entity hierarchy using the JOINED inheritance strategy triggering the problem. I have reported an issue at HHH-10490.

Current workaround is to remove those <schema> elements for entities using JOINED inheritance strategy from the mapping file. If it's not good for your case, you can also downgrade to Hibernate 5.0.1. For those WildFly 10 users, add the following property to your persistence.xml:

<property name="jboss.as.jpa.providerModule" value="application" />

Then, add Hibernate 5.0.1 as a dependency of your application, so that the required Hibernate artifacts will be packaged along with your application.

Environments

  • WildFly 10
  • Hibernate 5
  • MySQL Connector/J 5.1.37

Monday, November 23, 2015

Wildfly 9 - Execute Batch Jobs from a JAR in a WAR

It's very common to package Java EE JSR-352 batch jobs and artifacts in a JAR file, and execute the jobs in a web application with the JAR as a dependency. In Wildfly 9, due to the Class Loading based on JBoss Modules and an issue in Wildly 9, you might end up with an exception: javax.batch.operations.JobStartException: JBERET000601: Failed to get job xml file for job XXX.

This post is about how to execute Java EE JSR-352 batch jobs from a JAR file in a WAR archive on Wildfly 9 particularly.

META-INF/batch-jobs in the WAR

In the WAR archive, make sure you have a META-INF/batch-jobs directory. It goes under the WEB-INF/classes directory in a WAR archive. If you don't really have any job XML files in this directory, put a README file for example to make sure it's not empty in order to avoid being ignored by the packaking tool.

WEB-INF/beans.xml in the WAR

If you are using CDI for job artifacts in the WAR, make sure you have a beans.xml file for CDI under the WEB-INF directory. This is the trigger which leads Wildfly implicit module dependency to CDI subsystem being added.

META-INF/batch-jobs in the JAR

In the JAR file, you need storing the job XML documents under the META-INF/batch-jobs directory of course.

META-INF/beans.xml in the JAR

If you are using CDI for job artifacts in the JAR, you should have a CDI beans.xml file under the META-INF directory in the JAR. This will ensure Wildfly will scan the JAR for job artifacts. This is optional for some deployments though.

META-INF/services/org.jberet.spi.JobXmlResolver in the JAR

As a workaround for Wildfly 9 particularly, you need place a service provider configuration file in the resource directory META-INF/services in the JAR, with the name org.jberet.spi.JobXmlResolver. The configuration file contains only the following line:

org.jberet.tools.MetaInfBatchJobsJobXmlResolver

This service provider configuration file will ensure Wilefly 9 to scan the META-INF/batch-jobs directory in the same JAR file for job XML documents.

Resources

Thursday, November 5, 2015

JPA Inheritance and SQLException: Parameter Index Out of Range

JPA (Java Peristence API) supports inheritance. When working with the SINGLE_TABLE or JOINED mapping strategy, the @DiscriminatorColumn annotation (or discriminator-column element if you are using XML mapping descriptor) is used to specify the name of the type discriminator column. This colummn will not be mapped to any field in any of the classes in the entities hierarchy. If you do so, you might encounter the SQLException: Parameter index out of range. I'm using MySQL and Hibernate, the stack trace looks like this:

Caused by: org.hibernate.exception.GenericJDBCException: could not insert: [...]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:65)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3556)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:97)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:191)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:807)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
    ... 1 more
Caused by: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
    at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3367)
    at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3352)
    at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3389)
    at com.mysql.jdbc.PreparedStatement.setNull(PreparedStatement.java:3428)
    at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:77)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:282)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:277)
    at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
    at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2818)
    at org.hibernate.persister.entity.AbstractEntityPersister$4.bindValues(AbstractEntityPersister.java:3025)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
    ... 20 more

There's not necessarily a field mapping to the discriminator column, because for any specific concrete entity, its type discriminator value is basically a constant.

Environment

  • Java Persistence API 2.1
  • Hibernate 4.3.1
  • MySQL Connector 5.1.36

Tuesday, June 30, 2015

ADF - Time Zone for History Columns

In my last post of the time zone series - Time Zone for Oracle JDBC Driver, I introduced how the Oracle JDBC Driver processes date values with regards to time zones. As a special note, in this post, I will introduce how time zones affect the ADF Business Components 'Date' history columns, specifically, "Created On" and "Modified On" columns.

Here's the description from the official document (see the resources below):

  • Created On: This attribute is populated with the time stamp of when the row was created. The time stamp is obtained from the database.
  • Modified On: This attribute is populated with the time stamp whenever the row is updated/created.

So, the time stamp is obtained from the database (when there is a connection), rather than JVM in which ADF is running. Basically, an appropriate query will be executed in the database to get the current database time; then the value is returned by JDBC and converted to appropriate Java Date type. In this process, the rules introduced in my last post apply.

For example, for Oracle Database, the query (see resources below) would be like this:

select sysdate from dual

Whenever an entity object is about to initialize or update its history columns, the current transaction object is inquiried about the current database time. The transaction object executes the query statement and returns the timestamp obtained as the result from the database (for performance benefit, the query statement is executed only for the first time, and then a difference between the database time and JVM time is saved and added to the JVM time to get a result for a subsequent request).

Now it's clear, to get correct history columns, we need make sure both the database time zone and JVM time zone are configured correctly. Typically, both of them should be configured to be UTC time zone, and then we can use converters for UI components to display date values or accept user input for date values in any other time zones appropriate, as introduced in my another post, ADF - Time Zone for af:convertDateTime.

Resources

Monday, March 23, 2015

Time Zone for Oracle JDBC Driver

In my last post - Time Zone for af:convertDateTime, I introduced how the date values are passed around in an typical ADF application, and specifically, how the ADF Faces handles the date values conversion with respect to the time zone configuration. To review it, let's take a look at this figure again:

Image: Date Data Handling

In this post I will be talking about another part of the puzzle - how the Oracle JDBC driver processes date values with regards to time zones. It can be illustrated as the following simple figure:

Image: Oracle JDBC Driver and Time Zone

As shown in the figure, this post will use java.sql.Date (or simply Date in monospace type) and the Oracle DATE datatype (or simply DATE in monospace type) for the discussion. The term "date value" will be used for general purposes.

Oracle Database stores date values in its own internal format. A DATE value is stored in a fixed-length field of seven bytes, corresponding to century, year, month, day, hour, minute, and second. When a date value goes from the application to the database; and out of the database back to the application. It works like this, basically:

  1. A java.sql.Date value is created to hold the date value, and it's in the time zone GMT.
  2. The Date value is sent to the Oracle JDBC Driver, and the driver converts it to the Oracle DATE value and passes it to the database.
  3. The Oracle JDBC Driver retrieves the DATE value out of the datbase, converts it back to the java.sql.Date value.

The Java Date value carries the time zone information implicitly which is always GMT by definition; but the Oracle DATE datatype does not. For Oracle JDBC Driver to convert the value between these two datatypes, another time zone must be specified in some way as the source or destination time zone. If you just want a quick answer, here is it: Oracle JDBC Driver will use the default time zone of the Java VM if it's not explicitly specified.

The key lies in the class oracle.sql.Date, which provides conversions between the Oracle DATE datatype and the Java java.sql.Date (and java.sql.Time, java.sql.Timestamp). Specifically, I'll talk about its two overloaded methods used to convert the Oracle DATE value into the Java Date value. The reverse conversions are handled by its constructors with the same ideas shared.

One of methods is:

public static Date toDate(byte[] date, Calendar cal)

And another one is:

public static Date toDate(byte[] date)

Calling the second one is simply equivalent to call toDate(date, null). Let's focus on the first one. This method accepts two parameters. The first parameter represents the Oracle DATE value to be converted with each byte in the array corresponding to each field in the internal format of the Oracle DATE datatype (that seven-byte, fixed-length format). For the other parameter, it's documented as this:

cal - Calendar which encapsulates the timezone information to be used to create Date object

Here is how this method works:

  1. A new Calendar instance is created using the TimeZone encapsulated in the specified Calendar parameter (cal1 = Calendar.getInstance(cal.getTimeZone())). In case the Calendar parameter is null, use the default time zone (cal1 = Calendar.getInstance()).
  2. Populate each field of the new Calendar instance with the value of each corresponding field in the byte array.
  3. Create and return a new java.sql.Date object using the long value of the time returned from the populated Calendar instance (new java.sql.Date(cal1.getTime().getTime())).

In summary, Oracle JDBC Driver interprets the date values retrieved from the database as in the time zone of the Java VM by default. The values that are actually loaded into the Java Date values may vary depending on your Java VM, and vice versa.

Series on Time Zone

Environment

  • JDeveloper 12.1.3.0.0 Build JDEVADF12.1.3.0.0GENERIC_140521.1008.S
  • Oracle Database 12.1.0
  • Oracle JDBC 12.1.0
  • Mac OS X Version 10.10

Resources

Friday, March 20, 2015

ADF - Time Zone for af:convertDateTime

In the last post about configuring WebLogic Server time zone, I mentioned one of reasons you do it is to configure the default time zone for ADF Faces to convert date and time for input and output components. This post will focus on it - how the ADF Faces convertDateTime converter and the af:convertDateTime tag work with the time zone configuration in detail. This is only the first piece of the puzzle. Hopefully, I can put other pieces together to complete the puzzle with another two or more subsequent posts.

Here you can find the Source Code of the sample application or Download ZIP of it.

Image: ADF Samples - Time Zone for af:convertDateTime

To make it easier, I'm using java.util.Date in the discussion and the sample application, and Oracle data type DATE in some figures. The basic idea applies to java.sql.Date, etc.

In Java, the class java.util.Date represents a specific point in time. As per the javadocs for one of its constructors - Date(long date):

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Clearly, the class Date represents a determinate point in time which is in the time zone GMT. To display a Date, we need a converter or a formatter to turn the Date into a String which represents the "wall clock time" local to a specific time zone. When the target time zone changes, the resulting String or the "wall clock time" could change, but the value of the Date does not change in this process.

The following figure illustrates how the date and time data passes through a typical ADF application:

Image: Date Data Handling

  • The ADF Faces component accepts the user input as a String value and convert it into a Java Date value with a DateTimeConverter.
  • The Oracle JDBC driver passes the Date value into the database as an Oracle DATE value.
  • For output, the JDBC driver retrieves the Oracle DATE value out of the datebase as a Java Date value.
  • The ADF Faces component display the date and time after converts the Java Date value into a String value with a DateTimeConverter.

I'll talk about the JDBC part in my next post, and here will focus on how the time zone configuration comes into play in the view part:

Image: View Layer Time Zone

When an ADF Faces component works with a DateTimeConverter, a java.util.TimeZone object can be configured with it, as shown in the following code snippet from the sample application:

<af:inputText 
        id="it_dt"
        label="Date Time: "
        value="#{userBean.dateTime}" autoSubmit="true">
    <af:convertDateTime 
        pattern="yyyy-MM-dd HH:mm" 
        timeZone="#{userBean.inputTimeZone}"/>
</af:inputText>

Here's the description from ADF RichClient API - <af:convertDateTime> for the timeZone attribute:

Time zone in which to interpret any time information in the date string. If not set here, picks this value from trinidad-config.xml configuration file. If not defined there, then it is defaulted to the value returned by TimeZone.getDefault(), which is usually server JDK timezone.

When the component is used for user input, the TimeZone object specifies the source time zone in which the date string should be interpreted, and convert the String input value into a Date value which is in the destination time zone GMT. When the component is used for output, the TimeZone object specifies the destination time zone, and the Date value is converted into a String representing the local date and time in the time zone specified by the TimeZone object.

You can configure the time zones in three levels:

  • System-level time zone
  • Application-level time zone
  • Converter-level time zone

The system-level time zone can be configured as described in my last post - Configuring the Time Zone with WebLogic Server. The application-level time zone can be configured like this as in the sample application:

<trinidad-config xmlns="http://myfaces.apache.org/trinidad/config">
  <time-zone>#{applicationBean.applicationTimeZone}</time-zone>
</trinidad-config>

The converter-level time zones can be configured with business-specific time zones or user preference time zones according to your application requirement. For example, in an application displaying a flight's departure time and arrival time, two different time zones for the departure airport and arrival airport respectively can be used. That's the business-sepcific time zone approach. You can also support the user preference time zones in this case as an user-friendly feature.

This post covers how the time zones participate in the date values processing in the ADF Faces view layer. In the next post, I'll introduce what happens when the date values are accessed with the Oracle JDBC driver.

Special Note for the ADF prior to 12c

In the ADF 11g, the timeZone attribute of the af:convertdateTime is documented as this:

Time zone in which to interpret any time information in the date string. If not set here, picks this value from adf-faces-config.xml configuration file. If not defined there, then it is defaulted to GMT.

Series on Time Zone

Sample Application

Environment

  • Oracle Alta UI
  • JDeveloper 12.1.3.0.0 Build JDEVADF12.1.3.0.0GENERIC_140521.1008.S
  • Safari Version 8.0
  • Mac OS X Version 10.10

Resources

Monday, March 16, 2015

Configuring the Time Zone with WebLogic Server

In order to properly handle the date and time data in your ADF applications, you probably need to configure the WebLogic Server time zone, for the reasons including but not limited to:

  • Configure the default time zone for <af:convertDateTime> used by input and output components.
  • Configure the time zone that affects how the Oracle JDBC driver handles the date and time data.

This post introduces how to configure the time zone with an integrated or a standalone WebLogic Server, or the ADF Model Tester.

Integrated WebLogic Server and ADF Model Tester

When you are running and testing your application using an Integrated WebLogic Server, or testing your model project with the ADF Model Tester you can configure the time zone by adding the following system property to the Java Options on the Launch Settings page in the Edit Run Configuration window:

-Duser.timezone=UTC

To do this:

  1. Select the project in the Applications window.
  2. From the main menu, choose Application > Project Properties
  3. Select Run/Debug.
  4. Choose to Edit the selected run configuration (a default run configuration is created for each new project).
  5. Add the time zone system property to Java Options

Image: Edit Run Configuration

The configuration will apply when the Java program is launched from JDeveloper, for example the Integrated WebLogic Server and the ADF Model Tester. To confirm it, you can look for the system property in the Log window after the program is launched:

Image: Log Window

Another way to configure the Integrated WebLogic Server time zone is to set it by modifying the properties of the integrated application server:

  1. In the Application Servers window, right-click the integrated application server (the default instance is called IntegratedWebLogicServer), choose Properties.
  2. Select Launch Settings tab.
  3. Add the time zone system property to Java Options

Image: Application Server Properties

Please note that the Launch Settings of the Application Server Properties are used only when the server starts with no application selected (effectively meaning no application is open in the Applications window).

Caution: when the server starts with no application selected, and then open the application and run it against the server, the Launch Settings defined in the Application Server Properties will be used; the Java Options defined in the run configuration of the project will be ignored.

Standalone WebLogic Server

To configure the time zone with a standalone WebLogic Server instance, if you use a WebLogic Server script to start servers, you can edit the JAVA_OPTIONS in the script to set the system property, see "Specifying Java Options for a WebLogic Server Instance"; if you use the Node Manager to start servers, you can set Java Options for each server instance in the Oracle WebLogic Server Administration Console, see "Set Java options for servers started by Node Manager".

Series on Time Zone

Resources:

Tuesday, February 24, 2015

BEA-141297 - Could not get the server file lock

While starting the WebLogic Administration Server or a Managed Server, you might encounter the following error that prevents the server from starting up:

<Feb 9, 2015 1:40:34 PM CST> <Info> <Management> <BEA-141297> <Could not get the server file lock. Ensure that another server is not running in the same directory. Retrying for another 60 seconds.>

This is because the server lock file is left behind for some reason from the last run. To fix this error:

  • Navigate to the server-specific tmp directory under your $DOMAIN_HOME directory, in my case, for example: ~/Oracle/config/domains/base_domain/servers/AdminServer/tmp for the Administration Server or ~/Oracle/config/domains/base_domain/servers/wls_server_1/tmp for one of the Managed Servers;
  • Delete the lock file for the server instance, AdminServer.lok for the Administration Server or wls_server_1.lok for the mentioned Managed Server.
  • Start the server instance again.

Monday, February 9, 2015

WebLogic - Native library for the Node Manager

After the WebLogic domain configuration is complete, while starting the Node Manager, you might encounter an error as reported below:

WARNING: NodeManager native library could not be loaded to write process id
java.lang.UnsatisfiedLinkError: no nodemanager in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1088)
    at weblogic.nodemanager.util.UnixProcessControl.<init>(UnixProcessControl.java:25)
    at weblogic.nodemanager.util.ProcessControlFactory.getProcessControl(ProcessControlFactory.java:23)
    at weblogic.nodemanager.server.NMServer.writeProcessId(NMServer.java:253)
    at weblogic.nodemanager.server.NMServer.writePidFile(NMServer.java:230)
    at weblogic.nodemanager.server.NMServer.<init>(NMServer.java:121)
    at weblogic.nodemanager.server.NMServer.main(NMServer.java:505)
    at weblogic.NodeManager.main(NodeManager.java:31)

<Feb 9, 2015 10:19:50 AM CST> <SEVERE> <Fatal error in NodeManager server: Native version is enabled but NodeManager native library could not be loaded>

This is because by default, Oracle enables native libraries for the operating system to be used by the Node Manager, even when the native version is actually not provided for the specific operating system. Here's the statement from the Oracle documentation Administering Node Manager for Oracle WebLogic Server:

Oracle provides native Node Manager libraries for Windows, Solaris, Linux on Intel, Linux on Z-Series, and AIX operating systems.

To fix this error in an unsupported operating system (like Mac OS, in my case), you can simply disable the native version support by updating the configuration setting in the nodemanager.properties file. The file only gets created until the Node Manager has started up once. It's typically in the $DOMAIN_HOME/nodemanager directory. In the file, find the the following setting:

NativeVersionEnabled=true

Update it to be as follow:

NativeVersionEnabled=false

Now, you can start the Node Manager:

nohup ./startNodeManager.sh > nm.out&

Check out the log file, the warning about the NodeManager native library could not be loaded is still there, but the Node Manager should start up successfully after printing out the current configuration settings.

Resources:

Wednesday, January 7, 2015

ADF - The markScopeDirty() method for ADF memory scopes

We have a coding convention of using memory-scoped data in our ADF Faces development - always manage memory-scoped data, such as parameters or state as properties of managed beans. Comparing to putting the data directly into memory scopes, the convention has the following benefits:

  • allows proper documentation
  • allows validation, initialization and logging
  • helps understanding and maintenance.

There is a caveat however, when applying the coding convention to the ADF Faces-specific scopes - page flow scope and view scope.

The ADF Controller uses session scoped objects to hold the page flow scope and view scope. When the high availability (HA) mode is on, the application server will serialize any objects in the session scope and replicate the serialized data within the cluster. To void blind serialization of the page flow scope and view scope, ADF optimizes the process - you have to make sure the framework is aware of changes to one of these ADF scopes by marking the scope as dirty.

If the scope is modified by calling its put(), remove(), or clear() methods, the framework will handle the marking, such that you don't have to care about it when you put data directly into the scope. When the properties of managed beans are used as suggested in our coding convention, then the framework must be notified of changes to the properties. This can be done by the code like this:

Map<String, Object> viewScope = AdfFacesContext.getCurrentInstance().getViewScope();
ControllerContext ctx = ControllerContext.getInstance();
ctx.markScopeDirty(viewScope);

Repeating this for every property of managed beans is surely bad. Hard-coding the scope where the managed beans are put into does not look like a good idea either. These concerns lead to the following solution in the base class for all managed beans:

public static final String VIEW_SCOPE = "view";
public static final String PAGE_FLOW_SCOPE = "pageFlow";
private String scope;

public String getScope() {
    return scope;
}

public void setScope(String scope) {
    if (scope == null || VIEW_SCOPE.equals(scope) ||
        PAGE_FLOW_SCOPE.equals(scope)) {
        this.scope = scope;
    } else {
        throw new IllegalArgumentException("Unsupported ADF scope: " +
                                           scope);
    }
}

public void markScopeDirty() {
    if (this.scope == null) {
        return; // no scope is specified, skip
    }

    String prop =
        ControllerConfig.getCurrentProperty(ControllerProperty.ADF_SCOPE_HA_SUPPORT);
    if (!"true".equals(prop)) {
        return; // support not enabled, skip
    }

    Map<String, Object> scopeObject = null;
    if (VIEW_SCOPE.equals(this.scope)) {
        scopeObject = AdfFacesContext.getCurrentInstance().getViewScope();
    } else if ("pageFlowScope".equals(this.scope)) {
        scopeObject =
            AdfFacesContext.getCurrentInstance().getPageFlowScope();
    } else {
        // should never happen, setScope() has done the validation
    }

    ControllerContext.getInstance().markScopeDirty(scopeObject);

    System.out.println("DEBUG: markScopeDirty for HA [scope=" + scope +
                       "]");
}

Now it's much easier to mark the scope as dirty, simply call the markScopeDirty() method in the property setter method of the managed bean.

How to set the scope that should be marked? It's recommended to use the scope property as a managed property, e.g. set the scope property right at the point where and when the managed bean is declared to be in that scope:

Image: The scope managed property

Resources:

Wednesday, December 17, 2014

ADF - The value attribute of SelectMany components

The selection components allow the user to select single and multiple values from a list or group of items. The value attribute of SelectOne components is straightforward, but what about the value of SelectMany components?

ADF Faces provides a number of SelectMany components. The selectManyCheckbox component is one of them which allows the user to select multiple values from a series of checkboxes. In the Tag Reference of the component, the type of the value attibute is Object, and the description:

the value of the component. If the EL binding for the "value" points to a bean property with a getter but no setter, and this is an editable component, the component will be rendered in read-only mode.

Simply the same as it for other components. Not much helpful. After some digging, I found the following code snippet:

// org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.SimpleSelectManyRenderer

// OK, is this a List or an array?
boolean isList = ((modelClass == null) ||
                  modelClass.isAssignableFrom(List.class));
boolean isArray = (modelClass != null) && modelClass.isArray();
// We only support lists and arrays;  if neither, quit.
if (!isList && !isArray)
{
  _throwUnsupportedModelType(context, modelClass, component);
}

Clearly, the value attribute of SelectMany components, must be a List or an Array, and the default type is List.

You can download the sample application - SelectManyCheckbox.jws. This application demonstrates how to handle the value attribute and process the selected items of the selectManyCheckbox component.

Image: sample page

In this sample application. The value attribute of one of selectManyCheckbox components is designed to be an Array; and the other one is left simply as an Object.

private Weekday[] days = new Weekday[] { Weekday.Sunday, Weekday.Saturday };
private Object sports;

Once the user makes some selections on both components, and submit. You can find the message from the Log Window like this:

>>> days: [Lcom.adfsamples.view.beans.SelectManyBean$Weekday;
>>> sports: java.util.ArrayList

The data type of the first component (days) is an Array as expected, and the second one (sports) is handled as an ArrayList, the default data type for the value attribute.

Sample Applications:

Environment:

  • Oracle Alta UI
  • JDeveloper 12.1.3.0.0 Build JDEVADF12.1.3.0.0GENERIC_140521.1008.S
  • Safari Version 8.0.2 (10600.2.5)
  • Mac OS X Version 10.10.1 (Yosemite)

Resources:

Oracle Fusion Middleware Tag Reference for Oracle ADF Faces 12c (12.1.3)

Monday, December 15, 2014

ADF - panelLabelAndMessage's undocumented skin property

When working on the skinning of the panelLabelAndMessage component, you may have noticed a special skinning technique used for this component. For example, from a simple snippet below:

<af:panelLabelAndMessage label="Label 1" id="plam1">
  <af:outputText value="outputText in panelLabelAndMessage" id="ot1"/>
</af:panelLabelAndMessage>

An HTML output is rendered with something like this:

<td valign="top" style="padding-left:14px" class="AFPanelFormLayoutContentCell af_panelLabelAndMessage_content-cell">outputText in panelLabelAndMessage</td>

I'm talking about the "padding-left:14px" inline style which actually comes from the skin (Alta UI skin for this case). For some reason, a special undocumented ADF Skin property is used to give the hint to the renderkit to generate this inline style. You can find it in the skin file of for example Alta UI (or Skyros):

alta-v1-desktop.css:

/* For non-input content, we need to render some padding on the panelLabelAndMessage
 * content-cell to align the leading edge of the content with the input content. */
af|panelLabelAndMessage {
  -tr-output-content-padding: 14px;
}

Here's the Properties window:

Image: af|panelLabelAndMessage - Properties

Luckily, we can customize the value in the extended skin file, or simply remove it with the -tr-inhibit ADF Skin property:

af|panelLabelAndMessage {
  -tr-inhibit: -tr-output-content-padding;
}

Chinese Summary:

ADF 在 组件 panelLabelAndMessage 的皮肤中,使用了一个没有正式文档的 ADF 皮肤属性 "-tr-output-content-padding" 用以为 panelLabelAndMessage 的非输入型内容生成 HTML 的内联样式,添加前置留白,从而方便其与输入型的内容对齐。

Resources:

Tuesday, December 9, 2014

Alta UI Workarounds - panelFormLayout

After days of hard working to fix issues of vertical alignment and distribution between different components in a complex form, I realized I need a unified solution, instead of ad-hoc, case by case pixel tuning for Oracle Alta UI skin. This is the second post on Alta UI Workarounds, but it would be first in the table of content of the series.

Considering the massive size of the skin file, the posts and workarounds are by no means exaustive, just some notes, good ideas or bad ideas. We will start from some basic rules and then the panelFormLayout component.

To align inline-level boxes, the basic idea here is to align them vertically using "vertical-align: middle", then make sure the height of all inline-level boxes is as described below.

For replaced inline elements, inline-block elements, and inline-table elements, the height of the inline-level box is their margin box; for non-replaced inline elements, it's their "line-height". Thus, we use a global "line-height"; setup a target line box height, then try best to make the height of margin boxes of all inline elements other than non-replaced inline elements to be the target line box height.

To simplify alignment, as long as possible, try keep vertical padding and margin distributed evenly to the top and bottom side, so that they work for any "vertical-align" value in the same way. For horizontal padding and margin, distribute them evenly to the left and right side, so that they work for both ltr and rtl direction.

Ok, here comes the basic rules I'm using:

.XTargetLineBoxHeight:alias {
  height: 28px;
}

/* The target line-height in pixel for the default font-size (12px) is 18px 
 * (leaving 10px for the top and bottom paddings), thus set line-height here
 * to unitless value of 1.5 (18/12 = 1.5). 
 */
.XDefaultLineHeight:alias {
  line-height: 1.5;
}

/* margin box height = border box height + margin-top + margin-bottom */
.XDefaultFormControlHeightMarginBox:alias {
  -tr-rule-ref: selector(".XTargetLineBoxHeight:alias");
}

.XDefaultFormControlHeightBorderBox:alias {
  -tr-rule-ref: selector(".XTargetLineBoxHeight:alias");
}

.XFormControlVerticalMargins:alias {
  margin-top: 0;
  margin-bottom: 0;
}

/* TODO: revisit this setting */
.XFormCellVerticalPaddings:alias {
  padding-top: 2px;
  padding-bottom: 2px;
}

Now, apply the basic rules to panelFormLayout:

/* in panelFormLayout, use consistent line-height for better vertical
 * alignment and vertical distribution. 
 */
af|panelFormLayout {
  -tr-rule-ref: selector(".XDefaultLineHeight:alias");
}

/* use the same padding for the top and bottom of the form cell to simplify
 * the logic of vertical spacing between cells.
 */
.AFPanelFormLayoutContentCell,
af|panelFormLayout::content-cell,
af|panelFormLayout::label-cell,
af|panelLabelAndMessage::content-cell.AFPanelFormLayoutContentCell {
  -tr-rule-ref: selector(".XFormCellVerticalPaddings:alias");
}

Then, we need style the label in the panelFormLayout component.

/* make label an fixed-height inline-block element, so that it aligns with
 * other components easier, either for start or top labelAlignment, or 
 * for top, middle or bottom vertical-align.
 */
.XLabel:alias {
  box-sizing: border-box;
  display: inline-block;
  vertical-align: middle;
  padding: 5px 0;
  -tr-rule-ref: selector(".XDefaultLineHeight:alias");    
  -tr-rule-ref: selector(".XTargetLineBoxHeight:alias");
}

af|panelFormLayout label {
  -tr-rule-ref: selector(".XLabel:alias");
}

Now, the bad news first, we still have to play that tedious pixel game - fixing line-height and padding for many form control components, especially agent specific styles. The good news is, this time, we have clearly defined simple rules. We can do it in a consistent way. For example, to fix the styles of the inputText component, I have the following:

/* basic styling of inputText */
.XInputText:alias {
  box-sizing: border-box;
  display: inline-block;
  vertical-align: middle;
  margin: 0;
  padding: 4px 6px;
  border-width: 1px;
  -tr-rule-ref: selector(".XDefaultLineHeight:alias");    
  -tr-rule-ref: selector(".XTargetLineBoxHeight:alias");    
}

af|inputText::content {
  -tr-rule-ref: selector(".XInputText:alias");    
}

The really dirty part is actually to remove styles from the inherited skin. I'm trying to do it in this way:

af|inputText::label {
  -tr-inhibit: padding-top;
}
af|inputText::label:rtl {
  -tr-inhibit: padding-top;
}

and in this way:

/* reset native radio and checkbox input elements, so that they line up 
 * with their labels properly. 
 */
.XSelectOneRadioNativeInput:alias {
  position: static;
  vertical-align: middle;
  margin: 0;
  padding: 0;    
}

af|selectBooleanRadio::native-input,
af|selectOneRadio::native-input,
af|selectBooleanCheckbox::native-input,
af|selectManyCheckbox::native-input,
af|selectBooleanRadio::native-input:rtl,
af|selectOneRadio::native-input:rtl,
af|selectBooleanCheckbox::native-input:rtl,
af|selectManyCheckbox::native-input:rtl {
    -tr-rule-ref: selector(".XSelectOneRadioNativeInput:alias");
}

@agent webkit, gecko, ie {
  af|selectOneRadio::native-input,
  af|selectBooleanRadio::native-input,
  af|selectBooleanCheckbox::native-input,
  af|selectManyCheckbox::native-input,
  af|selectOneRadio::native-input:rtl,
  af|selectBooleanRadio::native-input:rtl,
  af|selectBooleanCheckbox::native-input:rtl,
  af|selectManyCheckbox::native-input:rtl {
    -tr-rule-ref: selector(".XSelectOneRadioNativeInput:alias");
  }
}

Here's the display result of the sample page with Alta UI:

Image: panelFormLayout with Alta UI

This is the result from the extended UI skin:

Image: panelFormLayout with Alta UI Workarounds

The workaround looks better. It perfectly lines up components and labels horizontally, distributes components vertically, and it works in a consistent way for different components and layouts.

Sample Applications:

Environment:

  • Oracle Alta UI
  • JDeveloper 12.1.3.0.0 Build JDEVADF12.1.3.0.0GENERIC_140521.1008.S
  • Safari Version 8.0
  • Mac OS X Version 10.10

Sunday, December 7, 2014

Alta UI Workarounds - inputDate's vertical-align in webkit

Having a lot of fun, and even more pain in the last month, playing with new Oracle Alta UI. This post is meant to be the opening of the Alta UI Workarounds topic, a collection of short posts on working around Alta UI skin. Check out the AltaUIWorkarounds label and the Sample Application!

Okay, here comes the first case. When the inputDate component is grouped with other sibling components in a panelGroupLayout component, and placed in a panelLabelAndMessage component, and then in a panelFormLayout component, it might not be vertically aligned properly in webkit browsers. Say, the following code:

<af:panelFormLayout id="pfl1">
    <af:panelLabelAndMessage id="plam1" label="Starts">
        <af:panelGroupLayout id="pgl3">
            <af:selectBooleanRadio id="sbr1" text="On" label="On" simple="true"/>
            <af:inputDate id="id1" label="On" simple="true"/>
        </af:panelGroupLayout>
    </af:panelLabelAndMessage>
</af:panelFormLayout>

The fragment is rendered like this:

Image: inputDate with Alta UI

Th problem is in the Alta UI skin file (alta-v1-desktop.css, ln:6133):

@agent webkit {
  af|panelLabelAndMessage::content-cell.AFPanelFormLayoutContentCell af|inputDate {
    /*TODO ALTA*/
    vertical-align: 50%;
  }
}

To fix the issue, simply override the rule in your extended skin file like this:

@agent webkit {
  af|panelLabelAndMessage::content-cell.AFPanelFormLayoutContentCell af|inputDate {
    vertical-align: middle; /* vertical-align: 50%; (ln:6133) */
  }
}

Now the fragment is rendered as expected:

Image: inputDate with Alta UI Workarounds

Vertically aligning those input components in a consistent way, say with vertical-align: middle, helps to avoid this kind of glitches.

Sample Applications:

Environment:

  • Oracle Alta UI
  • JDeveloper 12.1.3.0.0 Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S
  • Safari Version 8.0
  • Mac OS X Version 10.10

Friday, December 5, 2014

ADF - Change Skin at Runtime

For a ADF Faces application, you can configure the skin family for the application in the trinidad-config.xml file. The trinidad-config.xml allows you to define properties using the Expression Language (EL) or static values. The skin-family is one of such properties that accepts EL expression as the value, so that you can enable end users to change the application’s ADF skin at runtime by exposing a component that allows them to update the value of the skin-family property.

In the Sample Application, the `trinidad-config.xml” file is configured like this:

<?xml version="1.0" encoding="UTF-8"?>
<trinidad-config xmlns="http://myfaces.apache.org/trinidad/config">
  <skin-family>#{skinSelectorBean.skinFamily}</skin-family>
</trinidad-config>

Then in the sample page, a selectOneRadio component is provided, allowing end users to switch between the Alta skin and the Skyros skin:

<af:selectOneRadio id="sor1" label="Select Skin" autoSubmit="true"
                   valueChangeListener="#{skinSelectorBean.skinFamilyValueChanged}"
                   value="#{skinSelectorBean.skinFamily}">
  <af:selectItem id="si1" label="Alta" value="alta"/>
  <af:selectItem id="si2" label="Skyros" value="skyros"/>
</af:selectOneRadio>

When the end user chooses the skin from the list, the skinFamily property value of the backing bean is updated, and then the valueChangeListener method of the backing bean is called. The method updates the whole view in response to the change of the skin, such that the view is rendered with the selected skin. Here, nothing special. The only interesting part is how to update the whole view properly. Please see the comments for the detail.

public void skinFamilyValueChanged(ValueChangeEvent valueChangeEvent) 
throws IOException {
    // ValueChangeEvent is handled in the PROCESS_VALIDATIONS phase. 
    // Calling refreshPage() will skip the UPDATE_MODEL_VALUES phase 
    // which we need to update skinFamily. We have to queue this event 
    // to the INVOKE_APPLICATION phase.
    if (valueChangeEvent.getPhaseId() != PhaseId.INVOKE_APPLICATION) {
        valueChangeEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
        valueChangeEvent.queue();
        return;
    }

    // refresh the whole view
    refreshView();
}

private void refreshView() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    String viewId = facesContext.getViewRoot().getViewId();
    ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
    UIViewRoot root = viewHandler.createView(facesContext, viewId);
    root.setViewId(viewId);
    facesContext.setViewRoot(root);
}

Chinese Summary:

在 trinidad-config.xml 配置文件中,可以设置 skin-family 属性的值为 EL 表达式。通过相应的组件可以允许用户在运行时更新该表达式的值,从而动态地选择用应用程序的 ADF 皮肤。

Sample Application:

Environment:

JDeveloper 12.1.3.0.0 Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S

Thursday, November 27, 2014

ADF - Access resources packaged in an ADF Library JAR

Oracle ADF and JDeveloper support packaging a reusable component and its resources into an ADF Library JAR. When the component is consumed by a web application, ADF and JDeveloper automatically make the resources of component available at runtime to serve requests. At most time, you don’t have to care about the detail behind the scene. But if the resources (css, js, png, jpeg, etc.) cannot be served from the ADF Library JAR, or only some special resources cannot be accessed, then this post is probably for you. As using bundled font files in a web application is getting so popular these days (e.g. Bootstrap uses font files for its glyph icons), I guess you are reading this post probably because of missing font files (eot,ttf,woff,svg).

When you deploy a project into an ADF Library JAR, JDeveloper packages artifacts under the web content root directory (if any) to the JAR. When you make use of a component from the JAR in your web application JDeveloper extends the web.xml file in your web application with two key players for accessing resources from an ADF Library JAR - the adflibResources servlet and the ADFLibraryFilter.

Here’s the entries for the adflibResources servlet:

<servlet>
  <servlet-name>adflibResources</servlet-name>
  <servlet-class>oracle.adf.library.webapp.ResourceServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>adflibResources</servlet-name>
  <url-pattern>/adflib/*</url-pattern>
</servlet-mapping>

And the entries for the ADFLibraryFilter:

<filter>
  <filter-name>ADFLibraryFilter</filter-name>
  <filter-class>oracle.adf.library.webapp.LibraryFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>ADFLibraryFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>REQUEST</dispatcher>
</filter-mapping>

Usually, JDeveloper can add these entries automatically if it’s aware that you are using a component from an ADF Library JAR, for example, when you use the wizard to create a page based on a page template exposed from the JAR. If for some reason, these entries are not there, you can surely manually add them there.

At runtime, when the web application serves a request, if a resource is not found in the web content directory of the web application, the ADFLibraryFilter forwards the request to the adflibResources servlet to load the resource from the ADF Library JAR. By default, the resources handled by the ADFLibraryFilter are files with an extension in the following list:

",png,jpg,jpeg,gif,js,css,htm,html,"

So, for any other type of resources, you will end up with a 404 error. Fortunately, it’s allowed to customize this list. For the Bootstrap font files case, you can customize the extension list with the include-extension-list initialization parameter of the ADFLibraryFilter like this:

<filter>
  <filter-name>ADFLibraryFilter</filter-name>
  <filter-class>oracle.adf.library.webapp.LibraryFilter</filter-class>
  <init-param>
    <param-name>include-extension-list</param-name>
    <param-value>,png,jpg,jpeg,gif,js,css,htm,html,eot,ttf,woff,svg,</param-value>
  </init-param>
 </filter>

Chinese Summary:

为了加载 ADF 库文档中的资源,Web 应用程序的 web.xml 文件需要配置 adflibResources servlet 以及 ADFLibraryFilter 过滤器。对于特殊文件类型的资源,例如字体文件等,还需要配置 ADFLibraryFilter 的初始化参数以允许其处理此类文件。

Sample Application:

Environment:

JDeveloper 12.1.3.0.0 Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S

Tuesday, November 25, 2014

ADF - Package reusable components into an ADF Library JAR

When we work on ADF components, we may want to reuse them across different projects, applications and teams. Oracle ADF and JDeveloper support to package reusable components and associated artifacts into an ADF Library JAR. An ADF Library JAR is a special JAR containing ADF components and appropriate control files for the components. ADF page templates is one of types of these high-level reusable components that can be packaged into an ADF Library JAR.

I’m not going to introduce how to package reusable ADF components into an ADF Library JAR in general here again, because the official documentation Developing Fusion Web Applications with Oracle Application Development Framework itself is a great resource where you can learn about it. You can find the information from the chapter 44 Reusing Application Components.

In this post, taking page templates as an example, I’ll be talking about a practical approach to package only required artifacts into an ADF Library JAR, leaving irrelevant files out of it, and still allowing us to develope and test the reusable components easily.

You can find and download sample sources for this post. The sample sources consists of two applications - the pagetemplates application for the ADF Library containing the page template, and the consumer application that uses the page template from the ADF Library:

Image: Sample Applications

To create ADF page templates as reusable components, we start from an ADF ViewController project. In the sample applications, the pagetemplates-webapp project in the pagetemplates application is such an ADF ViewController project. It uses the popular Bootstrap framework to create a very simple page template. We can test the page template with test pages in the root directory of web contents.

If we create an ADF Library JAR deployment profile for the pagetemplates-webapp project to package the page template as a reusable component, we will have all the required artifacts and resources in the result ADF Library JAR. As a side-effect, some artifacts we don’t really want will also be included, such as those test pages and irrelevant metadata files, in this case, files under the WEB-INF/ directory, etc. Unfortunately, it’s now allowed to configure the files and folders that are to be packaged into an ADF Library JAR.

You can surely remove unwanted artifacts from the project to get a tidy JAR, but that will make development and testing of your page templates very hard. You might consider creating another ADF ViewController project that uses the deployed ADF Library JAR to test the page templates. Better this time, but every time you make a change to you page templates, you have to build and deploy your ADF Library JAR, and then rebuild and run your testing project to see the result. You would eventually rather stay with your untidy JAR.

To get a clean ADF Library JAR without making testing a nightmare, instead of deploying the ADF Library JAR directly from the original ADF ViewController project containing the page templates, we can create another ADF ViewController project dedicated in deployment purpose. This second project is a bare ViewController project actually, with all appropriate project source paths configured to point to the corresponding ones in the original project. With project source paths, it’s allowed to configure a list of files or folders that are to be specifically included in the current project, such that you can choose now which artifacts are going to be packaged into the ADF Library JAR deployment profile.

In the sample application, the pagetemplates-adflib project is created as an ADF ViewController project for this purpose. Once the project is created, its project source paths are set to point to the respective ones in the pagetemplates-webapp project, and choose to include or exclude selected files or folders for the current project.Particularly, In the Project Source Paths window, it looks like this:

Image: Project Properties / Project Source Paths

And in the Project Source Paths: Web Application window, the setting is as follow:

Image: Project Properties / Project Source Paths: Web Application

Finally, create an ADF Library JAR deployment profile for the pagetemplates-adflib project:

Image: Project Properties / Deployment

Note: the deploy folder is configured intentionally under the root folder containing the sample applications.

With this approach, we can develop and test the page templates in the full ADF ViewController project, and deploy the ADF Library JAR any time from the bare ViewController project. The same approach also works for other types of reusable ADF components. Enjoy!

Chinese Summary:

在开发可重用的 ADF 组件,并将其打包为 ADF 库文档时,如果不希望包含那些无关的配置文件和用于测试的文件时。可以创建两个 ADF 视图控制器项目,其中之一为完整项目,包含组件及其所需工件和资源文件,以及所有用于测试的文件。另一个为裸项目,其项目源代码路径都设置指向完整项目中的对应路径,同时设置包含在该项目中的文件或目录的列表。基于这个方法,完整的项目用于开发和测试可重用组件;而为裸项目定义一个 ADF 库文档部署概要文件,专门用于部署 ADF 库文档。

Sample Applications:

Environment:

  • Mac OS X Version 10.10
  • Safari Version 8.0
  • JDeveloper 12.1.3.0.0 Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S
  • Oracle Alta UI

Monday, October 27, 2014

Ignoring Files Specific to Oracle JDeveloper & ADF

If you are using Oracle JDeveloper and ADF with some version control system, such as Git, here’s a minimum list of JDeveloper and ADF specific untracked files and directories you will want to add to your .gitignore file to ignore them:

.data/
temp/
classes/
cwallet.sso.lck

The .data/ directory is the application storage directory used by the IDE Performance Cache feature. For each application, you can specify a directory where application-specific caches and indexes used by JDeveloper are stored. To customize the location of the directory, open the Application Properties dialog, then go to the IDE Performance Cache page.

Image: IDE Performance Cache

The default location is the root directory of the application:

Image: IDE Performance Cache

The temp/ directory is used for ADF styles caching. It gets created under the WEB-INF/ directory in the web content directory of the view project, when you open a page or page fragment in the design mode in JDeveloper.

Image: ADF Styles caching

The classes/ directory is the default Output Directory for the project. It can be customized in the Project Properties dialog, Project Source Paths page.

Image: Project Source Paths

The cwallet.sso.lck file is the lock file for the wallet.sso file which is a part of Oracle Credential Store Framework.

The ignore file list is also useful when you are using Subversion or CVS.

Chinese Summary:

针对 Oracle 的 JDeveloper 和 ADF 的,用于版本控制系统的忽略文件列表。可以添加到诸如 Git 的 .gitignore 文件,或者类似的其它版本控制系统(Subversion 和 CVS)的忽略文件中。

Sunday, October 26, 2014

ADF - Displaying Multi-Line Text with outputText Component

With ADF, the inputText component can be used to generate a multi-row text area control in browser, allowing the user to enter multi-line text. To display the multi-line text that the user input, a common practice is using a read-only multi-row inputText component. I bet this approach isn't always what you want, as the inputText component has fixed rows, and shows a scrollbar when necessary. In this post, I'm describing how to display multi-line text with the outputText component. It's about CSS line-wrapping and word-breaking pertaining to ADF faces components.

To display multi-line text, the basic idea is applying the white-space CSS property to the element with one of following values: pre, pre-wrap and pre-line. This property controls the processing of whitespace inside an element. The exact value you need depends on the behavior you want. In this post, I'm using pre-wrap as the example, which means "Sequences of whitespace are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.". Here's the code snippet from the skin of the sample application:

.PreWrap {
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    word-wrap: break-word;      /* IE 5.5-7 */
}

In this rule, the word-wrap CSS property specifies whether the break within a word is allowed to prevent overflow when an otherwise-unbreakable string is too long to fit within line box. The property is applies only when the white-space property allows wrapping. The value of break-word means "Normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line." This property is useful for the cases, such as really long URLs.

For example, the normal word-breaking runs like the following:


As you can see, it tries the best to wrap the text to fit within the line box by breaking the text after the hyphens which are acceptable break points. But it still overflows.

With break-word, it runs like this:


Now, it breaks the text at arbitrary points in addition to those acceptable break points.

The white-space and word-wrap properties are supposed to be what exactly you need to display multi-line text with the outputText ADF Faces component, but it's not the whole story. You have to deal with the layout component to make sure the outputText component inside it works as you expect. Here, I'm talking about the panelFormLayout and then panelGridLayout components - the most common layout components that the multi-line outputText components will work with.

To work with the panelFormLayout component, wrap the outputText component with the PreWrap style class in a panelLabelAndMessage component, and put it into the panelFormLayout component:

<af:panelFormLayout id="pfl1" labelWidth="100" fieldWidth="350">
    <af:inputText id="it1" label="inputText"
                  placeholder="Add some multi-line text and click Update to display it below."
                  contentStyle="width:340px;" rows="12" value="#{pageFlowScope.text}"/>
    <af:button text="Update" id="b_updt"/>
    <af:panelLabelAndMessage id="plam1" label="outputText" labelStyle="vertical-align:top">
        <af:outputText id="ot1" value="#{pageFlowScope.text}" partialTriggers="b_updt"
                       styleClass="PreWrap"/>
    </af:panelLabelAndMessage>
</af:panelFormLayout>

If there is a long unbreakable string in the text, it works like this (See panelFormLayout page in the sample application):



Even with the fieldWidth="350" property, the content cells (with yellow background) of the panelFormLayout still expand to fit the longest unbreakable string.

The panelFormLayout component generates table elements to layout the components inside it. By default, the table element uses the automatic table layout algorithm. In case the content does not fit in the column,  the column's width is set by the preferred minimum width, e.g. by trying all acceptable line breaks.

This is how it works - by default. Fortunately, we can change this behavior by changing the table-layout CSS property of the table from auto to fixed. For example:

.FixedTableLayout af|panelFormLayout::column > table {
    table-layout: fixed;
    width: 100%;
}

This ADF skin rule makes sure that tables generated by the panelFormLayout component for columns use the fixed layout algorithm: "Table and column widths are set by the widths of table and col elements or by the width of the first row of cells. Cells in subsequent rows do not affect column widths".  Apply the rule to the example (panelFormLayout-fixedTableLayout.jsf):

<af:panelFormLayout id="pfl1" labelWidth="100" fieldWidth="350" styleClass="FixedTableLayout">
    <af:inputText id="it1" label="inputText"
                  placeholder="Add some multi-line text and click Update to display it below."
                  contentStyle="width:340px;" rows="12" value="#{pageFlowScope.text}"/>
    <af:button text="Update" id="b_updt"/>
    <af:panelLabelAndMessage id="plam1" label="outputText" labelStyle="vertical-align:top">
        <af:outputText id="ot1" value="#{pageFlowScope.text}" partialTriggers="b_updt"
                       styleClass="PreWrap"/>
    </af:panelLabelAndMessage>
</af:panelFormLayout>


Or, keeping the table-layout: auto property, to achieve the same purpose, we can wrap the outputText component inside a fixed-width containing box (panelFormLayout-fixedWidthContainer.jsf):

<af:panelFormLayout id="pfl1" labelWidth="100" fieldWidth="350">
    <af:inputText id="it1" label="inputText"
                  placeholder="Add some multi-line text and click Update to display it below."
                  contentStyle="width:340px;" rows="12" value="#{pageFlowScope.text}"/>
    <af:button text="Update" id="b_updt"/>
    <af:panelLabelAndMessage id="plam1" label="outputText" labelStyle="vertical-align:top">
        <af:panelGroupLayout id="pgl1" layout="vertical" styleClass="FixedWidthContainer">
            <af:outputText id="ot1" value="#{pageFlowScope.text}" partialTriggers="b_updt"
                           styleClass="PreWrap"/>
        </af:panelGroupLayout>
    </af:panelLabelAndMessage>
</af:panelFormLayout>

Here's the CSS rule:

.FixedWidthContainer {
    display: block;
    width: 340px;
    background-color: #fbf; /* for visual hint only */
}


We are good with the panelFormLayout component now. Let's try out the panelGridLayout Component. If we put the multi-line outputText component directly inside a gridCell component as in the following code snippet (panelGridLayout.jsf):

<af:gridCell id="gc4" marginStart="10px" marginEnd="10px" width="340px"
             inlineStyle="background-color:#ffb;">
    <af:outputText id="ot1" value="#{pageFlowScope.text}" partialTriggers="b_updt"
                   styleClass="PreWrap"/>
</af:gridCell>

It works like this:


Pretty much the same problem as that in the panelFormLayout component. That's because for the geometry management purpose, the gridCell component generates an absolutely positioned div element inside the div element generated by the panelGridLayout component. For an absolutely positioned block, it width is determined by so-called shrink-to-fit width - similar to calculating the width of a table cell using the automatic table layout algorithm.

We don't have a layout property this time, but we can still work around this by wrapping the outputText component inside a fixed-width containing block (panelGridLayout-fixedWidthContainer.jsf):

<af:gridCell id="gc4" marginStart="10px" marginEnd="10px" styleClass="af_gridCell">
    <af:panelGroupLayout id="pgl3" layout="vertical" styleClass="FixedWidthContainer">
        <af:outputText id="ot1" value="#{pageFlowScope.text}" partialTriggers="b_updt"
                       styleClass="PreWrap"/>
    </af:panelGroupLayout>
</af:gridCell>

Now, it works like this:


In summary, we can make use of the white-space and word-wrap CSS properties to display multi-line text with the outputText component. To get the expected width of the outputText component in a panelFormLayout or panelGridLayout component, we can wrap the outputText component in a fixed-width containing box. For the panelFormLayout component particularly, we can also apply table-layout: fixed to the content cells of the panelFormLayout component in the skin file to enforce the field width.

Chinese Summary:

利用 white-space 和 word-wrap CSS 属性,我们可以用 ADF 的 outputText 组件显示自动折行的多行文本。将 outputText 组件配合 panelFormLayout 和 panelGridLayout 布局组件使用时,为了保证 outputText 输出指定宽度的多行文本,可以将 outputText 组件包裹在一个定宽的 panelGroupLayout 组件中,然后再置于 panelFormLayout 或者 panelGridLayout 组件中。对于 panelFormLayout 组件,也可以在 ADF 皮肤文件中为 panelFormLayout 组件的 column 伪元素中对应的 table 元素设置 table-layout: fixed 属性,以关闭默认的表格自动布局算法,保证表格按照指定的宽度布局。

Resources:
Sample Application:

Environment:

  • Mac OS X Version 10.10
  • Safari Version 8.0
  • JDeveloper 12.1.3.0.0 Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S
  • Oracle Alta UI