Tuesday, December 11, 2012

Log4j 2.0 - Some important features


Log4j’s latest 2.0 version has been recently released. Following are few of the important and very useful features of Log4j-2.0:

1.       Supports parameter substitution (same as slf4j)
For example:
   LOGGER.info (“User Id is { } and User Email is { }”, userId, userEmail);

2.       Flow Tracing:
To print the entry and exit of a method.
Example:
  public String getUserEmail(int userId) {
    logger.entry(userId);
    User user = UserDao.getUser(userId)
    String email = user.getEmail();
    return logger.exit(email);
  }
  This method will log following messages:
    19:08:07.061 TRACE com.class.MyClass 10 getUserEmail -  entry parms(1)
    19:08:07.061 TRACE com.class.MyClass 13 getUserEmail -  exit with (User.Email@gmail.com)
 
3.       Markers:
To log some special messages.
For example:
 public class MyApp {
 
   private Logger logger = LogManager.getLogger(MyApp.class.getName());
   private static final Marker QUERY_MARKER = MarkerManager.getMarker("SQL");
               
   public String doQuery(String table) {
     logger.entry(param);
     logger.debug(QUERY_MARKER, "SELECT * FROM {}", table);
     return logger.exit();
   }
} 
 
4.       Messages:
Very useful to standardize the format of an application’s log messages.
Example:
            logger.info("User {} has logged in using id {}", username, userId);        
      The above log message can be standardized by implementing a class ‘LoggedInMessage’ implementing ‘Message’ interface.
            logger.info(new LoggedInMessage(userName, userId)); 
                    (‘getFormattedMessage’ method of ‘Message’ interface is used to log the message string.)
        
Some more important types of messages are ThreadDumpMessage, TimestampMessage, MapMessage and few more.
 
5.       Plug-ins:
Log4j 2 uses a Plugin system that makes it extremely easy to extend the framework by adding new Appenders, Filters, Layouts, Lookups, and Pattern Converters without requiring any changes to Log4j.           


-          Sarang Anajwala      

Friday, November 23, 2012

git - tips

  • git remote –v                    
o   Shows remote branches

  • git remote add <remote branch name> <remote branch url>
o   Add a new remote branch

  • git push <remote branch name> <local branch name>
o   push changes from local branch to remote branch

Ref:

Thursday, November 22, 2012

Maven - include a lib manually in local repo

Use following command to include a lib manually in local maven repository:

 

mvn install:install-file -Dfile=./EWSJavaAPIWithJars_1.2.0.jar -DgroupId=local.disk -DartifactId=EWSJavaAPI -Dversion=1.2 -Dpackaging=jar

Thursday, October 25, 2012

Installing git man pages

Git installation by default does not include all the man pages.
So if you try to look for help on git commands like “git help commit”, you may see and error like this: “No manual entry for git-commit”.
It is strange to see a popular tool like git does not including man pages by default; however, following are the steps to download and install the man pages.

> Download man-pages: 
http://git-core.googlecode.com/files/git-manpages-[GIT_VERSION_NO].tar.gz >  git-manpages-[GIT_VERSION_NO].tar.gz 
> Untar the man-pages: 
tar xvj -C /usr/local/share/man -f git-manpages-[GIT_VERSION_NO].tar.gz
Done – Now you should be able to use all git manpages.

Thursday, August 30, 2012

How to enable jmx-agent to monitor a java process from remote machine:

A quick tip on how to enable jmx-agent to monitor a java process from remote machine:

Add following system property in the java process while starting it: “-Dcom.sun.management.jmxremote.port=<port number>”
 
We can add security features as well to it: 
For example, (run com.example.MyApp with jmx-agent enabled) 
% java -Dcom.sun.management.jmxremote.port=3000
-Dcom.sun.management.jmxremote.password.file=password.properties
-Dcom.sun.management.jmxremote.access.file=access.properties
-Djavax.net.ssl.keyStore=keystore
-Djavax.net.ssl.keyStorePassword=password
com.example.MyApp


Monday, June 25, 2012

Security - Array is stored directly

Sonar Violation: Security - Array is stored directly
Means: Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user (caller/client) affect the internal functionality.

public void setMyArray(String[] myArray) {
  this.myArray = myArray;
}

Solution:

public void setMyArray(String[] newMyArray) {
  if(newMyArray == null) {
    this.myArray = new String[0];
  } else {
   this.myArray = Arrays.copyOf(newMyArray, newMyArray.length);
  }
}

Friday, May 18, 2012

JBoss - Too many open files

Issue: I faced this issue in JBoss while doing load testing. Under heavy load, jboss http connector crashed and it refused to accept any new connections. On checking logs, I found out that the root cause was “Too many open files” issue.

 

Resolution: “Too many open files” – this issue is a linux issue. OS enforces a limit on each process for maximum number of files that can get attached to a process. Normally the default value is 1024. (Default value can be checked using this command: “ulimit -n“) This value is not sufficient for processes like application containers.

 

All the files associated with given process can be seen with this command: lsof -p <pid>

 

More details about how can this value be changed is available on this wonderful blog post - http://tech-torch.blogspot.com/2009/07/linux-ubuntu-tomcat-too-many-open-files.html

 

One thing missing in this blog is that for ‘root’ user, you have to specifically mention the user name while modifying /etc/security/limits.conf file. Wild cards are not applicable for root user.

For example, following lines should be enter in /etc/security/limits.conf file for root user –

 

root            soft      nofile        4096

root            hard    nofile        8192

 

Tek-Olweiz,

Sarang

 

Friday, May 4, 2012

JBoss TimerService - bug fix

As such the TimerService implementation is not stable in jboss6.1.
The version of timer-service library (of JBoss6.1.0.Final) itself says it is only an ALPHA lib… not a GA (jboss-ejb3-timerservice-mk2.jar, version 1.0.0-alpha-13)

I was facing an issue with the TimerService and while looking for a solution, found out JBoss team doesn’t support issues of JBoss-6x any longer.
The issue was related to Transaction management in Timer Service implementation.

Following is the JIRA defect and attached is the library with fix of the issue.
You can get the source code also at my GitHub page mentioned below.

Fixed lib jar file – https://www.box.com/s/5c6d4a99cfd7e07df091/1/275092885/2167714863/1

Regards,
Sarang

Tuesday, February 21, 2012

JBoss Trimming - remove JSF

If you are not using JSF, you can trim jboss and remove JSF from getting deployed!
You can do this by commenting everything in the deployers\jsf.deployer\META-INF\jsf-integration-deployer-jboss-beans.xml.
Just keep following lines.
<?xml version="1.0" encoding="UTF-8"?>
<!--
    JBoss JSF + JBossAS integration
-->
<deployment xmlns="urn:jboss:bean-deployer:2.0">
</deployment>

This will save a lot of time while starting jboss… the time jboss uses in JSF initialization.

Courtesy: Vishnu Gopal Singhal

Friday, February 10, 2012

Android installation issue

I was facing problem while downloading 3rd party plugins for Android SDK.
Following was the error I was facing –
“Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, 
reason: Connection to https://dl-ssl.google.com refused”

Following is the solution -
Go to the SDK Manager (Navigate to it on the computer, not from eclipse), then open it up and provide proxy. Also check the checkbox which says force http connection for https urls.
(I was behind a proxy.)

Friday, December 16, 2011

Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();

Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();

 

A relatively simple concept that confuses many java beginners!

 

Java Code:

String path = getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();

 

Means:

This code will try to get exact path of folder “myfolder/data/file.txt”.

The parent folder of this folder “myfolder/data/file.txt” should be mentioned in class path.

 

e.g. If the exact path of this folder is “C:/properties/myfolder/data/file.txt”; path “C:/properties” should be mentioned in classpath of the application (build-path in eclipse). When the above mentioned code is executed in application, it returns the exact path of the folder location and assigns it to ‘path’ variable.

 

Hence after execution of this code, ‘path’ variable will contain value “C:/properties/myfolder/data/file.txt”.

 

If we change root location of the application or we change folder structure of the parent folder of “myfolder/data/file.txt“, we will need to change only classpath.

This avoids hard-coding of the absolute path in source code. (Important for portability of application across windows and unix platforms.)

 

 

Monday, December 5, 2011

Hibernate: wrong usage of merge()

Note the wrong usage of merge():

merge() doesn't make the object passed into it persistent, it returns another instance with the same state instead,

So you should write: bean.setManufacturer(s.merge(bean.getManufacturer()));

 

 

Tuesday, November 15, 2011

type-mappinmg for byte[] in standardjbosscmp-jdbc.xml

http://community.jboss.org/thread/23104?decorator=print&displayFullThread=true

 

After many hours investigating this problem I have found a solution myself.

Here the mapping required in standardjbosscmp-jdbc.xml if you want to read and write to blob fields using an byte[] java type rather than some serialized java.lang.Object:

<java-type>[B</java-type>
<jdbc-type>VARBINARY</jdbc-type>
<sql-type>IMAGE</sql-type>

and the entity bean abstract get & set methods will be as below:

public abstract byte[] getField();
public abstract void setField(byte[] value);

Now I can read and write to the blob using array's of bytes just like any byte[] which is simple, neat and tidy coding exercise.

I guess you would need to be a bit careful with really big blobs as when the entity bean is read from the DB it will bring the whole blob into memory and hold it in a byte[].

The <java-type> of '[B' means a byte[] type. This you will not find in any documentation. I found this by looking at the JBoss source code in the process of trying to understand what was going on with blobs. The class in where I found the '[B' is:

org.jboss.ejb.plugins.cmp.jdbc.JDBCUtil

 

Cheers,

Sarang

As I mentioned in my previous post on productivity, using the productivity tools DOES help a lot.... a snapshot of my productivity analysis since I started using these tools. I have been, according to RescueTime, amongst top 13% productive people! :)
Not reading too much into these statistics, I can definitely say that I have felt considerable improvement in my productivity!






Enhanced by Zemanta

Wednesday, November 2, 2011

Some good productivity tools

Some excellent FOSS tools to enhance productivity –
  1. Grindstone – Timers for Task Management
  2. RescueTime – For analyzing computer usage
  3. ManicTime tracker – Similar to RescueTime
  4. Approach: Pomodoro Technique
Will blog about more details sometime later.
Right now, I don’t want this post to affect my productivity ;)

And yeah, this DOES help a lot!!!

Cheers,
Sarang

Tuesday, October 18, 2011

VNC Configuration

Some of the configuration tips for VNC server instances and window sizes.

To create new instance, add an entry in file /etc/sysconfig/vncservers.
For example, I have created two instances and following is the content of this file:

VNCSERVERS="1:root 2:root"
VNCSERVERARGS[1]="-geometry 1280x800 -depth 16"
VNCSERVERARGS[2]="-geometry 1260x710 -depth 16"

The first line indicates the usernames to access each of the server instances.
In this case both are ‘root’. So it can be accesses by entering <ip-address>:1 and <ip-address>:2 in the VNC client window.

The reason for creating two instances here is nothing but two different resolutions.
The first instance’s resolution “1280x800” is best for full-screen usage.
The second instance’s resolution “1260x710” is best for full-size client window. (Expand the vnc client window to fill size by clicking on ‘Maximize’ button on top right corner)

One more important point, you need to keep ‘vncconfig’ running to be able to share clipboard to/from your desktop to VNC server.
Use following command to start vncconfig:
vncconfig -nowin &

Cheers,
Sarang

Enhanced by Zemanta

Wednesday, October 5, 2011

Eclipse Proxy settings - bug and workaround

Many a times I experienced weird behavior of eclipse network connectivity (despite providing proxy settings) especially while installing plugins from update sites.
However, didn’t pay enough heed to the issues and many a times moved on with installing the plugins by manually downloading it.

With Eclipse Indigo, as the Eclipse marketplace makes plugin installation quite easier, I thought of checking out the exact issue with eclipse network connectivity.

As always, found the bug and work around easily by searching on net (community power!!!)

The bug is with Eclipse proxy settings. Normally, when we enable proxy on eclipse, we enable all types of proxies – HTTP, HTTPS and SOCKS.
The issue is that if you add ‘SOCKS’ proxy entry, eclipse will ignore HTTP/HTTPS whereas normally you will always connect to an HTTP/S url.
So the solution is that remove ‘SOCKS’ proxy entry and keep only HTTP/HTTPS entry. (Make sure you select Active provider as ‘Manual’)

Following is the screenshot for the proxy setting.


Update: You need to restart your eclipse after making this change.

Cheers,
Sarang
Enhanced by Zemanta

Subclipse plugin installation in Eclipse Indigo on RHEL- Bug and resolution

I was facing issue while using subclipse plugin in my Eclipse Indigo on my RHEL (Redhat Linux) box.
Installation was successful but was giving error while connecting with SVN.

On searching for the solution, I found out that the issue was related to JavaHL. JavaHL is a "High Level" API and is provided with custom written C++ code to serve as the JNI bridge between Java code and the native libraries (C-libraries).

So the solution to the issue is providing JavaHL in eclipse classpath.
For me, the solution was relatively simple as I already had CollabNet SVN client installed on my box. If you don’t have thisclient installed, you will have to install it first from here – http://www.collab.net/downloads/subversion/redhat.html

CollabNet client contains required library (library name is libsvnjavahl-1.so)
So add following vm argument in your eclipse.ini right after the line that reads “-vmargs” and that should resolve the issue.
 
-Djava.library.path=/opt/CollabNet_Subversion/lib
 
Your eclipse.ini might look like this –
 
-showsplash
org.eclipse.platform
-framework
plugins/org.eclipse.osgi_3.4.0.v20080605-1900.jar
-vmargs
-Djava.library.path=/opt/CollabNet_Subversion/lib
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m

Refer this wiki page for more details and for resolving this issue on other operating systems - http://subclipse.tigris.org/wiki/JavaHL

Cheers,
Sarang
Enhanced by Zemanta

Friday, September 30, 2011

Code to compare difference in working copy and specific branch of svn for multiple directories:

Code to compare difference in working copy and specific branch of svn for multiple directories:

find . -type d -maxdepth 1 -printf "%f\n" | while read -d $'\n' file
do
  echo "svn diff --old http://135.10.61.14/svn/DAWN/tags/Dev_Version0.11.5/$file  --new ./$file  > ../diff/$file.diff"
  svn diff --old http://135.10.61.14/svn/DAWN/tags/Dev_Version0.11.5/$file  --new ./$file  > ../diff/$file.diff
  #echo "$file"
done
Enhanced by Zemanta

Eclipse settings for performance improvement

If you use eclipse, I am sure you have come across moments when you banged your head waiting for eclipse to respond.
By applying following settings, your eclipse performance should become bad, which otherwise is worst! (There is no such thing in this world called "Good Eclipse performance".)

Update your eclipse.ini file (in your <ECLIPSE-HOME> directory) with following settings.
(VERYIMPORTANT: Do NOT miss to update the “-vm” parameter (in bold below) to your own <JAVA_HOME>)

-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-showlocation
-vm
C:\PROGRA~1\Java\jdk1.6.0_20\jre\bin\client\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms512M
-Xmx512M
-Xss128k
-XX:NewSize=128M
-XX:MaxNewSize=128M
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CompileThreshold=5
-Dcom.sun.management.jmxremote

After applying these settings, if you ever get StackOverflowError, increase the value of “-Xss” to 192m (or 256m, if required).
To understand the significance of “-Xss” parameter, read this post on my blog.
Enhanced by Zemanta