Sunday, December 23, 2012

Configuring jBoss for UTF-8 Character Encoding

 request.setCharacterEncoding("UTF8"); has only effect on POST requests, not on GET requests. For GET requests its need to be configured at servletcontainer level.

path :  jboss-as-7.1.0.Final --->   standalone ---> configuration --->standalone.xml 



<server xmlns="urn:jboss:domain:1.1">

   .......

    <system-properties>
        <property name="org.apache.catalina.
connector.URI_ENCODING" value="UTF-8"/>
        <property name="org.apache.catalina.
connector.USE_BODY_ENCODING_FOR_QUERY_STRING" value="true"/>
    </system-properties>





Thursday, December 6, 2012

Spring Transaction - @Transactional for private methods


Spring documentation says, "a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional."

One solution is to set "mode" in <tx:annotation-driven/> as aspectj, which will override the default mode proxy.
Another solution is make the methods public and invoke them directly from the upper layer,for the methods, which need to be in separate transaction.

For more details refer the spring docs.

static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.



Friday, November 23, 2012

Unix commands


1.Delete a file:
rm filename

2.Delete a directory and its contents
rm -rf directoryName/

3.To give permission to execute:
sudo chmod 755 jdk-6u21-linux-i586.bin

4.Copy to remote system
scp -r /home/rocky/ROOT15Sep.war user@192.168.0.60:/home/user/

4.To change user password:
passwd rocky
[enter new paasword]

5.Find and kill jboss process
ps -ef | grep jboss
sudo kill -9 6789


6.Rename system name
http://www.makeuseof.com/tag/change-computer-ubuntu-1010/

7. text search in files under a folder
find myDir -type f -name *.txt -exec grep "hello" {} /dev/null \;

Note: Here search text is "hello", folder is "myDir", file name is in the format "*.txt"

Creation of executable JAR file with dependent libraries

1.Create Manifest file with following entries

     a.Class-Path: <lib1.jar> <lib2.jar> <path/lib3.jar>

     b.Main-Class: <classname>

     c.Place a new line at the end of this file

2. use "jar" command to create jar

    jar cvfm <your_jar_file.jar> <manifest_file>  <class_files> <libraries>             

3. To execute jar using unix command

   java -jar <your_jar_file.jar>




Tuesday, November 13, 2012

C3P0 Connection Pool Configuration Rules of Thumb

http://javatech.org/2007/11/c3p0-connectionpool-configuration-rules-of-thumb/
C3P0 is a fantastic open source ConnectionPool that is feature rich, stable, and positively production ready. I personally like it more than DBCP because there is too much blocking encountered when checking in/out connections with DBCP. C3P0 dodges that problem with an asynchronous return to the pool, but you might end up using a lot more connections than you need to if you're not careful. Here's a list of the most important C3P0 settings and good production settings to use – along with some words of wisdom as to why the change from default is a good thing.
acquireIncrement=5 default(3) Batching the retrieval of Connections is wise because the process of opening a Connection is expensive. Why do it 5 times instead of once? The downside to this is that you may only need the one connection. Read on to maxIdleTime settings to make sure idle connections make their way back into the pool.
maxIdleTime=3600 default(0) Setting the maxIdleTime to a non-zero value permits C3P0 to remove Connections from the pool and freeing up database resources. This will never happen when maxIdleTime is set to 0. Setting to a small value might have Connections being retrieved and returned on too frequent a basis to be practical, so I've picked 3600 seconds ( 1 hour ) as a nice happy medium. Once the peak traffic is over, then the connections can be returned.
maxIdleTimeExcessConnections=300 default(0) You need to set this in addition to maxIdleTime to have the Connections removed from the pool and returned to the DB.
maxPoolSize=100 default(15) You'll have to fine tune this setting base on your own individual situation, but it's important to keep this on the largish side for the simple reason that C3P0 doesn't synchronously return connections to the pool. The implication of this is that the pool should actually be sized slightly larger than what you think the maximum number of Connections needed at peak time would be. For more on this, see numHelperThreads.
minPoolSize=20 default(3) This one too can be fine tuned based on your individual needs, but let's just say that you don't always want to be returning all your Connections and having to reacquire new ones. 20 is a good size to allow for handling of new bursts of sporadic traffic w/o having to reacquire them.
numHelperThreads=6 default(3) This is a very important property if you're going to have large bursts of traffic on your site. C3P0 ( as was alluded to previously ) doesn't return connections to the pool synchronously and as a result doesn't have the same issues with blocking that DBCP has. However, as a result, Connections are not made available until some arbitrary time after they are returned to the pool. C3P0 has helperThreads which are responsible for doing the actual return work and making them available. Under large load I've experienced times where these spikes could require 400 Connections using the default setting of 3. Using 6 HelperThreads will keep this spike under 100 connections. If you can afford the connections or won't have huge loads on the system, then the default of 3 will probably be fine for you.
unreturnedConnectionTimeout=3600 default(0) I've set this to 1 hour. If a Connection is used for longer than an hour, then C3P0 will assume it's been orphaned and will reclaim the Connection to the pool – closing it in the process.

Friday, November 2, 2012

Spring Transaction propagation: required and requires new

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-propagation

Transaction propagation

This section describes some semantics of transaction propagation in Spring. Please note that this section is not an introduction to transaction propagation proper; rather it details some of the semantics regarding transaction propagation in Spring.

In Spring-managed transactions, be aware of the difference between physical and logical transactions, and how the propagation setting applies to this difference.

10.5.7.1 Required

PROPAGATION_REQUIRED

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).

However, in the case where an inner transaction scope sets the rollback-only marker, the outer transaction has not decided on the rollback itself, and so the rollback (silently triggered by the inner transaction scope) is unexpected. A corresponding UnexpectedRollbackException is thrown at that point. This is expected behavior so that the caller of a transaction can never be misled to assume that a commit was performed when it really was not. So if an inner transaction (of which the outer caller is not aware) silently marks a transaction as rollback-only, the outer caller still calls commit. The outer caller needs to receive an UnexpectedRollbackException to indicate clearly that a rollback was performed instead.

10.5.7.2 RequiresNew

PROPAGATION_REQUIRES_NEW

PROPAGATION_REQUIRES_NEW, in contrast to PROPAGATION_REQUIRED, uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status.




Thursday, November 1, 2012

HQL - left join vs left join fetch

Official hibernate reference
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

A fetch join does not usually need to assign an alias, because the associated objects should not be used in the where clause (or any other clause). The associated objects are also not returned directly in the query results. Instead, they may be accessed via the parent object. The only reason you might need an alias is if you are recursively join fetching a further collection


Thursday, July 5, 2012

Solution for issues in IE on using jQuery Ajax

Internet explorer has issues with jquery ajax. For getJASON method, the result obtained in the callback function will be null, in IE (Internet explorer) .

To solve this, the following code to be added, before returning from ajax method

       
        response.setContentType("application/Json");
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache"); // HTTP/1.1
        response.addHeader("Cache-Control", "no-store"); // HTTP/1.1
        response.addHeader("Cache-Control", "must-revalidate"); // HTTP/1.1
        response.setContentType("application/x-json;charset=UTF-8");



This can be used for solving issues with IE on using DataTable also.


Wednesday, June 20, 2012

Hibernate : A workaround for avoiding explicitly setting DTO object properties from entity object

Using HQL query

Query query = sessionFactory.
getCurrentSession().createQuery("select custType.customerTypeId as customerTypeId, custType.customerTypeName as customerTypeName from CustomerType custType");

List<CustomerTypeData> customerTypeDataList =  query.setResultTransformer(Transformers.aliasToBean(CustomerTypeData.class)).list();       

 
 
 
Using Criteria

List<CustomerTypeData> customerTypeDataList  = sessionFactory.getCurrentSession()
                .createCriteria(CustomerType.class)
                .setProjection(
                        Projections.projectionList().add(
                                Projections.property("customerTypeId"),
                                "customerTypeId").add(Projections.property("customerTypeName"),
                                "customerTypeName"))
                .setResultTransformer(
                        Transformers.aliasToBean(CustomerTypeData.class)).list();

Spring MVC:Handling multiple submit buttons in a single form

Specify the parameter name in the name attribute. 


<input type = "submit" name = "update" value = "Update" />
<input type = "submit" name = "delete" value = "Delete" />

Include the "params" attribute, with the corresponding parameter name as value, in the annotation for request mapping



@RequestMapping(..., params = "update")
public ModelAndView updateCustomer(...) { ... }

@RequestMapping(..., params = "delete")
public ModelAndView deleteCustomer(...) { ... }


Saturday, June 16, 2012

JavaHL : Installation in Ubuntu and eclipse configuration


Execute the command

sudo apt-get install libsvn-java Add given below line in ~eclipse/eclipse.ini file VMARGS="-Djava.library.path=/usr/lib/jni'
Restart eclipse.  Note: For Ubuntu  12.04, the "path "is "/usr/lib/i386-linux-gnu/jni"

Tuesday, May 29, 2012

Jboss 7 configuration to reflect jsp modification without redeployment

Add <configuration> entry in standalone.xml

<subsystem xmlns="urn:jboss:domain:web:1.0" default-virtual-server="default-host">
...
    <configuration>
        <jsp-configuration development="true"/>
    </configuration>
</subsystem>



Temporary files can be found in standalone/tmp/vfs

Sunday, May 13, 2012

Soln for the exception - Specified VM install not found: type Standard VM, name java-6-openjdk, on building a project in Eclipse


On trying to build a project in Eclipse, a dialogue appears, showing the exception - "Specified VM install not found: type Standard VM, name java-6-openjdk" .

The solution is :
Delete the "[proj_name].launch" file in the location [workspace]/.metadata/.plugins/org.eclipse.debug.core/.launches

Os: Ubuntu 10
Eclipse : Indigo


Wednesday, May 2, 2012

Automatic comments generation in eclipse

In eclipse, it can be configured to generate the comments automatically.

Go to Windows -> Preferences -> Java -> Code style -> Code Templates in eclipse.

Here we can configure the comment formats to be generated automatically.

Otherwise, click the "import" button and select the tempalte xml file (click here for a sample template xml ).

On creating a new java class, check the "Generate Comments" checkbox(find it at the bottom of the wizard window) .

To add the comment template, for a method, right click on method name -> Source -> Generate element comment (Shift + Alt  + j).


Tuesday, April 24, 2012

Reusable search component using - java reflection, custom annotation, jsp:usebean and tiles




If 'searching of tabular list' is present in a number of pages in the application, a reusable search component can be used. Search component contains, a combo box, listing items, populated from the DTO class fields, using reflection. To restrict, which fields to be listed, and to show, custom labels for each filed, a custom annotation class is created, and that annotation is applied in the DTO class.








1. Need to add only the  "tiles:insertTemplate" on all pages, where the search component is required, and pass the className as an attribute and its fields will be listed in the Search by item combo.
 
<tiles:insertTemplate template="/WEB-INF/jsp/searchComponent.jsp">
   <tiles:putAttribute name="className" type="string" cascade="true" value="com.rocky.dto.Customer"></tiles:putAttribute>
</tiles:insertTemplate>


2. Create a reusable search component jsp

searchComponent.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

<tiles:useAttribute id="className" name="className" classname="java.lang.String" />

<jsp:useBean id = "searcItemsPopulatorBean" class="com.rocky.common.SearcItemsPopulatorBean" >
   <jsp:setProperty name="searcItemsPopulatorBean" property="entityClassName"  value="${className}"/>
</jsp:useBean>    

<table width="80%" >
   <tr>
       <td width="15%">Search by item:</td>
       <td align="left" width="20%">
           <select name="searchByItem" >
               <c:forEach items="${searcItemsPopulatorBean.searchItems}" var="item">
                   <option value="${item.key}">
                       <c:out value="${item.value}"/>
                   </option>
               </c:forEach>
           </select>
       </td>
       <td width="15%">Search criteria:</td>
       <td width="20%" align="left">
           <select name="searchCriteria">
               <option  value="startsWith">Starts with</option>
               <option value="endsWith">Ends with</option>
               <option value="contains">Contains</option>
               <option value="exact">Exact</option>
           </select>
       </td>
       <td width="15%">
           <input type="text" name="searchText"/>
       </td>
       <td width="15%">
           <input type="submit" value="Search"/>
       </td>
   </tr>
</table>


3. Define a Bean class to include in the searchComponent.jsp


SearchItemsPopulatorBean.java

package com.rocky.common;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SearcItemsPopulatorBean {
   private String entityClassName;
   private Map<String, String> searchItems;

   public SearcItemsPopulatorBean() {
       this.searchItems = new HashMap<String, String>();
   }

   public String getEntityClassName() {
       return entityClassName;
   }

   public void setEntityClassName(String entityClassName) {
       this.entityClassName = entityClassName;
       Field fieldArray[] = null;
       try {
           fieldArray = Class.forName(entityClassName).getDeclaredFields();
       } catch (SecurityException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       if (fieldArray != null) {
           for (int i = 0; i < fieldArray.length; i++) {
               ColumnHeaderSpecifier columnHeaderSpecifier = fieldArray[i]
                       .getAnnotation(ColumnHeaderSpecifier.class);
               if (columnHeaderSpecifier.isSearchable()) {
                   searchItems.put(fieldArray[i].getName(),
                           columnHeaderSpecifier.columnHeader());
               }
           }
       }
   }

   public Map<String, String> getSearchItems() {
       return searchItems;
   }
}




4. Define a custom annotation class ColumnHeaderSpecifier.java


package com.rocky.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnHeaderSpecifier {
   
   boolean isSearchable() default true;
   String columnHeader() default "";

}



5. Define DTO class with annotation to configure, which field to be listed in the search combo and the label to be displayed for each field.

Customer.java 

package com.rocky.dto;

import java.io.Serializable;

import com.rocky.common.ColumnHeaderSpecifier;

public class Customer implements Serializable{

   @ColumnHeaderSpecifier(isSearchable = false)
   private static final long serialVersionUID = -5235355839338180539L;

   @ColumnHeaderSpecifier(columnHeader = "ID")
   int id;
   
   @ColumnHeaderSpecifier(columnHeader = "Customer Name")
   String customerName;
   
   @ColumnHeaderSpecifier(columnHeader = "State")
   String state;
   
   public Customer(int id, String name, String state) {
       super();
       this.id = id;
       this.customerName = name;
       this.state = state;
   }

   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }

   public String getCustomerName() {
       return customerName;
   }

   public void setCustomerName(String customerName) {
       this.customerName = customerName;
   }

   public String getState() {
       return state;
   }

   public void setState(String state) {
       this.state = state;
   }
   
}