Tuesday, April 05, 2011

JDev:Unable to create an instance of the Java Virtual Machine

I installed JDeveloper11g Studio Edition with no JDK bundle but when i tried to start JDeveloper, it gave me error

Unable to start Java Virtual Machine located at ....

In order to fix this type of error, go to installation_directoy\Middleware\JDeveloper\jdev\bin folder
and edit file jdev.conf.
Locate line "AddVMOption -XX:MaxPermSize=256M".
Now add another line just below this line:

AddVMOption -Xmx256M

Coding Standards

For any ADF/Webcenter/SOA/J2EE Java code, Model and UI layer, here are few points to make code better from writing from performance and standard point of view,that comes from our coding practice and experience.This was the list we were using while developing the Fusion Apps in Oracle.

Here I have tried to consolidate a set of checkpoints we should check before source controlling any changes.This ensures making code better, robust, standards compatible and performant.

Keep this article opened in your web browser and just before checkin, make a habit to just glance through it once to make sure, you havent forgotten unknowingly anything.

Note:
This list is expandable.It would be great to add as much as points you find I have missed in respective sections.

JSFF/JSPX code- Checkpoints

  • Make sure, you have used Resource Bundle whereever its required.
  • For Bounded taskFlows, make sure to use activation as conditional/deferred(Not Immediate) and use active condition EL expression.
  • Id of the component, length should be <= 7.
  • Make sure, you have removed unwanted PageDef Bindings.
  • If af:popup is used, make sure to set the contentDelivery to "LazyUncached".
  • If using af:contextInfo, make sure the af:dialog has modal="false".
  • If using af:contextInfo, make sure the af:showPopupBehavior has triggerType="contextInfo".
  • If using af:popup from af:commandLink, make the partialSubmit to true for af:commandLink.
  • If using af:popup. make childCreation property to "deferred" so that only when the Popup is launched the WebBean hierarchy would get created in server memory.
  • Run JAudit for the file you make changes, from Menu->Run->JAudit file.
  • Right click->Reformat before checkin.
  • If using JavaScript, can you think to avoid that.
  • jsff/jspx files must reside under /page package.
  • Taskflows must reside under /flow package.
  • Menu model xml files must reside under /menu package.
  • In Case of deriving the Url parameters, preferably use the following syntax to derive declaratively #
    Unknown macro: {facesContext.externalContext.requestParameterMap['Empno']}

    (Empno is url parameter)

Any Java Code - Checkpoints

  • Managed Bean class name should end with "Bean".
  • Dont use SOP statements.
  • New methods introduced, make sure they are modular so that they can be JUnitized.
  • New Method should aways return a value so that they can be JUnitized.
  • Add Logger statements to the new methods.
  • Make sure you have thrown sufficiently Exceptions.
  • Run JAudit for the file you make changes, from Menu->Run->JAudit file.
  • Make sure to define the Variables with a name starting with small letter.
  • Do not use underscore (_) in Variable and Method names.
  • Make sure to check for Null condition for all operation that could throw NullPointerException. Ex: CollectionModel, Row, ViewObject, ApplicationModule, String objects etc.
  • Right click->Reformat before checkin.

AM - Check Points

  • Number of occurances of createRootApplicationModule() or *AMImpl.getInstance() should be same as releaseRootApplicationModule().

Entity Object - Check Points

  • Can you convert the code you have just written into Groovy?
  • Run JAudit for the file you make changes, from Menu->Run->JAudit file.

ViewObject - CheckPoints

  • Get SQL explain plan everytime you touches a VO.
  • For new Attributes added, make sure you use proper UI hints.
  • If creating a New VO, make sure its is based on an EO(Exceptions to be considered).
  • if createViewObject calls are present, then make sure, you remove those dynamic ViewObjects.
  • If setting rangeSize() to -1, restore the rangeSize after you work on that.
  • Dont set ListRangeSize == '-1' unless the ViewAttribute using the LOV has CONTROLTYPE 'choice' or 'radio.' or 'default'
  • FetchSize should be <= 25 or same as number of rows to be displayed in UI.
  • Avoid use of vo.getROwCount()
  • View Criteria shouldnt have "null checking" checkbox checked.
  • LOVs shouldn't have "query automatically" checked.
  • SQL based VOs,should have query optimizer hint set to "FIRST_ROWS(10)".
  • Always test the application with ampooling= false when our bc4j txn involves any transient vos.

JDBC - Checkpoints

  • Move to the latest releases of Java as they become available.
  • Use prepared statements (PreparedStatement class) [article provides coded example of using Statement vs. PreparedStatement].
  • Note that two database calls are made for each row in a ResultSet: one to describe the column, the second to tell the db where to put the data. PreparedStatements make the description calls at construction time, Statements make them on every execution.
  • Avoid retrieving unnecessary columns: don't use "SELECT *".
  • If you are not using stored procedures or triggers, turn off autocommit. All transaction levels operate faster with autocommit turned off, and doing this means you must code commits. Coding commits while leaving autocommit on will result in extra commits being done for every db operation.
  • Use the appropriate transaction level. Increasing performance costs for transaction levels are: TRANSACTION_NONE; TRANSACTION_READ_UNCOMMITTED; TRANSACTION_READ_COMMITTED; TRANSACTION_REPEATABLE_READ; TRANSACTION_SERIALIZABLE. Note that TRANSACTION_NONE, with autocommit set to true gives access to triggers, stored procedures, and large object columns.
  • Store string and char data as Unicode (two-byte characters) in the database.
  • Avoid expensive database query functions such as: getBestRowIdentifier; getColumns; getCrossReference; getExportedKeys; getImportedKeys; getPrimaryKeys; getTables; getVersionColumns.
  • Use connection pooling, either explicitly with your own implementation, or implicitly via a product that supports connection pooling.
  • Use blocked fetchs (fetching table data in blocks), and tailor the block size to reduce calls to the database, according to the amount of data required.
  • Use batch updates (sending multiple rows to the database in one call).
  • Use stored procedures where appropriate. These benefit by reducing JDBC complexity, are faster as they use static SQL, and move execution to the server and potentially reduce network trips.
  • Use the type-correct get() method, rather than getObject().

EJB - Performance Checkpoints

  • Use session bean wrapper for returning multiple data rows from an entity bean, rather than returning one row at a time.
  • Use session beans for database batch operations, entity beans typically operate only one row at a time.
  • Use entity beans when only a few rows are required for the entity, and when rows need to be frequently updated.
  • Tune the underlying system, e.g. TCP/IP parameters, file limits, connection pool parameters, EJB pools sizes, thread counts, number of JVMs, JVM heap size, shared pool sizes, buffer sizes, indexes, SQL queries, keep/alive parameters, connection backlogs.
  • Transactions should span the minimum time possible as transactions lock database rows.
  • Use the lowest cost locking available from the database that is consistent with any transaction.
  • Use a dirty flag where supported by the EJB server to avoid writing unchanged EJBs to the database.
  • Commit the data after the transaction completes rather than after each method call (where supported by EJB server).
  • Do bulk updates to reduce database calls.
  • Tune the connection pool size to minimize the creation and destruction of database connections.
  • Use JDBC directly rather than using entity beans when dealing with large amounts of data such as searching a large database.
  • Use container-managed persistence when you can. An efficient container can avoid database writes when no state has changed, and reduce reads by retrieving records at the same time as find() is called.
  • Minimize database access in ejbStores. Use a "dirty" flag to avoid writing tee bean unless it has been changed.
  • Always prepare your SQL statements.
  • Close all database access/update statements properly.
  • Avoid deadlocks. Note that the sequence of ejbStore calls is not defined, so the developer has no control over the access/locking sequence to database records.

Fine Tune ADF Faces UI Layer(Performance Improvement)

Use AJAX to boost up the performance of your web pages

ADF Faces component trigger Partial Page Rendering (PPR) by default. However action components, by default, triggers full page refresh which is quite expensive and may not be required in most of the cases. Make sure that you set partialSubmit attribute to true whenever possible to optimize the page lifecycle. When partialSubmit is set to true, then only the components that have values for their partialTriggers attribute will be processed through the lifecycle.

Avoid mixing of html tags with ADF Faces components

Mixing raw html contents with ADF Faces components may produce undesired output, especially when you have complex layout design for your page. It's highly discouraged to use to embed JavaScript or CSS, instead you can use which adds the resource to the document element and optimizes further processing during tree rendering.

Avoid long Ids for User Interface components

It's always recommended to use short Ids for your User Interface (UI) components. Your JSF page finally boils down to html contents, whose size decides the network bandwidth usage for your web application.

Avoid inline usage of JavaScript/Cascading Style Sheets (CSS) whenever possible

If you need to use custom JavaScript functions or CSS in your application, try using external files to hold the same. Avoid inline usage of JavaScripts/CSS as much as possible. A better idea is to logically group them in external files and embed the required one in the candidate page using tag. If you keep JavaScript and CSS in external files, they are cached by the browser.

Avoid mixing JSF/ADF Faces and JavaServer Pages Standard Tag Library (JSTL) tags

Stick on JSF/ADF Faces components for building your UI as much as you can. JSF component may not work properly with some JSTL tags as they are not designed to co-exist. Relying on JSF/ADF Faces components may give you better extensibility and portability for your application as bonus.

Don't generate client component unless it's really needed

Set clientComponent to true only if you need to access the component on the client side using JavaScript. Otherwise this may result in increased Document Object Model (DOM) size at the client side and may affect the performance of your web page.

Prefer not to render the components over hiding components from DOM tree

If you need to hide UI components conditionally on a page, try achieving this with rendered property of the component instead of using visible property. Because the later creates the component instance and then hides the same from client side DOM tree, where as the first approach skips the component creation at the server side itself and client side DOM does not have this element added. Apparently setting rendered to false, reduces the client content size and gives better performance as bonus.

Prefer to use click-To-Edit over edit-All mode for tables

The click-To-Edit mode table lets the end user to edit the selected rows in a lockstep fashion, one row at a time. Advantages of using click-To-Edit mode are listed below.

  • In a click-To-Edit, non editable rows are rendered as output components which tend to generate less HTML than input components.
  • Client components are not created for the read-only rows.
  • Validation phase is also optimized to handle one row at a time.
  • Request and Response data is significantly lower in this mode as data relevant to the current editable row alone is being transferred between client and server. Really a good option if the table has large number of rows.

Fine tune the UI tables(af:table, af:tree, af:treeTable), displayed on your web page

  • Use appropriate content delivery mode
    Pick up the suitable content delivery mechanism for your UI table to accelerate the performance. Data can be delivered to table either upon rendering the page or lazily as separate Partial Page Request (PPR). This behavior is controlled by the contentDelivery attribute. Possible values for this attribute are:
    • immediate
    • lazy
    • whenAvailable

If the page contains only the table context or the number of rows displayed are low (say 50 or below) use immediate delivery. You can opt for lazy delivery when the page contains a number of components other than a table or if the number of rows filled is on the higher side.

  • Use suitable fetch size
    Data fetch size for a table plays critical role in deciding the performance of the containing pages. The attribute fetchSize decides the number of rows needs to be retrieved during each server round trip. You may need to ensure that value specified for this attribute is good enough to fill the displayed table rows to avoid further server round trips.

Pickup right component to display list of values (LOV)

ADF Faces provides multiple components or modes to display the 'list of values'. You may need to choose the right one based on your business requirements.

List Type Component
Input Text with List of Values af:inputListOfValues
Combo Box with List of Values af:inputComboboxListOfValues
Choice List, Combo Box, List Box, Radio Group af:selectOneChoice

Both af:inputListOfValues and af:inputComboboxListOfValues are smart enough to load the list of values on demand(lazy loading) where as af:selectOneChoice reads the entire list and populates the same when the page renders(greedy loading). You need to me be aware of the performance cost associated with each of these components. As a rule of thumb, consider af:selectOneChoice to display the list of values if the number of elements is less (say 15 or less) .In all other cases consider using either af:inputListOfValues or af:inputComboboxListOfValues, which loads list on demand.

we can disable ADF Faces Rich Client animation functionality globally, just by adding one line in trinidad-config.xml file:

  • animation-enabled = false

This will help greatly when rendering LOV popups, drawing data tables and etc. By disabling animation, artificial delay of components rendering is removed and this allows to achieve better UI performance.

Choose the right layouts to design your pages

  • While lay outing components on page, choose the right layout component that meets your requirement. If you don’t want stretch-to-fit layout, then dot use them at all. A stretch-to-fit layout is not as good performant as fixed height-width layouts.
  • Situation becomes worse, if you have nested containers with many child UI components inside.
  • You may need to be measured while opting for columnStretching property for a table to stretch the column to fit the available width. The columnStretching adds extra overhead on the client side at runtime. When the table is a complex one with large number of columns and rows, this becomes very expensive operation.
  • The same point is applicable for table with frozen columns (frozen=true), they are also expensive on the client side.

Avoid repetitive coding by improving the reusability

Use

  • Page templates
  • Declarative components
  • ADF task flows
  • Page Fragments

Use resource bundles intelligently

  • If the size of your resource bundle is huge, logically split that into multiple resource bundles. While splitting, please make sure that a single page doesn't need to look in to multiple bundles to get the localized strings.
  • Don’t over engineer your product by caching the ResourceBundle in your managed bean or through a custom way, it's already cached for you by design.

Always design your Managed Bean for High Availability

You may need to take care of following points in regards to managed bean while developing a high available fusion web application.

  • Keep the managed beans in the lowest possible scope
    While defining managed bean always try to keep them in the lowest possible scope, which reduces the runtime overhead associated with state replication across nodes in a clustered environment.
  • Keep the getters/setters of your managed bean (data model) lightweight
    You may need to understand that getters and setters for a managed bean used in a page may get called multiple times during the life cycle. Always make sure that assessors specified for the data model doesn't have any complex logic. Use managed bean only to store book keeping information, business logic should reside in your business service layer.
  • Bean should be serializable
    If the managed bean scope is higher than request, then its state needs to be serialized and copied to other nodes at the end of each request. Obviously beans need to implement java.io.Serializable interface. Note that, member variable of you class should also be serializable, or marked as transient if their state does not need to be replicated at the end of a request.
  • Mark ADF scopes as dirty to enable state replication
    ADF optimizes state replication of ADF scoped beans to avoid the blind copy of the state at the end of each request. So you may need to ask for state replication by marking them as dirty, based on bean mutation state. Use the below API to ensure the state replication for viewScope or pageFlowScoped bean if its modified for any request.
    ControllerContext.getInstance().markScopeDirty(viewScope/pageFlowScope);

Log your debugging messages smartly with ADFLogger

  • It's a bad practice to use System.out.println() to log your debugging or diagnostic messages. There is no easy way to turn off or control these logs when your application goes for production.
  • it is recommended to use oracle.adf.share.logging. ADFLogger to log all debugging messages which gives more control on the logging part. You can easily change log levels (turn off or customize) of ADFLogger using the configuration parameters present in logging.xml.

Feel free to override the default rules set for JavaScript Partitioning

  • ADF Faces provides a way to group (partitions) the JavaScript source files logically and down load each partition on demand.
  • ADF Faces allows you to tune the JavaScript library footprint to meet the needs of their application.
  • You can override the default partition rules (that come with ADF Faces) by creating your own adf-js-partitions.xml in the WEB-INF directory.

Speed up your web application by caching static contents

  • Caching static contents such as images, JavaScript, css etc. improves performance of the system.
  • ADF Faces is packaged with oracle.adf.view.rich.webapp.AdfFacesCachingFilter (servlet filter) which marks the application resources for caching at external Web Cache and/or user-agents (browsers).
  • ADF Faces comes with set of default rules for caching static contents; however developers can override the default caching behavior with application's adf-config.xml file.
  • This file is located under your web application's WEB-INF folder. Following diagram shows the syntax for defining caching rules in adf-config.xml.

    <adf-config xmlns="http://xmlns.oracle.com/adf/config"
    xmlns:adf="http://xmlns.oracle.com/adf/config/properties"
    xmlns:sec="http://xmlns.oracle.com/adf/security/config">
    <adf-faces-config xmlns="http://xmlns.oracle.com/adf/faces/config">
    <caching-rules>
    <caching-rule id="cache js">
    <cache>true</cache>
    <compress>true</compress>
    <duration>99999</duration>
    <agent-caching>true</agent-caching>
    <cache-key-pattern>*.js</cache-key-pattern>
    </caching-rule>
    <caching-rule id="cache jpeg">
    <cache>true</cache>
    <compress>false</compress>
    <duration>99999</duration>
    <agent-caching>true</agent-caching>
    <cache-key-pattern>*.jpeg</cache-key-pattern>
    </caching-rule>
    </caching-rules>
    </adf-faces-config>
    </adf-config>

Chapter 8 of Fusion Middleware Performance Tuning has more tips and information

http://download.oracle.com/docs/cd/E17904_01/core.1111/e10108/adf.htm#CIHHGADG

Usecase(ADF)-Controlling UI components Behaviour from Model Layer

Requirement

Say,an ADF UI has 50 UI components and you want to control these UI components behaviour dynamically.For example,

* 15 UI components shouldnt be rendered in a specific condition.
* 10 UI components should be ReadOnly in a specific condition.
* 20 UI components should have a MaxLength 120 in a specific condition.
* 30 UI components should have a different Label in a specific condition.
* and so on.

Simple Solution

Simplest solution is to manipulate the "rendered", "disabled" ,"label", "shortDesc", "maximumLength" etc properties in the JSFF/JSPX using EL expressions which can be calculated using a managed bean method.
Smart Solution

The simple solution makes the JSFF/JSPX messy with complex conditional EL expressions which is hard to maintain and improvise.

A smart solution is to handle this entirely in the Model Layer if your UI is driven by a View Object. View Object attributes have Control Hints which derive their values and represent themselves in the UI layer.

These are the things you need to do to achieve this.

Create a Service/Util class that will handle the logic to derive the values of the properties based on some business requirement.

import java.util.HashMap;
import java.util.Map;

import oracle.jbo.AttributeHints;

public class UIHintsService {

private static UIHintsService uiHintsService;

private UIHintsService() {
super();
}

public static synchronized UIHintsService getInstance() {
if (uiHintsService == null) {
uiHintsService = new UIHintsService();
}
return uiHintsService;
}
//Your Business Logic goes here, which says, for DepartmentName Attribute following UI properties need to be changed at the runtime.
public Map getAttributeHints(String attributeName) {
Map map = new HashMap();
if("DepartmentName".equalsIgnoreCase(attributeName))
{
map.put(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 100);
map.put(AttributeHints.ATTRIBUTE_LABEL,
attributeName + "[Overridden1111]");
map.put(AttributeHints.ATTRIBUTE_TOOLTIP,
attributeName + "[Overridden1111]");
map.put(AttributeHints.ATTRIBUTE_DISPLAY_HINT,
AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
map.put(AttributeHints.HINT_NAME_UPDATEABLE,
"NEVER");
}
return map;
}
}



Create a Custom Class in your Model Layer called LazyViewRowAttrHintsImpl.java that extends oracle.jbo.server.ViewRowAttrHintsImpl.

public class DepartmentsViewRowImpl extends ViewRowImpl {


/**
* This is the default constructor (do not remove).
*/
public DepartmentsViewRowImpl() {
}

/**
* Gets Departments entity object.
* @return the Departments
*/
public EntityImpl getDepartments() {
return (EntityImpl)getEntity(0);
}

@Override
protected ViewRowAttrHintsImpl createViewRowAttrHints(AttributeDefImpl attrDef) {
//See here, we are returning the custom RowAttrHintsImpl class which has our own logic
return new LazyViewRowAttrHintsImpl(attrDef, this);
}

}
import java.util.HashMap;

import java.util.Map;

import oracle.jbo.AttributeHints;
import oracle.jbo.LocaleContext;
import oracle.jbo.server.AttributeDefImpl;
import oracle.jbo.server.ViewAttributeDefImpl;
import oracle.jbo.server.ViewRowAttrHintsImpl;
import oracle.jbo.server.ViewRowImpl;

import model.UIHintsService;

public class LazyViewRowAttrHintsImpl extends ViewRowAttrHintsImpl {

public LazyViewRowAttrHintsImpl(AttributeDefImpl attributeDefImpl,
ViewRowImpl viewRowImpl) {
super(attributeDefImpl, viewRowImpl);
decorateWithLazyHints(attributeDefImpl);

}

public LazyViewRowAttrHintsImpl() {
super();
}

private void decorateWithLazyHints(AttributeDefImpl attributeDefImpl) {
String flag = (String)attributeDefImpl.getProperty("Populated");
if ("true".equals(flag)) {
return;
}
System.out.println("##### Inside decorateWithLazyHints for : " +
attributeDefImpl.getName());
Map propMap =
UIHintsService.getInstance().getAttributeHints(attributeDefImpl.getName());
if (propMap != null && propMap.size() > 0) {
attributeDefImpl.setPropertyMap(propMap);
AttributeDefImpl entAttr =
((ViewAttributeDefImpl)attributeDefImpl).getEntityAttributeDef();
if (entAttr != null) {
entAttr.setPropertyMap(propMap);
}
}
attributeDefImpl.setProperty("Populated", "true");
}
}



In your VORowImpl.java, override the method createViewRowAttrHints(AttributeDefImpl attrDef) to return the custom LazyViewRowAttrHintsImpl like this.

Your UI JSFF/JSPX would look like this as you have already used the VO bound UI and the control hints would automatically be bound to these components.

<af:inputText value="#{bindings.DepartmentId.inputValue}"
label="#{bindings.DepartmentId.hints.label}"
rendered="#{bindings.DepartmentId.hints.displayHint == 'DISPLAY'}"
required="#{bindings.DepartmentId.hints.mandatory}"
columns="#{bindings.DepartmentId.hints.displayWidth}"
maximumLength="#{bindings.DepartmentId.hints.precision}"
shortDesc="#{bindings.DepartmentId.hints.tooltip}"
id="it3">
<f:validator binding="#{bindings.DepartmentId.validator}"/>
<af:convertNumber groupingUsed="false"
pattern="#{bindings.DepartmentId.format}"/>
</af:inputText>
<af:inputText value="#{bindings.DepartmentName.inputValue}"
label="#{bindings.DepartmentName.hints.label}"
rendered="#{bindings.DepartmentName.hints.displayHint == 'DISPLAY'}"
required="#{bindings.DepartmentName.hints.mandatory}"
columns="#{bindings.DepartmentName.hints.displayWidth}"
maximumLength="#{bindings.DepartmentName.hints.precision}"
shortDesc="#{bindings.DepartmentName.hints.tooltip}"
id="it1">
<f:validator binding="#{bindings.DepartmentName.validator}"/>
</af:inputText>
<af:inputText value="#{bindings.ManagerId.inputValue}"
label="#{bindings.ManagerId.hints.label}"
rendered="#{bindings.ManagerId.hints.displayHint == 'DISPLAY'}"
required="#{bindings.ManagerId.hints.mandatory}"
columns="#{bindings.ManagerId.hints.displayWidth}"
maximumLength="#{bindings.ManagerId.hints.precision}"
shortDesc="#{bindings.ManagerId.hints.tooltip}"
id="it4">
<f:validator binding="#{bindings.ManagerId.validator}"/>
<af:convertNumber groupingUsed="false"
pattern="#{bindings.ManagerId.format}"/>
</af:inputText>
<af:inputText value="#{bindings.LocationId.inputValue}"
label="#{bindings.LocationId.hints.label}"
rendered="#{bindings.LocationId.hints.displayHint == 'DISPLAY'}"
required="#{bindings.LocationId.hints.mandatory}"
columns="#{bindings.LocationId.hints.displayWidth}"
maximumLength="#{bindings.LocationId.hints.precision}"
shortDesc="#{bindings.LocationId.hints.tooltip}"
id="it2">
<f:validator binding="#{bindings.LocationId.validator}"/>
<af:convertNumber groupingUsed="false"
pattern="#{bindings.LocationId.format}"/>
</af:inputText>