Monday, April 9, 2012

Refresh Record on click Custom Button or Link in Force.com (Salesforce) using Javascript

Create the custom button or link on your object and assign the behavior "Execute Javascript".

Within your Javascript after your implementation (let's say post updating the record from your javascript code) you can reload the active window which would in turn refresh the record with the latest content for it.

You can use the following to trigger the window reload.

// Updating the record
var result = sforce.connection.update([wi]); 
// Refresh window to refresh and show updated record
if (result[0].getBoolean("success")) { 
window.location.reload();
}

Saturday, March 31, 2012

Set Timeouts for services in JAX-WS Webservice Client

To set the Service call Connection and Request timeouts in the JAX-WS Client implementations for specific services, once the Proxy is created we need to do the following:


1.  Cast the Proxy to the javax.xml.ws.BindingProvider 
2.  Fetch the Request Context (java.util.Map<String, Object>)
3.  Set the timeout properties, as demonstrated in the following snippet of code below. Please note that the keys for the entries are 'com.sun.xml.ws.connect.timeout' and 'com.sun.xml.ws.request.timeout', for connection timeout and request timeout respectively, which are added to the RequestContext Map

private void setYourServiceCallTimeOut(YourPort yourPort){
  
  if (logger.isDebugEnabled()) {
   logger.debug(":setYourServiceCallTimeOut(): Entering method.");
  }
  java.util.Map requestContext = ((javax.xml.ws.BindingProvider)docPublisherPort).getRequestContext();
  requestContext.put("com.sun.xml.ws.connect.timeout", 15000); 
  requestContext.put("com.sun.xml.ws.request.timeout", 15000); 
  if (logger.isDebugEnabled()) {
   logger.debug(":setYourServiceCallTimeOut():Exiting method.");
  }
 }

Friday, March 30, 2012

DTD and XSD - Primary differences

Both these mechanisms provide a definition for the XML document, which serves two purposes primarily - Firstly, this is to ensure that the data that makes it past the parsing stage is at least in the right structure and the undesired input is rejected. Secondly, the definition documents the protocol in a standard, formal way, which makes it easier for developers to understand what’s available.


DTD (Document Type Definition): This format defines the elements that may be included in your document, what attributes these elements have and the ordering and nesting of the elements.


XSD (XML Schema Definition): XML Schemas provide a powerful mean to define your XML document structure and the limitations. XML Schemas are themselves XML documents. They reference the XML Schema Namespace and even have their own DTD. 


Now, let us look at the 5 most prominent differences:

 DTD (Document Type Definition)           XSD (XML Schema Document)
1 Non-XML ! This is a XML as well.
2 Not namespace aware. Namespace aware.
3 Inline DTDs can be included within the XML document Inline is not possible
4 DTD definition applies to the entire xml document Can describe individual segments
5 Importantly, fails to address data typing Can define to the detail of data types (custom complex and primitive types), incorporate inheritance and supports packaging and modularization (can be imported/included)

Friday, March 16, 2012

Easy Java Thread Pool Implementation (using java.util.concurrent.ThreadPoolExecutor)

Thread Pool is one of the commonly used implementation in order to improve performance or facilitate handling of complex and time-consuming operations in an efficient manner. As outlined by Oracle (and previously Sun Microsystems) the Thread pools essentially address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead and they provide means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.

Jdk 5.0 provides a new thread operational control mechanism, the realization of which is within the java.util.concurrent.* package. We have at our disposal the java.util.concurrent.ThreadPoolExecutor class now, which makes the ThreadPool implementation easy and more thorough as the ThreadPoolExecutor not only outlines the concept and makes the feature out of the box, but also maintains some basic statistics, such as the number of completed tasks, etc.

I am going to illustrate an implementation that I had coded for different migration projects to handle and migrate large volume of data. Threadpooling was an automatic choice for me as I had tight migration windows and time constraints.

I have a simple wrapper over the java.util.concurrent.ThreadPoolExecutor class, which acts as a helper for the consuming applications to initialize a thread pool with the desired settings and add tasks to the pool (runnable threads).
//Java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
//Apache Logger
import org.apache.log4j.Logger;

/**
 * This executor class is a generic implementation to initialize a thread pool and execute
 * tasks from the desired pool of defined thread class.
 *  
 * @author Somesh Mukherjee
 */
public class BatchThreadPoolExecutor {
    
 public static final Logger log = Logger.getLogger(BatchThreadPoolExecutor.class);
    
 private ThreadPoolExecutor threadPool = null;
    private ArrayBlockingQueue queue = null;
 
    /**
     * Default Constructor (Should not be Used)
     */
    @Deprecated
    public BatchThreadPoolExecutor(){
     
     throw new RuntimeException("Must assign proper values for int poolSize(int), maxPoolSize(int), keepAliveTime(long), queueSize (int)");
    }
    
    /**
     * ThreadPool initializer constructor.
     * 
     * @param poolSize
     * @param maxPoolSize
     * @param keepAliveTime
     * @param queueSize
     */
    public BatchThreadPoolExecutor(int poolSize, 
           int maxPoolSize,
           long keepAliveTime,
           int queueSize) {
     
     if(0 == poolSize
       || 0 == maxPoolSize
       || 0L == keepAliveTime
       || 0 == queueSize){
      throw new RuntimeException("Must assign proper values for int poolSize(int), maxPoolSize(int), keepAliveTime(long), queueSize (int)");
     }
     log.debug("Initializing BatchThreadPoolExecutor...");
     queue = new ArrayBlockingQueue(queueSize);
     threadPool = new ThreadPoolExecutor(poolSize, 
                 maxPoolSize,
                 keepAliveTime, 
                 TimeUnit.SECONDS, 
                 queue);
    }
 
    /**
     * Fires the individual thread task
     * 
     * @param task
     */
    public void runTask(Runnable task){
     
     log.debug("Beginning runTask, threadPool.getTaskCount():" + threadPool.getTaskCount());
     log.debug("runTask, Starting queue.size():" + queue.size());
     threadPool.execute(task);
     log.debug("runTask, Finishing queue.size():" + queue.size());
    }
 
    /**
     * Shuts down the thread pool. Previously submitted tasks are executed, 
     * but no new tasks will be accepted. Invocation has no additional effect if already shut down.
     */
    public void shutDown(){
     
     log.debug("Shutting down BatchThreadPoolExecutor...");
        threadPool.shutdown();
    }
    
    /**
     * An utility method to find out if the thread pooled tasks are complete or if the pool
     * this has active tasks.
     */
    public boolean isTerminated(){
     
     if(threadPool.isTerminated()){
      log.debug("$$$$ The Thread Pool has Terminated... $$$$");
     } else {
      log.debug("###### The Thread Pool has NOT Terminated yet. Active Jobs in the pool: " + threadPool.getActiveCount());
     }
     return threadPool.isTerminated();
    }
}
Before getting into the code contained within the above wrapper class, I would include one more snippet of code which outlines the mechanism to initialize and spawn the tasks using the above wrapper.
//Assume interimDataSetlist is the list containing the data to be processed in a concurrent fashion
if (interimDataSetlist != null && !interimDataSetlist.isEmpty()) {
     Iterator iterator = interimDataSetlist.iterator();
     BatchThreadPoolExecutor mtpe = new BatchThreadPoolExecutor( Integer.parseInt(this.getBatchedThreadPoolSize()),
       Integer.parseInt(this.getBatchedThreadPoolMaxPoolSize()),
       Long.parseLong(this.getBatchedThreadPoolKeepAliveTime()),
       Integer.parseInt(this.getBatchedThreadPoolQueueSize()));
     while (iterator.hasNext()) {
      data = iterator.next();
      if(null != data){
//Enqueue the runnable task here - the createProcessor helper method will simply create an instance of the class with implements the Runnable interface and overrides the run() method with the desired processing implementation
       mtpe.runTask(this.createProcessor(data, this.getProcessorBeanName()));
      }
     }
     //Now the tasks are fired and the pool executor will take care of the execution. Number of max active tasks at one
     //point will be the allowed pool size
     mtpe.shutDown();
     interimDataSetlist = null;
     //Wait for the spawned threaded tasks in the pool to finish to invoke the next batch of tasks
     while(true){
      if(mtpe.isTerminated()){
       log.debug("Thread pool of Image upload jobs finished! Would initiate the next set if available.");
       break;
      } else {
       //Pooled tasks in progress, would wait for the batch to finish to trigger the next set of job
       Thread.sleep(busyWaitMS);
      }
     }
    }
In the illustrated code snippet above, notice line #4, where the wrapper class is instantiated with the attribute settings for the required thread pool. I would give a quick note, so as to what the attributes implicate:

  • poolSize - Core thread pool size, allowed to execute concurrently 
  • maxPoolSize - Allowed max size for the pool. Core Pool Size must be less than or equal to this. Let's assume that our poolSize is set to 10 and the maxPoolSize is set to 20, the executor would allow 10 threads to execute concurrently. If more tasks are enqueued, they go into the waiting queue. Hence, in our example, if the runTask fires 20 processor threads, the first 10 executes concurrently, whilst the next 10 processor thread await for them to complete. Please note that you have to careful so as to fire only a certain number of processor threads, which are less than the allowed max pool size, otherwise the processor threads beyond the limit would be Rejected
  • keepAliveTime - Defines the time period the queued processor tasks would be alive. Our wrapper identifies the unit for this as Seconds
  • queueSize - Sets the initialization figure for the pool's java.util.concurrent.ArrayBlockingQueue, which holds the enqueued processor tasks
Once the ThreadPoolExecutor is initialized, we fire the runTask (line #12) on the wrapper class, which accepts a Runnable implementation and internally spawns the run() method for the Processor Thread class. The runTask on the wrapper class executes the runTask on the executor.


After all the processor tasks are enqueued, I am immediately shutting the Executor pool, to stop accepting more Processor tasks (line #17). Please note that, this does not suspend or shut down the spawned tasks, but only marks the pool as saturated and shut to accepting more tasks.



The loop starting line #20, ensures that all the Processor thread tasks enqueued in the pool has finished, by checking the Executor termination using the wrapper class method.


I hope this articles helps you to build the ThreadPool you are looking for using Java. For any clarifications or if you have any questions, please drop a comment below and I would try to provide more information or a solution. If you notice any discrepancies, please let me know.

Lastly, I would highly appreciate if you like my post, please visit some of the advertisements the sponsors and advertisers have posted on the site :-)

Monday, March 12, 2012

Java Garbage Collection and the Java HotSpot VM


The Garbage Collection model in today’s JVM achieve maximum efficiency incorporating the Generational Garbage Collection Model. This implementation was first introduced in the Java HotSpot VM for Solaris and is widely.


The implementation essentially eliminates the overhead involved in the JVMs attempt to scan through all the objects in the Java heap space, during every single GC attempt. The entire heap space is broken into two Generations, providing distinct and separate memory pools for Long Lived Objects (typically Singletons in a Web container) and Young or New Objects. The newly created Young objects are pushed into the new generation (also called as Eden). If they protrude a longer life then subsequently these are pushed into the old generation.


The GC attempts are classified as either Minor Collections or Major Collections. In the Minor collection the GC passes through the new generation and in the Major collection the GC passes through the entire heap space, including the old generation pool. As evident, the Minor collections are more frequent, as compared to the Major collections, which happen only when the old generation pool runs out of space. During the Major GC the live threads are suspended and may terminate abnormally.

Spring JDBC and ORACLE XMLType Columns

If you have a table in the Oracle database with a XMLType column and you are using Spring JDBC to write your data access classes, how do you map your XMLType column parameter to the corresponding attribute on the Java DAO layer? I had confronted this and had figured out a implementation to achieve this. Would provide the working, in-production snippet of code segments, which would illustrate the implementation:

For insertion into database table:

Step1: Map the parameter on the Java DAO layer to the XMLType SQL attribute:


declareParameter(new SqlParameter("YOUR_XMLType_Column_Name", Types.OTHER));

Here, Types is java.sql.Types class

Step 2: Set the value for the XMLType column:

parametersMap.put(
"YOUR_XMLType_Column_Name" , new SqlTypeValue() {
     public void setTypeValue(PreparedStatement cs, int colIndx, int sqlType, String typeName) throws SQLException {
      Connection con = null;
      ((CallableStatement)cs).setObject(colIndx, new XMLType(getNativeJDBCConnection(con,getJdbcTemplate()), yourJavaObject.getXmlTypeValue()));
      if(null != con)
       con.close();
     }
    });
Assuming parametersMap HashMap carries the input parmeter

Here, 
SqlTypeValue is org.springframework.jdbc.core.SqlTypeValue
PreparedStatement is java.sql.PreparedStatement
SQLException is java.sql.SQLException
Connection is java.sql.Connection
CallableStatement is java.sql.CallableStatement
XMLType is oracle.xdb.XMLType

getNativeJDBCConnection helper method derives the native JDBC connection on the basis of the connection type specified. A sample implementation of this method is as follows:
private Connection getNativeJDBCConnection( Connection con, JdbcTemplate jdbcTemplate ) throws SQLException {
  NativeJdbcExtractorAdapter nativeJdbcExtractorAdapter = null;
  if (connectionType.equalsIgnoreCase("dbcp")) {
   nativeJdbcExtractorAdapter = new CommonsDbcpNativeJdbcExtractor();
   con = nativeJdbcExtractorAdapter.getNativeConnection(jdbcTemplate.getDataSource().getConnection());
  } else if (connectionType.equalsIgnoreCase("websphere")) {
   nativeJdbcExtractorAdapter = new WebSphereNativeJdbcExtractor();
   con = nativeJdbcExtractorAdapter.getNativeConnection(jdbcTemplate.getDataSource().getConnection());
  } else if (connectionType.equalsIgnoreCase("weblogic")) {
   nativeJdbcExtractorAdapter = new WebLogicNativeJdbcExtractor();
   con = nativeJdbcExtractorAdapter.getNativeConnection(jdbcTemplate.getDataSource().getConnection());
  } else {
   con = jdbcTemplate.getDataSource().getConnection();
  }
  return con;
 }
For reading a XMLType column value using a SQL from database table:

In the rowmapper, you can use the way as illustrated in the snippet below to read the XMLType column value:
if (rs.getObject(MarshForceProcessLogImpl.PROCESS_XML) != null) {    
    OPAQUE opq = ((OPAQUE) rs.getObject("YOUR_XMLType_Column_Name"));
    XMLType xt = oracle.xdb.XMLType.createXML(opq);
    processXmlData = xt.getStringVal();
   }
Here, 
OPAQUE is oracle.sql.OPAQUE
XMLType is oracle.xdb.XMLType

I have mostly used code in this segment to describe the way we can use XMLType Oracle columns in Spring JDBC based DAO Java layer. If you have any questions please feel free to drop a note and I can chip in more clarification. Also, if you want the physical java class, I can upload the same and share.

Hope this helps!

Saturday, March 10, 2012

Lightweight Messaging

I have always liked MDBs. But in a very recent project, which was entirely lightweight, I just did not want a EJB container in the frame. So, I looked around… Considered simple Java messaging and it was then that I bumped into MDPs!

MDPs are the Message Driven POJOs, Spring’s answer to JMS implementations and Asynchronous reception. It ships with a fantastic DefaultMessageListenerContainer and comes in 3 interface implementation options – Conventional JMS MessageListener, Session Aware Message Listener and the Message Listener Adapter. For details, so as to how you can get this up and running please refer -


Quick, seamless and bingo no EJB container! So, next time you need an Asynchronous infrastructure, give this implementation a thought