2015. 5. 12. 04:28

Exception Handling in Spring MVC

The following link provides good explanation for exception handling in Spring MVC.


https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc


In addition, it also provides the sample to demonstrate it.


https://github.com/paulc4/mvc-exceptions


I recognized the ResponseStatus annotation is very useful to return abnormal http status.


@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such order")
public class OrderNotFoundException extends RuntimeException {

	/**
	 * Unique ID for Serialized object
	 */
	private static final long serialVersionUID = -8790211652911971729L;

	public OrderNotFoundException(String orderId) {
		super(orderId + " not found");
	}
}


In the case of using ControllerAdvice, the following code should be considered if you let other exceptions with ResponseStatus annotation  be handled as it is.


@ControllerAdvice
public class GlobalExceptionHandlingControllerAdvice {

	@ExceptionHandler(SupportInfoException.class)
	public ModelAndView handleError(HttpServletRequest req, Exception exception)
			throws Exception {

		// Rethrow annotated exceptions or they will be processed here instead.
		if (AnnotationUtils.findAnnotation(exception.getClass(),
				ResponseStatus.class) != null)
			throw exception;

		logger.error("Request: " + req.getRequestURI() + " raised " + exception);

		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", exception);
		mav.addObject("url", req.getRequestURL());
		mav.addObject("timestamp", new Date().toString());
		mav.addObject("status", 500);

		mav.setViewName("support");
		return mav;
	}

}


mvc-exceptions.zip


2015. 4. 15. 23:34

Spring Security JSP Tag Libraries

Declaring the Taglib


<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>


The authorize Tag


<sec:authorize access="hasRole('supervisor')">

This content will only be visible to users who have the "supervisor" authority in their list

of <tt>GrantedAuthority</tt>s.

</sec:authorize>


<sec:authorize access="hasPermission(#domain,'read') or hasPermission(#domain,'write')">

This content will only be visible to users who have read or write permission to the Object found as a

request attribute named "domain".

</sec:authorize>


<sec:authorize url="/admin">

This content will only be visible to users who are authorized to send requests to the "/admin" URL.

</sec:authorize>


Disabling Tag Authorization for Testing


If you set the system property spring.security.disableUISecurity to true, the authorize tag will still run but will not hide its contents. By default it will also surround the content with <span class="securityHiddenUI">…</span> tags. This allows you to display "hidden" content with a particular CSS style such as a different background colour. Try running the "tutorial" sample  application with this property enabled, for example.


This can be tested by using the following sample:



tutorial-xml.zip


After downloading it, type the command as below (need to install gradle) :


gradle jettyRun -Dspring.security.disableUISecurity=true


If it succeeded to run, visit the "http://localhost:8080/sample". Then you will see the following page. 





The texts highlighted with orange background will be hidden if it's false.


The authentication Tag


<sec:authentication property="principal.username" />


You can access the Authentication object in your MVC controller

(by calling SecurityContextHolder.getContext().getAuthentication()) and add the data

directly to your model for rendering by the view.


The accesscontrolllist Tag


<sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}">

This will be shown if the user has all of the permissions represented by the values "1" or "2" on the

given object.

</sec:accesscontrollist>



The csrfInput Tag


If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for

the CSRF protection token. If CSRF protection is not enabled, this tag outputs nothing.

Normally Spring Security automatically inserts a CSRF form field for any <form:form> tags you use,

but if for some reason you cannot use <form:form>, csrfInput is a handy replacement.

You should place this tag within an HTML <form></form> block, where you would normally place

other input fields. Do NOT place this tag within a Spring <form:form></form:form> block—Spring

Security handles Spring forms automatically.


<form method="post" action="/do/something">

<sec:csrfInput />

Name:<br />

<input type="text" name="name" />

...

</form>


The csrfMetaTags Tag


If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form

field and header names and CSRF protection token value. These meta tags are useful for employing

CSRF protection within JavaScript in your applications.


You should place csrfMetaTags within an HTML <head></head> block, where you would normally

place other meta tags. Once you use this tag, you can access the form field name, header name, and

token value easily using JavaScript. JQuery is used in this example to make the task easier.


<!DOCTYPE html>

<html>

<head>

<title>CSRF Protected JavaScript Page</title>

<meta name="description" content="This is the description for this page" />

<sec:csrfMetaTags />

<script type="text/javascript" language="javascript">

var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");

var csrfHeader = $("meta[name='_csrf_header']").attr("content");

var csrfToken = $("meta[name='_csrf']").attr("content");

// using XMLHttpRequest directly to send an x-www-form-urlencoded request

var ajax = new XMLHttpRequest();

ajax.open("POST", "http://www.example.org/do/something", true);

ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded data");

ajax.send(csrfParameter + "=" + csrfToken + "&name=John&...");

// using XMLHttpRequest directly to send a non-x-www-form-urlencoded request

var ajax = new XMLHttpRequest();

ajax.open("POST", "http://www.example.org/do/something", true);

ajax.setRequestHeader(csrfHeader, csrfToken);

ajax.send("...");

// using JQuery to send an x-www-form-urlencoded request

var data = {};

data[csrfParameter] = csrfToken;

data["name"] = "John";

...

$.ajax({

url: "http://www.example.org/do/something",

type: "POST",

data: data,

...

});

// using JQuery to send a non-x-www-form-urlencoded request

var headers = {};

headers[csrfHeader] = csrfToken;

$.ajax({

url: "http://www.example.org/do/something",

type: "POST",

headers: headers,

...

});

<script>

</head>

<body>

...

</body>

</html>


If CSRF protection is not enabled, csrfMetaTags outputs nothing.


References: spring-security-reference

2015. 4. 15. 05:56

Functional Testing and Non-Functional Testing

ISO 9126 introduces the following quality model :


  • Functionality 기능성

    • Suitability
provide an appropriate set of functions

    • Accuracy
provide the right or agreed results or effect

    • Interoperability
interact with one or more specified systems

    • Security
protect information and data so that unauthorised persons or systems cannot read or modify them and authorised persons or systems are not denied access to them.

    • Functionality Compliance


  • Reliability 신뢰성

    • Maturity
avoid failure as a result of faults

    • Fault Tolerance
maintain a specified level of performance

    • Recoverability
re-establish a specified level of performance and recover the data

    • Reliability Compliance


  • Usability 사용성

    • Understandability
enable the user to understand whether the software is suitable

    • Learnability
enable the user to learn its application.

    • Operability
enable the user to operate and control it

    • Attractiveness
attractive to the user

    • Usability Compliance


  • Efficiency 효율성

    • Time Behaviour
provide appropriate response and processing times and throughput rates

    • Resource Utilization
use appropriate amounts and types of resources

    • Efficiency Compliance


  • Maintainability 유지보수성

    • Analyzability
be diagnosed for deficiencies or causes of failures

    • Changeability
enable a specified modification to be implemented

    • Stability
avoid unexpected effects from modifications

    • Testability
enable modified software to be validated

    • Maintainability Compliance


  • Portability 이식성

    • Adaptability
be adapted for different specified environments without applying actions or means

    • Installability
be installed in a specified environment

    • Co-Existence
co-exist with other independent software

    • Replaceability
be used in place of another specified software product

    • Portability Compliance


Only Functionality of 6 items above is under Functional Testing. The rest is under Non-Functional Testing. 

References: 
- 자바 개발자도 쉽고 즐겁게 배우는 테스팅 이야기


2015. 4. 7. 23:24

Spring MVC and HDIV example application and Debugging

Source: https://github.com/hdiv/hdiv-spring-mvc-showcase.git            

Reference: http://javahotpot.blogspot.in/2013/11/running-tomcat-maven-plugin-in-debug.html


I'll explain how to add showcase sample into the eclipse from git repository above then how to set the debugging environment step by step. 


1. Make a eclipse project


  • Select Import from the context menu in the Navigator or Project Explorer
  • Navigate to the Git folder and select "Projects from Git"
  • Select "Clone URI" from the repository source page
  • Paste the following URI into the URI 
https://github.com/hdiv/hdiv-spring-mvc-showcase.git
  • Then click Next Until "Select a wizard to use for importing projects" page is shown
  • Select "Import s general project"
In my case, other option could not import any project
  • Finally click Finish.

2. Set up the debug environment for this sample

  • Open the context menu by clicking the right mouse button on the Navigator or Project explorer
  • Go to the "Debug As" menu and select the "Debug configurations..."
  • Select "Maven Build" like the following


  • Click the right mouse button on the "Maven Build" then select "New"
  • The new configuration will be made like the following then enter name as "Debug tomcat"


  • It's time to specify "Base directory". Click "Browse Workspace" and select "hdiv-spring-mvc-showcase" as shown in the following figure.


  • Then click the Source tab and click "Add" like the following


  • Select Project like the figure above then click OK. and select "hdiv-spring-mvc-showcase".
  • Finally press the "Debug" button. 

That's all. If you meet some error, try to build maven project then start debugging. If you finished all the steps above, you can easily start debugging by clicking the menu like the following:














2015. 3. 17. 02:03

Responsive Web

Here's good article :


http://helloworld.naver.com/helloworld/textyle/81480

2015. 2. 3. 23:13

Move window to the monitor

If you have more than one monitor:


  • Win + Shift + Left arrow : Move window to the monitor on the left
  • Win + Shift + Right arrow : Move window to the monitor on the right


As you know, there are the useful shortcuts for manipulating the active window:


  • Win + Left arrow : Snap to the left half of the screen
  • Win + Right arrow : Snap to the right half of the screen
  • Win + Up arrow: Maximize the window
  • Win + Down arrow: Minimize/Restore if it's maximized


2015. 2. 3. 00:04

Useful Shortcuts in Eclipse

Here are the shortcuts that is used very often  by me.


 Ctrl + Shift + O

 imports all classes in a file automatically

 Ctrl + O

 show code outline / structure

 Atl + Shift + F

 Correct indentation in a file

 Ctrl + I

 Correct indentation in a selection

 Ctrl + D delete a line

 Ctrl + 1

 Quick fix 

 Ctrl + B

 Build all. 

 Change this short cut to "Build Project" to save your time.

 F11 Debug
 Ctrl + F11 Run
 F3 Open declaration. Go to source.

 Alt + Left Arrow

 Go to back 

 Alt + Right Arrow 

 Go to forward 

 Ctrl + Shift + R

 Open resource like a file

 Ctrl + Shift + B

 Toggle break point

 Alt + Shift + J Add 
 Alt + Shift + E

 Show in navigator.

 Not default. Need to set this short cut by yourself

 Ctrl + K 

 Find next
 Ctrl + Shift + K Find previous 

 Ctrl + Shift + W

 Close others.
 Not default. Need to set this shout cut by yourself 

 Ctrl + H

 Show search dialog with various options

 Ctrl + / Toggle line comment 

 Ctrl + Shift + /

 Add block comment
 Ctrl + Shift + \

 Remove block comment 

 Alt + G

 Open implementation
 Alt + Shift + G Open super implementation


2015. 2. 2. 23:51

Sharing session state over multiple services using StateServer

For about a week I went through how to share session state over multiple services because our customers wanted to make their service to become HA (High availability). To construct our service as HA, sharing session state over multiple WAS was very important. And because we're using MySQL, using StateServer instead of SqlServer was unavoidable option.


It was really hard to find any document related to this knowledge. Finally I found very helpful site which gives simple solution to us. 


http://weblogs.asp.net/lichen/sharing-session-state-over-multiple-asp-net-applications-with-asp-net-state-server


Thanks to Li Chen. In addition to the link, I made sample project to show this. Here it is.



StateSeverTest.zip



To run this example, you have to start "ASP.NET State Service" as below:


1. Type Windows + R and type the "services.msc"


2. Find the "ASP.NET State Service"





3. Start that service


That's it. 


Updated at 2015.02.02


In case of WCF, to share session between difference wcf services routed by wcf routing, you should set SoapProcessingEnabled option to false. (Thanks to my smart colleague, Mr. Oh)


Refer the following for more information:


https://msdn.microsoft.com/en-us/library/ee816917(v=vs.110).aspx


2015. 2. 2. 23:46

Spring Framework Reference Documentation 4.1.4 RELEASE

Here is the official spring framework reference document:



spring-framework-reference.pdf


http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/pdf/spring-framework-reference.pdf



2015. 2. 2. 23:42

cglib - Byte Code Generation Library

cglib - Byte Code Generation Library is high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.

https://github.com/cglib/cglib/wiki


Here is good example for this:


http://markbramnik.blogspot.kr/2010/04/cglib-introduction.html


In addition, I attached sample project to be able to run his explanation:



CglibTest.zip



TODO: I need to investigate and study cglib's usage more!


It's now widely used at famous frameworks like Hibernate, Spring and more.