Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Sunday, October 27, 2013

Spring 3 Scheduler

Basic Schduler in spring 3

<beans
 xmlns:task="http://www.springframework.org/schema/task"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task-3.0.xsd
  ">


<task:scheduler id="Scheduler" pool-size="10" />
 <task:executor id="TaskExecutor" pool-size="10"/>
 <task:annotation-driven executor="TaskExecutor" scheduler="Scheduler"/>

 <bean id="schedulerService" class="com.operation.service.SchedulerService"
    scope="singleton"/>


/**
 * @author jjhangu
 *
 */
public class SchedulerService {
 @Scheduled(fixedDelay = 5000)
 public void doSomething() {
  final long time = System.currentTimeMillis();
  final SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
  final String str = dayTime.format(new Date(time));
  System.out.println("gap is 5 second" + str);
 }
}


log gap is 5scond2013-06-28 02:06:44
log gap is 5scond2013-06-28 02:06:49

Thursday, May 2, 2013

AOP Method Signiture Pattern

AOP Method Signiture Patterns
I studied a lot of time to study AOP.
as i studied i feel like master of AOP but as time gone by i forget how to use
and re searching online guide of AOP
so I want summarize about use of AOP
Hope that it would be helpful me and you guys


The first wild card means method type : public, private, protected, *(all)

If AopTest.class exist in different package
execution(* com.sang.hwa.AopTest.*(..)) if AopTest.class exist in same package
all method mapping in AopTest.class
execution(* AopTest.*(..)) //If class name has xxxxController.class it will be mapped execution(public * com.sns.controller..*Controller.*(..)) package com.sns.common.aspect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * {@link SnsPointDay} 의 point-cut 지정 및 결과 코드 처리를 위한 어노테이션 * */ @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SnsPointDay { public String div() default "00"; public String category(); public String item(); public int point() default 1; public String status() default ""; } @Before(@annotation(com.sns.common.aspect.SnsPointDay)) @AfterReturning("@annotation(point)") public void afterControllerWithPoint(JoinPoint jp, SnsPoint point) throws Throwable { } //Annotation Expression //$$(And), ||(or), !(not) @Pointcut("operation() || execution() || @annotation(pointDay)") @Before("execution(* *.*(..)) && target(target) && args(a,b)") public void logParameter(Object target, dobule a, double b){ log.info("class : " + taget.getClass().getName()); log.info(" values : " + a + " , " + b); }

Sunday, April 28, 2013

Extends Session Time for Every Request

Extend Session
Why I worte this post?


1. After loging application, session time starts {Session Time}
2. For example, Session time set as 30 It means, your Session will validate after 30minutes late from first login
3. if you want to extends session time from some request within 30minute
4. you have to add duration from
4. below is solution to extends session time
// this is the time session created
long createdtime=session.getCreationTime();
// current Time
long currentTime = System.currentTimeMillis();
long lastAcessedTime = session.getLastAccessedTime();
// duration from first session created
int duration= (int)((currentTime - lastAcessedTime)/1000);
// session time
int inactive=session.getMaxInactiveInterval();
// set new session time (duration + original session Time)
request.getSession().setMaxInactiveInterval(duration+ inactive);


Wednesday, April 24, 2013

Spring Scope

Generally Spring has 5type of scopes
  • 1. SingleTon : Spring IOC make one bean context for container
  • 2. Prototypes : Every request, Spring IOC make every new context
  • 3. Request : For One Request, Spring IOC make one bean context
  • 4. Session : For Session, Spring IOC make one bean context
  • 5. GlobalSession : ...
First default Scope(Singleton)
Student class
package prototype;

/**
 * @author jjhangu
 * 
 */
public class Student {
 private String name = null;

 /**
  * @author jjhangu @create 2013. 4. 25.
  */
 public String getName() {
  return name;
 }

 /**
  * @author jjhangu @create 2013. 4. 25.
  */
 public void setName(String name) {
  this.name = name;
 }

}
Bus class
package prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jjhangu
 * 
 */
public class Bus {

 private List students = new ArrayList();

 public void addStudent(Student student) {
  students.add(student);
 }

 public String getStudents() {
  String names = "";
  for (final Student student : students) {
   names = names + "," + student.getName();
  }
  return names;
 }
}

Main class
package prototype;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author jjhangu
 * 
 */
public class Main {

 public static void main(String args[]) {
  final ApplicationContext context = new ClassPathXmlApplicationContext("Prototype.xml");

  final Student aaa = (Student) context.getBean("aaa");
  final Student bbb = (Student) context.getBean("bbb");
  final Student ccc = (Student) context.getBean("ccc");

  final Bus bus1 = (Bus) context.getBean("bus");
  bus1.addStudent(aaa);
  bus1.addStudent(bbb);

  System.out.println(" Bus 1 list : " + bus1.getStudents());

  final Bus bus2 = (Bus) context.getBean("bus");
  bus2.addStudent(ccc);

  System.out.println(" Bus 2 list : " + bus2.getStudents());
 }
}

Prototype.xml class


      
    
 
 
 
   
    aaa
   
 
 
 
   
    bbb
   
 
 
 
   
    ccc
   
 
 
 

Bus 1 list : ,aaa,bbb
Bus 2 list : ,aaa,bbb,ccc

Second Scope(prototype)
Prototype.xml class


      
   
 
 
 
   
    aaa
   
 
 
 
   
    bbb
   
 
 
 
   
    ccc
   
 
 
 

Bus 1 list : ,aaa,bbb
Bus 2 list : ,ccc

Tuesday, April 23, 2013

Spring Annotation Qualifier

@Autowired Annotation finds which bean is proper to set
if there are more than one bean, @Autowired don't know which bean is proper
so use @Qualifier to target the proper bean

HelloController class
public class Qualifier{
package com.sang.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/welcome")
public class HelloController {

 @Autowired
 @Qualifier("helloTwoWorld")
 private HelloWorld helloWorld;

 @RequestMapping(method = RequestMethod.GET)
 public String printWelcome(ModelMap model) {

  model.addAttribute("message", helloWorld.getName());
  return "hello";

 }

}
}
HelloWorld class

package com.sang.common.controller;

/**
 * Spring bean
 * 
 */
public class HelloWorld {
 private String name;

 public void setName(String name) {
  this.name = name;
 }

 /**
  * @author jjhangu @create 2013. 4. 24.
  * 
  * @return the name
  */
 public String getName() {
  return name;
 }

 public void printHello() {
  System.out.println("Spring 3 : Hello ! " + name);
 }
}
mvc-dispatcher-servlet.xml


 

 
  
   /WEB-INF/pages/
  
  
   .jsp
  
 
 
 


Qualifier.xml


      
 
   
    one
    
   
 
 
 
   
    two
    
   
 
 
 
Log
http://localhost:8080/SpringQualifier/welcome
you will see : Message : two

Thursday, April 18, 2013

@Async in Spring Future

FutureAnnotaion class
/**
 * (c)Copyright 2010-2010, BaruSoft Co., Ltd. All rights reserved 
* * @description
* * @create 2013. 4. 18. * @author jjhangu */ package com.jjhangu.core; import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; /** * @author jjhangu * */ public class FutureAnnotaion { @Async public Future getMessage(int j) { final int result = 0; for (int i = 0; i < 10000000; i++) { if (i == (10000000 - 1)) { System.out.println("finish : " + j); } } return new AsyncResult(result); } }
FutureAnnotationMain class
/**
 * (c)Copyright 2010-2010, BaruSoft Co., Ltd. All rights reserved 
* * @description
* * @create 2013. 4. 18. * @author jjhangu */ package com.jjhangu.core; import java.util.concurrent.ExecutionException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author jjhangu * */ public class FutureAnnotationMain { public static void main(String args[]) throws InterruptedException, ExecutionException { final ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); final FutureAnnotaion obj = (FutureAnnotaion) context.getBean("futureAnnotaion"); for (int i = 0; i < 10; i++) { obj.getMessage(i); } } }
SpringBeans.xml


      
 
      
 

 
 
 
pom.xml

 4.0.0
 com.mkyong.core
 Spring3Example
 jar
 1.0-SNAPSHOT
 Spring3Example
 http://maven.apache.org

 
  3.0.5.RELEASE
 

 
  
   junit
   junit
   4.8.2
   test
  

  
  

  
   org.springframework
   spring-context
   ${spring.version}
  

  
   cglib
   cglib
   2.2.2
  

 


log
finish : 8
finish : 4
finish : 9
finish : 7
finish : 6
finish : 5
finish : 3
finish : 0
finish : 2
finish : 1

Wednesday, March 13, 2013

Spring Properties get in class

test.properties
application.file.home = fileHomeString
spring.xml


      
        classpath:/properties/test.properties
      


Bean class
public PropertyTest class{

  @Value("${" + "application.file.home" + "}")
  private String propertiValue;

}

Spring Mvc jsp Exception Page

Web.xml
  
  java.lang.Exception
  /WEB-INF/pages/error.jsp
  
error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" isErrorPage="true"
    pageEncoding="EUC-KR"%>
<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>





Insert title here


${hello} This is an error page <%= exception %>


HandlerExceptionResolver class
public class SnsHandlerExceptionResolver implements HandlerExceptionResolver

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception error) {

     if (request.getRequestURI().contains(".htm")) {
request.setAttribute("javax.servlet.error.exception", error);
request.setAttribute("hello", "hello");
final ModelAndView view = new ModelAndView();
return view;
}

}
If servlet Exception Occured this error.jsp page will called