'분류 전체보기'에 해당되는 글 2491건

  1. 2013.09.26 flex add Dynamic children to an array or arraycollection 1
  2. 2013.09.13 JSONUtil
  3. 2013.09.12 [펌] 세션 가져오는 법
  4. 2013.09.12 [펌] Flex Log log4j 처럼 사용하기
  5. 2013.09.12 [펌] spring+flex4+mybatis
  6. 2013.09.11 How do you set focus in Flash ActionScript 3 (AS3)?
  7. 2013.09.11 Working with States in Flex 4
  8. 2013.09.10 [펌] BlazeDS 와 스프링(Spring) 연동하기 1
  9. 2013.09.09 [펌]maven local repository에 jar 추가
  10. 2013.09.09 [펌] Spring 프로젝트를 assembly (jar-with-dependencies) 하여서 배포하였을 때, beans 스키마 못찾는 오류
  11. 2013.09.09 [펌] (Flex 4)Blazeds + Spring 설정 완료된 war 1
  12. 2013.09.09 [펌] [Flex + Spring] Annotation 기반 Flex BlazeDS 서비스 개발하기
  13. 2013.09.05 spring blazeds integration
  14. 2013.09.04 <flex-remoting> 태그 사용시 발생하는 오류
  15. 2013.09.02 Spring BlazeDS Integration 환경 설정
  16. 2013.09.02 [펌] Spring BlazeDS Integration 1.0.0 Release(정식) 적용하기(1) - 세팅 및 Remoting적용
  17. 2013.09.02 Spring BlazeDS Integration
  18. 2013.08.20 jqgrid 데모싸이트
  19. 2013.08.13 flex style explorer
  20. 2013.08.06 Request.getParameterMap values not castable to string
  21. 2013.08.06 [펌] [java] for 문으로 Map loop돌때 쓰면 좋은 방법.
  22. 2013.07.26 [펌] FLEX에 움직이는 GIF 넣기
  23. 2013.07.26 flex Tree Icon Spinner (not using animated gif)
  24. 2013.07.25 Datagrid avec ItemRenderer avec CheckBox, ComboBox, ColorPicker
  25. 2013.07.24 [펌] Progressbar in Datagrid Example
  26. 2013.07.22 TabNavigator와 ModuleLoader 사용시 문제
  27. 2013.07.19 Copy Flex UIComponent
  28. 2013.07.19 flex DataGrid Border remove
  29. 2013.07.17 flash.printing pagesize
  30. 2013.07.17 flex Printing
반응형
var paths:Array = ['one/two/three','one/two/four','five/six'];
var pathsCollection:ArrayCollection = new ArrayCollection();

for(var i:int = 0 ; i < paths.length ; i++){
   
var folderArr:Array = paths[i].split('/');
   
var folderNum:int = folderArr.length;
   
var folderLabel:String = '';
   
for(var j:int = 0 ; j < folderNum; j++){
        trace
(folderLabel+folderArr[j]);
        pathsCollection
.addItem({label:folderLabel+folderArr[j],level:j,path:folderArr});
        folderLabel
+= '...';
   
}
}

 

Posted by 1010
01.JAVA/Java2013. 9. 13. 09:34
반응형
package com.ociweb.json;

import java.util.*;
import net.sf.json.*;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;

import static com.ociweb.lang.SystemUtil.*;

public class JSONUtil {

  private Map<String, Class> classMap = new HashMap<String, Class>();

  /**
   * Adds a mapping that is used when converting from a JSON map
   * to a Java Bean.  Values of map entries with the given key
   * will be converted to Java Beans with the given Class.
   */
  public void addMapping(String key, Class clazz) {
    classMap.put(key, clazz);
  }

  /**
   * Converts a JSON string representing an array
   * to an array of Java Beans of a given Class.
   */
  public Object[] fromJSONArray(String json, Class clazz) {
    JSONArray ja = JSONArray.fromString(json);
    return JSONArray.toArray(ja, clazz, classMap);
  }

  /**
   * Converts a JSON string representing an array
   * to a java.util.List that contains Java Beans of a given Class.
   */
  public List fromJSONList(String json, Class clazz) {
    JSONArray ja = JSONArray.fromString(json);
    return JSONArray.toList(ja, clazz, classMap);
  }

  /**
   * Converts a JSON string representing an object
   * to a Java Bean object of a given Class.
   */
  public Object fromJSONObject(String json, Class clazz) {
    JSONObject jo = JSONObject.fromString(json);
    return JSONObject.toBean(jo, clazz, classMap);
  }

  /**
   * Pretty prints a JSONArray or JSONObject.
   */
  private void prettyPrint(JSON j) {
    out(j.toString(2));
  }

  /**
   * Pretty prints a JSON string that represents an array.
   */
  public void prettyPrintArray(String json) {
    prettyPrint(JSONArray.fromString(json));
  }

  /**
   * Pretty prints a JSON string that represents an object.
   */
  public void prettyPrintObject(String json) {
    prettyPrint(JSONObject.fromString(json));
  }

  /**
   * Converts a java.util.List to a JSON string.
   */
  public String toJSON(List list) {
    JSONArray ja = JSONArray.fromCollection(list);
    return ja.toString();
  }

  /**
   * Converts a Java Bean to a JSON string.
   */
  public String toJSON(Object object) {
    JSONObject jo = JSONObject.fromObject(object);
    return jo.toString();
  }

  /**
   * Converts an array of booleans, numbers, strings and Java Beans
   * to a JSON string.
   */
  public String toJSON(Object[] array) {
    JSONArray ja = JSONArray.fromArray(array);
    return ja.toString();
  }
}

 

Posted by 1010
반응형

출처 : http://sjp007.mireene.com/tc/entry/Tip-5?category=4

 

*세션 가져오는 법
SessionV fooAttrib = new SessionV();
Vector objList = new Vector();
try{
       fooAttrib=(SessionV)flashgateway.Gateway.getHttpRequest().getSession().getAttribute("ss_SVS");
objList.add(fooAttrib);
DataGrid
createApp => if(aReDeviceInfo == undefined || aReDeviceInfo.length<1){
                              dgDevice.rowCount = 0;
                              addRow();
                   }else{
                              dgDevice.rowCount = aReDeviceInfo.length;
                   }

funciton showDetail(event):Void{
     cidVboxSub.visible = true;
     cidVboxSub.height = "100%";
     stackNum.text = dgDevice.getItemAt(event.ItemIndex).STACK;
     cidNum.text = event.itemIndex;
     cidDeviceSLSizeX.text = dgDevice.getItemAt(event.itemIndex).SLSIZE_X;
     for(var j=0;j<3;j++){
             if(dia.getItemAt(j).LABEL == dgDevice.getIntemAt                                  (event.itemIndex.WFDIAMETER){
               dia.selectedIndex = j;
              }
      }

function addRow():Void{
  aReDeviceInfo.push({STACK:String(aReDeviceInfo.length+1),GCM_CODE:" ",......
                                MASTER_SEQ:" "
                               });
                               dgDevice.dataProvider = aReDeviceInfo;
                               crateApp();

<focusing Out 할 때마다>
private function setGridValues(compId):Void{
   if(compId == "cidDeviceSLSizeX"){
         dgDevice.getItemAt(Number(cidNum.text)).SLSIZE_X = this[compId].text;
   }

< mx:DataGrid id="dgDevice" width="766" cellpress="showDetail(event)"
  showHeaders="false" cellFocusOut="sizeChange(event)"
  <mx:DataGridColumn cellRendrer="{com.infonia.rendere.DeviceDelRenderer}"

 

Posted by 1010
반응형

출처 : http://sjp007.mireene.com/tc/entry/Flex-Log-log4j-%C3%B3%B7%B3-%BB%E7%BF%EB%C7%CF%B1%E2?category=4

 

///////////////////////////////////////////////////////////////
// LogUtil.as
///////////////////////////////////////////////////////////////

package utils
{
        import flash.utils.getQualifiedClassName;
       
        import mx.logging.ILogger;
        import mx.logging.Log;
        import mx.logging.LogEventLevel;
        import mx.logging.targets.TraceTarget;

        public class LogUtil
        {
               
                public function LogUtil()
                {
                       
                }
               
                public static function initLogging():void{
                        //create a Target
                        var logTarget:TraceTarget = new TraceTarget();
                       
                        logTarget.filters = ["none"];        //이부분을 적절히 변경해주면 된다. Ex> "comp.*"
                       
                        //Log all log levels
                        logTarget.level = LogEventLevel.DEBUG;
                       
                        //Add category, date, time, and log level to the output
                        logTarget.includeCategory = false;
                        logTarget.includeDate = true;
                        logTarget.includeTime = true;
                        logTarget.includeLevel = true;
                       
                        //Begging logging
                        Log.addTarget(logTarget);
                }
               
                public static function getLogger(c:*):ILogger{
                        var className:String = getQualifiedClassName(c).replace("::", ".");
                        return Log.getLogger(className);
                }
        }
       
}


///////////////////////////////////////////////////////////////
// Main Application
///////////////////////////////////////////////////////////////

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                           layout="vertical"
                           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
                           xmlns:comp="comp.*"
                           creationComplete="creationCompleteHdlr()">
       
        <fx:Declarations>
                <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
       
        <fx:Script>
                <![CDATA[
                        import utils.LogUtil;
                       
                       
                        private function creationCompleteHdlr():void{
                                LogUtil.initLogging();
                        }
                       
                ]]>
        </fx:Script>
       
        <comp:LogComp1/>
        <comp:LogComp2/>
</mx:Application>


///////////////////////////////////////////////////////////////
// LogComp1.mxml
///////////////////////////////////////////////////////////////

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                 xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
       
        <fx:Declarations>
                <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
       
        <fx:Script>
                <![CDATA[
                        import flash.utils.getQualifiedClassName;
                       
                        import mx.logging.ILogger;
                        import mx.logging.Log;
                       
                        import utils.LogUtil;
                       
                        private var logger:ILogger = LogUtil.getLogger(this);
                       
                        private function test():void{
                                logger.debug("comp1 debug test");
                        }
                ]]>
        </fx:Script>
       
        <s:Button label="log comp1" click="test()"/>
</s:Group>


///////////////////////////////////////////////////////////////
// LogComp2.mxml
///////////////////////////////////////////////////////////////

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                 xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
       
        <fx:Declarations>
                <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
       
        <fx:Script>
                <![CDATA[
                        import mx.logging.ILogger;
                        import mx.logging.Log;
                       
                        import utils.LogUtil;
                       
                        private var logger:ILogger = LogUtil.getLogger(this);
                       
                        private function test():void{
                                logger.debug("comp2 debug test");
                        }
                ]]>
        </fx:Script>
       
        <s:Button label="log comp2" click="test()"/>
</s:Group>

 

Posted by 1010
반응형

출처 : http://sjp007.mireene.com/tc/?page=5

 

구성

Adobe Flash Builder 4.6 Premium

Spring 3.2 FrameWork

Tomcat 7.0(Web Application Server)

MyBatis 3.2(iBatis 2.5 이후로 아파치 재단 지원력에서는 현재의 정보와 신기술을 맞춰갈 수 없다 판단하여 구글 코드 팀으로 옮겼단다.)

blazeds 4.0(데이타 서비스 통신)

spring-flex-1.5 integration(Spring 과 Flex를 통신하기 위해 직접 클래스를 만들어 써야 하는 수고가 없도록 spring project 팀들이 고맙게도 만들어 두었다. ㄱㅅㄳ~)

SLF4J(Simple logging Facade for Java) (로깅찍는거) 요즘 이거 많이쓴다.

이유는 : http://devday.tistory.com/entry/SLF4J%EC%9D%98-%EC%9E%A5%EC%A0%90 참고.

일단 플렉스를 이클립스의 플러그인으로 깔고 톰캣도 설치되있다는 전제하에 시작.

먼저 이클립스의 왼쪽 빈공간에서 마우스 오른쪽을 눌러 New > Flex Project를 선택.

사용자 삽입 이미지

Project name에 자기가 입력하고 싶은 프로젝트 이름을 입력. Next

사용자 삽입 이미지


Application Server Type은 자바를 이용할것이니 Java, Use remote object access service는 blazeds를 이용할 것이니 그곳을 선택.

 

Java source folder 는 src로 그냥 나두어도 되는데 나는 java_src(flex는 flex_src로 되있는데 자바는 src로 되있으면 이샹해서;;)로 바꿔줬다.

Output folder 역시 기본은 bin-debug나 WebContent로 바꿔 주었다.(즉 나는 컴파일된 파일을 WebContent 밑으로 바로 놓겠다는 거다)

Target runtime 옆의 New 버튼을 클릭.

사용자 삽입 이미지


Apach 폴더의 자기에 맞는(나는 7.0)버젼을 찾아 선택해 주면 아래의 항목들이 기본으로 보인다. Finish를 눌러 완료.

사용자 삽입 이미지


이제 톰캣을 설정하였으므로 Target runtime에서 콤보박스 화살표를 누르면 방금 설치한 이름의 톰캣이 보인다.

 

그걸로 바꿔주고 Next.

사용자 삽입 이미지


Output folder URL에 일단 로컬에서 돌리기때문에 톰캣의 기본설정 포트 8080으로 Context root가 TEST 이므로 TEST 위와 같이 한다. Finish.

사용자 삽입 이미지


보면 output folder를 바꿨기 때문에 bin-debug 폴더가 안보이고 WebContent 폴더밑으로 기본 파일들이 생긴걸 확인할 수 있다.

 

다음으로 Spring과 Flex를 연동 해야한다.

모든 jar파일들은 합해놓은게 http://blog.naver.com/sjp007774/150153185137 여기에 있다.

먼저 Spring을 사용하기 위하여 다운.

http://www.springsource.org/download/community

다운받은 Spring 폴더의 libs(3.2 기준)밑의 필요한 파일들(난 그냥 잘몰라서 다 복사하였다;;)을 복사.

MyBatis를 사용하기 위하여 MyBatis를 다운.

http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DMyBatis

다운 받은 MyBatis 폴더의 jar파일(mybatis-3.2.0-SNAPSHOT.jar)을 복사.

MyBatis와 Spring을 연동하기 위하여 필요한 jar파일을 다운.

http://code.google.com/p/mybatis/downloads/list?q=label:Product-Spring

다운받은 폴더의 jar파일(mybatis-spring-1.1.1.jar)을 복사.

Spring의 Aspect을 사용하기 위해(3.0 부터는 Aspectj 관련 jar파일들이 함께 있지 않다.) 다운.

http://www.eclipse.org/aspectj/downloads.php

주의 할게 내가 잘몰라 이상한걸 받았을수도 있는데 다른 파일들은 모두 zip으로 압축이 되있는반면 jar로 압축이 되있었다. 압축을 풀면 lib폴더가 보인다.
(이것때문에 엄청 고생했다. 당연히 jar파일이라서 그대로 넣으면 될줄 알았다 ㅠㅠ)

압축을 푼 lib 폴더 밑의 jar파일들(aspectjrt.jar, aspectjtools.jar, aspectjweaver.jar, org.aspectj.matcher.jar 이역시 몰라서 다 복사했다;;)을 복사.

Spring의 AOP alliance(namespace AOP를 사용할 수 있게 해줌)를 사용하기 위하여 다운.

http://sourceforge.net/projects/aopalliance/

이아이는 바로 jar파일로되있었다.

aopalliance.jar 파일을 복사.

SLF4J(log4j 같은거) 를 사용하기 위하여 다운.

http://slf4j.org/download.html

다운받은 폴더의 jar파일들(slf4j-api-1.7.2.jar, slf4j-log4j12-1.7.2.jar)을 복사.

log4jdbc(쿼리의 ?에 바로 값을 대입하여 보여줌)를 사용하기 위하여 다운.

http://code.google.com/p/log4jdbc/downloads/list

다운받은 lib폴더의 jar파일(slf4j-api-1.6.0.jar)을 복사.

log4j(로깅 찍는거)를 사용하기 위하여 다운.

log4j-1.2.16.jar 파일을 복사

지금까지 복사한 모든 파일들을 WebContent/WEB-INF/lib 폴더밑으로 다 넣는다.

사용자 삽입 이미지


다음으로 WEB-INF/web.xml 파일을 수정해야 된다.

 

[web.xml]

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TEST</display-name>

        <context-param>
                <param-name>flex.class.path</param-name>
                <param-value>/WEB-INF/flex/hotfixes,/WEB-INF/flex/jars</param-value>
        </context-param>

        <!-- Http Flex Session attribute and binding listener support
        <listener>
                <listener-class>flex.messaging.HttpFlexSession</listener-class>
        </listener>-->
       
        <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>

        <!-- MessageBroker Servlet
        <servlet>
                <servlet-name>MessageBrokerServlet</servlet-name>
                <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
                <init-param>
                        <param-name>services.configuration.file</param-name>
                        <param-value>/WEB-INF/flex/services-config.xml</param-value>
                </init-param>
                <init-param>
                        <param-name>flex.write.path</param-name>
                        <param-value>/WEB-INF/flex</param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
        </servlet>
       
        <servlet-mapping>
                <servlet-name>MessageBrokerServlet</servlet-name>
                <url-pattern>/messagebroker/*</url-pattern>
        </servlet-mapping>-->
       
        <servlet>
         <servlet-name>MessageBrokerServlet</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>
                     /WEB-INF/configs/web-application-config.xml
                     /WEB-INF/configs/bean-remoting-destination.xml
                     /WEB-INF/configs/mybatis-config.xml
             </param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
         </servlet>

        <servlet-mapping>
                <servlet-name>MessageBrokerServlet</servlet-name>
                <url-pattern>/messagebroker/*</url-pattern>
        </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

        <!-- for WebSphere deployment, please uncomment -->
        <!--
                <resource-ref>
                <description>Flex Messaging WorkManager</description>
                <res-ref-name>wm/MessagingWorkManager</res-ref-name>
                <res-type>com.ibm.websphere.asynchbeans.WorkManager</res-type>
                <res-auth>Container</res-auth>
                <res-sharing-scope>Shareable</res-sharing-scope>
        </resource-ref>
        -->
</web-app>

servlet-name을 MessageBrokerServlet으로 하였기때문에 spring에서 MessageBrokerServlet-servlet.xml을 찾으려 할것이다.

하지만 파일들을 다른걸로 할거기 때문에 ContextLoaderListener를 달아준다.

xml파일 하나에 모든걸 다 때려넣을 수도 있지만 spring에서도 권장하듯이 서비스단, 데이타단, 화면단, 보안단 등등 이렇게 분할해 놓는게 나중에 유지보수 하기에도 좋다.

나는 설정을 가지고 있는 web-application-config.xml, flex의 remote object의 destination과 해당 자바정보를 갖고 있는 bean-remoting-destination.xml, 마지막으로

MyBatis에 관련한 mybatis-config.xml 세가지 xml로 분류하여 WEB-INF/configs 라는 폴더 밑에 넣어두었다.

servlet-mapping의 url-pattern의 /messagebroker/* (flex의 AMF통신) 오는건 spring의 DispatcherServlet 클래스에서 처리하게된다.

[web-application-config.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
                          
        <!-- MessageBroker Configuration -->                      
    <bean id="widwinMessageBroker" class="org.springframework.flex.core.MessageBrokerFactoryBean"/>
 
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
            p:mappings="/*=widwinMessageBroker"/>
       
    <bean class="org.springframework.flex.servlet.MessageBrokerHandlerAdapter"/>                                            
                          
    <!-- Properties Configuration -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                <property name="locations">
                        <list>
                                <value>classpath*:resources/properties/**/*.properties</value>
                        </list>
                </property>
        </bean>
   
    <!-- MyBatis Configuration -->
        <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="configLocation">
                        <value>/WEB-INF/configs/mybatis-config.xml</value>
                </property>
                <property name="dataSource" ref="dataSource" />
                <property name="mapperLocations" value="classpath*:resources/mappers/**/*.xml" />
        </bean>
       
        <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> 
                <constructor-arg index="0" ref="sqlSessionFactoryBean" />
        </bean>
       
    <!-- DataSource Configuration -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <property name="driverClassName" value="${jdbc.widwin.driverClassName}"/>
                <property name="url" value="${jdbc.widwin.url}"/>
                <property name="username" value="${jdbc.widwin.username}"/>
                <property name="password" value="${jdbc.widwin.password}"/>
        </bean>

        <!-- Transaction Configuration -->
        <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
                <property name="transactionManager">
                        <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                                <property name="dataSource" ref="dataSource"/>
                        </bean>
                </property>
                <property name="transactionAttributes">
                        <props>
                                <prop key="insert*">PROPAGATION_REQUIRED</prop>
                                <prop key="update*">PROPAGATION_REQUIRED</prop>
                                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
                        </props>
                </property>
        </bean>
       
        <!-- Common Logger Configuration -->
        <aop:aspectj-autoproxy/>
        <bean id="commonLogger" class="test.widwin.common.CommonLogger"/>
       
        <!-- <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/>
       
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource">
                        <ref local="dataSource"/>
                </property>
                <property name="nativeJdbcExtractor">
                        <ref local="nativeJdbcExtractor"/>
                </property>
        </bean> -->
</beans>

properties configuration에서 반드시 classpath*를 붙여주어야한다. 상대경로로 찾기때문에 안붙여주면 찾지 못한다.

[jdbc.test.properties]

#jdbc.widwin.driverClassName= oracle.jdbc.OracleDriver
jdbc.widwin.driverClassName=net.sf.log4jdbc.DriverSpy

#jdbc.widwin.url=jdbc:oracle:thin:@xxx.xxx.x.x:1521:TEST
jdbc.widwin.url=jdbc:log4jdbc:oracle:thin:@xxx.xxx.x.x:1521:TEST
jdbc.widwin.username=TEST
jdbc.widwin.password=test

slf4j를 사용하면 driverClassName과 url에 log4jdbc를 끼어넣어야 함.(xxx 를 아이피로 바꿔주면 됨)

[bean-remoting-destination.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flex="http://www.springframework.org/schema/flex"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/flex
                           http://www.springframework.org/schema/flex/spring-flex-1.5.xsd">
                          
        <!--         <context:annotation-config/>                            -->
        <context:component-scan base-package="test.widwin.blogics.board"/>                
        
    <bean class="test.widwin.blogics.board.BoardController">
                <flex:remoting-destination destination-id="BoardRO" message-broker="widwinMessageBroker"/>
        </bean>
 
</beans>

<context:component-scan... 이 있으면 <bean에 class를 설정하지 않아도 됨. destination에 message-broker 꼭 설정해줘야 함. remoting-config.xml 파일은 관리안함.

[mybatis-config.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
        <!-- <environments default="development">
                <environment id="development">
                        <transactionManager type="JDBC"/>
                        <dataSource type="POOLED">
                                <property name="driver" value="${driver}"/>
                                <property name="url" value="${url}"/>
                                <property name="username" value="${username}"/>
                                <property name="password" value="${password}"/>
                        </dataSource>
                </environment>
        </environments>
       
        <settings>
                <setting name="cacheEnabled" value="true"/>
                <setting name="lazyLoadingEnabled" value="true"/>
                <setting name="multipleResultSetsEnabled" value="true"/>
                <setting name="useColumnLabel" value="true"/>
                <setting name="useGeneratedKeys" value="false"/>
                <setting name="autoMappingBehavior" value="PARTIAL"/>
                <setting name="defaultExecutorType" value="SIMPLE"/>
                <setting name="defaultStatementTimeout" value="25000"/>
                <setting name="safeRowBoundsEnabled" value="false"/>
                <setting name="mapUnderscoreToCamelCase" value="false"/>
                <setting name="localCacheScope" value="SESSION"/>
                <setting name="jdbcTypeForNull" value="OTHER"/>
                <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
        </settings> -->
       
        <!-- <mappers>
                <mapper resource="resources/mappers/BoardMapper.xml"/>
        </mappers> -->
       
        <typeAliases>
                <typeAlias alias="Board" type="test.widwin.blogics.board.vo.BoardBean"/>
        </typeAliases>
       
</configuration>

<mappers>부분을 주석을 풀어서 관리해도 되나 web-application-config.xml에서 mapperLocations를 *로 잡아주었으므로

따로 관리하지 않아도 된다.

[TEST.mxml]

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                           xmlns:s="library://ns.adobe.com/flex/spark"
                           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
       
        <fx:Script>
                <![CDATA[
                        import mx.collections.ArrayCollection;
                        import mx.controls.Alert;
                        import mx.rpc.events.FaultEvent;
                        import mx.rpc.events.ResultEvent;
                       
                        import test.widwin.modules.board.vo.BoardVO;
                        import test.widwin.utils.RemoteObjectUtil;
                       
                        private function test2():void{
                                RemoteObjectUtil.doMethod("BoardRO", "getBoardList", getBoardListRstHdlr, [1]);
                        }
                       
                        private function insertBoard():void{
                                var vo:BoardVO = new BoardVO();
                                vo.name = tiName.text;
                                vo.title = tiTitle.text;
                                vo.description = tiDescription.text;
                                vo.pass = tiPass.text;
                                RemoteObjectUtil.doMethod("BoardRO", "insertBoard", insertBoardRstHdlr, [vo]);
                        }
                       
                        private function getBoardListRstHdlr(evt:ResultEvent):void{
                                adg.dataProvider = evt.result as ArrayCollection;
                        }
                       
                        private function insertBoardRstHdlr(evt:ResultEvent):void{
                                Alert.show("등록 성공");
                        }
                       
                        private function faultHdlr(evt:FaultEvent):void{
                                Alert.show(evt.fault.message.toString());
                        }
                ]]>
        </fx:Script>
       
        <fx:Declarations>
               
        </fx:Declarations>
       
        <s:layout>
                <s:VerticalLayout/>
        </s:layout>
       
        <s:Button label="test" click="test2()"/>
       
        <mx:AdvancedDataGrid id="adg">
                <mx:columns>
                        <mx:AdvancedDataGridColumn headerText="이름" dataField="name"/>
                        <mx:AdvancedDataGridColumn headerText="제목" dataField="title"/>
                        <mx:AdvancedDataGridColumn headerText="내용" dataField="description"/>
                </mx:columns>
        </mx:AdvancedDataGrid>
       
        <s:Form id="frm" defaultButton="{btnIns}">
                <s:FormHeading label="게시판" backgroundColor="haloSilver" />
                <s:FormItem sequenceLabel="i)" label="이름:" required="true">
                        <s:TextInput id="tiName" maxChars="64" />
                </s:FormItem>
                <s:FormItem sequenceLabel="ii)" label="제목:">
                        <s:TextInput id="tiTitle" maxChars="64" />
                </s:FormItem>
                <s:FormItem sequenceLabel="iii)" label="내용:" required="true">
                        <s:TextInput id="tiDescription" maxChars="32" />
                </s:FormItem>
                <s:FormItem sequenceLabel="iv)" label="비밀번호:" required="true">
                        <s:TextInput id="tiPass" maxChars="32" displayAsPassword="true" />
                </s:FormItem>
                <s:FormItem>
                        <s:Button id="btnIns" label="등록" click="insertBoard()" />
                </s:FormItem>
        </s:Form>

</s:Application>

[BoardVO.as]

package test.widwin.modules.board.vo
{

         [RemoteClass(alias="test.widwin.blogics.board.vo.BoardBean")]        
        public class BoardVO
        {
                public var board_code:int;
                public var registration_date:String;
                public var name:String;
                public var title:String;
                public var description:String;       
                public var email:String;       
                public var homepage:String;       
                public var ip:String;        
                public var pass:String;       
                public var pos:int;       
                public var hit:int;
                public var file_yn:String;       
                public var depth:int;
                public var is_delete:String;
                public var created_timestamp:Date;
                public var creator_code:String;
                public var updated_timestamp:Date;
                public var updater_code:String;
                public var total_row:int;
                public var page:int;
        }
}

[BoardController.java]

package test.widwin.blogics.board;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import test.widwin.blogics.board.service.IBoardService;
import test.widwin.blogics.board.vo.BoardBean;

@Controller
public class BoardController {
//        final Logger logger = LoggerFactory.getLogger(BoardController.class);
       
        @Autowired
        private IBoardService iBoardService;
       
        public List<BoardBean> getBoardList(int pageView){
                return iBoardService.getBoardList(pageView);
        }
       
        public int insertBoard(BoardBean boardBean){
                return iBoardService.insertBoard(boardBean);
        }
       
}

[IBoardService.java]

package test.widwin.blogics.board.service;

import java.util.List;

import test.widwin.blogics.board.vo.BoardBean;

public interface IBoardService {
        public List<BoardBean> getBoardList(int pageView);
       
        public int insertBoard(BoardBean boardBean);

}

[BoardServiceImpl.java]

package test.widwin.blogics.board.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import test.widwin.blogics.board.dao.BoardDao;
import test.widwin.blogics.board.vo.BoardBean;

@Service("iBoardService")
public class BoardServiceImpl implements IBoardService {
       
        @Autowired
        private BoardDao boardDao;
       
        @Override
        public List<BoardBean> getBoardList(int pageView) {
                return boardDao.getBoardList(pageView);
        }

        @Override
        public int insertBoard(BoardBean boardBean) {
                return boardDao.insertBoard(boardBean);
        }
       
}

[BoardDao.java]

package test.widwin.blogics.board.dao;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import test.widwin.blogics.board.vo.BoardBean;


@Repository("boardDao")
public class BoardDao extends SqlSessionDaoSupport{
//        @Resource(name="sqlSessionTemplate")
//        private SqlSession sessionTemplate;
       
        public List<BoardBean> getBoardList(int pageView){
//                IBoardMapper iBoardMapper = sessionTemplate.getMapper(IBoardMapper.class);
//                return iBoardMapper.getBoardList(pageView);
                return getSqlSession().selectList("test.widwin.blogics.board.dao.IBoardMapper.getBoardList", pageView);
        }
       
        public int insertBoard(BoardBean boardBean){
                return getSqlSession().insert("test.widwin.blogics.board.dao.IBoardMapper.insertBoard", boardBean);
        }
       
}

신기한게 내부적으로 구현이 되있는진 몰라도 패키지 인터페이스명.메소드 이름하고 BoardMapper.xml 에서 같은 인터페이스이름으로 namespace를 정의하면 된다.

[IBoardMapper.java]

package test.widwin.blogics.board.dao;

import java.util.List;

import test.widwin.blogics.board.vo.BoardBean;

public interface IBoardMapper {
        public List<BoardBean> getBoardList(int pageView);

        public int insertBoard(BoardBean boardBean);
       
}

[BoardMapper.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="test.widwin.blogics.board.dao.IBoardMapper">
        <select id="getBoardList" parameterType="int" resultType="Board">
                SELECT *
            FROM (SELECT BOARD.* ,ROWNUM AS RNUM ,FLOOR(((ROWNUM-1)/15)+1) AS PAGE
                     ,COUNT(*) OVER() AS TOTAL_ROW
                FROM (SELECT *
                      FROM BOARD
                      ORDER BY BOARD_CODE DESC) BOARD)                                    
            WHERE PAGE = #{pageView}
            ORDER BY POS ASC      
        </select>
       
        <insert id="insertBoard" parameterType="Board">
                INSERT INTO BOARD(BOARD_CODE, REGISTRATION_DATE, NAME, TITLE, DESCRIPTION, PASS, IP)
                VALUES((SELECT TRIM(NVL(MAX(BOARD_CODE + 1),1)) FROM BOARD), '201212', #{name}, #{title}, #{description}, #{pass}, '192.168.0.9')
        </insert>
</mapper>

namespace가 인터페이스랑 같아야한다.

[log4j.xml] log4j.properties로 관리해도 됨(log4j.xml이 가독성도 좋고 관리가 용이함)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<!-- An example log4j configuration xml file for log4jdbc -->
<!-- Logging levels are:                                  -->
<!-- DEBUG < INFO < WARN < ERROR < FATAL                  -->

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="stdout-appender" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p %c{1}: %m%n"/>
    </layout>
  </appender>

  <appender name="sql-appender" class="org.apache.log4j.FileAppender">
    <param name="File" value="./logs/sql.log"/>
    <param name="Append" value="false"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="-----&gt; %d{yyyy-MM-dd HH:mm:ss.SSS} &lt;%t&gt; %m%n%n"/>
    </layout>
  </appender>

  <appender name="sql-timing-appender" class="org.apache.log4j.FileAppender">
    <param name="File" value="./logs/sqltiming.log"/>
    <param name="Append" value="false"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="-----&gt; %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n"/>
    </layout>
  </appender>

  <appender name="jdbc-appender" class="org.apache.log4j.FileAppender">
    <param name="File" value="./logs/jdbc.log"/>
    <param name="Append" value="false"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
    </layout>
  </appender>

  <appender name="jdbc-connection" class="org.apache.log4j.FileAppender">
    <param name="File" value="./logs/connection.log"/>
    <param name="Append" value="false"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
    </layout>
  </appender>

  <!--
       The Following 5 logs can be turned on and off while the server is running
       LIVE in order to trace the SQL and/or all JDBC coming out of the application.

       To turn a log on, set the level value to INFO or DEBUG (to see class name and
       line number information in the log)  The DEBUG setting is much more inefficient
       but the output is much more useful.

       To turn off JDBC logging completely, you must set all 5 logs to a level higher
       than ERROR (FATAL is suggested.)
  -->

  <!-- log SQL (pre-execution) plus exceptions caused by SQL -->
  <logger name="jdbc.sqlonly" additivity="false">
    <level value="debug"/>
    <appender-ref ref="sql-appender"/>
  </logger>

  <!-- log SQL with timing information, post execution -->
  <logger name="jdbc.sqltiming" additivity="false">
    <level value="debug"/>
    <appender-ref ref="stdout-appender"/>
<!--     <appender-ref ref="sql-timing-appender"/> -->
  </logger>

  <!-- only use the two logs below to trace ALL JDBC information,
       NOTE:  This can be very voluminous!  -->

  <!-- log all jdbc calls except ResultSet calls -->
  <logger name="jdbc.audit" additivity="false">
    <level value="fatal"/>
    <appender-ref ref="jdbc-appender"/>
  </logger>

  <!-- log the jdbc ResultSet calls -->
  <logger name="jdbc.resultset" additivity="false">
    <level value="fatal"/>
    <appender-ref ref="jdbc-appender"/>
  </logger>
 
  <!-- log connection open/close events and dump of all open connection numbers -->
  <logger name="jdbc.connection" additivity="false">
    <level value="fatal"/>
    <appender-ref ref="connection-appender"/>
  </logger>

  <!-- this log is for internal debugging of log4jdbc, itself -->
  <!-- debug logging for log4jdbc itself -->
  <logger name="log4jdbc.debug" additivity="false">
    <level value="debug"/>
    <appender-ref ref="stdout-appender"/>
  </logger>

  <!-- by default, log everything to the console with a level of WARN or higher -->
  <root>
    <level value="debug"/>
    <appender-ref ref="stdout-appender"/>
  </root>
</log4j:configuration>

[applicationContext.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flex="http://www.springframework.org/schema/flex"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/flex
                           http://www.springframework.org/schema/flex/spring-flex-1.5.xsd">
</beans>

리스너를 따로 달아줬어도 applicationContext.xml은 WEB-INF/밑에 위치하여야 함.

[service-config.xml]

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

    <services>
        <service-include file-path="remoting-config.xml" />
        <service-include file-path="proxy-config.xml" />
        <service-include file-path="messaging-config.xml" />    
        <default-channels>
           <channel ref="my-amf"/>
        </default-channels>       
    </services>

    <security>
        <login-command class="flex.messaging.security.TomcatLoginCommand" server="Tomcat"/>
        <!-- Uncomment the correct app server
        <login-command class="flex.messaging.security.TomcatLoginCommand" server="JBoss">
                <login-command class="flex.messaging.security.JRunLoginCommand" server="JRun"/>       
        <login-command class="flex.messaging.security.WeblogicLoginCommand" server="Weblogic"/>
        <login-command class="flex.messaging.security.WebSphereLoginCommand" server="WebSphere"/>
        -->

        <!--
        <security-constraint id="basic-read-access">
            <auth-method>Basic</auth-method>
            <roles>
                <role>guests</role>
                <role>accountants</role>
                <role>employees</role>
                <role>managers</role>
            </roles>
        </security-constraint>
         -->
    </security>

    <channels>

        <channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
            <endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
        </channel-definition>

        <channel-definition id="my-secure-amf" class="mx.messaging.channels.SecureAMFChannel">
            <endpoint url="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure" class="flex.messaging.endpoints.SecureAMFEndpoint"/>
            <properties>
                <add-no-cache-headers>false</add-no-cache-headers>
            </properties>
        </channel-definition>

        <channel-definition id="my-polling-amf" class="mx.messaging.channels.AMFChannel">
            <endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling" class="flex.messaging.endpoints.AMFEndpoint"/>
            <properties>
                <polling-enabled>true</polling-enabled>
                <polling-interval-seconds>4</polling-interval-seconds>
            </properties>
        </channel-definition>

        <!--
        <channel-definition id="my-http" class="mx.messaging.channels.HTTPChannel">
            <endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/http" class="flex.messaging.endpoints.HTTPEndpoint"/>
        </channel-definition>

        <channel-definition id="my-secure-http" class="mx.messaging.channels.SecureHTTPChannel">
            <endpoint url="https://{server.name}:{server.port}/{context.root}/messagebroker/httpsecure" class="flex.messaging.endpoints.SecureHTTPEndpoint"/>
            <properties>
                <add-no-cache-headers>false</add-no-cache-headers>
            </properties>
        </channel-definition>
        -->
    </channels>

    <logging>
        <target class="flex.messaging.log.ConsoleTarget" level="Error">
            <properties>
                <prefix>[BlazeDS] </prefix>
                <includeDate>false</includeDate>
                <includeTime>false</includeTime>
                <includeLevel>false</includeLevel>
                <includeCategory>false</includeCategory>
            </properties>
            <filters>
                <pattern>Endpoint.*</pattern>
                <pattern>Service.*</pattern>
                <pattern>Configuration</pattern>
            </filters>
        </target>
    </logging>

    <system>
        <redeploy>
            <enabled>false</enabled>
            <!--
            <watch-interval>20</watch-interval>
            <watch-file>{context.root}/WEB-INF/flex/services-config.xml</watch-file>
            <watch-file>{context.root}/WEB-INF/flex/proxy-config.xml</watch-file>
            <watch-file>{context.root}/WEB-INF/flex/remoting-config.xml</watch-file>
            <watch-file>{context.root}/WEB-INF/flex/messaging-config.xml</watch-file>
            <watch-file>{context.root}/WEB-INF/flex/data-management-config.xml</watch-file>
            <touch-file>{context.root}/WEB-INF/web.xml</touch-file>
             -->
        </redeploy>
    </system>

</services-config>

<default-channels 꼭 달아주어야 함.

BoardRO destination을 못 찾을때

[.flexProperties]

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<flexProperties enableServiceManager="false" flexServerFeatures="4" flexServerType="8" flexWarLocation="C:/자료/교육시이트/blazeds-bin-4.0.0.14931/blazeds.war" serverContextRoot="/TEST" serverRoot="C:/testWorkspace/TEST/WebContent" serverRootURL="http://localhost:8080/TEST" toolCompile="true" useServerFlexSDK="false" version="2"/>

serverContextRoot가 /WebContent로 잡혀있는데 꼭 맞는 contextRoot 바꿔줘야 함(여기서는 /TEST)

flex bug report에 기재되있음 http://bugs.adobe.com/jira/browse/FB-20894

Posted by 1010
반응형

How do you set focus in Flash ActionScript 3 (AS3)?

Answer

Use the stage focus method:

stage.focus = object;

Source Code

import flash.text.TextField;
import flash.text.TextFieldType;
import fl.controls.Button;

var exampleTextField:TextField = new TextField();
exampleTextField.width = 100;
exampleTextField.height = 20;
exampleTextField.x = 50;
exampleTextField.y = 20;
exampleTextField.type = TextFieldType.INPUT;
exampleTextField.border = true;
addChild(exampleTextField);

var focusInButton:Button = new Button();
focusInButton.label = "Focus";
focusInButton.width = 80;
focusInButton.height = 20;
focusInButton.x = 10;
focusInButton.y = 70;
addChild(focusInButton);

var focusOutButton:Button = new Button();
focusOutButton.label = "Focus Out";
focusOutButton.width = 80;
focusOutButton.height = 20;
focusOutButton.x = 110;
focusOutButton.y = 70;
addChild(focusOutButton);

focusInButton.addEventListener(MouseEvent.MOUSE_UP, function(){ 
  stage.focus = exampleTextField;
});
focusOutButton.addEventListener(MouseEvent.MOUSE_UP, function(){ 
  stage.focus = null;
});
Posted by 1010
반응형

Working with States in Flex 4
by Frank Sommers
September 16, 2009

Advertisements

Summary
Flex 4's new syntax simplifies working with application states. This article provides a tutorial introduction into UI state management with Flex 4, and includes a complete example.

Stateless Web applications aim to store as little state on the server as possible. Reducing, or even eliminating, reliance on server-side state makes it easier to implement a scalable infrastructure, at least in principle.

At the same time, only the simplest Web applications can function completely without state. Dispatching a request to an online weather reporting service may work in a purely stateless fashion, but more sophisticated applications must keep track of where a user is in a complex data entry process, possible data validation errors, and so on. Data-intensive applications may also need to cache a user's frequently accessed data in order to reduce response time.

Client-Side State

Instead of storing state data on the server, rich-client applications may choose to store such information on the client. A key benefit of rich-client frameworks is that they provide APIs and programming language constructs that make it easier to work with application state on the client. In addition to client-side collections APIs and language support for data processing, rich-client frameworks typically offer high-level constructs to manage application state related to display logic as well.

Consider, for example, a sign-in component typical of many Web applications: A user is presented with text input boxes to enter a user name and a password, as well as a button to initiate the sign-in. A login box may also provide a handy way for the user to create a new account. If the user chooses to register a new account, another view is presented with text boxes for additional information, such as first and last names, and so forth:

Click on "Need to register?" to toggle between UI states. To view the source code, right-click or control-click on the application.

In a traditional, server-generated HTML user interface, the server may return an entirely newly rendered page when a user chooses to register instead of signing in. By contrast, a rich-client can affect the change in the user interface entirely on the client side, without interaction from the server.

The simplest way to code that is to write display logic that inserts and removes new labels and text boxes in the UI at runtime, for instance, by modifying the UI's DOM in the browser. More sophisticated rich-client frameworks, however, provide a much handier abstraction to accomplish the same goal: UI states.

UI States in Flex

A UI state is the set of all components and component properties in effect in a component at any given point in time. Multiple UI states can be associated with a component: Switching from one state to another causes the rich-client runtime to add, remove, or modify components based on the differences between states. The login form, for instance, could have "login" and "register" states: The register state defines additional input boxes, changes the label of the button component from "Sign in" to "Register", and also causes the button click to invoke a register() method instead of signin().

In Flex, defining and working with application states has been possible since the 2.0 version of the Flex SDK. In Flex versions 2 and 3, states were defined inside a states array in an MXML document; inside each state definition, in turn, were declarations of what should be added, removed, or modified, related to some base state. It was also possible to build one state on another.

 

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> 

  <mx:Script>
      <![CDATA[
            private function signin():void {
                // Implementation of signin
            }

            private function register():void {
                // Implementation of register
            }
        ]]>
  </mx:Script>

  <mx:states>

    <mx:State name="Register">        

        <mx:AddChild relativeTo="{loginForm}" position="lastChild" creationPolicy="all">
            <mx:FormItem id="frmPasswordConfirm" label="Confirm:">
                <mx:TextInput id="passwordConfirm" displayAsPassword="true"/>
            </mx:FormItem>        
        </mx:AddChild>

        <mx:AddChild relativeTo="{loginForm}" position="lastChild">
            <mx:FormItem label="First name:" id="frmFirstName">
                <mx:TextInput id="firstName" width="220"/>
            </mx:FormItem>
        </mx:AddChild>

        <mx:AddChild relativeTo="{loginForm}" position="lastChild">            
            <mx:FormItem label="Last name:" id="frmLastName">
                <mx:TextInput id="lastName" width="220"/>
            </mx:FormItem>
        </mx:AddChild>

        <mx:AddChild relativeTo="{loginButton}" position="after">
            <mx:LinkButton label="Return to login" click="setCurrentUIState()"/>
        </mx:AddChild>            

        <mx:RemoveChild target="{registerLink}"/>            

        <mx:SetProperty target="{loginLabel}" name="text" value="Create a new account:"/>    
        <mx:SetProperty target="{loginButton}" name="enabled" value="false"/>
        <mx:SetProperty target="{loginButton}" name="label" value="Register"/>
            
     </mx:State>        

  </mx:states>
    
 <mx:Label text="Sign In:" 
            fontWeight="bold" paddingLeft="12" fontSize="14" 
            id="loginLabel" width="100%"/>
        
        <mx:Form id="loginForm" width="100%">

            <mx:FormItem label="Email:" id="frmEmail">
                <mx:TextInput id="email" width="220"/>
            </mx:FormItem>            

            <mx:FormItem label="Password:" id="frmPassword">
                <mx:TextInput id="password" displayAsPassword="true" width="220"/>
            </mx:FormItem>        
        </mx:Form>

        <mx:CheckBox id="rememberMe" label="Remember me on this computer"    
            paddingLeft="77" selected="true"/>

        <mx:ControlBar width="100%"    paddingLeft="84">
            <mx:Button label="Sign in" id="loginButton" click="signin()" enabled="false"/>            
            <mx:LinkButton label="Need to Register?" id="registerLink"
                click="currentState='Register'"/>            
        </mx:ControlBar>
</mx:VBox>

Listing 1: Login box with Flex 3

In the above Flex 3.0 implementation, AddChild and RemoveChild tags indicate that the runtime should add or remove child components, respectively, in the register state. The SetProperty tag, in turn, changes the button's label to "Register," and the SetEventHandler tag ensures that a register() method is invoked when the UI is the register state. Clicking on the LinkButton component toggles between the signin and register states.

While the Flex 2 and 3 state syntax works well, adding and removing components is rather cumbersome: For instance, you have to specify where new components are to be added apart from the new components' parents. UI components supporting a large number of states end up becoming unwieldy, with significant portions of related UI logic scattered across a large MXML file.

Flex 4's State Improvements

To simplify state definition, Flex 4 introduces a new states syntax. Although the various component states are still declared inside the states tag, the definition of each state is specified inline. To see how that works, consider the Flex 4 implementation of the login component. To make the Flex 4 implementation mirror the Flex 3 version as closely as possible, we didn't define separate component and skin files, a Flex 4 best practice:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/halo">
	
    <fx:Script>
        <![CDATA[
            private function signin(): void {
                 // Implementation of signin 
            }

            private function register(): void {
                // Implementation of register
            }
        ]]>
    </fx:Script>
	
    <s:states>
        <s:State name="signin"/>
        <s:State name="register"/>
    </s:states>
	
    <s:Group id="mainGroup">
        <s:layout>
            <s:VerticalLayout/>
        </s:layout>
		
    <mx:Label text="Sign in:" fontWeight="bold" paddingLeft="12" fontSize="14" id="loginLabel" width="100%"/>
		
    <mx:Form id="loginForm" width="100%" paddingTop="3" paddingBottom="3">

        <mx:FormItem label="First name:" includeIn="register" id="firstNameItem" alpha="0.0">
            <s:TextInput id="firstName" width="220"/>
        </mx:FormItem>

        <mx:FormItem label="Last name:" includeIn="register" id="lastNameItem" alpha="0.0">
            <s:TextInput id="lastName" width="220"/>
        </mx:FormItem>

        <mx:FormItem label="Email:" id="emailItem">
            <s:TextInput id="email" width="220"/>			
        </mx:FormItem>

        <mx:FormItem label="Password:" id="passwordItem">
            <s:TextInput id="password" displayAsPassword="true" width="220"/>
        </mx:FormItem>

        <mx:FormItem label="Confirm:" includeIn="register" id="confirmItem" alpha="0.0">
             <s:TextInput id="passwordConfirmation" displayAsPassword="true" width="220"/>			
        </mx:FormItem>
    </mx:Form>

    <s:Group>
        <s:layout>
            <s:HorizontalLayout paddingLeft="100"/>
        </s:layout>
        <s:Button label="Sign in" label.register="Register" id="loginButton" 
            enabled="true" click.signin="signin()" click.register="register()"/>
			
        <mx:LinkButton label="Need to register?" 
            click="currentState = 'register'" includeIn="signin"/>
        <mx:LinkButton label="Return to signin"
            click="currentState = 'signin'" includeIn="register"/>
     </s:Group>
		
    <mx:CheckBox id="rememberMe" label="Remember me on this computer" paddingLeft="110"/>
 </s:Group>
</s:Application>

Listing 2: Login box with Flex 4 state syntax

Instead of AddChild and RemoveChild methods, components that should be visible in the register state only are added an includeIn="register" tag. You can specify a comma-separated list of state names for the includeIn tag. Flex 4 also provides an excludeFrom tag, if you need to declare what states a component should be removed from. This new syntax allows you to declare components in place, inside the parent.

Properties can similarly be set inline using a new dot-separated syntax. For example, the Button component's label property is defined as follows:

... label="Sign in" label.register="Register" 

This tells Flex to set the button's label property to "Register" in the register state, and to "Sign in" in other states (the default). And listeners can be declared similarly: When the component is in the register state, the register() method is invoked on a button click, otherwise the signin() method is called:

click="signin()" click.register="register()"

The new component syntax makes it much easier to define sophisticated components with relatively straightforward, declarative code. The Flex 4 component states syntax also supports state groups as well as the ability to assign a new parent to a component. It is important to note that the new syntax only impacts MXML declarations—which is what the Flex compiler uses to generate ActionScript code. States can be defined in ActionScript as well, but that syntax does not change in Flex 4.

Flex gives you convenient ways not only to define component states, but also to specify transitions between states. To make the transition between the signin and register states smoother, this example includes a transition effect between those states. A forthcoming Artima article will describe Flex 4 transitions in greater detail.

Share Your Opinion

Have an opinion on Flex 4's states syntax? Discuss this article in the Articles Forum topic, Working with States in Flex 4.

Resources

Adobe's Flash Builder 4
http://labs.adobe.com/technologies/flashbuilder4

Flex 4 SDK
http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK

Gumbo Project
http://opensource.adobe.com/wiki/display/flexsdk/Gumbo

Flex.org
http://www.flex.org

About the Authors

Frank Sommers is Editor-in-Chief of Artima.

Posted by 1010
반응형

 

 

BlazeDS 와 스프링(Spring) 연동하기

 

출처 : http://youthgonewild.co.kr/category/FLEX

 

blazeds-spring-beta1.jar



BlazeDS를 이용하여 Remote Object Service를 이용할 때 스프링과 연동할 수는 없을까 라는 의문을 가지고
자료를 찾아보았습니다. 역시 이미 연동해서 사용하는 방법이 있더군요

다음의 remoting-config.xml 파일을 봅시다.

 <!-- 스프링 프레임워크를 이용한 remote object -->
<destination id="simpleLoadService">
 <properties>
  <factory>springfactory</factory> 
  <source>simpleLoadDao</source> 
 </properties>
</destination>    

일반적인 destination을 정의하는 부분과 다릅니다. 바로 <factory>라는 부분인데요, springfactory 라는
새로운 factory를 정의해서 스프링과 remote object를 연결시실수 있습니다.
그러면 springfactory 가 정의된 부분이 있어야 겠죠?

바로 services-config.xml 파일에 정의합니다.

 <!-- 스프링 프레임워크를 사용할수 있게 하기 위한 팩토리 설정  -->
 <factories>
  <factory id="springfactory" class="flex.messaging.factory.SpringFactory" /> 
 </factories>


위의 내용이 springfactory를 정의한 부분입니다.
이제 이 factory를 통해서 스프링과 remote object가 연결됩니다.
그러면 flex.messaging.factory.SpringFactory 는 원래 flex package에 존재하는 클래스일까요?
그렇지 않습니다. 스프링과의 연동을 위해 따로 제작된 클래스죠. 저도 외국 사이트에서 다운로드 했습니다.
첨부파일로 올리니 다운 받아서 lib에 등록해서 사용하시면 됩니다..


remoting-config.xml 에서 source로 설정되어 있는 simpleLoadDao도 마저 살펴봅시다.
스프링의 bean설정파일인 applicationContext.xml 파일에 등록되어 있겠죠.

applicationContext.xml

 <bean id="simpleLoadDao" class="flexintegration.spring.sample.SimpleLoadDao">
   <property name="sqlMapClient" ref="sqlMapClient" />
  </bean>

 <!-- SqlMap setup for iBATIS Database Layer : 스프링 프레임워크와 iBATIS의 연동  -->
 <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <property name="configLocation" value="WEB-INF/ibatis/sql-map-config.xml" />
  <property name="dataSource" ref="dataSource" />
 </bean>

  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}"/>
      <property name="url" value="${jdbc.url}"/>
      <property name="username" value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>
  </bean>

  <bean id="propertyConfigurer" 
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
          <list>
              <value>classpath:jdbc.properties</value>
          </list>
      </property>
  </bean>


이렇게 설정이 되면 Remote Object로 바로 스프링의 DI(Dependency Injection)를 이용하는 bean을 
사용할수가 있게 됩니다. ( iBatis를 이용하고 있어서 iBatis에 대한 경험이 없으시면 약간 이해하기
힘들수도 있겠네요 )

여기까지 Remote Object로 스프링 bean을 연동해서 사용하는 방법에 대해서 알아보았습니다.
Remote Object로 스프링의 강력한 DI를 바로 사용할 수 있다는 건 대단한 장점이죠.

참고로 AOP도 Remote Object 사용시 제대로 동작합니다. ( 테스트 해 보았죠 )

스프링과의 연동을 생각하셨던 분들에게 도움이 되셨기를...

 

Posted by 1010
반응형

출처 : http://lng1982.tistory.com/133

FTP 모듈을 사용하게 될 일이 생겨 예전에 만들었던 FTP 프로그램을 메이븐 프로젝트로 옮기게 되었다. 


내가 만든 FTP 모듈은 NetComponents-1.3.8.jar 라이브러리를 필요로 하는데 메이븐 중앙 리포지토리에서는 해당 라이브러리를 관리 안하고 있었다.


결국 아래와 같은 명령어를 이용하여 .m2\repository 디렉토리에 NetComponents-1.3.8.jar를 추가하여 문제를 해결 할 수 있었다.


mvn install:install-file -Dfile=C:\NetComponents-1.3.8.jar -DgroupId=com.oroinc -DartifactId=NetComponents -Dversion=1.3.8 -Dpackaging=jar -DgeneratePom=true


빨간색 글씨 부분을 상황에 맞게 변경해 주면 되고, 명령어를 실행하면 .m2\repository 경로에 class 파일이 install 된다.



NetComponents-1.3.8.jar

 

Posted by 1010
반응형

출처 : http://slothink.tistory.com/m/post/view/id/74

 

maven 의 assmbly 기능을 이용해서 단일 dependency 로 만들었을 경우(jar-with-dependencies 사용)에 만들어진 jar 파일로 실행하면 spring.scheas 파일들이 중복되는 오류가 발생한다.

해당 이슈에 대하여서 Spring JIRA 에 등록되어 있다. http://jira.codehaus.org/browse/MASSEMBLY-360

여하튼, 해결 방법은 assembly:assembly 를 시행할 프로젝트의 리소스 폴더에 META-INF 하위로 스프링 스키마 파일들을 복사해놓고 assembly 시키는 것이다.

예를 들어
디렉터리 구조
src/main/resources/META-INF/spring.handlers
src/main/resources/META-INF/spring.schemas

console>mvn assembly:assembly

하면 된다. 스키마 파일들은 스프링 jar 파일들을 풀면 구할 수 있다.

 

Posted by 1010
반응형

출처 : http://softworld.tistory.com/entry/Flex-4Blazeds-Spring-%EC%84%A4%EC%A0%95-%EC%99%84%EB%A3%8C%EB%90%9C-war

 

blazeds-spring.war

 

blazeds.war

 

Adobe가 제공 다운로드에다가 장난질을 쳐놨넹..

Turnkey안에 spring 설정된 war가 있었는데 지워놓은듯... spring설정시 의존성때문에 잘 되지도 않더만 이걸 지워 놓으면 고생할 사람많겠구만...

LiveCycle Data Services살릴려고 Blazeds는 개발 완전 중단되있고 그나마 남은 Freamwork는 graniteds

우선 제공되는 blazeds + spring 연동 war file을 남겨 본다. Test 결과는 잘 돌아감!!!

blazeds-spring.war

Blazeds Ver.4 + Spring Ver.3.0.1

spring ver.을 최신으로 올려봤지만 의존성때문에 잘 안됨..

blazeds.war

기본 Blazeds ver.4 도 올려 놓는다!

Posted by 1010
카테고리 없음2013. 9. 9. 09:55
반응형

출처 : http://theeye.pe.kr/entry/Flex-BlazeDS-with-Spring-Annotation?category=11

 

 

remotingdestination-annotation.zip

Flex 개발을 하다보면 서버와의 통신을 통해 다양한 방법을 사용할수 있다는 장점을 쉽게 알 수 있습니다.

하지만 안타까운게 Remote Object를 사용하기 위해서는 얼마인지 산출하기도 힘든 비싼 FDS (LCDS)를 구매해야 한다는 장벽이 있었죠.

이 장벽에 막혀 안정성이 확보되지 못한 일부 오픈 소스제품군을 사용하거나 다른 방식의 통신을 사용하여야 했습니다.

하지만 LCDS의 빠른 속도를 보장받을수는 없었죠. 현재 LCDS의 Remote Object 통신 프로토콜은 AMF3 (Action Message Format 3)까지 나왔습니다.

하지만 Adobe에서 BlazeDS라는 이름의 LCDS 무료버젼을 내놓았습니다. 또한 오픈소스로 개발 진행중입니다.

또한 Jeff Vroom 이라는 멋진 분이 Spring ↔ BlazeDS 간 통신할 수 있는 Factory를 개발하였습니다.

관련 정보는 다음을 참고하세요

[ 어도비 기술문서 ]
[ Sewon님 블로그 ]
[ 머드초보님 블로그 ]

하지만 위의 기술 내용들은 Spring Framework를 이용하여 어노테이션 기반으로 개발중이라면 여간 성가시게 만드는 부분이 많지 않은가 싶습니다.

위의 내용도 매우 간단해 지고 쉬워졌지만 BlazeDS도 어노테이션을 이용해 연동할 수 있으면 얼마나 좋을까 생각하게 만들었습니다.

그러던중에 좋은 자료를 발견하였습니다.

1. Spring에서 @RemotingDestination 어노테이션을 사용하기 위해 다음의 라이브러리를 다운받습니다. 여기에는 Jeff Vroom씨가 만든 Spring Factory도 포함하고 있습니다.

[ 다운받으러 가기 ]

2. remotingdestination-annotation.zip 파일을 개발중인 프로젝트의 WEB-INF/lib 디렉토리에 넣어줍니다.

3. BlazeDS의 설정파일인 services-config.xml 에 SpringAutowiringBootStrapService를 등록해 줍니다.

<?xml version="1.0" encoding="UTF-8"?>
<services-config>
   
<services>
       
<service-include file-path="remoting-config.xml" />
       
<service-include file-path="proxy-config.xml" />
       
<service-include file-path="messaging-config.xml" />
           
<service id="spring-autowiring-bootstrap-service"
               
class="flex.contrib.services.SpringAutowiringBootstrapService"/>
       
<default-channels>
           
<channel ref="my-amf"/>
       
</default-channels>
   
</services>

 


....

   
<factories>
       
<factory id="spring" class="flex.contrib.factories.flex.SpringFactory" />
   
</factories>
</services-config>


SpringAutowiringBootStrapService은 BlazeDS 로딩시에 모든 @RemotingDestination 어노테이션이 포함된 클래스를 등록합니다. 이것은 Spring Factory를 통해 동적으로 Spring의 Bean을 불러다 사용할 수 있음을 뜻합니다. 밑에 추가한 factory의 경우 id는 꼭 spring이어야 합니다.

4. 마지막으로 당신의 서비스 클래스에 @RemotingDestination 어노테이션을 붙여줍니다.

package flex.contrib.samples.mortgage;

 


import org.springframework.beans.factory.annotation.Autowired;
import flex.contrib.stereotypes.RemotingDestination;


@RemotingDestination(destination="mortgageService")
public class Mortgage {
   
@Autowired RateFinder rateFinder;
   
public void setRateFinder(RateFinder rateFinder) {
       
this.rateFinder = rateFinder;
   
}


    public double calculate(double amount) {
       
int term = 360; // 30 years
       
double rate = rateFinder.findRate();
       
return (amount*(rate/12)) / (1 - 1 /Math.pow((1 + rate/12), term));
   
}
}



5. 물론 Spring에서 component-scan과 annotation-config를 설정해 주는걸 잊지 말자고요.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       
xmlns:context="http://www.springframework.org/schema/context"
       
xsi:schemaLocation="http://www.springframework.org/schema/beans
           
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           
http://www.springframework.org/schema/context
           
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 


    <context:annotation-config/>
   
<context:component-scan base-package="flex.contrib.samples"/>
</beans>



6. Flex 에서는 다양한 방법의 Remote Object 통신방법으로 서버의 서비스에 직접 접근할 수 있게 됩니다.

var amfChannel:AMFChannel = new AMFChannel("my-amf", "http://localhost/messagebroker/amf");
var channelSet:ChannelSet = new ChannelSet();
channelSet
.addChannel(amfChannel);
   
var remoteObject:RemoteObject = new RemoteObject();
remoteObject
.channelSet = channelSet;
remoteObject
.destination = "mortgageService";
remoteObject
.addEventListener(ResultEvent.RESULT, resultHandler);
remoteObject
.addEventListener(FaultEvent.FAULT, faultHandler);
remoteObject
.calculate(5);



+. @RemotingDestination에서 지정한 destination이 Flex에서 지정하는 destination이 됩니다. 주의할점이 하나 있는데 web.xml의 contextConfigLocation 설정에서 정의한 컨텍스트의 Bean만 가져올 수 있습니다.

참고자료 : http://marceloverdijk.blogspot.com/2008/01/code-by-convention-with-flex-and-spring.html

Posted by 1010
반응형

출처 : http://lahuman.tistory.com/55

 

주요 몇가지 소스를 간단히 소개 하면,

1. /WEB-INF/web.xml


 <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
 <servlet>
     <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/config/web-application-config.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
 </servlet>

 <!-- Map all *.spring requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/spring/*</url-pattern>
    </servlet-mapping>


2. /WEB-INF/flex/services-config.xml

        <channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
            <endpoint url="http://{server.name}:{server.port}/{context.root}/spring/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
        </channel-definition>


3. application-context.xml

 <!-- Maps request paths at /* to the BlazeDS MessageBroker -->
 <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
     <property name="mappings">
         <value>
             /*=mySpringManagedMessageBroker
         </value>
     </property>
 </bean>
 
 <!-- Dispatches requests mapped to a MessageBroker -->
 <bean class="org.springframework.flex.messaging.servlet.MessageBrokerHandlerAdapter"/>
 <!-- Bootstraps and exposes the BlazeDS MessageBroker -->
 <bean id="mySpringManagedMessageBroker" class="org.springframework.flex.messaging.MessageBrokerFactoryBean" /> 
    <!-- Implementation of ProductDAO using low-level JDBC -->
    <bean id="productDAO" class="flex.spring.samples.product.ProductDAO" >
        <constructor-arg ref="dataSource"/>
    </bean>
   
 <!-- Expose the productDAO bean for BlazeDS remoting -->
 <bean id="product" class="org.springframework.flex.messaging.remoting.FlexRemotingServiceExporter">
     <property name="messageBroker" ref="mySpringManagedMessageBroker"/>
     <property name="service" ref="productDAO"/>
 </bean>
   



위 예제를 보면 Spring MVC를 이용해서 flex BlazeDS를 호출 한다.

아래 파일을 찬찬히 봐라!

Posted by 1010
반응형

시스템 환경

BlazeDS 4.0.x

Spring 3.0.x

SBI 1.3 or 1.5

 

Webapplicationcontext.xml에서 <flex-remoting> 태그 사용시 발생하는 오류

예)

    <bean id="SimpleExampleService2" class="com.mydomain.data.SimpleExample">

        <flex:remoting-destination/>

    </bean>

 

오류메시지

SEVERE: Context initialization failed

org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.flex.core.MessageInterceptionAdvice] for bean with name 'org.springframework.flex.core.MessageInterceptionAdvice#0' defined in null: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1211)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getType(AbstractBeanFactory.java:523)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.findRemotingDestinations(RemotingAnnotationPostProcessor.java:148)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.postProcessBeanFactory(RemotingAnnotationPostProcessor.java:79)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:624)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:614)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:398)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    at java.lang.ClassLoader.defineClass1(Native Method)

    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)

    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)

    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1814)

    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:868)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1321)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1200)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200)

    ... 30 more

Feb 20, 2012 5:19:32 PM org.apache.catalina.core.ApplicationContext log

SEVERE: StandardWrapper.Throwable

org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.flex.core.MessageInterceptionAdvice] for bean with name 'org.springframework.flex.core.MessageInterceptionAdvice#0' defined in null: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1211)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getType(AbstractBeanFactory.java:523)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.findRemotingDestinations(RemotingAnnotationPostProcessor.java:148)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.postProcessBeanFactory(RemotingAnnotationPostProcessor.java:79)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:624)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:614)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:398)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    at java.lang.ClassLoader.defineClass1(Native Method)

    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)

    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)

    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1814)

    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:868)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1321)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1200)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200)

    ... 30 more

Feb 20, 2012 5:19:32 PM org.apache.catalina.core.StandardContext loadOnStartup

SEVERE: Servlet /web1 threw load() exception

java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    at java.lang.ClassLoader.defineClass1(Native Method)

    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)

    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)

    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1814)

    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:868)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1321)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1200)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getType(AbstractBeanFactory.java:523)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.findRemotingDestinations(RemotingAnnotationPostProcessor.java:148)

    at org.springframework.flex.config.RemotingAnnotationPostProcessor.postProcessBeanFactory(RemotingAnnotationPostProcessor.java:79)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:624)

    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:614)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:398)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

 

해결방법

Aopalliance-1.0.jar lib폴더에 추가

 

오류메시지

SEVERE: Context initialization failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBrokerDefaultHandlerMapping': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBroker': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBroker': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isSingleton(AbstractBeanFactory.java:392)

    at org.springframework.context.support.AbstractApplicationContext.isSingleton(AbstractApplicationContext.java:1024)

    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:370)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.registerHandlers(SimpleUrlHandlerMapping.java:129)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.initApplicationContext(SimpleUrlHandlerMapping.java:104)

    at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)

    at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:71)

    at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)

    at org.springframework.context.support.ApplicationContextAwareProcessor.doProcess(ApplicationContextAwareProcessor.java:116)

    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:99)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    ... 31 more

Caused by: org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.flex.core.MessageBrokerFactoryBean.afterPropertiesSet(MessageBrokerFactoryBean.java:185)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1398)

    ... 50 more

Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)

    at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104)

    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)

    at org.springframework.flex.core.EndpointConfigProcessor.processAfterStartup(EndpointConfigProcessor.java:69)

    at org.springframework.flex.core.MessageBrokerFactoryBean.processAfterStart(MessageBrokerFactoryBean.java:294)

    at org.springframework.flex.core.MessageBrokerFactoryBean.afterPropertiesSet(MessageBrokerFactoryBean.java:168)

    ... 52 more

Feb 20, 2012 5:21:11 PM org.apache.catalina.core.ApplicationContext log

SEVERE: StandardWrapper.Throwable

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBrokerDefaultHandlerMapping': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBroker': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_messageBroker': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isSingleton(AbstractBeanFactory.java:392)

    at org.springframework.context.support.AbstractApplicationContext.isSingleton(AbstractApplicationContext.java:1024)

    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:370)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.registerHandlers(SimpleUrlHandlerMapping.java:129)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.initApplicationContext(SimpleUrlHandlerMapping.java:104)

    at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)

    at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:71)

    at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)

    at org.springframework.context.support.ApplicationContextAwareProcessor.doProcess(ApplicationContextAwareProcessor.java:116)

    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:99)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    ... 31 more

Caused by: org.springframework.beans.factory.BeanInitializationException: MessageBroker initialization failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.flex.core.MessageBrokerFactoryBean.afterPropertiesSet(MessageBrokerFactoryBean.java:185)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1398)

    ... 50 more

Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)

    at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104)

    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)

    at org.springframework.flex.core.EndpointConfigProcessor.processAfterStartup(EndpointConfigProcessor.java:69)

    at org.springframework.flex.core.MessageBrokerFactoryBean.processAfterStart(MessageBrokerFactoryBean.java:294)

    at org.springframework.flex.core.MessageBrokerFactoryBean.afterPropertiesSet(MessageBrokerFactoryBean.java:168)

    ... 52 more

Feb 20, 2012 5:21:11 PM org.apache.catalina.core.StandardContext loadOnStartup

SEVERE: Servlet /web1 threw load() exception

org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

    at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)

    at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104)

    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)

    at org.springframework.flex.core.EndpointConfigProcessor.processAfterStartup(EndpointConfigProcessor.java:69)

    at org.springframework.flex.core.MessageBrokerFactoryBean.processAfterStart(MessageBrokerFactoryBean.java:294)

    at org.springframework.flex.core.MessageBrokerFactoryBean.afterPropertiesSet(MessageBrokerFactoryBean.java:168)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1398)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isSingleton(AbstractBeanFactory.java:392)

    at org.springframework.context.support.AbstractApplicationContext.isSingleton(AbstractApplicationContext.java:1024)

    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:370)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.registerHandlers(SimpleUrlHandlerMapping.java:129)

    at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.initApplicationContext(SimpleUrlHandlerMapping.java:104)

    at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)

    at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:71)

    at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)

    at org.springframework.context.support.ApplicationContextAwareProcessor.doProcess(ApplicationContextAwareProcessor.java:116)

    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:99)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)

    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)

    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)

    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)

    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)

    at javax.servlet.GenericServlet.init(GenericServlet.java:211)

    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1164)

    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:984)

    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4043)

    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4349)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)

    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)

    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)

    at org.apache.catalina.core.StandardService.start(StandardService.java:450)

    at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)

    at org.apache.catalina.startup.Catalina.start(Catalina.java:551)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412)

 

해결방법

cglib-nodep-2.2.jar 라이브러리 추가

 

참조

http://develop.sunshiny.co.kr/80 (스프링 라이브러리 의존성)

Posted by 1010
반응형

3.Spring BlazeDS Integration 설치

본 문서에서는 Flex Plugin을 사용하지 않고 별도로 Flex개발 환경을 구성하는 방법에 대해서 다루도록 한다. Spring BlazeDS Integration을 설치 하기 위해서는 BlazeDS가 먼저 설치 되어야 한다. Web Application 프로젝트에 BalzeDS를 설치 한 후, Spring BlazeDS Integration을 추가로 설치 하는 방법에 대해 살펴 보도록한다.

3.1.BlazeDS의 설치

Adobe Open Source Site에서 최신 버전의 BlazeDS을 다운 받을 수 있다. Turnkey버전과 Binary Distribution을 다운 받을 수 있다. Turnkey의 경우 BlazeDS설치 파일 이외에 Reference 문서, Sample Application, BlazeDS Console Application등이 포함되어 있다.

BlazeDS를 다운 받아 압축을 풀면 blazeds.war파일이 포함되어 있는다. blazeds.war파일은 아래와 같은 폴더들로 구성된다.

다음은 각 폴더와 파일들에 대한 간략한 설명이다.

  • WEB-INF/web.xml : 어플리케이션의 배포지시자로 MessageBrokerServlet에 대한 Servlet설정과 HttpFlexSession 등에 대해 설정되어 있다. SpringBlazeDS Integration을 사용햘 경우에는 MessageBrokerServlet이 아닌 SpringMVC의 DispatcherServlet이 Client요청을 처리 할 수 있도록 Servlet설정을 변경해야 한다.

  • WEB-INF/flex : BlazeDS의 환경 설정 파일들이 있다. 서버측과 통신하기 위한 채널, 아답터, 로깅등의 정보가 세팅되어 있는 파일들이 위치한다.

  • WEB-INF/lib : BlazeDS 서버 측 라이브러리들이 위치해 있다.

3.1.1.BlazeDS 설정 파일

BlazeDS의 WEB-INF/flex폴더의 4개의 xml파일(services-config.xml, remoting-config.xml, proxy-config.xml, messaging-config.xml)을 Web Application Project의 {Web Root folder}/WEB-INF/flex란 이름의 폴더를 생성한 후 아래 그림과 같이 복사한다.

service-config.xml 파일을 열어 remoting-config.xml, messaging-config.xml파일의 include 부분을 삭제 또는 주석처리 한다. 두 파일을 include에서 제외하는 이유는 Spring BlazeDS Integration의 설정파일에서 Remoting, Messaging 통신에 대한 환경설정을 할 수 있기 때문이다. 그리고 Web Application 레벨의 default-channels을 설정한다. 아래는 수정된 service-config.xml파일의 일부이다.

<services-config>
    <services>
        <!-- service-include file-path="remoting-config.xml" / -->
        <service-include file-path="proxy-config.xml" />
        <!-- service-include file-path="messaging-config.xml" / -->  
        <default-channels>
        	<channel ref="my-amf"/>
    	</default-channels>      
    </services>

    <security>
    <!-- 중략 -->

3.1.2.BlazeDS 라이브러리

BlazeDS의 WEB-INF/lib폴더의 BlazeDS 서버 측 라이브러리를 Web Application Project의 {Web Root folder}/WEB-INF/lib폴더에 복사한다. 이 때 Web Application에 이미 등록되어 있는 라이브러리와 충돌나지 않도록 확인해서 복사한다. 예를들어 Anyframe의 Foundation Plugin으로 설치된 Web Application에는 common-logging-1.1.1.jar을 포함하고 있으므로 common-logging.jar은 제외한 후 복사한다.

3.2.Spring BlazeDS Integration 설치

BlazeDS설치가 끝났으면 Spring BlazeDS Integration을 Web Application에 설치 하도록 한다.

3.2.1.Spring BlazeDS Integration 라이브러리

Spring Source Community에서 Spring BlazeDS Integration 1.0.1을 다운 받아 org.springframework.flex-1.0.1.RELEASE.jar파일을 Web Application Project의 {Web Root folder}/WEB-INF/lib에 복사한다.

또 Spring BlazeDS Integration과 Dependency관계에 있는 jackson-core-asl-x.x.x.jar을 다운로드페이지에서 다운 받아 Web Application Project의 {Web Root folder}/WEB-INF/lib에 복사한다.

3.2.2.Servlet 설정

Spring BlazeDS Integration 라이브러리 복사가 끝났으면, Flex UI에서 RPC요청이 왔을 때 MessageBrokerServlet이 아닌 Spring MVC의 DispatcherServlet이 요청을 처리 할 수 있도록 web.xml파일에 Servlet설정을 아래와 같이 추가 한다. 이 때 Spring MVC에 대한 Servlet설정이 이미 정의되어 있으면 새로운 Servlet을 추가 정의한다.

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/springmvc/common-servlet.xml,
                    classpath:/springmvc/generation-servlet.xml,	
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
	
<servlet>
    <servlet-name>SpringBlazeDS</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/springmvc/flex-servlet.xml
        </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

위와 같이 SpringBlazeDS Servlet설정을 완료 한 후 아래와 같이 /messagebroker/*에 대한 요청을 SpringBlazeDS Servlet이 처리 할 수 있도록 servlet-mapping을 정의한다.

<servlet-mapping>
    <servlet-name>SpringBlazeDS</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

Flex Client에서 RemotingService, HTTPProxyService, MessageService의 Request url 패턴은 /messagebroker/*형태이다.

3.2.3.Spring WebApplicationContext 설정

Web Appliaction의 classpath:/spring위치에 Flex관련 Spring WebApplicationContext설정 파일(flex.xml)을 생성한다.

flex-servlet.xml파일을 열어 flex namespace를 사용하기 위해 다음과 같이 xsd를 정의한다.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:flex="http://www.springframework.org/schema/flex"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/flex 
	http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
		
	
</beans>

BlazeDS설정 파일인 services-config.xml파일을 읽어 MessageBrokerFactoryBean에 등록할 수 있도록 같이 flex namespace를 사용해 정의한다.

<flex:message-broker/>

위는 Default설정으로 services-config.xml파일이 classpath*:services-config.xml에 있을 경우에 사용할 수 있다. 추가적인 설정에 대해서는 Spring BlazeDS Integration Configuration을 참고한다.

3.3.Spring Bean Exporting

BlazeDS, Spring BlazeDS Integration의 설치가 끝났으면 Spring Bean을 Flex의 RemotingService가 접근 할 수 있도록 RemotingDestinationExporter에 등록한다. Spring Bean을 Exporting하기 위해서는 여러 방법이 있는데 여기에서는 @RemotingDestination annotation을 사용하도록 한다.

@Service("foundationGenreService")
@RemotingDestination
public class GenreServiceImpl implements GenreService {

	@Inject
	@Named("foundationGenreDao")
	private GenreDao genreDao;

	public List<Genre> getList() throws Exception {
		return genreDao.getList();
	}

}

@RemotingDestination annotation에 아무런 옵션을 주지 않으면 Bean Id가 Destination Id가 된다. 위의 소스코드에서는 foundationGenreService이 Destination Id가 되고 Flex Client에서는 foundationGenreService란 이름으로 해당 Service에 접근한다.

RemotingService가 접근 할 수 있도록 Spring Bean을 Exporting하는 자세한 방법은 Spring Blazeds Integration Configuration을 참고한다.

3.4.Flex Project 생성

Flex Web Application개발을 하기 위한 서버 측 설정이 완료 됐으면 Flex프로젝트를 생성한다. Flex UI를 개발하기 위해서는 편집기를 이용한 방법과 Flex Builder를 이용한 방법이 있다. Flex Builder는 Flex UI를 개발하기 위한 이클립스 기반의 상용 S/W 로 WYSIWYG Editor, mxml의 자동컴파일, 디버깅등 의 다양한 기능을 제공한다. 본 문서에서는 Flex Builder를 이용해 개발하는 방법에 대해서만 설명한다.

Adobe Flex Builder 3 Download에서 60일동안 사용가능한 Trial버전을 다운 받을 수 있다.

Flex Builder 3를 처음 실행 하게 되면 아래와 같은 화면을 볼 수 있다.

Flex Builder에서 File -> New -> Flex Project를 선택하면 새로운 Flex Project를 생성할 수 있다.

New Flex Project 창이 열리면 Project Name과 Flex Project의 Location등을 입력하고 Application type은 Web application(runs in Flash Player)을 선택, Server technology의 Application server type는 J2EE, Use remote object access service의 체크 박스를 선택, LiveCycle Data Services를 선택한 후 Next버튼을 클릭한다.

Configure J2EE Server창 Server location에서는 BlazeDS가 설치된 Web Application의 정보를 세팅한다. 서버 정보를 입력 한 후 Validate Configuration 버튼을 클릭해 BlazeDS가 설치 된 Web Application인지 확인한다.

Compiled Flex application location의 Output folder는 Flex Project가 컴파일 되서 위치할 경로를 입력한다. 일반적으로는 Web Application Project의 Web Root folder의 특정 폴더를 지정한다. 여기에서는 {Web Root folder}/flex를 Output folder로 설정했다. 입력이 끝났으면 Next버튼을 클릭한다.

다음으로는 Flex Project의 build path를 설정하는 창이 열리는데 Main application file에 Main Application mxml파일의 파일 이름을 입력한 후 Finish버튼을 클릭한다.

아래 그림과 같이 신규 프로젝트가 생성되고 Main Application mxml파일이 열리면 성공적으로 Flex Project가 생성된 것이다.

Web Application Project의 {Web Root folder}/flex폴더에 Flex Project가 컴파일 되어 아래와 같은 파일들이 생성된 것을 확인 할 수 있다. Flex Application Main Application mxml(main.mxml) 파일명(main)이 Flex Application 실행 html파일명(main.html)이 된다.

WAS를 시작해 Flex Application실행 html을 브라우저에서 호출한다.(http://localhost:8080/myproject/flex/main.html) 아래와 같이 화면이 출력 됐다면 Flex Project가 정상적으로 설치 된 것이다.

3.5.Remoting Service Call

Flex Applicatin Main mxml에서 Spring Bean(foundationGenreService)의 getList메소드를 호출한다. 아래와 같이 RemotingObject태그를 사용해 destination(Spring Bean)과 호출할 method를 정의한다.

<mx:RemoteObject id="remotingService" destination="foundationGenreService">
    <mx:method name="getList" result="resultHandler(event)"/>
</mx:RemoteObject>

foundationGenreService getList의 호출 결과는 resultHandler메소드에서 처리한다. 아래는 foundationGenreService getList메소드를 호출한 결과를 DataGird에 바인딩하는 예이다.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" initialize="getList()">
    <mx:Script>
        <![CDATA[
            import mx.rpc.events.ResultEvent;
            import mx.collections.ArrayCollection;
			
            [Bindable]
            private var genreList:ArrayCollection;
			
            private function getList():void{
                remotingService.getList();
            }
			
            private function resultHandler(event:ResultEvent):void{
                genreList = event.result as ArrayCollection;
            } 
        ]]>
    </mx:Script>
	
    <mx:RemoteObject id="remotingService" destination="foundationGenreService">
        <mx:method name="getList" result="resultHandler(event)"/>		
    </mx:RemoteObject>
   <mx:Array id="columnsInfo">
		<mx:DataGridColumn dataField="genreId" headerText="GENRE ID" editable="true"/>
		<mx:DataGridColumn dataField="name" headerText="NAME" editable="true"/>	
	</mx:Array>
	
	<mx:DataGrid id="grdGenre" dataProvider="{genreList}" columns="{columnsInfo}"/>
</mx:Application>

위와 같이 작성 한 후 main.html을 호출 하면 다음과 같은 화면을 볼 수 있다.

 

4.Spring BlazeDS Integration 환경 설정

Spring BlazeDS Integration은 Flex를 이용해 Web Application을 개발 할 경우, 서버측과 RPC방식으로 통신할 때 필요한 BlazeDS를 Spring Framework와 연계하여 편리하게 사용할 수 있도록 한다. 복잡한 환경 설정이 flex namespace를 통해 간편해 졌고 Spring Bean을 Exporting하기 위한 annotation이 제공된다.

Spring BlazeDS Integration을 사용하기 위한 환경은 다음과 같다.

  • Java 5 이상

  • Spring 2.5.6 이상

  • Adobe BlazeDS 3.2 이상

4.1.Spring BlazeDS MessageBroker 환경 설정

4.1.1.Spring DispatcherServlet

BlazeDS 에서는 MessageBrokerServlet 을 front Controller 로 사용하여 Flex client 의 요청을 처리했다. Spring BlazeDS Integration 을 사용하면 Spring MVC 의 DispatcherServlet 이 Flex client 의 요청을 처리한다. 따라서 web.xml 에 아래와 같은 설정을 추가한다.

<servlet>
    <servlet-name>SpringBlazeDS</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/springmvc/flex-servlet.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>SpringBlazeDS</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

4.1.2.MessageBroker

Spring BlazeDS Integration에서는 BlazeDS와 Spring과의 연계를 위한 복잡한 환경 설정을 간단히 하기 위해 flex namespace를 제공한다. flex namespace를 사용하기 위해서는 Spring WebApplicationContext 설정 파일에 다음과 같이 xsd를 정의를 추가한다.

<?xml version="1.0" encoding="UTF-8"?>	
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:flex="http://www.springframework.org/schema/flex" 
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/flex 
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
        
        ...
</bean>

web.xml 파일의 설정에 의해 flex client 의 요청을 DispatcherServlet 이 처리함으로 그 요청을 MessageBroker로 위임해야 한다.

MessageBroker 설정은 flex namespace 추가로 아래와 같이 간단한 설정만으로 가능하다.

<?xml version="1.0" encoding="UTF-8"?>	
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:flex="http://www.springframework.org/schema/flex" 
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/flex 
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
			
    <flex:message-broker />
</beans>

위의 설정의 경우 기본적으로 /WEB-INF/flex/services-config.xml 파일을 참조하게 된다. 설정 파일의 위치가 다를 경우 services-config-path attribute 설정을 통해 변경이 가능하다.

<flex:message-broker services-config-path="classpath*:services-config.xml" />

flex namespace를 사용하지 않을 때에는 아래와 같이 설정한다.

<bean id="messageBroker" 
           class="org.springframework.flex.core.MessageBrokerFactoryBean">
    <property name=""serviceConfigPath" value="classpath*:services-config.xml"/>
</bean>

Configuring the Spring DispatcherServlet에서 처럼 /messagebroker/*요청에 대한 servlet-mapping을 별도로 설정하지 않고 모든 요청에 대해서 DispatcherServlet이 처리 할 경우 /messagebroker/*에 대한 요청을 MessageBroker가 처리 하기 위해서는 아래와 같이 SimpleUrlHandlerMapping을 설정한다.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <value>
        /messagebroker/*=_messageBroker
        </value>
    </property>
</bean>

<bean class="org.springframework.flex.servlet.MessageBrokerHandlerAdapter"/>

위의 SimpleUrlHandlerMapping설정은 flex namespace를 사용할 경우는 아래와 같다.

<flex:message-broker>
    <flex:mapping pattern="/messagebroker/*" />
</flex:message-broker>

4.2.Exporting Spring Beans

4.2.1.RemotingService 환경 설정

Application 레벨의 채널 세팅은BlazeDS설정 파일인 services-config.xml파일에 services태그 안에 아래와 같이 정의 한다. Flex Client에서 RemotingService에 별도의 채널 설정이 없을 경우 my-amf채널을 이용한다.

<services>
    ..중략
    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>        
</services>

RemotingService에 대해 특정 채널을 이용하고자 할 경우에는 아래와 같이 remoting-service의 default-channels속성에 채널 이름을 등록한다.

<flex:message-broker>
    <flex:remoting-service default-channels="my-amf, my-secure-amf" />
</flex:message-broker>

4.2.2.remoting-destination 태그

remoting-destination 태그는 Spring Bean 을 Remote 객체로 노출 시킨다.

<bean id="productService" class="flex.samples.product.ProductServiceImpl" />
<flex:remoting-destination ref="productService" />

다음과 같은 설정도 가능 하다.

<bean id="productService" class="flex.samples.product.ProductServiceImpl">
    <flex:remoting-destination />
</bean>

include-methods / exclude-methods 속성을 이용해 method 단위의 제어도 가능하다. include-method / exclude-method를 정의하지 않을 경우 default는 include-method이다.

<flex:remoting-destination ref="productService"
    include-methods="read, update"
    exclude-methods="create, delete"
    channels="my-amf, my-secure-amf" />

4.2.3.@RemotingDestination

@RemotingDestination 을 사용해서도 Spring Bean 을 Remote 객체로 노출이 가능하다.

@Service("productService")
@RemotingDestination
public class ProductServiceImpl implements ProductService {
..중략

@RemotingInclude, @RemotingExclude annotation을 이용해 method별 노출 여부를 설정할 수 있다.

@RemotingInclude
public Category getCategoryList(SearchVO searchVO) throws Exception{
..
}

@RemotingExclude
public void removeCategory(Category category) throws Exception{
...
}

@RemotingDestination annotaion을 이용해 Spring Bean을 노출 할 때 Destination 채널 설정은 아래와 같이 한다.

@Service("categoryService")
@RemotingDestination(channels={"my-amf","my-secure-amf"})
public class CategoryServiceImpl implements CategoryService {

 

Posted by 1010
반응형

출처 : http://blog.naver.com/PostView.nhn?blogId=thunder1119&logNo=100091204490

 

올해초 Srping BlazeDS Integration 1.0.0 M1 으로 스프링과 BlazeDS를 적용해 보았는데

( 머드초보님의 M1 사용기 : http://mudchobo.tomeii.com/tt/371 )

한학기 마치고 다시 접하려고 했더니 정식버전이 나왔더군요!

그래서 반가운 마음에 적용해보려고 Spring 홈페이지( http://www.springsource.org )에서 다운로드후

문서를 보았는데. M1에 비해서 문서의 양이 늘어나있고 영어 잼병인 저에겐 소스코드만이 유일한

해독가능한 언어인데 상황에 따라 다르게 적용해야되는 코드들이라 영 도움이 안되 몇일간 삽질을 시켜주었습니다ㅜㅜ

우선 설명하기에 앞서 플렉스 컴퍼넌트 카페( http://cafe.naver.com/flexcomponent.cafe ) 에 서기님이 올려주신

Flex3+eclipse europa + BlazeDS 셋팅 게시물의 첨부된 문서의 세팅방법을 모두 완료했다는 가정하에 설명하도록

하겠습니다. ( http://cafe.naver.com/flexcomponent.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=10906

서기님이 작성하신 셋팅문서 첨부해 두겠습니다.)



자 이제 위 과정으로 BlazeDS_Hello.mxml을 실행하였을 경우 "Welcome BlazeDS 성공!" 이란 문구를 보았다고 치고

이제 Srping BlazeDS Integration을 적용해 보도록 하겠습니다.

우선 Srping BlazeDS Integration에 필요한 환경(Java 5 or higher, Spring 2.5.6 or higher ,Adobe BlazeDS 3.2 or higher)

을 구성해주어야 되는데 http://www.springsource.org/download 에서 우선 Srping BlazeDS Integration과 Spring 2.5.6

을 받아서 lib안에 넣어줍니다.


그리고 web.xml을 수정해보겠습니다.

우선 spring을 사용하면서 필요없어진 리스너를 삭제합니다.

<!-- 아래의 리스너 삭제 -->
<listener>
        <listener-class>flex.messaging.HttpFlexSession</listener-class>
</listener>


그리고 스프링을 사용하기 위한 ContextLoaderListener를 삽입합니다.

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


<servlet-mapping>태그는 그대로 두고 <servlet> 태그만 스프링을 사용하기 위해 아래와 같이 수정합니다.

<servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/web-application-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>


여기 까지가 web.xml 수정사항입니다.

그 후 spring을 사용하려면 기본적으로 WEB-INF밑에 applicationContext.xml 파일이 있어야 하기에 만들어 줍니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      
</beans>



 



이제 web.xml에서 <servlet>태그밑에 <param-value>에 선언해 두었던 web-application-config.xml을 만들어줍니다.

안의 내용은 뒤에 설명하도록 하겠습니다.


이제 WEB-INF밑에 flex폴더에 들어있는 BlazeDS관련 xml들을 수정하겠습니다.

우선 remoting-config.xml에 선언해둔 blaze id에 destination 태그를 삭제합니다. 이태그는 이제 spring 관리하에

web-application-config.xml에서 새로운 인생(?)을 살게 될 것입니다.

그리고 services-config.xml <services> 태그밑에  아래와 같이 default-channels 태그를 추가해 줍니다.

<services>
        <service-include file-path="remoting-config.xml" />
        <service-include file-path="proxy-config.xml" />
        <service-include file-path="messaging-config.xml" />   
        <default-channels>
           <channel ref="my-amf"/>
        </default-channels>     
    </services>


자 이제 주역인 web-application-config.xml에 내용을 넣도록 하겠습니다.

우선 설명하기에 앞서 전체코드 나갑니다.

<!-- web-application-config.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:flex="http://www.springframework.org/schema/flex"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
               http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/flex
            http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
       
       <bean id="mySpringManagedMessageBroker" class="org.springframework.flex.core.MessageBrokerFactoryBean" />

       <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
             p:mappings="/*=mySpringManagedMessageBroker" />
      
       <bean class="org.springframework.flex.servlet.MessageBrokerHandlerAdapter" />
                
       <bean id="test" class="test.Test">
               <flex:remoting-destination destination-id="blaze" message-broker="mySpringManagedMessageBroker"/>
       </bean>

</beans>



얼핏 복잡해보이기도 하지만 사실 그렇게 어렵지 않습니다.

우선 네임스페이스 부분을 보면 xmlns:flex="http://www.springframework.org/schema/flex 추가됬고

스키마부분을 보면

http://www.springframework.org/schema/flex
http://www.springframework.org/schema/flex/spring-flex-1.0.xsd

기존 스프링에서 이두개가 추가되었고

web.xml에서 들어오는 MessageBroker를 아래 태그가 담당합니다.

<bean id="mySpringManagedMessageBroker" class="org.springframework.flex.core.MessageBrokerFactoryBean" />


id는 편하신데로 주시면 되고 사실 이부분을 doc에 보면 여러가지 방법으로 표현할 수 있는데 <flex:message-broker/>등

짧게 표현이 가능하지만 doc이 부실한지 제가 못찾는지 이대로 실행하면 오류가나서 실행이안됩니다.

2009/07/13 추가사항

<flex:message-broker/> 방식의 사용법을 보시려면 다음의 페이지를 참고해주세요!

http://actionscripter.tistory.com/27



그래서 전 그냥 기존 spring 방식으로 bean으로 처리했습니다.

다음으로 스프링에 SimpleUrlHandlerMapping 으로 MassageBroker와 연결합니다.

저는 편의상 p 네임스페이스로 축약해서 사용했습니다.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
             p:mappings="/*=mySpringManagedMessageBroker" />

또는

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/messagebroker/*=mySpringManagedMessageBroker
</value>
</property>
</bean>


그리고 이부분은 저도 잘 모르겠는데 messageBroker와 관련된 adapter인듯 합니다.

<bean class="org.springframework.flex.servlet.MessageBrokerHandlerAdapter" />


그리고 저를 가장 고생시킨.. remoting 부분인데 1.0.0 정식이 나오면서 <flex:remoting-service>태그가

<flex:remoting-destination>으로 바겼는지 국내와 국외문서 모두에 <flex:remoting-service>으로 되어있어서

상당히 고생했습니다. 이부분도 다양한 사용방법이 있는데 자세한것은 레퍼런스를 참조하시고 우선 성공한 방법만

소개하겠습니다.

<bean id="test" class="test.Test">
               <flex:remoting-destination destination-id="blaze" message-broker="mySpringManagedMessageBroker"/>
</bean>

또는

<bean id="test" class="test.Test"/>
      
<flex:remoting-destination ref="test" destination-id="blaze" message-broker="mySpringManagedMessageBroker"/>

또는

<bean id="test" class="test.Test"/>

<bean id="product" class="org.springframework.flex.remoting.RemotingDestinationExporter"
             p:messageBroker-ref="mySpringManagedMessageBroker" p:service-ref="test"
             p:destinationId="blaze" />

레퍼런스문서에 ref 외에는 나와있질 않아서 계속 메시지브로커를 찾지못한다는 에러를 보았는데

결국 flex스키마 문서를 죄 뒤져서 속성을 찾아냈습니다 ㅡㅠ

message-broker="mySpringManagedMessageBroker" 부분은 꼭 넣어주시고

remoting-config.xml에서 destination id로 사용되는 부분과 같은 속성이 destination-id 입니다.

사실 이외에도 채널등 여러 속성이 있는데 불필요하다고 판단해서 다 제외했습니다.

자이제 여기까지 설정을 하시고 BlazeDS_Hello.mxml을 실행해보시면 다음과 같은 아름다운 화면을 보실 수 있습니다!


 

Posted by 1010
반응형

Spring Projects

Spring Flex

Spring BlazeDS Integration is a top-level Spring project, and a component of the complete Spring Web stack.  This project's purpose is to make it easier to build Spring-powered Rich Internet Applications using Adobe Flex as the front-end client.  It aims to achieve this purpose by providing first-class support for using the open source Adobe BlazeDS project and its powerful remoting and messaging facilities in combination with the familiar Spring programming model.

The Flex Addon for Spring Roo is a new component that raises the bar for productivity in building Flex clients backed by Spring BlazeDS Integration on the server-side. By utilizing the next-generation code-generation and management facilities of Spring Roo, it provides the fastest way to get up and running with a new Spring-based Flex project by letting developers focus on doing what they do best - write code.

 

Spring BlazeDS Integration is a top-level Spring project, and a component of the complete Spring Web stack.  This project's purpose is to make it easier to build Spring-powered Rich Internet Applications using Adobe Flex as the front-end client.  It aims to achieve this purpose by providing first-class support for using the open source Adobe BlazeDS project and its powerful remoting and messaging facilities in combination with the familiar Spring programming model.

The Flex Addon for Spring Roo is a new component that raises the bar for productivity in building Flex clients backed by Spring BlazeDS Integration on the server-side. By utilizing the next-generation code-generation and management facilities of Spring Roo, it provides the fastest way to get up and running with a new Spring-based Flex project by letting developers focus on doing what they do best - write code.

#maven

Latest News

Spring Flex Resources

Spring Flex Presentations

Spring Flex Articles and Tutorials

 

Maven Artifacts

Here is the Spring External Repository needed for BlazeDS dependencies:

<repository>
<id>spring-external</id>
<name>Spring External Repository</name>
<url>http://maven.springframework.org/external</url>
</repository>

Here is the Spring Flex dependency definition:

<dependency>
<groupId>org.springframework.flex</groupId>
<artifactId>spring-flex-core</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>

 

Posted by 1010
반응형
Posted by 1010
반응형
Posted by 1010
01.JAVA/Java2013. 8. 6. 17:37
반응형

i am trying to get the complete parameter map from the request object and iterate over it.

here is the sample code

  Map map = request.getParameterMap();
for(Object key : map.keySet()){
    String keyStr = (String)key;
    Object value = map.get(keyStr);     
    System.out.println("Key " + (String)key + "     :    " + value);
}

output

  Key businessunit     :    [Ljava.lang.String;@388f8321
   Key site     :    [Ljava.lang.String;@55ea0889
  Key startDate     :    [Ljava.lang.String;@77d6866f
  Key submit     :    [Ljava.lang.String;@25141ee0
  Key traffictype     :    [Ljava.lang.String;@4bf71724

its evident from the output that the value object is an instance of String

now when i change my code to something like this

  Map map = request.getParameterMap();
  for(Object key : map.keySet()){
    String keyStr = (String)key;
    Object value = map.get(keyStr);
    if(value instanceof String)
    System.out.println("Key " + (String)key + "     :    " + (String)value);
}

it prints nothing but as per the previous output it should have printed the values and if i remove instanceOf check it gives ClassCastException. is this the expected behavior or i am doing something wrong here ?

share|improve this question
Three possibilities: 1. Did you redeclare class String somewhere (try using java.lang.String instead of String to find out)? 2. Are you using the exact same values when running the two pieces of code? 3. Try using String.valueOf(value) or value.toString() and see what happens. Hope it helps. – The Nail Dec 5 '11 at 7:34
Ah forget the above, it's an array. Fooled me. – The Nail Dec 5 '11 at 7:36
add comment (requires an account with 50 reputation)

[Ljava.lang.String;@XXXXXXX means it is array of String not a single String. So your condition fails and it does not print anything.

share|improve this answer
add comment (requires an account with 50 reputation)

The value is an array. If you're sure that the array is not empty, you should get the string value like this:

String value = (String) map.get(keyStr)[0];
share|improve this answer
add comment (requires an account with 50 reputation)

As the object which is returned is an array of strings as Harry Joy pointed out, you will have to use the Arrays.toString() method in order to convert that array to a printable string:

    Map map = request.getParameterMap();
    for (Object key: map.keySet())
    {
            String keyStr = (String)key;
            String[] value = (String[])map.get(keyStr);
            System.out.println("Key" + (String)key + "   :   " + Arrays.toString(value));
    }
share|improve this answer
Posted by 1010
01.JAVA/Java2013. 8. 6. 16:50
반응형

출처 : http://lotus.tistory.com/78

 

Map 같은 자료구조로 이터레이션 할때 여러가지 방법을 쓸 수 있는데 검색하다가 깔끔한 코드를 발견해서 첨부해 본다. ㅋ
난 자바 뉴비..ㅎㅎ

- 그저 그런 방법

Set<Integer> set = map.keySet();
for(Integer key : set)
{
System.out.println(key + " " + map.get(key));
}

- 좀 더 깔끔한 방법
for (Map.Entry<Integer, String> entry : map.entrySet() )
{
System.out.println(entry.getKey() + " " + entry.getValue());
}


아래의 주소에서 소스코드를 참조했음
http://jtoee.blogspot.com/2008/05/better-way-to-iterate-java-maps.html 
Posted by 1010
반응형

첨부한 파일을 다운 받아서 프로젝트에 넣어주시구요.

(출처 : http://flexology.wordpress.com/2008/09/30/loadinganimated_gif_in_flex/ )

AnimatedGIFImage.as 파일을 추가합니다.
소스는 아래와 같습니다.

package gif
{
 import flash.net.URLRequest;

 import mx.controls.Image;
 import mx.core.UIComponent;

 import org.gif.player.GIFPlayer;

 public class AnimatedGIFImage extends Image
 {
  private var _gifImage:UIComponent;

  public function AnimatedGIFImage()
  {
   super();
   this._gifImage=new UIComponent();
  }

  override public function set source(value:Object):void
  {
   if (!value is String)
   {
    throw new ArgumentError("Source must be of type String");
   }

   super.source=value;
  }

  override protected function createChildren():void
  {
   super.createChildren();
   var player:GIFPlayer=new GIFPlayer();
   player.load(new URLRequest(this.source as String));
   this._gifImage.addChild(player);
  }

  override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
  {
   this.addChild(this._gifImage);
   super.updateDisplayList(unscaledWidth, unscaledHeight);
  }
 }
}

그리고 사용하실땐
<gif:AnimatedGIFImage source="test.gif" width="100" height="100"/> 와 같이 사용하시면 됩니다.

Posted by 1010
반응형
Tree Icon Spinner (not using animated gif)
I've been disappointed that Flex doesn't natively support animated gifs. I especially wanted to use them inside Flex Trees when I'm loading the children dynamically. So instead of trying to get animated gifs to work (see this example if you are interested) I created a relatively simple Spinner class that draws a circular spinner using just Flex Graphics. The spinner is animated using a Timer. If you set the startImmediately property to true then the animation starts when the spinner component is added to a parent component. And it is always stopped when it gets removed from its parent.
There are also the start(), stop() and running functions to control the spinner manually.

The spinners have a few styles that you can set to customize the appearance:
<ui:Spinner
  Properties
delay="100"
startImmediately="false"
Styles
backgroundAlpha="1"
backgroundColor="NaN"
spinnerColor="#829AD1"
spinnerHighlightColor="#001A8E"
spinnerThickness="3"
spinnerLineThickness="2"
spinnerType="gradientcircle"/>

I've created an example of the four types of spinners in four Trees. Each tree node loads its children after a 2 second delay during which time the spinner is shown, so try expanding each tree (right click to view source):


Let me know if you like them!

Also, make sure you do call stop() on the spinner when you don't need it anymore... otherwise you might notice your Flex app starts to run very slowly like mine did...

 

Posted by 1010
반응형

Datagrid avec ItemRenderer avec CheckBox, ComboBox, ColorPicker

Updated for Flex 3

Voici un exemple d'utilisation du composant DataGrid en Flex 2 Flex 3 avec des ItemRenderer.

Chaque champ peut-être édité. Cet exemple montre l'utilisation de CheckBox, de ComboBox, de NumericStepper et de ColorPicker comme Renderer.

Voir la démo - See the demo

Voir les sources - View the sources

Obtenir les sources dgRendererSimple.zip

DataGrid avec ItemRenderer

Explication

Tout est dans le code.

Les ItemRenderer de chaque colonne sont programmés en MXML.

Posted by 1010
반응형

Progressbar in Datagrid Example

Line Break

Author: Roelof (13 Articles) - Author Website

Roelof is a SAP Consultant specialized in Front-End development. In his spare free time he is either developing on the web, playing basketball, watching soccer or traveling. He is also the co-owner of Flex-Blog.com.


In the comments of our previous post about using the ProgressBar, one of our readers asked if a ProgressBar could be used inside a DataGrid.

This is, ofcourse, possible. So we decided to write an example about this.

There are a couple of things you need to know before we start:

  1. Use an ItemRenderer to show the ProgressBar inside the DataGrid instead of text.
  2. Create a DataProvider for the DataGrid (in our case we use an ArrayCollection).
  3. Create an action to start the ProgressBar (in our case we simulate a download).
  4. Make sure the ArrayCollection is updated on every progress of the ProgressBar.

First we create an ItemRenderer in a seperate ActionScript file (myProgressBar.as):

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
32
33
34
package
{
    import mx.containers.HBox;
    import mx.controls.ProgressBar;
    import mx.controls.dataGridClasses.*;

    public class myProgressBar extends HBox
    //This should normally be extends ProgressBar, we are using HBox to have more control over the layout.
    {
        private var pb:ProgressBar;
       
        public function myProgressBar():void {
            //Create new ProgressBar Instance
            pb = new ProgressBar();
            //Set some layout things
            pb.mode = "manual";
            pb.percentWidth = 100;         
            pb.labelPlacement = "center";
            this.setStyle("verticalAlign","middle");
            //Add ProgressBar as child
            addChild(pb);
        }
       
        override public function set data(value:Object):void
        {
            super.data = value;
        }  
       
        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number) : void{
            super.updateDisplayList(unscaledWidth, unscaledHeight);
            pb.setProgress(data.loaded, data.total);
        }
    }
}

Then we will use this ItemRenderer inside the DataGrid column.

1
<mx:DataGridColumn itemRenderer="myProgressBar" dataField="progress" headerText="Progress" width="180" paddingLeft="5"/>

To start the ‘fake’ ProgressBar download progress, we are using an Image as a Button inside the DataGrid.

1
2
3
4
5
6
7
8
9
10
            <mx:DataGridColumn width="112" headerText="Download">
                <mx:itemRenderer>
                    <fx:Component>
                        <mx:HBox horizontalAlign="center" verticalAlign="middle">    
                            <s:Label text="{data.file}"/>
                            <mx:Image buttonMode="true" toolTip="'Download'" click="outerDocument.downloadFile()" source="@Embed(source='images/down_alt.png')"/>
                        </mx:HBox>
                    </fx:Component>
                </mx:itemRenderer>             
            </mx:DataGridColumn>

Why use outerDocument?
Since the itemRenderer is within another Component, we need to use outerDocument to call a method inside your ‘main’ Component.

Next step was to implement the method downloadFile():

1
2
3
4
5
6
7
            public function downloadFile():void{
                //start timer
                var timer:Timer = new Timer(500);
                // add event listener
                timer.addEventListener(TimerEvent.TIMER, updateProgressBar);
                timer.start();             
            }

Next, implement the eventListener. Inside the eventListener we need to make sure the DataGrid / ArrayCollection gets updated.

1
2
3
4
5
6
7
            private function updateProgressBar(event:TimerEvent):void{
                var myItem:Object
                // Add a 'random' number to loaded. To fake the progress..
                myDataGrid.selectedItem.loaded += Math.ceil(Math.random() * 5);
                //refesh arraycollection to refresh the datagrid
                myArrayCollection.refresh();               
            }

Then you are done. Below you will find a working example. For the full source code either use Right Mouse Click -> View Source or scroll down.

Full Source Code:
ProgressBarInsideDatagridExample.mxml

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/halo" width="500"  height="200" initialize="init();" viewSourceURL="srcview/index.html">

    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
           
            [Bindable]private var myArrayCollection:ArrayCollection;
           
            private function init():void {
                // Create instance of myArrayCollection
                myArrayCollection = new ArrayCollection;
                // Create new Object
                var obj:Object = new Object;
               
                obj.file = "File 1";
                obj.total = 100;
                obj.loaded = 0;
                // Add object to myArrayCollection
                myArrayCollection.addItem(obj);
                obj = new Object;
                obj.file = "File 2";
                obj.total = 100;
                obj.loaded = 0;
                // Add object to myArrayCollection
                myArrayCollection.addItem(obj);
            }

            public function downloadFile():void{
                //start timer
                var timer:Timer = new Timer(500);
                // add event listener
                timer.addEventListener(TimerEvent.TIMER, updateProgressBar);
                timer.start();             
            }

            private function updateProgressBar(event:TimerEvent):void{
                var myItem:Object
                // Add a 'random' number to loaded. To fake the progress..
                myDataGrid.selectedItem.loaded += Math.ceil(Math.random() * 5);
                //refesh arraycollection to refresh the datagrid
                myArrayCollection.refresh();               
            }
           
           
        ]]>
    </fx:Script>
   
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->    
    </fx:Declarations>
   
    <mx:DataGrid id="myDataGrid" height="200" width="500" dataProvider="{myArrayCollection}">
        <mx:columns>
            <mx:DataGridColumn width="112" headerText="Download">
                <mx:itemRenderer>
                    <fx:Component>
                        <mx:HBox horizontalAlign="center" verticalAlign="middle">    
                            <s:Label text="{data.file}"/>
                            <mx:Image buttonMode="true" toolTip="'Download'" click="outerDocument.downloadFile()" source="@Embed(source='images/down_alt.png')"/>
                        </mx:HBox>
                    </fx:Component>
                </mx:itemRenderer>             
            </mx:DataGridColumn>
           
            <mx:DataGridColumn itemRenderer="myProgressBar" dataField="progress" headerText="Progress" width="180" paddingLeft="5"/>
        </mx:columns>          
    </mx:DataGrid>
   
</s:Application>

myProgressBar.as

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
32
33
34
package
{
    import mx.containers.HBox;
    import mx.controls.ProgressBar;
    import mx.controls.dataGridClasses.*;

    public class myProgressBar extends HBox
    //This should normally be extends ProgressBar, we are using HBox to have more control over the layout.
    {
        private var pb:ProgressBar;
       
        public function myProgressBar():void {
            //Create new ProgressBar Instance
            pb = new ProgressBar();
            //Set some layout things
            pb.mode = "manual";
            pb.percentWidth = 100;         
            pb.labelPlacement = "center";
            this.setStyle("verticalAlign","middle");
            //Add ProgressBar as child
            addChild(pb);
        }
       
        override public function set data(value:Object):void
        {
            super.data = value;
        }  
       
        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number) : void{
            super.updateDisplayList(unscaledWidth, unscaledHeight);
            pb.setProgress(data.loaded, data.total);
        }
    }
}

 

Posted by 1010
반응형

TabNavigator와 ModuleLoader 사용시 문제

TabNavigator 가 포함된 상위 노드에 creationPolicy="all" 로 해주면 어느정도 문제는 해결됨

Posted by 1010
반응형

Copy Flex UIComponent

I was trying to copy a canvas(UIComponent), but realize that it’s not a simple job as it looks like.

1. One can use the ObjectUtil.copy()..method to copy a simple object, but we can not use the same for UIComponent.

2. Secondly,  one can use Bitmap to copy the Image type. Like…

public static function cloneImage(image:Image):Image
          {
               var clone:BitmapData = Bitmap(image.source).bitmapData.clone();
               var bitmap:Bitmap           = new Bitmap(clone);
               
               var newImage:Image          = new Image();
               newImage.source           = bitmap;
               
               return newImage;
          }
3.Thirdly, we can use the componentDescriptor to create a container

Like..

 <?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”horizontal”>
     <mx:Script>
          <![CDATA[
               private function cloneButton_clickHandler (event:MouseEvent):void
               {
                    var childDescriptors:Array = original.childDescriptors;
                    var descriptorsCount:int = childDescriptors.length;
                    for (var i:int; i < descriptorsCount; i++)
                    {
                         cloned.createComponentFromDescriptor(original.childDescriptors[i],
                                                                       false);
                    }
                    cloned.validateNow();
               }
          ]]>

     </mx:Script>
     <mx:Button label=”Clone Canvas” click=”cloneButton_clickHandler(event);” />
     <mx:Canvas id=”original” width=”100″ height=”100″ borderStyle=”solid” >
          <mx:Label text=”Some Label” />
          <mx:ComboBox dataProvider=”{['data1', 'data2']}” bottom=”0″ />
     </mx:Canvas>
     <mx:Canvas id=”cloned” width=”100″ height=”100″ borderStyle=”solid” >
          
     </mx:Canvas>
</mx:Application>

but, still there is a problem in the above method. It copy only the first level children.

For more usefulness we need to make RECURSIVE call to this method to copy each and every children it has which is really frustating…:(

4. I also tried to implement this by using Reflection API or taking a snapshot of the current view…

But, unfortunately  flex does not have snapshot method. I guess we need to take help of ExternalInterface to implement the sanpshot method..

After going through all this I find that flex should have make this more simplify by providing an interface to clone any UICompoent.

Sorry to say, I guess flex is really lagging in this regard…

 

Posted by 1010
반응형

flex DataGrid Border remove

화면 전환시 데이터그리드 외곽선이 지워지는 현상

variableRowHeight="true"

Posted by 1010
반응형
Package flash.printing
Class public final class PaperSize
Inheritance PaperSize Inheritance Object

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

 

This class provides the available values for the paperSize parameter of the PrintJob.selectPaperSize() method. Each constant represents a paper size that is used to print a page.

The following table shows the approximate size for each paper type. The size is approximate because there is some variation among printer drivers. For example, the width of A4 paper can be 595.0, 595.2, 595.22 or 595.28 points depending on the driver.

Value Size in points
A4 595 x 842
A5 420 x 595
A6 297 x 420
CHOUKEI3GOU 340 x 666
CHOUKEI4GOU 298 x 666
ENV_10 297 x 684
ENV_B5 499 x 709
ENV_C5 459 x 649
ENV_DL 312 x 624
ENV_MONARCH 279 x 540
ENV_PERSONAL 261 x 468
EXECUTIVE 522 x 756
FOLIO 612 x 936
JIS_B5 516 x 729
LEGAL 612 x 1008
LETTER 612 x 792
STATEMENT 396 x 612

 

Related API Elements



Public Properties
  Property Defined By
  Inherited constructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  Inherited prototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
  Method Defined By
  Inherited
Indicates whether an object has a specified property defined.
Object
  Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  Inherited
Indicates whether the specified property exists and is enumerable.
Object
  Inherited
Sets the availability of a dynamic property for loop operations.
Object
  Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
  Inherited
Returns the string representation of the specified object.
Object
  Inherited
Returns the primitive value of the specified object.
Object
Public Constants
  Constant Defined By
        A4 : String = "a4"
[static] A4
PaperSize
        A5 : String = "a5"
[static] A5
PaperSize
        A6 : String = "a6"
[static] A6
PaperSize
        CHOUKEI3GOU : String = "choukei3gou"
[static] Japanese choukei 3 gou (envelope)
PaperSize
        CHOUKEI4GOU : String = "choukei4gou"
[static] Japanese choukei 4 gou (envelope)
PaperSize
        ENV_10 : String = "env_10"
[static] Legal envelope
PaperSize
        ENV_B5 : String = "env_b5"
[static] B5 envelope
PaperSize
        ENV_C5 : String = "env_c5"
[static] C5 envelope
PaperSize
        ENV_DL : String = "env_dl"
[static] DL envelope
PaperSize
        ENV_MONARCH : String = "env_monarch"
[static] Monarch envelope
PaperSize
        ENV_PERSONAL : String = "env_personal"
[static] Personal envelope
PaperSize
        EXECUTIVE : String = "executive"
[static] Executive size
PaperSize
        FOLIO : String = "folio"
[static] Folio size
PaperSize
        JIS_B5 : String = "jis_b5"
[static] Japanese B5
PaperSize
        LEGAL : String = "legal"
[static] Traditional legal size
PaperSize
        LETTER : String = "letter"
[static] Traditional letter size
PaperSize
        STATEMENT : String = "statement"
[static] Statement size
PaperSize
Constant Detail
    

A4

Constant
public static const A4:String = "a4"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

A4

    

A5

Constant  
public static const A5:String = "a5"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

A5

    

A6

Constant  
public static const A6:String = "a6"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

A6

    

CHOUKEI3GOU

Constant  
public static const CHOUKEI3GOU:String = "choukei3gou"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Japanese choukei 3 gou (envelope)

    

CHOUKEI4GOU

Constant  
public static const CHOUKEI4GOU:String = "choukei4gou"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Japanese choukei 4 gou (envelope)

    

ENV_10

Constant  
public static const ENV_10:String = "env_10"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Legal envelope

    

ENV_B5

Constant  
public static const ENV_B5:String = "env_b5"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

B5 envelope

    

ENV_C5

Constant  
public static const ENV_C5:String = "env_c5"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

C5 envelope

    

ENV_DL

Constant  
public static const ENV_DL:String = "env_dl"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

DL envelope

    

ENV_MONARCH

Constant  
public static const ENV_MONARCH:String = "env_monarch"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Monarch envelope

    

ENV_PERSONAL

Constant  
public static const ENV_PERSONAL:String = "env_personal"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Personal envelope

    

EXECUTIVE

Constant  
public static const EXECUTIVE:String = "executive"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Executive size

    

FOLIO

Constant  
public static const FOLIO:String = "folio"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Folio size

    

JIS_B5

Constant  
public static const JIS_B5:String = "jis_b5"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Japanese B5

    

LEGAL

Constant  
public static const LEGAL:String = "legal"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Traditional legal size

    

LETTER

Constant  
public static const LETTER:String = "letter"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Traditional letter size

    

STATEMENT

Constant  
public static const STATEMENT:String = "statement"

 

Language Version:  ActionScript 3.0
Runtime Versions:  AIR 2

 

 

Statement size


 

Posted by 1010
반응형
Printing

Adobe® Flash® Player and Adobe® AIR™ can communicate with an operating system’s printing interface so that you can pass pages to the print spooler. Each page Flash Player or AIR sends to the spooler can contain content that is visible, dynamic, or offscreen to the user, including database values and dynamic text. Additionally, Flash Player and AIR set the properties of the flash.printing.PrintJob class based on a user’s printer settings, so that you can format pages appropriately.

This chapter details strategies for using the flash.printing.PrintJob class methods and properties to create a print job, read a user’s print settings, and make adjustments to a print job based on feedback from Flash Player or AIR and the user’s operating system.

 

Posted by 1010