Tuesday, July 07, 2015

Overview of Log4j

Log4J is the frame work used extensively in today java based example. It is based on singleton design pattern i.e. only one instance of Log class is maintained and hence is highly performance oriented.
Log4J has three main components

1-      Logger
2-      Appender
3-      Layout

1-      Logger: - This is base class which does the activity of logging. Advantage of this class is that we can differentiate the logging text in five different aspects. i.e. DEBUG, INFO, WARN,FATAL and ERROR.
2-      Appender :-  This is used to define the appender base. i.e. we had different appender like console, log file, xml,remote sockets  etc.
3-      Layout:- Define the layout in which format and layout structure we want the output. Many times it become easy to store the log file on date wise, sometime our requirement ask us to store the log files depends on its size. It the size get greater than specific number layout help us to crate a new file.

All the above three aspect of Log4J can be controlled by one single configuration files either it is called as log4j.xml or log4j.properties. If we had both then xml always take presentence over properties files.

#set the rootloger priority to DEBUG and its appender to stdout
log4j.rootLogger=debug, stdout, R

#set stdout to console appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#set layout to PatternLayout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

#Print only message of Priority WARN or above in the package com.test.myapp
log4j.Logger.com.myapp=WARN



Disadvantage using logger if not handled properly.
-           In production it is generally mistaken to keep the Log level at DEBUG, but this wrong. Keeping log level to DEBUG will create huge log file on expense of loggin it. So generally for Production it is used as ERROR or FATAL.
-          Don’t try to use accessed method in log in side loop
i.e. log.debug(“-----------”+String.valueOf(myArray[i]));

This will execute even though you had not set your log level to debug. In such case it is always advisible to use condition base logging.

if(log.isDebugEnabled())
{
log.debug(“-----------”+String.valueOf(myArray[i]));
}

How to Initialize and use Log4j?

Use following sets of line to log your application logger

Static Logger log = Logger.getLog(“com.test.siddhu.MyLogClass”);

log.debug(“Print this when logger level is set to DEBUG”);

Friday, July 03, 2015

What is JMX= JAVA Management Extension



JMX= JAVA Management Extension

Name itself suggest it is extension provided by JAVA for managing  JAVA Application/System my monitoring application performance problem, some critical events like quick increase in network traffic and decrease in application performance. With using JMX we can notify the developer about such behavior of the application using JMX console. In JDk 8 you can refer to this command in bin folder of java i.e. jmc.

Lets try to learn basics of JMX and learn how to use JConsole to connect and manage MBeans.

Step 1- Create MBean. It should be interface in nature. The interface name must end with MBean.

package com.test.siddhu;

public interface SiddhuMBean {
        
    public void setMyCount(int myCount);
    public int getMyCount();
    
    public void setMyName(String schemaName);
    public String getMyName();
    
    // Method started with get and set are considered as attributes for getter and setter methods
    // We are using do* for perform action.
    public String doAction();
}


Step 2- Provide the actual implementation of the MBean interface. As per the standard of JMX Naming convention we need to keep implementation class name as same of interface except– MBean. So my implementation class will be Siddhu.

package com.test.siddhu;

public class Siddhu implements SiddhuMBean {

    private int myCount;
    private String myName;
   
   
       @Override
       public void setMyCount(int myCount) {
              // TODO Auto-generated method stub
              this.myCount=myCount;
             
       }
       @Override
       public int getMyCount() {
              // TODO Auto-generated method stub
              return this.myCount;
       }
       @Override
       public void setMyName(String myName) {
              // TODO Auto-generated method stub
                this.myName=myName;
             
       }
       @Override
       public String getMyName() {
              // TODO Auto-generated method stub
              return this.myName;
       }
       @Override
       public String doAction() {
              // TODO Auto-generated method stub
              return "My Count="+this.myCount+" and My Name="+this.myName;
       }
    
       

}
Step 3- Now register our MBean implementation to the MBean server. We are using SiddhuActionManagement class for this. After registering MBean,To check our application is on we will print out mycount and myName value frequently. But same operation we will stop once we declare out myCount value as 0.



 













Click on Jconsole in bin folder of JAVA












Change value from 1 to 0 and we will see our application get stop.




If we change the name in the jconsole we found at run time with out changing the java class out put is changed







How to get print request and response for Apache axis log.

How to get print request and response for Apache axis log.

Many times it become necessary  to print Request and Response xml of SOAP UI accessed by Apache Axis Tool. I had implemented different option to do the same.
1

11-      By creating *.WSDD file

Refer to belwo site:-

http://www.google.com/support/adwordsapi/bin/answer.py?answer=15137&topic=237

Save this file as "client-config.wsdd" in the working directory
of your Axis client. Axis will load it automatically.


xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">



name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>


22 -  Use following code in your file where you want to log the request and response.

SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
OMElement requestElement = request.getOMElement(RegisterIntegrationAgent.MY_QNAME, factory);

LOGGER.debug(requestElement);

Thursday, July 02, 2015

Simple GWT MVP Pattern Example


Let try to build GWT MVP Pattern example. This will ask user to enter two number and in return will give addition of this two number.

Eclipse View of GWT MVP Project

























This are the code of the files :-

SiddhuMVPExample.html


SiddhuMVPExample.gwt.xml


HelloViewImpl.ui.xml



HelloView

package com.test.client.ui;


import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.IsWidget;


public interface HelloView extends IsWidget
{
String getFirstNumber();
String getSecondNumber();
void setAnswer(String answer);
void setPresenter(Presenter listener);

public interface Presenter
{
void goTo(Place place);
void buttonAddClicked();
}
}

HelloViewImpl


package com.test.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class HelloViewImpl extends Composite implements HelloView
{
private static HelloViewImplUiBinder uiBinder = GWT.create(HelloViewImplUiBinder.class);

interface HelloViewImplUiBinder extends UiBinder
{
}

@UiField TextBox FirstNumber;
@UiField TextBox SecondNumber;
@UiField TextBox Answer;

private Presenter listener;

public HelloViewImpl()
{
initWidget(uiBinder.createAndBindUi(this));
}



@Override
public void setPresenter(Presenter listener)
{
this.listener = listener;
}

@Override
public String getFirstNumber() {
return FirstNumber.getText();
}

@Override
public String getSecondNumber() {
return SecondNumber.getText();
}

@Override
public void  setAnswer(String answer) {
Answer.setText(answer);
}
@UiHandler("buttonAdd")
void buttonAddClicked(ClickEvent e)
{
listener.buttonAddClicked();
}
}




HelloPlace


package com.test.client.place;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

public class HelloPlace extends Place
{
private String firstNumber;
private String secondNumber;
private String answer;
private String helloName;
public String getFirstNumber() {
return firstNumber;
}

public void setFirstNumber(String firstNumber) {
this.firstNumber = firstNumber;
}

public String getSecondNumber() {
return secondNumber;
}

public void setSecondNumber(String secondNumber) {
this.secondNumber = secondNumber;
}

public String getAnswer() {
return answer;
}

public void setAnswer(String answer) {
this.answer = answer;
}
public HelloPlace(String token)
{
this.helloName = token;
}

public String getHelloName()
{
return helloName;
}

public static class Tokenizer implements PlaceTokenizer
{

@Override
public String getToken(HelloPlace place)
{
return place.getHelloName();
}

@Override
public HelloPlace getPlace(String token)
{
return new HelloPlace(token);
}

}

}


AppActivityMapper


package com.test.client.mvp;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.place.shared.Place;
import com.test.client.ClientFactory;
import com.test.client.activity.HelloActivity;
import com.test.client.place.HelloPlace;

public class AppActivityMapper implements ActivityMapper {

private ClientFactory clientFactory;

/**
* AppActivityMapper associates each Place with its corresponding
* {@link Activity}
* @param clientFactory
*            Factory to be passed to activities
*/
public AppActivityMapper(ClientFactory clientFactory) {
super();
this.clientFactory = clientFactory;
}

/**
* Map each Place to its corresponding Activity. This would be a great use
* for GIN.
*/
@Override
public Activity getActivity(Place place) {
// This is begging for GIN
if (place instanceof HelloPlace)
return new HelloActivity((HelloPlace) place, clientFactory);
else 
return null;
}

}


AppPlaceHistoryMapper

package com.test.client.mvp;

import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.place.shared.WithTokenizers;
import com.test.client.place.HelloPlace;

/**
 * PlaceHistoryMapper interface is used to attach all places which the
 * PlaceHistoryHandler should be aware of. This is done via the @WithTokenizers
 * annotation or by extending PlaceHistoryMapperWithFactory and creating a
 * separate TokenizerFactory.
 */
@WithTokenizers( { HelloPlace.Tokenizer.class })
public interface AppPlaceHistoryMapper extends PlaceHistoryMapper {
}



HelloActivity


package com.test.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.test.client.ClientFactory;
import com.test.client.GreetingService;
import com.test.client.GreetingServiceAsync;
import com.test.client.place.HelloPlace;

public class HelloActivity extends AbstractActivity implements com.test.client.ui.HelloView.Presenter {
// Used to obtain views, eventBus, placeController
// Alternatively, could be injected via GIN
private ClientFactory clientFactory;
// Name that will be appended to "Hello,"
//private String answer;
com.test.client.ui.HelloView helloView;
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);

public HelloActivity(HelloPlace place, ClientFactory clientFactory) {
//this.answer = place.getAnswer();
this.clientFactory = clientFactory;
}

/**
* Invoked by the ActivityManager to start a new Activity
*/
@Override
public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
helloView = clientFactory.getHelloView();
helloView.setPresenter(this);
containerWidget.setWidget(helloView.asWidget());
}

/**
* Ask user before stopping this activity
*/
@Override
public String mayStop() {
return "Please hold on. This activity is stopping.";
}

/**
* Navigate to a new Place in the browser
*/
public void goTo(Place place) {
clientFactory.getPlaceController().goTo(place);
}

@Override
public void buttonAddClicked() {
String fnumber = helloView.getFirstNumber();
String snumber = helloView.getSecondNumber();
// to check if code is coming here we can add following below line and can check we are getting answer
// From here only our RPC call is remaining.
/*int answer = Integer.parseInt(fnumber) + Integer.parseInt(snumber);
helloView.setAnswer(""+answer);*/
greetingService.getAddValue(fnumber, snumber, new AsyncCallback() {
@Override
public void onSuccess(String result) {
helloView.setAnswer(result);
}
@Override
public void onFailure(Throwable caught) {
helloView.setAnswer(""+caught);
}
});
}
}


ClientFactory

package com.test.client;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.test.client.ui.HelloView;

public interface ClientFactory
{
EventBus getEventBus();
PlaceController getPlaceController();
HelloView getHelloView();
}




ClientFactoryImpl


package com.test.client;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.place.shared.PlaceController;
import com.test.client.ui.HelloView;
import com.test.client.ui.HelloViewImpl;

public class ClientFactoryImpl implements ClientFactory 
{
private static final EventBus eventBus = new SimpleEventBus();
private static final PlaceController placeController = new PlaceController(eventBus);
private static final HelloView helloView = new HelloViewImpl();
@Override
public EventBus getEventBus()
{
return eventBus;
}

@Override
public HelloView getHelloView()
{
return helloView;
}

@Override
public PlaceController getPlaceController()
{
return placeController;
}

}


GreetingService


package com.test.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * The client-side stub for the RPC service.
 */
@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String getAddValue(String firstNumber, String secondNumber) throws IllegalArgumentException;
}


GreetingServiceAsync



package com.test.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * The async counterpart of GreetingService.
 */
public interface GreetingServiceAsync {
void getAddValue(String firstNumber, String secondNumber, AsyncCallback callback)
throws IllegalArgumentException;
}



SiddhuMVPExample



package com.test.client;

import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.test.client.mvp.AppActivityMapper;
import com.test.client.mvp.AppPlaceHistoryMapper;
import com.test.client.place.HelloPlace;


/**
 * Entry point classes define onModuleLoad().
 */
public class SiddhuMVPExample implements EntryPoint {


/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
private Place defaultPlace = new HelloPlace("World!");
private SimplePanel appWidget = new SimplePanel();

/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Create ClientFactory using deferred binding so we can replace with different
// impls in gwt.xml
ClientFactory clientFactory = GWT.create(ClientFactory.class);
EventBus eventBus = clientFactory.getEventBus();
PlaceController placeController = clientFactory.getPlaceController();

// Start ActivityManager for the main widget with our ActivityMapper
ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
activityManager.setDisplay(appWidget);

// Start PlaceHistoryHandler with our PlaceHistoryMapper
AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
historyHandler.register(placeController, eventBus, defaultPlace);

RootPanel.get().add(appWidget);
// Goes to place represented on URL or default place
historyHandler.handleCurrentHistory();
}
}


FieldVerifier

package com.test.shared;

/**
 *
 * FieldVerifier validates that the name the user enters is valid.
 *
 *
 * This class is in the shared package because we use it in both
 * the client code and on the server. On the client, we verify that the name is
 * valid before sending an RPC request so the user doesn't have to wait for a
 * network round trip to get feedback. On the server, we verify that the name is
 * correct to ensure that the input is correct regardless of where the RPC
 * originates.
 *
 *
 * When creating a class that is used on both the client and the server, be sure
 * that all code is translatable and does not use native JavaScript. Code that
 * is not translatable (such as code that interacts with a database or the file
 * system) cannot be compiled into client-side JavaScript. Code that uses native
 * JavaScript (such as Widgets) cannot be run on the server.
 *
 */
public class FieldVerifier {

/**
* Verifies that the specified name is valid for our service.
* In this example, we only require that the name is at least four
* characters. In your application, you can use more complex checks to ensure
* that usernames, passwords, email addresses, URLs, and other fields have the
* proper syntax.
* @param name the name to validate
* @return true if valid, false if invalid
*/
public static boolean isValidName(String name) {
if (name == null) {
return false;
}
return name.length() > 3;
}
}



package com.test.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.test.client.GreetingService;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
public String getAddValue(String firstNumber, String secondNumber) throws IllegalArgumentException {
String result;
int i=Integer.parseInt(firstNumber)+ Integer.parseInt(secondNumber);
result=String.valueOf(i);
return result;
}
}




You can get complete code file from :
https://drive.google.com/open?id=0B1EOBpl9Kvo1SzJOSmFBRTFkSzA