Tuesday, June 14, 2011

JBoss MDB for Websphere MQ

Download and install websphere MQ. I downloaded latest available version 7.0. It has many rpm files to be installed. I am using ubuntu 11. So I used bellow command to install a one rpm.

rpm -ivh --nodeps --force-debian file_name.rpm

This installation didn’t have some requried files so I downloadd 7.0.1-WS-MQ-LinuxX64-FP0005.tar.gz patch and installed as previous installation.

Ok if you have installed it correctly now you can run MQ Explorer. That is a Nice GUI based on eclipse. You can create queues and put messages to that queue via this GUI. This UI has many features but it is out of topic.

Normally MQ installation will be in /opt/mqm. Switch to root and switch to mqm and goto /opt/mqm/bin and run ./strmqcfg. That will start MQ Explorer. If it does not start GUI without any message. you many need to give permission to mqm user to use your X resources. for that open a new terminal and enter ‘xhost +’ command. You can check whether you can run gui by running xclock application.

Ok After you starting MQ Explorer it will give a nice documentation about how to create a queue manager and queue. Follow Sending a message to a local queue to create your first queue. It says about queue manager QM_APPLE. follow that as it is because I am using default one to configure JBoss resource adapter.

Now you need to install MQ resource adapter in JBoss. copy /opt/mqm/java/lib/jca/wmq.jmsra.rar to $JBOSS_HOME/server/default/deploy. In addition to resource adapter you need to copy MQ client library to $JBOSS_HOME/server/default/lib. that file is availble in /opt/mqm/java/lib/com.ibm.mqetclient.jar.

Now create a file in $JBOSS_HOME/server/default/deploy/messaging/wmq.jmsra-ds.xml. Configure it as below.


<?xml version="1.0" encoding="UTF-8"?>

<connection-factories>

<!-- mbeans defining JCA administered objects -->
<mbean code="org.jboss.resource.deployment.AdminObject"
name="jca.wmq:name=ivtqueue">

<!-- Bind this AdminObject with the JNDI name myAppleQueue -->
<attribute name="JNDIName">
myAppleQueue
</attribute>

<!-- this MBean depends on the WebSphere MQ resource adapter -->
<depends optional-attribute-name="RARName">
jboss.jca:service=RARDeployment,name='wmq.jmsra.rar'
</depends>

<!-- this admin object is a javax.jms.Queue -->
<attribute name="Type">javax.jms.Queue</attribute>

<!--
Configuration for Queue Q1 on queue manager QM_APPLE.
-->
<attribute name="Properties">
baseQueueManagerName=QM_APPLE
baseQueueName=Q1
</attribute>
</mbean>


<!-- JCA Connection factory definitions -->
<tx-connection-factory>

<!-- Bind this ConnectionFactory with the JNDI name MyAppleCF -->
<jndi-name>MyAppleCF</jndi-name>

<!-- Indicate that the connection factory supports XA transactions -->
<xa-transaction />

<!-- rar-name is the actual RAR file name, in this case wmq.jmsra.rar -->
<rar-name>wmq.jmsra.rar</rar-name>

<!-- connection-definition is the ConnectionFactory interface
defined in the ra.xml -->
<connection-definition>
javax.jms.ConnectionFactory
</connection-definition>

<!--
Configuration for the ConnectionFactory. This defines the channel, hostname, port,
queueManager, and transportType properties for a client (TCP/IP) connection to WMQ
-->
<config-property name="channel" type="java.lang.String">
SYSTEM.DEF.SVRCONN
</config-property>
<config-property name="hostName" type="java.lang.String">
127.0.0.1
</config-property>
<config-property name="port" type="java.lang.String">
1414
</config-property>
<config-property name="queueManager" type="java.lang.String">
QM_APPLE
</config-property>
<config-property name="transportType" type="java.lang.String">
CLIENT
</config-property>

<!-- define security domain -->
<security-domain-and-application>JmsXARealm</security-domain-and-application>
</tx-connection-factory>

</connection-factories>


OK configurations done. Now write a MDB with given annotations. you can keep those annotated configurations in xml file if you need.
@MessageDriven(name = "myMqMDBean",
activationConfig =
{
@ActivationConfigProperty(propertyName = "messagingType", propertyValue = "javax.jms.MessageListener"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "myAppleQueue"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "channel", propertyValue = "SYSTEM.DEF.SVRCONN"),
@ActivationConfigProperty(propertyName = "useJNDI", propertyValue = "true")
})
@ResourceAdapter(value = "wmq.jmsra.rar")
public class MqMDBean implements MessageListener {

@Override
public void onMessage(Message message) {
try {

if (message instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) message;
System.out.println("Message Received ...");
System.out.println(" >> " + txtMsg.getText());
} else {
System.out.println("Unknown message received. type of message is " + message.getClass());
}
} catch (Exception e) {
System.out.println("Exception occurred while processing the message");
}

}
}

After deploying start JBoss. if there are no any exception you are lucky.

Ok now goto MQ explorer and put a message. Your MDB will grab it. You can find complete source in github. use bellow to get source
'git clone git@github.com:changit/jboss-mdb-with-wsmq.git'

Friday, May 13, 2011

What is the best way to implement Singleton pattern

We use singleton pattern when we need only one instance to be created. Why do we need to create only one instance.
* Object creation and destruction might be a high expensive task.
* Object might share some information need to be accessed through out the system. If multiple instance are there. Different different classes will see different different values.

We can find many articles on how to implement Singleton pattern. The best solution I found so far is below.

public class Singleton {

private static class SingletonHolder {
static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}

}

We can guaraty that above is lazily loaded and thread safe. if you don't need it to be loaded lazily use below. that is the simplest.


public class Singleton {

private static Singleton instance = new Singleton();

public static Singleton getInstance() {
return instance;
}

}


As I remember in head first design pattern book, after saying so many stories they finally has given double locking solution like below. they talked much about volatile and double locking there.

class Singleton {

private static volatile Singleton instance;

public static Singleton getInstance(){
if(instance == null){
syncronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

}


OK Still I can't guarantee that only one instance is created for all scenarios. With java reflection we can call private constructor and create a new object as below.


Class cl = Class.forName("Singleton");
java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
c[0].setAccessible(true);
Singleton instance2 = (Singleton) c[0].newInstance();


There is a way to prevent that. We can implement Singleton by using enums. By default enums are singleton. As I found Enums can't be instantiate through reflection.


enum EnumSingleton {
SINGLETON;

public void test() {
System.out.println("This is also a singleton " + this);
}

private EnumSingleton(){
System.out.println("Constructing the singleton ...");
}

}

you can get the singleton object through EnumSingleton.SINGLETON and call test() method.

So what do you think what is the best last one or first one. I prefer the first one.

Thursday, May 5, 2011

AOP with Spring

Spring makes AOP easy. Before explaining Spring AOP let's discuss about AOP and why do we need that. AOP modularise cross cutting concerns to one place. Then what is a cross cutting concern? ....
Logging and Security are the common examples for cross cutting concerns. For example in authorisation we need to check permission for the user when the user try to execute some method that need to be secured. If there are many this type of method that checks security, it will be duplicated every where and code will be tangle and scattered. In AOP it has their own terminology which explain those points.

1. Join Point
A join point is a execution point that has cross cutting concern. This might be a method or some exceptional case.

2.Point Cut
Point cut is the expression that explain about Joint points. So one point cut may represent many join points. For example below point cut represent all methods in com.xyz.service or sub package.

@Pointcut(value = "execution(* com.xyz.service.*.*(..))")
private void anyMethod() {
}


3.Advice
Advice is a code fragment that need to be implemented at defined point cut. For example think we need to have a log every time before executing above mentioned point cut. That means before calling any method in com.xyz.service or sub package we need to have a log message. we can define that advice below.

@Before("anyMethod()")
public void logMessage() throws Throwable {
logger.debug("Going to execute com.xyz.service method");
}


We can see different type of advice as below.
* Before advice
* After returning advice
* After throwing advice
* After (finally) advice
* Around advice



4. Aspect
Aspect modularise similar concerns spread every where into one place. In spring Aspect is a class which has @Aspect annotation.

Let's try to implement this using AOP.

public class MyService implements IMyService{

private static final Logger logger = LoggerFactory.getLogger(MyService.class);

public void someSecuredMethod(String userName) {
logger.debug("Hi " + userName + ". I have a secret to tell you");
}
}

@Aspect
public class MyAopAspect {

private static Logger logger = LoggerFactory.getLogger(MyAopAspect.class);

@Pointcut(value = "execution(public * someSecuredMethod(..))")
private void anyPublicOperation() {
}


@Around("anyPublicOperation() && args(userName)")
public void checkPermission(ProceedingJoinPoint pj, String userName) throws Throwable {
if (userName.equals("che guevara")) {
pj.proceed();
} else {
logger.error("User {} doesn't have permission", userName);
}
}
}


In above example I have used around advice. With around advice aspect can decide whether it need to execute doSomething() method or not. If you don't call ProceedingJoinPoint.proced(), doSomeThing() will never be invoked.

get working example with test cases here.

Wednesday, February 16, 2011

Spring Security For vaadin

I found that implementing security in vaadin is not easy as in normal Spring MVC application. So I created this simple project with spring form based authentication.

I used maven to create the project with vaadin-archetype-clean .

1. Run mvn archetype:generate and select 14 to create project with vaadin-archetype-clean. I used mvn 3.0.2.
2. Run mvn jetty:run to start your web application. Yeah ... jetty will start the web application, you no need a separate web server for this. If you need run mvn package. it will create the war file and you can deploy it in your preferred java web server.
3. Add spring securtiy dependencies to pom.xml.
 <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-web</artifactId>
     <version>3.0.0.RELEASE</version>
 </dependency>

 <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-config</artifactId>
     <version>3.0.0.RELEASE</version>
 </dependency>

 <dependency>
     <groupId>jstl</groupId>
     <artifactId>jstl</artifactId>
     <version>1.1.2</version>
 </dependency>

4. I used spring form based authentication, so we can create custom login and error page with and you need to configure them in spring security xml.

<http auto-config='true'>
  <intercept-url pattern="/jsp/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
  <intercept-url pattern="/jsp/login_error*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
  <intercept-url pattern="/**" access="ROLE_USER" />
  <form-login login-page='/jsp/login' authentication-failure-url="/jsp/login_error" />
 </http>

 <authentication-manager>
  <authentication-provider>
   <user-service>
    <user name="jimi" password="a" authorities="ROLE_USER, ROLE_ADMIN" />
    <user name="bob" password="b" authorities="ROLE_USER" />
   </user-service>
  </authentication-provider>
 </authentication-manager>


 <global-method-security pre-post-annotations="enabled" />

5. Configure web.xml as below.
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
      /WEB-INF/spring-sec.xml
      /WEB-INF/app-context.xml
  </param-value>

</context-param>

<servlet>
  <servlet-name>login</servlet-name>
  <jsp-file>/jsp/login.jsp</jsp-file>
</servlet>

<servlet>
  <servlet-name>login_error</servlet-name>
  <jsp-file>/jsp/login_error.jsp</jsp-file>
</servlet>

<servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>/jsp/login</url-pattern>
</servlet-mapping>

<servlet-mapping>
  <servlet-name>login_error</servlet-name>
  <url-pattern>/jsp/login_error</url-pattern>
</servlet-mapping>

<servlet>
  <servlet-name>Vaadin Application Servlet</servlet-name>
  <servlet-class>kws.vaadin.MyVaadinApplication</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>Vaadin Application Servlet</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

6. My login.jsp is below
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div align="center">
Login here
<form action="/vaadin-sec/j_spring_security_check" method="post">
<table>
  <tr>
      <td>
          User
      </td>
      <td>
          <input name="j_username">
      </td>
  </tr>
  <tr>
      <td>
          Password
      </td>
      <td>
          <input type="password" name="j_password"/>
      </td>
  </tr>
  <tr>
      <td>
          <input type="submit" value="login">
      <td>
  </tr>
</table>
</form>
</div>
</body>
</html>

7. Now Add the main applicaton Servlet.

package kws.vaadin;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

public class MyVaadinApplication extends AbstractApplicationServlet
{
private WebApplicationContext appContext;
private Class<? extends Application> applicationClass;

@Override
protected Application getNewApplication(HttpServletRequest httpServletRequest) throws ServletException {
    System.out.println("Creating a new application");
    MainApplication mMa = (MainApplication) appContext.getBean("applicationBean");
    mMa.setWebApplicationContext(appContext);
    return  mMa;
}

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.service(request, response);    //To change body of overridden methods use File | Settings | File Templates.
}

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);    //To change body of overridden methods use File | Settings | File Templates.
    appContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
}

@Override
protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException {
    return MainApplication.class;
}
}

8. This is the application class.

package kws.vaadin;

import java.util.Collection;

import kws.vaadin.security.Roles;
import kws.vaadin.service.SecuredService;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.expression.WebSecurityExpressionRoot;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Component("applicationBean")
@Scope("prototype")
public class MainApplication extends Application {

@Autowired
private SecuredService securedService;

public WebApplicationContext appContext;

@Override
public void init() {
    Window window;
    window = new Window("My Vaadin Application");
    window.addComponent(new HeaderWindow(this));
    window.addComponent(new BodyWindow(this));
    window.addComponent(new FooterWindow(this));
    setMainWindow(window);
}

public boolean hasAnyRole(String ... roles){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<GrantedAuthority> authorities = authentication.getAuthorities();
    for(GrantedAuthority authority: authorities){
        for(String role: roles){
            if(role.equals(authority.getAuthority())){
                return true;
            }
        }
    }
    return false;
}

public void setWebApplicationContext(WebApplicationContext appContext){
    this.appContext = appContext;
}

}


9. Ok Done. You can find complete project from 'git clone git@github.com:changit/vaadin-spring-sec.git'

Saturday, February 5, 2011

SCWCD short Notes

Bean should have a default empty
constructor ? yes it is


what is the default scope for a java bean and can it see to included page. default is page. if it is

<error-page> tag. can we include
a error type here, you need provide the <error-code> or
<exception-type> with <location> tag


Sorry about this, I am not continuing this note because now I have done the exam. I was able to get 95 marks. I found more than half of the questions were in whislab exam simulator, So this exam can be easily pass to any one who can memorise that questions. This exams should not be like this. It should give different questions that we can't find within simulators.


Tuesday, February 1, 2011

Java web services

We can use fallowing tools to create and test web services.

CXF web services
Spring web services

SoapUi to test web services.

for spring follow this

http://justcompiled.blogspot.com/2010/09/building-web-service-with-spring-ws.html

Sunday, October 24, 2010

Spring 3 Security

Use java 1.5 or higher when using spring 3 security. The most fundamental object in spring security is Security Context Holder. Security Context Holder use ThreadLocal to store security information. Inside Security Context Holder Authentication object is used to store principle information which currently interact with the application.

UserDetail is an Central Interface which can provide userInformation like email , employee number etc.. To provide those Information You need to provide the userService inside the spring context. You can include a custom userService by implementing UserDetailService interface. It has following method.
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
Spring provide Some UserService based on Memory Map and JdbcDao. You can use those or you can implement your own.