Spring: RestController vs Controller

Spting MVC provides us with annotation controller which tells Spring contailner that this class is a specialized component which will act as a controller.

To make REST support easy in Spring, it has added a @RestController annotation which is combination of @Contoller and @ResponseBody (Annotation that indicates a method return value should be bound to the web response body.).

http://stackoverflow.com/questions/25242321/difference-between-spring-controller-and-restcontroller-annotation
http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html
http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Controller.html

Inversion of Control: Dependency Injection vs Dependency Lookup

Inversion of Control is a principle which recommends moving unwanted responsibilities out of a class and letting the class focus on core responsibilities, hence providing loose coupling.

There are two basic ways in Java to provide IOC- Dependency Injection and Dependency lookup.

As the name suggest, Dependency Injection is where the dependency is injected from outside the class, and class is not worried about details – http://kamalmeet.com/coding/more-on-dependency-injection/

Dependency lookup is where class itself looks up for dependency and chooses appropriate implementation. Use of JNDI lookup for proper bean of datasource is a good example.

InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(“jndiName”);

Understanding LDAP

Directory Services: In simple words, a directory service would map a name to a value. A simple example is DNS or Domain Name System which is used by internet to map human readable names to an IP address. For example 10.22.12.22 might map to kamalmeet.com. It is easier for user to remember names, so DNS comes to help by converting the names to IP addresses.

Directory services can store simple or complex data for each name/ key based on requirement. One major point that distingushes Directory services from ususal database system is that we expect a lot of read operations but only a few writes. More on Directory Services – https://en.wikipedia.org/wiki/Directory_service

X.500: X.500 is a series of standars covering directory services. Most popular is DAP (Directory Access Protocol). More on X.500 on https://en.wikipedia.org/wiki/X.500

LDAP: Now as we know about Directory Services. LDAP or Lightweight Directory Access Protocol, provides us set of commands or rules to access a directory services. Most common implementation for LDAP is found for Single Signon systems.

Some of the operations supported by LDAP are – bind, search, compare, add new entry, delete an entry, modify an entry etc

A sample LDAP entry might look like

 dn: cn=John Doe,dc=example,dc=com
 cn: John Doe
 givenName: John
 sn: Doe
 telephoneNumber: +1 888 555 6789
 telephoneNumber: +1 888 555 1232
 mail: john@example.com
 manager: cn=Barbara Doe,dc=example,dc=com
 objectClass: inetOrgPerson
 objectClass: organizationalPerson
 objectClass: person
 objectClass: top

Source https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol

Using Java class based configuration with Spring

In last few posts about Sring, I have used XML based configuration. But offlate I have figured out that it is easier to use Java based configuration. Here is how it is done for a simple spring mvc application

1. Firstly you will tell web.xml that you will use which class for configuring spring

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.myapp.config.MyConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>

2. You will mark your class with annotation @Configuration

3. For MVC application @EnableWebMvc

4. For component scan- to tell your spring application where to find compoenent @ComponentScan(basePackages = “com.app.my com.app.service com.app.aspect”)

5. If you are using AOP @EnableAspectJAutoProxy

So a sample file would look like

@Configuration
@EnableAspectJAutoProxy
@EnableWebMvc
@ComponentScan(basePackages = "com.app.my com.app.service com.app.aspect")
public class MyConfig extends WebMvcConfigurerAdapter {


	@Bean
	public UrlBasedViewResolver urlBasedViewResolver() {
		UrlBasedViewResolver res = new InternalResourceViewResolver();
		res.setViewClass(JstlView.class);
		res.setPrefix("/WEB-INF/");
		res.setSuffix(".jsp");

		return res;
	}

	@Override
	public void addResourceHandlers(final ResourceHandlerRegistry registry) {

		registry.addResourceHandler("/fonts/**")
				.addResourceLocations("/fonts/").setCachePeriod(31556926);
		registry.addResourceHandler("/css/**").addResourceLocations("/css/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("/images/**")
				.addResourceLocations("/images/").setCachePeriod(31556926);
		registry.addResourceHandler("/js/**").addResourceLocations("/js/")
				.setCachePeriod(31556926);
	}


	@Bean
	public CommonsMultipartResolver multipartResolver() {
		CommonsMultipartResolver mr = new CommonsMultipartResolver();
		mr.setMaxUploadSize(50000000);
		return mr;
	}


}

AOP: Spring aop vs AspectJ

If you are using Spring framework, it is easy to implement Spring AOP. Ease of implementation comes with some limitations like you can only use aspects with spring managed beans and only methods can be used as pointcuts. Another limitation is that you cannot apply aspects for method calling another in same class. Whereas AspectJ does not have these limitations.

The reason behind this is the way Spring and AspectJ implements AOP. Spring uses runtime weaving whereas AspectJ uses load time weaving. Spring implements proxy based approach. Where it adds a proxy wrapper aound your class, and every call to the class method, has to go through the proxy wrapper.

AspectJ implement load time waving by actually manipulating the bytecode using its compiler while class is loaded to JVM.

References:
http://kamalmeet.com/tag/aop-2/
https://en.wikipedia.org/wiki/AspectJ
http://stackoverflow.com/questions/26325732/spring-aop-with-aspectj-load-time-weaving
http://www.springindepth.com/book/aop-load-time-weaving.html
http://stackoverflow.com/questions/1606559/spring-aop-vs-aspectj

AOP- Understanding terms

In last few posts on AOP I have mentioned basics of AOP, and some sample implementations- http://kamalmeet.com/category/aop/

I will discuss some formal AOP terms here

JoinPoint: A well defined point in execution of a application. A point where something is happening in the applicaiton. For example when a method is called, an object is instantiation, an exception is being thrown etc.

Advice: The code that is to be executed at a particular joinpoint.

Pointcut: Collection of joinpoints where advice has to be applied.

A very good explanation of joinpoint & pointcut- http://stackoverflow.com/questions/15447397/spring-aop-whats-the-difference-between-joinpoint-and-pointcut

Aspect: Combination of pointcuts and advice, programmed in a class. For example see loginaspect class

Weaving: When do we add aspects to actual code- compile time, run time (Spring), load time (AspectJ)

Target Object: object whose execution flow is modified by an AOP process.

Introduction: Process by which you modify target object, by declaring additional methods or fields.

Types of advice:

Before: Before starting the execution

After: After completion of execution

After Throwing: After an exception is thrown

After Returning: After normal execution (no exception thrown)

Around: Before and After execution

Refer: http://docs.spring.io/spring/docs/4.0.1.RELEASE/spring-framework-reference/htmlsingle/#aop-introduction-defn

AOP – Logging utility

For basics of AOP refer

http://kamalmeet.com/aop/aspect-oriented-programming/
http://kamalmeet.com/aop/aspect-oriented-programming-implementation/

Here is a simple logging example using aspectj

package com.my.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * This is class implementing logging aspect. This is a generic class which can
 * be embedded into any piece of code for implementing logging.
 * 
 * @author kamalmeet
 * @version 1.0
 */
@Component
@Aspect
public class LoggingAspect {

	private static final Logger LOG = Logger.getLogger(LoggingAspect.class);;
	

	private static final String POINT_CUT = "execution(* com.my.package.*.*(..))";

	/**
	 * This method is used to log action before entering into point-cut method.
	 * 
	 * @param joinPoint
	 */
	// @Before(POINT_CUT)
	@Before(POINT_CUT)
	public void logBefore(JoinPoint joinPoint) {
		LOG.info("Entering function: "+ joinPoint.getSignature());
		
	}

	/**
	 * This method is used to log action after returning from point-cut method.
	 * 
	 * @param joinPoint
	 */
	@AfterReturning(POINT_CUT)
	public void logAfterReturing(JoinPoint joinPoint) {
		LOG.info("Exiting successfully from function: "+
				joinPoint.getSignature());
	}

	/**
	 * This method is used to log error in case some exception condition
	 * occurred in the given point-cut method.
	 * 
	 * @param joinPoint
	 */
	@AfterThrowing(POINT_CUT)
	public void logAfterThrowing(JoinPoint joinPoint) {
		LOG.error("Exiting with exception thrown from function: "+
				joinPoint.getSignature());
	}
}

Running WildFly/ Jboss as service

Here is a step by step guide to get WildFly 9 running as service

1. sudo ln -s /home/kamal/wildfly-9.0.1.Final /opt/wildfly
2. sudo cp /opt/wildfly/bin/init.d/wildfly.conf /etc/default/wildfly.conf
3. sudo vi /etc/default/wildfly.conf
Edit
JAVA_HOME=”/usr/java/jdk1.7.0_71″
JBOSS_HOME=”/opt/wildfly”
JBOSS_USER=wildfly ##root
JBOSS_MODE=standalone
JBOSS_CONFIG=standalone.xml
STARTUP_WAIT=60
SHUTDOWN_WAIT=60
JBOSS_CONSOLE_LOG=”/var/log/wildfly/console.log”

4. sudo cp /opt/wildfly/bin/init.d/wildfly-init-redhat.sh /etc/init.d/wildfly
5. sudo chkconfig –add wildfly
6. sudo chkconfig wildfly on
7. sudo mkdir -p /var/log/wildfly
8. sudo adduser wildfly
9. sudo chown -R wildfly:wildfly /opt/wildfly-8.2.0.Final
10. sudo chown -R wildfly:wildfly /home/kamal/wildfly-9.0.1.Final
11. sudo chown wildfly:wildfly /opt/wildfly
12. sudo chown wildfly:wildfly /var/log/wildfly

Finally sudo service wildfly start

Check logs
$ vi /var/log/wildfly/console.log

If you are facing issues with permission, you might want to set user as root in wildfly.conf file

Source:

developer-should-know.tumblr.com/post/112230363742/how-to-install-wildfly-as-a-service-on-linux

Adding Maven Jars to final war

There might be a requirement to let the war file include all maven dependencies (jars downloaded through maven) to avoid adding them manually to server, especialy while development time.

Right click project -> properties-> Deployment Assembly-> add ->build path entries->maven dependencies

Reference- http://stackoverflow.com/questions/6083501/maven-dependencies-not-visible-in-web-inf-lib