반응형
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