달력

10

« 2017/10 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  •  
  •  
  •  
  •  
2011.07.11 09:45

Spring + Akka 예제 (None Blocking) Terracotta2011.07.11 09:45

None Blocking 테스트 예제임. 호출 명령이 실행 완료후, 결과값이 구글로 부터 찍히는 것을 확인할수 있다. Spring 설정은 상당히 구려 보이는데, 이는 개선될 필요가 있다. AKKA의 특성을 감안하더라도... 어쩌자고 이따위 설정 구조 밖에 못했는지 이해하기 힘든.... (<akka:supervision> 테그는 제대로 동작하지도 않았다.)

1) XML 설정

<beans xmlns:akka="http://akka.io/schema/akka"
http://akka.io/schema/akka http://akka.io/akka-1.0.xsd >

<akka:typed-actor 
 id="googleGmailService"
 interface="net.max.wp.google.service.GoogleGmailService"
 implementation="net.max.wp.google.service.impl.GoogleGmailServiceImpl"
 timeout="5000" 
 scope="singleton">
<property name="googleDataTemplate" ref="googleDataTemplate"/>
<property name="feedUrl" ref="google.mail.feed"/>
<property name="linkUrl" ref="google.mail.linkurl"/>
</akka:typed-actor>     
<akka:typed-actor 
 id="googleDocsService"
 interface="net.max.wp.google.service.GoogleDocsService"
 implementation="net.max.wp.google.service.impl.GoogleDocsServiceImpl"
 timeout="5000"
 scope="singleton">
<property name="googleDataTemplate" ref="googleDataTemplate"/>
<property name="feedUrl" ref="google.docs.feed"/>
</akka:typed-actor>     
<akka:typed-actor 
 id="googleCalendarService"
 interface="net.max.wp.google.service.GoogleCalendarService"
 implementation="net.max.wp.google.service.impl.GoogleCalendarServiceImpl"
 timeout="5000"
 
 scope="singleton">
<property name="googleDataTemplate" ref="googleDataTemplate"/>
<property name="feedUrl" ref="google.calendar.feed"/>
</akka:typed-actor> 



2) Test 코드

@Test
public void non_blocking(){
System.out.println("1) 메일 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
googleGmailService.call(GoogleDataFixture.getGmailResult());
System.out.println("1) 메일 호출 끝=========================================================");
System.out.println("2) 문서 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
googleDocsService.call(GoogleDataFixture.getDocsResult());
System.out.println("2) 문서 호출 끝=========================================================");
System.out.println("3) 일정 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
googleCalendarService.call(GoogleDataFixture.getCalendarResult());
System.out.println("3) 일정 호출 끝=========================================================");


3) Test 실행결과(로그)

09:48:59.640 [main] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction
1) 메일 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
09:48:59.733 [main] INFO  a.d.LazyExecutorServiceWrapper - Lazily initializing ExecutorService for 
1) 메일 호출 끝=========================================================
2) 문서 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
09:48:59.742 [akka:event-driven:dispatcher:global-1] DEBUG akka.dispatch.MonitorableThread - Created thread akka:event-driven:dispatcher:global-1
2) 문서 호출 끝=========================================================
3) 일정 호출 시작+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
09:48:59.922 [akka:event-driven:dispatcher:global-2] DEBUG akka.dispatch.MonitorableThread - Created thread akka:event-driven:dispatcher:global-2
3) 일정 호출 끝=========================================================
09:48:59.941 [akka:event-driven:dispatcher:global-3] DEBUG akka.dispatch.MonitorableThread - Created thread akka:event-driven:dispatcher:global-3
09:49:00.075 [main] DEBUG o.s.t.c.t.TransactionalTestExecutionListener - No method-level @Rollback override: using default rollback [true] for test context [[TestContext@4934ce4a testClass = GoogleServiceSupervisorTest, locations = array<String>['classpath*:/META-INF/spring/applicationContext*.xml', 'file:src/main/webapp/WEB-INF/spring/webmvc-config.xml', 'file:src/main/webapp/WEB-INF/spring/jersey-config.xml'], testInstance = net.max.wp.actor.GoogleServiceSupervisorTest@29d381d2, testMethod = non_blocking@GoogleServiceSupervisorTest, testException = [null]]]
09:49:00.076 [main] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction rollback
09:49:00.076 [main] DEBUG o.s.orm.jpa.JpaTransactionManager - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@2da3e9cb]
09:49:00.076 [main] DEBUG o.h.transaction.JDBCTransaction - rollback
09:49:00.077 [main] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommit
09:49:00.077 [main] DEBUG o.h.transaction.JDBCTransaction - rolled back JDBC Connection
09:49:00.077 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
09:49:00.078 [main] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
09:49:00.080 [main] DEBUG o.s.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@2da3e9cb] after transaction
09:49:00.097 [main] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
09:49:00.098 [main] INFO  o.s.t.c.t.TransactionalTestExecutionListener - Rolled back transaction after test execution for test context [[TestContext@4934ce4a testClass = GoogleServiceSupervisorTest, locations = array<String>['classpath*:/META-INF/spring/applicationContext*.xml', 'file:src/main/webapp/WEB-INF/spring/webmvc-config.xml', 'file:src/main/webapp/WEB-INF/spring/jersey-config.xml'], testInstance = net.max.wp.actor.GoogleServiceSupervisorTest@29d381d2, testMethod = non_blocking@GoogleServiceSupervisorTest, testException = [null]]]
09:49:00.104 [main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [[TestContext@4934ce4a testClass = GoogleServiceSupervisorTest, locations = array<String>['classpath*:/META-INF/spring/applicationContext*.xml', 'file:src/main/webapp/WEB-INF/spring/webmvc-config.xml', 'file:src/main/webapp/WEB-INF/spring/jersey-config.xml'], testInstance = net.max.wp.actor.GoogleServiceSupervisorTest@29d381d2, testMethod = non_blocking@GoogleServiceSupervisorTest, testException = [null]]], class dirties context [false], class mode [null], method dirties context [false].
09:49:00.105 [main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test class: context [[TestContext@4934ce4a testClass = GoogleServiceSupervisorTest, locations = array<String>['classpath*:/META-INF/spring/applicationContext*.xml', 'file:src/main/webapp/WEB-INF/spring/webmvc-config.xml', 'file:src/main/webapp/WEB-INF/spring/jersey-config.xml'], testInstance = [null], testMethod = [null], testException = [null]]], dirtiesContext [false].
09:49:00.169 [Thread-1] INFO  o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@627a4489: startup date [Mon Jul 11 09:48:46 KST 2011]; root of context hierarchy
09:49:00.173 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
09:49:00.173 [Thread-1] INFO  o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@38f8ff42: defining beans [org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.openid.OpenIDAuthenticationFilter#0,org.springframework.security.openid.OpenIDAuthenticationProvider#0,org.springframework.security.config.http.UserDetailsServiceInjectionBeanPostProcessor#0,org.springframework.security.filterChainProxy,org.springframework.security.authenticationManager,demoAuthenticationProvider,userDetailsService,org.springframework.security.openid.ext.OpenIdAuthenticationHandler,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.config.internalBeanConfigurerAspect,accountDataOnDemand,companyDataOnDemand,gadgetDataOnDemand,layerDataOnDemand,pageDataOnDemand,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,transactionManager,org.springframework.transaction.config.internalTransactionAspect,entityManagerFactory,googleDataTemplate,dozerMapper,googleGmailService,googleDocsService,googleCalendarService,google.calendar.feed,google.docs.feed,google.mail.feed,google.mail.linkurl,akka.actor.timeout,akka.remote.server.port,akka.remote.server.hostname,googleController,openIdController,indexController,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#1,org.springframework.web.servlet.handler.MappedInterceptor#1,org.springframework.web.servlet.handler.MappedInterceptor#2,org.springframework.web.servlet.config.viewControllerHandlerAdapter,org.springframework.web.servlet.config.viewControllerHandlerMapping,messageSource,localeResolver,themeSource,themeResolver,org.springframework.web.servlet.handler.SimpleMappingExceptionResolver#0,multipartResolver,org.springframework.web.servlet.view.InternalResourceViewResolver#0,googleResource,googleServiceProviderImpl]; root of factory hierarchy
09:49:00.182 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#39': [org.springframework.web.servlet.config.viewControllerHandlerMapping]
09:49:00.184 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#31': [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0]
09:49:00.187 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'org.springframework.web.servlet.i18n.LocaleChangeInterceptor#0': [org.springframework.web.servlet.handler.MappedInterceptor#2]
09:49:00.188 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'org.springframework.web.servlet.theme.ThemeChangeInterceptor#0': [org.springframework.web.servlet.handler.MappedInterceptor#1]
09:49:00.188 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#30': [org.springframework.web.servlet.handler.MappedInterceptor#0]
09:49:00.190 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'entityManagerFactory'
09:49:00.190 [Thread-1] INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'persistenceUnit'
09:49:00.190 [Thread-1] INFO  o.hibernate.impl.SessionFactoryImpl - closing
09:49:00.192 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy method 'close' on bean with name 'dataSource'
09:49:00.197 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'layerDataOnDemand': [net.max.wp.gadget.domain.GadgetDataOnDemand]
09:49:00.197 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'pageDataOnDemand': [net.max.wp.layer.domain.LayerDataOnDemand]
09:49:00.197 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'companyDataOnDemand': [net.max.wp.page.domain.PageDataOnDemand]
09:49:00.198 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'org.springframework.context.config.internalBeanConfigurerAspect'
09:49:00.308 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'org.springframework.security.filterChainProxy'
09:49:00.308 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#14': [org.springframework.security.filterChainProxy]
09:49:00.308 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#14'
09:49:00.308 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#15'
09:49:00.309 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#16': [(inner bean)#16]
09:49:00.330 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#16'
09:49:00.330 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#18': [(inner bean)#18]
09:49:00.331 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#20': [(inner bean)#20]
09:49:00.331 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#18'
09:49:00.331 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#24'
09:49:00.331 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#25'
09:49:00.332 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#26'
09:49:00.332 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#27': [(inner bean)#27]
09:49:00.332 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#27'
09:49:00.332 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#28': [(inner bean)#28]
09:49:00.332 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name '(inner bean)#28'
09:49:00.333 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'org.springframework.security.openid.OpenIDAuthenticationFilter#0'
09:49:00.333 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#8': [org.springframework.security.openid.OpenIDAuthenticationFilter#0]
09:49:00.334 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#10': [(inner bean)#10]
09:49:00.340 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0'
09:49:00.341 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#6': [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0]
09:49:00.341 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#5': [org.springframework.security.web.savedrequest.HttpSessionRequestCache#0]
09:49:00.341 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#3': [(inner bean)#3, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0]
09:49:00.342 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#2': [org.springframework.security.access.vote.AffirmativeBased#0]
09:49:00.342 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)': [org.springframework.security.authentication.ProviderManager#0]
09:49:00.343 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#1': [(inner bean)#1]
09:49:00.343 [Thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Retrieved dependent beans for bean 'googleCalendarService': [net.max.wp.actor.GoogleServiceSupervisorTest]
09:49:00.343 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'googleCalendarService'
11
메일시작-----------------------------------
One More Week to Trial Premium Features
Final notice: Google Apps accounts will be automatically transitioned
UCM news: Out of beta at the end of June!
Improve Your Project Financials
UCM news: Smart Mail screencast online
Two week notice: Google Apps accounts will be automatically transitioned
Getting the Most out of Mavenlink
Take control with Manymoon
New features: Real-time Activity Feeds
Hello from Glasscubes
[Expensify Newsletter] Automatic Receipt Scanning, Categorization
메일끝-----------------------------------
일정시작-----------------------------------
XXX 관광
XXX 학교
XXX  Deployment
XXX  Deployment
Apps 테스트 일정
일정끝-----------------------------------
09:49:02.767 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'googleDocsService'
문서시작-----------------------------------
2011-07-05 XXX 견적서_XXXXXXX
2011-07-04 Google Apps Deployment Guide _XXX .doc
2011-07-01 XXX  견적서_XXX 
2011-07-04 Google Apps Deployment Guide _XXX .doc
2011-07-04XXX  구글 앱스 운용을 위한 XXX  정보.docx
문서시작-----------------------------------
09:49:02.831 [Thread-1] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'googleGmailService'
09:49:02.836 [Thread-1] INFO  akka.actor.Scheduler$ - Starting up Scheduler 

신고

'Terracotta' 카테고리의 다른 글

Spring + Akka 예제(Blocking)  (0) 2011.07.11
Spring + Akka 예제 (None Blocking)  (0) 2011.07.11
TAG akka, Spring
Posted by summerwars
2010.09.08 17:24

DWR CSRF Security Error 처리방법 Tips2010.09.08 17:24

'DWR CSRF Security Error' 로 구글링해보면, 포럼부터 이슈추적까지 많이 나오지만, 각설하고, web.xml의 DWR servlet의 설정을 다음과 같이 하면된다. 원래 crossDomainSessionSecurity 기본값은 true 이다.


	
		dwrServlet
		org.directwebremoting.spring.DwrSpringServlet
		
			debug
			true
		
	    
	      crossDomainSessionSecurity
	      false
	    		
crossDomainSessionSecurity의 param값을 false로 하면 된다. 왜 그럴까는 DWR 사용자 포럼에서 확인해 볼 것.
신고
TAG CSRF, DWR, Spring
Posted by summerwars
2010.08.17 11:10

MongoDB-Morphia DAO Support 사용하기 MongoDB2010.08.17 11:10

Document DB 역시 객체를 영속화 시키려면 객체 그대로를 저장할수는 없고, 나름대로 변경하는 작업이 필요했다. 이것은 Aspect로 뺄수 있을 것이다. 그래서 Morphia의 DAO클래스에서 그걸 처리해 준다. 해당 클래스에 대해서 좀더 알아보자. Morphia의 DAO 클래스르 확장한 Dao는 아래와 같다.

@Repository
public class AccountDaoImpl extends DAO implements AccountDao {

	@Autowired
	protected AccountDaoImpl( @Qualifier("mongo") Mongo mongo, 
							  @Qualifier("morphia") Morphia morphia, 
							  @Qualifier("dbName") String dbName) {
		super(mongo, morphia, dbName);
	}
	public Account update(Account entity) {
		this.save(entity);
		return entity;
	}
	public List find(String query) {
		return ds.find(entityClazz).filter("name = ", query).asList();
	}
}


생성자 방식의 의존성 주입 이외에 일반 DAO 클래스와 다를께 없다. Morphia DAO는 Datastore 개념의 몇가지 메서드를 제공하고 있다. 그것을 이용하여 원하는 CRUD를 구현하면 된다. 아래는 위 코드는 테스트한 코드다. 테스트 코드는 일반 테스트코드와 특별한게 없다.

	@Autowired AccountDao accountDao;
	
	@Test
	public void diTest(){
		Assert.assertNotNull(accountDao);
	}

	@Test
	public void save(){
		// save()
		Account account = new Account("yunsunghan","yunsunghan@gmail.com");
		Account account2 = accountDao.update(account);
		Assert.assertEquals("yunsunghan@gmail.com", account2.getEmail());
		// print
		System.out.println("=========================================");
		System.out.println(account.getId() +":"+account2.getId());
		System.out.println("=========================================");
		
		// find()
		List list = accountDao.find("yunsunghan");
		Assert.assertNotNull("하나이상 존재한다.", list);
		// print
		System.out.println("=========================================");
		for(Account a : list)System.out.println(a.getId() + " : " + a.getName());
		System.out.println("=========================================");
	}

이로써, 전에 봤던, toDBObject나 fromDBObject 같은 귀찮은 객체 전환 작업을 캡슐화 시킬수 있었다. 하지만 아직도 야생에서 쓰기엔 뭔가 어색해 보인다. 아직 개선의 여지가 있다는 생각이 드는 것인데, Morphia DAO를 Spring의 Template 시리즈나, Support 시리즈처럼 좀더 편리하게 쓸수는 없을까 하는 생각이 든다.

신고
Posted by summerwars
2010.08.16 18:07

Sprnig에서 Morphia Junit Test하기 MongoDB2010.08.16 18:07


1) applicationContext.xml 설정하기

  <bean id="mongo" class="com.mongodb.Mongo">
   <constructor-arg value="127.0.0.1"/>
   <constructor-arg value="27017"/>
  </bean>
 
  <bean id="db" class="com.sws.spring.config.DbFactoryBean">
   <property name="mongo" ref="mongo"/>
   <property name="name" value="test"/>
  </bean>
   
  <bean id="morphia" class="com.google.code.morphia.Morphia"/>


2) Junit Test 코드 작성하기
  @Autowired DB db;
 @Autowired Mongo mongo;
 @Autowired Morphia morphia;

...(생략)...

 @Test
 public void save(){
  // collection 가져오기
  DBCollection dBCollection = db.getCollection("account"); 
  // 저장할 객체선언후
  Account account = new Account("yunsunghan","yunsunghan@gmail.com1");
  // 객체를 MongoDB로 저장할수 있게, DBObject객체로 변환
  DBObject accountObj1 = morphia.toDBObject(account);
  // collection에 저장
  dBCollection.save(accountObj1);
  // 저장된 객체를 찾아서,
  DBObject accountObj2 = dBCollection.findOne(accountObj1);
  // 저장전 객체로 변환하고,
  Account account2 = morphia.fromDBObject(Account.class, accountObj2);
  // 각각의 객체와 비교 후, 같으면 통과
  Assert.assertEquals(accountObj1.get("name"), accountObj2.get("name"));
  Assert.assertEquals(account.getEmail(), account2.getEmail());
 }

물론 다른 방법도 존재한다. morphia.createDatastore(String dbName) 같은 메서드는, DB설정 정보가 기본값으로 저장되어 있어서, 따로 설정하지 않아도, DB에 저장을 간편하게 시킬수 있다.

Account 객체는 Morphia의 어노테이션을 써서 매핑했는데, 소스는 아래와 같고 더 많은 기능이 있는데, 여길 참고하자.

@Entity
public class Account {
 
 @Id private String id;
 private String name;
 private String email;
...(생략)...
신고

'MongoDB' 카테고리의 다른 글

MongoDB 관련 링크  (0) 2010.08.17
MongoDB-Morphia DAO Support 사용하기  (1) 2010.08.17
Sprnig에서 Morphia Junit Test하기  (0) 2010.08.16
MongoDB - Morphia Maven Dependency  (0) 2010.08.16
MongoDB Maven Dependency  (0) 2010.08.13
Java환경에서 MongoDB 설정(사용)하기  (0) 2010.08.13
Posted by summerwars


티스토리 툴바