달력

5

« 2024/5 »

  • 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
2012. 1. 23. 13:08

[JAVA] Vector와 ArrayList의 차이점 Enjoy/JAVA2012. 1. 23. 13:08

출처 : http://www.todayis.net/vSix/index.php?ct1=3&ct2=32


Vector와 ArrayList는 extends, implements가 동일하니 쌍둥이라고도 할 수 있을 만큼 동일합니다. 하지만 차이가 있는데, 

인용:

Vector는 synchronized이고, ArrayList는 아닙니다.
Vector는 1.0 부터 있어왔고, ArrayList는 1.2에서부터 생겼습니다.
Vector는 크기 조절이 알아서 되는 Array 오브젝트를 구현하려고 생겼다가 1.2가 나올 때 동일한 목적을 가진 List를 구현한 것으로 바뀌어 Collection framework에 포함이 되었습니다.
따라서 1.2부터는 다음처럼 써서 필요할 때 바꿔치는 것이 됩니다.

List list = new ArrayList()
List list = new Vector()


그럼 둘 중에 무엇을 쓰느냐가 다음 질문인데, ArrayList를 씁니다. 만약 concurrent 프로그래밍을 위해 Vector처럼 synchronized가 필요하면 Collections.synchronizedList()라는 Collections의 wrapper method를 다음처럼 쓰면 됩니다.
List list = Collections.synchronizedList(new ArrayList(...));

그럼 Vector는 언제 쓰느냐 라는 질문이면, 저는 1.1 호환의 예전 소스나 책에 매인 것이 아니라면 Vector는 쓰지말라고 하겠습니다.
:
Posted by 라면스프
2011. 12. 1. 10:32

[ORACLE] Oracle Index 정리 Enjoy/ORACLE2011. 12. 1. 10:32


출처 : http://zetswing.com/bbs/board.php?bo_table=ORACLE_TIP&wr_id=4&page=3


※ 인덱스생성 명령을 실행하면 해당 테이블에 테이블락이 자동으로 걸린다.

그래서 서비스상태에서는 인덱스를 주면 장애가 날수 있습니다.

 

Index 정의

 

1) 조회속도를 향상시키기 위한 데이터베이스 검색 기술

 

2) 색인이라는 뜻으로 해당 테이블의 조회결과를 빠르게 하기 위해 사용합니다.

보통 INDEX를 테이블의 특정 컬럼에 한개이상을 주게 되면 Index table 이 따로 만들지는데

이 INDEX table 에는 인덱스컬럼의 로우의 값과 rowid 값이 저장되게 되며 로우의값은 정렬된 B-TREE 구조로 저장시켜두어 검색시 좀더 빠르게 해당 데이타를 찾는데 도움을 준다.

하지만 UPDATE,INSERT,DELETE 시에 속도가 느려진다는 단점이 있다.

왜냐하면 INSERT, UPDATE, DELETE 시에는 원본TABLE은 물론 INDEX table 에도 데이타를 갱신시켜 주어야 하기 때문입니다.

하지만 너무 작은 로우(레코드)가 있는 TABLE에 INDEX를 사용하게 되면 index의 효력을 제대로 발휘못하며 반드시 INDEX키를 조건으로 검색시에는 연산이나 가공을 하면 INDEX를 탈수없다.

 

※ 테이블을 생성하고 컬럼을 만든후 데이타를 삽입하면 하나의 로우가 생성되며 이 로우는 절대적인 주소를 가지게 됩니다. 이 절대적인 주소를 ROWID 라고 합니다.

 

INDEX가 필요한 이유?

 

조회 속도를 최대한 줄일수 있다.

 

참고

인덱스를 만들 때 현재 컬럼수가 너무 많으면 DML의 성능이 떨어지고 너무 부족하면

쿼리의 성능이 떨어집니다. 데이터가 많고 B*Tree Index인 경우 컬럼level이 하나

늘어날 때 그에 따른 node의 추가가 엄청나게 일어날 수 있습니다

이런 node들이 너무 많으면 쿼리성능도 좋을 수 없습니다.

인덱스는 일반적으로 최대 5개 컬럼 내외정도로 상황에 따라 합리적으로 구성합니다.

인덱스(Index)가 필요한 경우

1. 데이타가 많이 쌓일거라고 예상되는 경우와 많이 쌓인 경우와 현재 화면에서 조회속도가 너무 느릴때

2) 조회결과가 전체 데이타수의 3~5% 미만일 경우에 인덱스스캔이 효율적이고

적은비용으로 빠르게 데이터를 찾아낼수있습니다.

하지만 Acess 대상범위가 전체범위의 3~5%이상쯤 되면 인덱스스캔 보다 풀스캔이 휠씬

유리합니다.

 

인덱스 스캔 = Index Scan

풀 스캔 = Full Scan

 

INDEX가 불필요한 경우?

 

1) 데이터가 적은(수천건 미만) 경우에는 인덱스를 설정하지 않는게 오히려 성능이 좋습니다.

2) 조회 보다 삽입, 수정, 삭제 처리가 많은 테이블

3) 조회결과가 전체행의 15% 이상 읽어들일것으로 예상될때

 

Index 튜닝의 시기단계

 

하드웨어

DBMS 환경체크 - INDEX설정 및 파티셔닝체크 - SQL최적화  등의 레벨 순서로 튜닝합니다.

 

소프트웨어

쿼리문의 조회조건이 인덱스를 타는지 체크한다.(조금 중요)

 

쿼리문의 JOIN키가 모두 INDEX 설정이 되어 있는지 체크한다. INDEX설정이 되어 있지 않는 컬럼을 JOIN키로 지정했다면 조회속도가 많이 느려질수 있다.(많이 중요)

 

INDEX 생성하는 방법?

 

자동 생성

 

유일 인덱스는 테이블 정의시 PRIMARY KEY와 UNIQUE KEY 제약조건을 정의할때 자동으로 생성한다.

 

수동 생성

 

사용자는 행에 대한 액세스 시간을 향상 시키기 위해 열에서 유일하지 않은 인덱스를 생성할수 있다.

 

INDEX 생성 문법?

 

사용형식

 

CREATE INDEX index_name ON table_name (column_name)

--단일 인덱스 지정

CREATE INDEX index_name ON table_name (column_name1,column_name2,column_name3)

--다중 인덱스(복합 인덱스) 지정

 

※ 복합 인덱스로 지정해준 테이블에서 복합 인덱스를 타게 하려면 복합 인덱스로 준 컬럼

을 조회쿼리에서 모두 조회조건에 사용해야 인덱스를 탈 확률이 높아진다.

 

사용예제

 

create index index_a_date on account(a_date);

create index index_a_date on account(a_date, b_date, c_date);

 

※ null 허용 컬럼은 인덱스를 만들수 없습니다.

 

INDEX 가능 컬럼

 

인덱스는 모든 컬럼에 적용가능하다.

그런데 오라클은 가공시킨 컬럼에도 적용가능하다. 아래 참고

 

CREATE INDEX IDX_NAME ON TABLE_NAME(ROUND(PRICE1-PRICE2));

 

ROUND(PRICE1-PRICE2) 는 컬럼은 아니지만 컬럼을 가공해서 만든것이다.

이런 가공컬럼은 다음과 같은 SQL 쿼리로 인덱스를 탈수 있다.

 

SELECT * FROM TABLE_NAME WHERE ROUND(PRICE1-PRICE2) > 0

 

※ 인덱스 줄때의 가공컬럼과 같아야 합니다.

 

SQL 쿼리의 INDEX SCAN 유무 체크 방법

 

1. 상용 DB 관리도구를 이용하는 방법

 

PL/SQL Developer, Toad 같은 도구에서 SQL문을 작성하고 실행하면 Explain plan 에서 확인 가능합니다.

 

INDEX를 사용해야할 컬럼은?

 

where절이나 조인 조건에서 자주 사용되는 열에 생성

열은 광범위한 값을 포함할때

열은 많은수의 null값을 포함할때

조회결과가 전체행의 2-4% 보다 적게 읽어들일것으로 예상될때

--테이블이 클때 적은 양의 로우를 검색할때 인덱스를 줍니다. 적은 양을 검색하는데 테이블을 전체 풀스캔하면 시간이 오래 걸려서 꼭 index를 줘야 합니다.

 

INDEX를 사용하지 말아야할 컬럼은?

 

테이블에 데이타가  작은 경우

where절에 자주 사용되지 않는 열은 사용되지 않는다.

조회결과가 전체행의 2-4% 이상을 읽어들일것으로 예상될때

테이블이 자주 갱신된다.

 

INDEX 생성시 고려사항?

 

고려사항

 

인덱스가 적용된 컬럼이 조건식에서 인덱스를 탈수있게  하려면 해당컬럼을 가공하지않거나 연산을 하지 않은 상태에서 비교해야 인덱스를 탑니다.

예를들어 연락처컬럼의경우(016-293-1965) 016 만 따로 문자열을 잘라(가공) 조건검색하면 인덱스를 타지 않습니다.

왜냐하면 인덱스 컬럼에 변형이 일어나면 상대값과 비교되기 전에 먼저 가공이 된 후에 비교된다.하지만 인덱스는 가공되기 전의 값으로 생성되어 있기 때문에 당연히 인덱스를 사용할 수 없게 된다. 여기에서 외부적(External) 변형이란 사용자가 인덱스를 가진 컬럼을 어떤 SQL함수나 사용자 지정함수(User Defined Stored Function), 연산, 결합(||) 등으로 가공을 시킨 후에 발생되는 것이며 이러한 경우는 인덱스를 탈수 없어 변형이 일어나지 않도록 제대로 기술해야 합니다.

그렇기때문에 016과 293과 1965를 각각의 컬럼으로 만들어 저장한후 각각의 컬럼에 인덱스를 주면

아무런  가공없이 조건 검색이 가능하므로 인덱스를 탈수 있습니다.

 

테이블 컬럼에 인덱스가 있따면 테이블 컬럼을 변경하는것보다 비교값을 변경하여

비교해주는데 좋다. 왜냐면 그래야 인덱스를 타기 때문이다.

WHERE to_char(joindate, 'yyyymmdd') = '20070612'

WHERE joindate = TO_DATE('20070612','yyyymmdd')

 

아래는 인덱스를 타지 않습니다.

 

SELECT * FROM ACCOUNT WHERE A_DAY+1>2;

SELECT * FROM ACCOUNT WHERE SUBSTR(A_STRDAY,1,1)='월';

SELECT * FROM EMP WHERE  EMP_ID = NVL(EMP_ID,'10');

 

아래는 인덱스를 탑니다.

 

SELECT * FROM ACCOUNT WHERE A_STRDAY='월요일';

SELECT * FROM ACCOUNT WHERE A_DAY>2;

SELECT * FROM    EMP WHERE  EMP_ID = NVL('10','20');

SELECT * FROM ACCOUNT WHERE A_STRDAY like '월요일%';

 

※ 첫번째 쿼리부터 인덱스효과가 크게 나타나는 순입니다.

 

INDEX 타는 경우와 안타는 경우

 

안타는 경우

1. SELECT * FROM emp WHERE empno <> '7369';

 

※ 오라클에서는 인덱스 타게 가능(exists 이용)

SELECT * FROM emp WHERE not exists

(select empno FROM emp WHERE empno = '7369' and a.empno = b.empno);

 

INDEX 보기?

 

SELECT * FROM USER_INDEXES

--데이터 사전 뷰는 인덱스의 이름과 그것의 유일성을 디스플레이 합니다.

 

SELECT * FROM USER_IND_COLUMNS

--뷰는 인덱스명,테이블명,열명을 디스플레이 합니다.

 

SELECT * FROM ALL_OBJECTS where object_type='INDEX';

--현재 계정에 생성된 모든 인덱스 보기(속도느림)

 

SELECT * FROM USER_OBJECTS WHERE OBJECT_TYPE='INDEX';
--현재 계정에 생성된 모든 인덱스 보기(속도빠름)

 

select ic.index_name,
       ic.column_name,
       ix.uniqueness
from   user_indexes ix, user_ind_columns ic
where  ic.index_name = ix.index_name
and    ic.table_name = 'ACCOUNT';
--ACCOUNT TABLE의 인덱스 정보를 검색합니다.

 

INDEX 삭제?

사용형식

DROP INDEX INDEX_NAME;

사용예제

DROP INDEX BYC_LOVE_IDX;

 

※ TABLE이 삭제되면 INDEX도 삭제된다.

※ 인덱스의 소유자와 DROP ANY INDEX권한을 가진 사람만 인덱스 삭제가 가능합니다.

 

datecolumn => '20060517' and datecolumn <= '20060517' 좌측의 쿼리가 인덱스 안

타는 경우

1. 인덱스키가 아님

2. 복합키 인덱스인데 첫번째 컬럼에 조건을 안준 경우

3. 인덱스 스캔을 했을때 전체 데이터의 10~15% 이상이 되어 옵티마이져가 판단했을때

4. 인덱스 스캔이 불리하다고 판단되어 강제로 인덱스안타는 풀스캔 타는 경우

5. 좌변이 가공되어 인덱스 안탐

 

자주 쓰이지 않는 통계용 쿼리에는 인덱스를 주지 않는다.

여기서 인덱스를 준다는 얘기는 조건절에 인덱스를 안타는 컬럼에 인덱스를 생성해준다는

얘기이다. 이때는 create temp table as 해서 임시 테이블 만들어 통계 내용을 모두 담은후에

해당 조건컬럼에 인덱스를 만들어 쿼리하는게 좋다.

:
Posted by 라면스프
2011. 11. 28. 11:28

영어 기초문법 MP3 출퇴근용 2011. 11. 28. 11:28

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2011. 11. 24. 10:30

Modifying data in a database Enjoy/FLEX2011. 11. 24. 10:30

출처 : http://www.adobe.com/devnet/flex/trial/examples/10_complex_app.html?trackingid=IJYYH

Modifying data in a database

 

Explanation

This sample project shows you how to connect a Flex application to server-side data to retrieve, update, add, and delete records in a database. To look at the code, right-click on the SWF in the browser and select View Source or download the sample files and view the source files in a text editor or follow the instructions to import the Flash Builder FXP.

Communicating with the server

Flex applications cannot connect directly to a remote database. Instead, they communicate with back-end servers using either direct socket connections or more commonly, through HTTP. HTTP requests are made to a remote data service written in your favorite web language (PHP, ColdFusion, Java, or any other server-side web technology) using one of the Flex framework's remote procedure call APIs: HTTPService, WebService, or RemoteObject. All three wrap Flash Player's HTTP connectivity, which in turn, uses the browser's HTTP library.

With HTTPService, you make HTTP requests to JSP, PHP, CFM, or XML files; RESTful web services; or other server files that returns text over HTTP. You specify the endpoint URL, listener functions (the callback functions to be invoked when the HTTPService request returns a successful or unsuccessful response), and a data type for the returned data (what type of data structure it should be translated into once received in the Flex application). You can specify the data to be handled as raw text and assigned to a String variable or converted to XML, E4X, or plain old ActionScript objects. If you get back JSON, you can use the Adobe Flex corelib package of classes to deserialize the JSON objects into ActionScript objects. To make calls to SOAP based web services, you can use the HTTPService API or the more specialized WebService API, which automatically handles the serialization and deserialization of SOAP formatted text to ActionScript data types and vice versa.

The third option for making remote procedure calls is to use the RemoteObject API. It makes a Flash Remoting request to a method of a server-side class (which can be a ColdFusion component) that returns binary Action Message Format (AMF) over HTTP. You specify an endpoint (which in this case is a server-side Flash Remoting class to handle the remoting request), a destination (the server-side class that has the methods you want to call), and listener functions to handle the responses. The data translation between the client and server-side data types is handled automatically.

This sample project uses Flash Remoting whose binary data transfer format enables applications to load data up to 10 times faster than with the more verbose, text-based formats such as XML, JSON, or SOAP. To see a comparison of AMF to other text-based serialization technologies, see James Ward's Census RIA Benchmark application.

Using Flash Remoting

Flash Remoting is a combination of client and server-side functionality that together provides a call-and-response model for accessing server-side objects from Flash Platform applications as if they were local objects. It provides transparent data transfer between ActionScript and server-side data types, handling the serialization into binary Action Message Format (AMF), deserialization, and data marshaling between the client and the server.

Flash Remoting uses client-side functionality built in to Flash Player and server-side functionality that must be installed on the application server. Flash Remoting is built in to some servers (like ColdFusion and Zend) but must be installed on other servers (as BlazeDS or LiveCycle Data Services on Java EE servers, WebORB or FluorineFX on .NET servers, the Zend Framework or amfphp on PHP servers, and more).

Setting up the server

Let's start by taking a look at the server-side files.

ColdFusion

Flash Remoting is built in ColdFusion servers and little setup is necessary. You need to make sure that Flash Remoting is enabled in the ColdFusion Administrator (Data & Services > Flex Integration > Enable Flash Remoting support) and then in your ColdFusion components, specify an access of remote for the functions you want to access from Flex applications. This sample project calls methods of EmployeeService.cfc located in/wwwroot/TestDrive/services/.

<cfcomponent output="false"> <cffunction name="getEmployees" output="false" access="remote" returntype="Query"> <cfset var qGetEmployees=""> <cfquery name="qGetEmployees" datasource="testdrive_db"> SELECT *FROM employees </cfquery> <cfreturn qGetEmployees> </cffunction> <!-- other functions --> </cfcomponent>

The files for configuring Flash Remoting files are located in /ColdFusion/wwwroot/WEB-INF/flex/. The main configuration file, services-config.xml, defines channels to specify how communication should take place between the client and server, including the protocol to use (for example, AMF over HTTP or HTTPS), the endpoints (the classes to handle and route the calls on the server), and other information for finetuning the calls (like specifying if query columns names and structure keys should be translated into ActionScript with lowercase or uppercase property names). You set the case by modifying the <property-case> tag as shown below.

<property-case> <!-- cfc property names --> <force-cfc-lowercase>true</force-cfc-lowercase> <!-- Query column names --> <force-query-lowercase>true</force-query-lowercase> <!-- struct keys --> <force-struct-lowercase>true</force-struct-lowercase> </property-case>

The services-config.xml file also includes a reference to the remoting-config.xml file, which is where you can define destinations, or mappings to specific ColdFusion components you want to call from Flex. (After changes to the configuration files, you must restart the server.) By default, remoting-config.xml contains one default destination (with an id of ColdFusion) that has its source property set to a wildcard so it can be used for any Flash Remoting calls to any ColdFusion components.

<destination id="ColdFusion"> <channels> <channel ref="my-cfamf"/> </channels> <properties> <source>*</source> </properties> </destination>

To make a call from Flex with RemoteObject, you specify a destination of ColdFusion and a source of TestDrive.services.employeeService, the fully qualified name of the ColdFusion component that you want to call from the webroot.

You can also add named destinations to remoting-config. For example, you could create a destination called employeeService that points to that same CFC:

<destination id="employeeService"> <properties> <source>TestDrive.services.EmployeeService</source> </properties> </destination>

... and then when making calls from Flex, you would specify a destination of employeeService (instead of ColFusion) and no source (because it is now included in the destination)

Java

To use Flash Remoting with Java, you need to install an implementation of Flash Remoting on the server. Adobe provides the open-source BlazeDS or the commercial LiveCycle Data Services. This sample uses BlazeDS and the BlazeDS files (JAR files and configuration files) are included in the Test Drive WAR file along with the Java classes to call from the Flex application. For more details, read the Flex and Java technology overview and the architecture overview.

This sample project calls methods of EmployeeService located in the testdrive webapp: /testdrive/WEB-INF/classes/services/. (The source files are also included for reference in /testdrive/webapps/WEB-INF/src/services/.) It uses a typical assembler design pattern and manipulates instances of an Employee data transfer object, which we will map to a corresponding client-side ActionScript object for passing data back and forth between the client and server. To be called from Flex, the Java class must have a no argument constructor.

package services; import java.util.List; import services.EmployeeDAO; import services.Employee; public class EmployeeService { public EmployeeService() { } public List getEmployees() { EmployeeDAO dao = new EmployeeDAO(); return dao.getEmployees(); } //more methods... }

The files for configuring Flash Remoting files are located in /testdrive/WEB-INF/flex/. The main configuration file, services-config.xml, defines channels to specify how communication should take place between the client and server, including the protocol to use (for example, AMF over HTTP or HTTPS), the endpoints (the classes to handle and route the calls on the server), and other information for finetuning the calls.

The services-config.xml file also includes a reference to the remoting-config.xml file, which is where you define destinations, or mappings to the specific Java classes you want to call from Flex. Here is the destination used for the sample projects called employeeService:

<destination id="employeeService"> <properties> <source>services.EmployeeService</source> <scope>application</scope> </properties> </destination>

To make a call from Flex with RemoteObject, you specify a destination of employeeService.

PHP

To use Flash Remoting with PHP, you need to install an implementation of Flash Remoting on the server. This sample uses the Zend Framework. You must install the framework and then create a PHP file (in this sample, gateway.php) to use the framework and handle all the requests from Flex, including passing them to the appropriate PHP classes, handling all the data translation and serialization, and more. If you use the Create Data Service wizard in Flash Builder to create a data service to connect to a PHP class, the Zend framework is automatically installed on your server (if it is not already) and gateway.php and an amf-config.ini file created and placed on the server along with the SWF. Although this sample does not use service files created with the Flash Builder Data Service wizard, it does use the gateway.php and amf-config.ini files it creates. (The Flex Test Drive has a tutorial for creating the service with the wizard.)

This sample project calls methods of EmployeeService located in /htdocs/TestDrive/services/.

<?php class EmployeeService { public function getEmployees() { $stmt = mysqli_prepare($this->connection,"SELECT *FROM employees"); //more code return $rows; } //more methods }

You specify directories that contain PHP classes to call from Flex in the amf-config.ini file.

;more code amf.directories[]=TestDrive/servicesc

To make a call from Flex with RemoteObject, you specify a destination of zend, an endpoint of gateway.php, and a source of EmployeeService, the name of the PHP class to call.

Creating a RemoteObject

Now that we've looked at the server-side files, let's see how to call them from Flex. The first step is to define an instance of the RemoteObject class either in the Script block with ActionScript or in the Declarations tag with MXML; they are equivalent. The Declaration tag provides a way to define non-visual objects with MXML. (The green color of the tag indicates it is a compiler tag associated with compiler instructions and not an instance of a class.)

Depending upon what server you are using, the RemoteObject will have slightly different properties specified (the destination and possibly the source and/or endpoint). For ColdFusion and Java, the endpoint is set dynamically using the services-config.xml file and for ColdFusion, a source needs to be set if the default ColdFusion destination is used. After substituting the values from the constants set in the Script block of the sample code, the RemoteObject tag will look like one of these.

<fx:Declarations> <!-- ColdFusion--> <s:RemoteObject id="employeeService " destination="ColdFusion" source="TestDrive.services.EmployeeService" showBusyCursor="true" fault="employeeService_faultHandler(event)"/> <!-- PHP --> <s:RemoteObject id="employeeService " destination="zend" source="EmployeeService" endpoint="gateway.php" showBusyCursor="true" fault="employeeService_faultHandler(event)"/> <!--Java--> <s:RemoteObject id="employeeService " destination="employeeService" showBusyCursor="true" fault="employeeService_faultHandler(event)"/> </fx:Declarations>

You call a method of the server-side class by calling that method on this client-side object, for example,employeesService.getEmployees().

Remote procedure calls are asynchronous so you also need to specify listener functions, the callback functions to be invoked when a request returns a successful or unsuccessful response. For Flex remote procedure calls, you register to listen for result and fault events. Because a data service often has multiple methods that can be called and they can be called at different times in the application, the callback functions are usually specified on a per call basis instead of on the service object.

In this sample, a fault handler is specified for the RemoteObject but no result handler. This fault handler will be used for all service calls that do not have their own fault handler specified. The handler uses the Flex Alert component (which has a static show() method), to display a popup with the fault message. The FaultEvent object has a property called fault that is equal to an instance of the Fault class that has properties faultString andfaultDetail.

import mx.controls.Alert; import mx.rpc.events.FaultEvent; protected function employeeService_faultHandler(event:FaultEvent):void { Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail,"Error"); }

Note: Instead of using the RemoteObject class directly as in this sample, you can also use Flash Builder's Create Data Service wizard to create a data service and then call methods of a generated service class that wraps the RemoteObject class. Flash Builder introspects the server-side class file and creates a corresponding client-side class with the same operations. (For this introspection and code generation to occur, RDS must be enabled on your server.) If the server returns strongly typed objects (which is the case for the Java classes in this sample), ActionScript classes are created that map to the corresponding objects manipulated by the methods of the class. If the server returns general objects (which is the case for the PHP class and CFC in this sample), you can configure the data service to create typed ActionScript objects whose properties match those for the general objects returned from the server. Of course, you can also write your PHP classes and CFC methods to return strongly typed objects instead of general objects as well. After creation, the data service, its methods, its argument types, and its return types are displayed in the Data/Services view and methods can be dragged and dropped on components in the application to add them. The Flex Test Drive tutorials create and use data services created with the Flash Builder Data Service wizard.

Retrieving data

Next, let's look at the calls to the server. We want to retrieve the employee and department data on application startup. To do this, you usually specify an event handler for the Application object's initialize orcreationComplete events. Every Flex component has a series of events that are broadcast as the component is created, from the time it is instantiated until the time it is drawn on the Flash Player drawing surface. Theinitialize event is broadcast after the component has been created and all of its properties are set and those of its subobjects. creationComplete is broadcast later after the component and all its subobjects also have sizes and positions. Use creationComplete if any of the code references any sizes or positions.

In the sample code, a handler is specified for the Application's initialize event:

<s:Application initialize="init()" ...>

... and inside the handler, the getEmployees() and getDepartments() methods of the service object are called.

protected function init():void { getEmployeesResult.token = employeeService.getEmployees(); getDepartmentsResult.token = employeeService.getDepartments(); }

When this code is executed, Flash Player makes a call to the server. This happens asynchronously in the background; the user can still interact with the application. 
When you make a service call, you need to specify what Flash Player should do when it gets a result or error back from the server. A fault handler was specified for the data service itself and will be used to display errors returned from calls to any of its operations in a popup box.

Using call responders to specify callbacks

To handle successful results, CallResponder objects are declared for each of the calls.

<fx:Declarations> <s:CallResponder id="getEmployeesResult" .../> <s:CallResponder id="getDepartmentsResult"/> (...) </fx:Declarations>

These need to be associated with the corresponding service call. When a service call is initiated, an instance of the AsyncToken class is created. To associate the CallResponder object with the service call, you set the CallResponder'stoken property equal to the AsyncToken generated at the time the service call is made. When data is returned from the server, it is handled by that CallResponder.

getEmployeesResult.token=employeeService.getEmployees();

A CallResponder object has a lastResult property that automatically gets populated with the data when it is returned to Flash Player from the server. It can be easily used by binding a control to it. In the application, thedataProvider property of a DataGrid component is bound to the lastResult property of thegetDepartmentsResult CallResponder object. Whenever the value of getDepartmentsResult.lastResultchanges, the DataGrid's dataProvider property is updated and the DataGrid repopulates itself with the new data.

<s:DataGrid id="deptDg" dataProvider="{getDepartmentsResult.lastResult}" ...> <s:columns> <s:ArrayList> <s:GridColumn headerText="Name" dataField="name" /> <s:GridColumn headerText="ID" dataField="id" width="40"/> <s:GridColumn headerText="Manager" dataField="manager" width="170"/> <s:GridColumn dataField="budget" headerText="Budget" width="155"/> <s:GridColumn dataField="actualexpenses" headerText="Expenses" width="155"/> </s:ArrayList> </s:columns> </s:DataGrid>

By default, one column is created for each of the fields in the objects used to populate the DataGrid. You control what properties to display and in what order by setting the columns property equal to an ArrayList of GridColumn objects. For each DataGridColumn object, you specify what property it should display (dataField), the title for the column (headerText), its size, and more.

Using the CallResponder lastResult property works fine if you just want to bind the results to a component as shown here, but many times you will want to execute some code when the results are returned. To do this, you register to listen for the result or fault events for the CallResponder. In the sample, a result handler is registered for the getEmployeesResult CallResponder.

<s:CallResponder id="getEmployeesResult" result="getEmployeesResult_resultHandler(event)"/>

... and the getEmployeesResult_resultHandler() defined.

Handling return data

This application manipulates employee data. When you bind controls to collections of objects (as we just saw in thedeptDg DataGrid and will see next for the empDg DataGrid), the data should be strored in a Flex collection class. For example, instead of storing the employee data objects in an Array (a top level data type in Flash Player), you should use an ArrayList or ArrayCollection. The ArrayList and ArrayCollection classes basically wraps an Array so that when any value in any position of the array changes, an event is broadcast and any controls bound to it will be updated. If the objects were stored in an Array, even if it was made bindable, events would be broadcast only when the value of the entire array changed, for example, if it went from null to a value or was set to an entirely different value. Unlike an ArrayList, an ArrayCollection can also be sorted, filtered, and traversed with a cursor.

In this application, an employees ArrayCollection is defined in the Declarations block:

<s:ArrayCollection id="employees"/>

... which is equivalent to setting a public, bindable variable in ActionScript:

[Bindable]public var employees:ArrayCollection;

The dataProvider property of the empDg DataGrid is bound to this collection.

<mx:DataGrid id="empDg" dataProvider="{employees}" ...>

Inside this collection, we want to store strongly typed, bindable Employee objects, not general Objects. This way we will get code-hinting when manipulating these objects and compiler and runtime property and property type checking. These objects will also be bindable, so if any of their properties change, an event will be broadcast and any objects bound to it updated.

If you look in the valueObjects folder, you will see an Employee class definition.

package valueObjects { [Bindable] //if server was returning typed objects like for java, ///[RemoteClass(alias="services.Employee")] public class Employee { public var id:uint; public var firstname:String; public var lastname:String; //other property declarations public function Employee() { } } }

If the server-side class returns strongly typed objects (as does the Java class in this sample), you need to include a RemoteClass metadata tag that maps this ActionScript class to the corresponding class on the server.

[RemoteClass(alias="services.Employee")]

This is the crucial information needed by Flash Player so it can map the server-side objects to the correct client-side objects automatically. In this case, the getEmployeeResult_resultHandler() only needs to populate the employees ArrayCollection with the data returned from the server because the data has already been translated to an ArrayCollection of Employee objects.

protected function getEmployeesResult_resultHandler(event:ResultEvent):void { employees=event.result as ArrayCollection; }

The data returned from a server-side method call is stored in the result property of the event object that is passed to the result event handler. The employees variable is data typed as an ArrayCollection but the resultproperty of the event object is data typed as a general Object, so you have to cast event.result to an ArrayCollection to assign it to employees.

To see what types of ActionScript objects the returned server-side data objects are converted to, place a breakpoint inside the result handler and debug the application. You can also look at tables of the data type mappings forActionScript and JavaActionScript and PHP, or ActionScript and ColdFusion.

If Employee objects are not returned from the server (as is the case for the PHP class and CFC in this sample),getEmployeesResult_resultHandler() needs to create this collection of Employee objects manually. For PHP, you get an Array of Objects back from the server and for ColdFusion, an ArrayCollection of Objects. To convert the Objects into Employee objects, you need to loop through the collection, creating a new Employee instance for each item and populating its properties with the corresponding properties of the general Object, and then adding that Employee object to the collection. You could explicitly write each property assignment:

emp.id=data[i].id;
emp.firstname=data[i].firstname;
emp.lastname=data[i].lastname;
//do the same for all properties

... but this code instead uses the describeType() method (in the flash.utils package). describeType() returns an XML object that contains an accessor element (which has nameaccesstype, and declaredBy attributes) for each of object's properties. This is the ActionScript implementation of reflection.

For ColdFusion, the getEmployeesResult_resultHandler() appears as shown here.

protected function getEmployeesResult_resultHandler(event:ResultEvent):void { var data:ArrayCollection=event.result as ArrayCollection; for(var i:uint=0; i<data.length; i++) { var emp:Employee=new Employee(); for each(var field:XML in describeType(emp)..accessor){ emp[field.@name]=data[i][field.@name]; } employees.addItem(emp); } }

The ArrayColletion addItem() method is used to add the new employee to the employees ArrayCollection.

The handler is slightly different for PHP because you get an Array instead of an ArrayCollection back from the server.

protected function getEmployeesResult_resultHandler(event:ResultEvent):void { var data:ArrayCollection=new ArrayCollection(event.result as Array); for(var i:uint=0; i<data.length; i++) { var emp:Employee=new Employee(); for each(var field:XML in describeType(emp)..accessor){ emp[field.@name]=data[i][field.@name]; } employees.addItem(emp); } }

Displaying details

When the user selects an employee in the DataGrid, that employee's details are displayed beneath it. In theDeclarations block, you'll see an employee variable defined of type Employee (that is bindable by default).

<valueObjects:Employee id="employee"/>

Beneath the Declarations block, you'll see a Binding tag:

<fx:Binding source="empDg.selectedItem as Employee" destination="employee"/>

This is just another way to create a binding between two variables without using {} in an MXML tag. Whenever theselectedItem property of empDg changes, the employee variable is updated.

As well, there is code to listen for the DataGrid's selectionChange event:

<s:DataGrid id="empDg" dataProvider="{employees}" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate,Employees" selectionChange="empDg_selectionChangeHandler(event)" ...>

Inside the selectionChange handler, you switch to the application's EmployeeDetails state:

protected function empDg_selectionChangeHandler(event:GridSelectionEvent):void{ currentState="EmployeeDetails"; }

... that includes a Form container that has one Label control for each of the employee object's properties.

<s:Form includeIn="EmployeeDetails" x="63" y="325"> <s:FormItem label="Last Name"> <s:Label id="lastnameLabel" text="{employee.lastname}"/> </s:FormItem> <s:FormItem label="First Name"> <s:Label id="firstnameLabel" text="{employee.firstname}"/> </s:FormItem> (...) </mx:Form>

The employee details will be displayed in the Label controls in the Form. A Flex Form container is purely a layout container, helping to easily line up multiple controls that have labels in front of them; it has no other purpose like in an HTML form. When you send data to the server which we will look at next, you specify explicity what objects to send; they have nothing to do with Form components.

Now that we have seen how to retrieve and display data from the server, let's look at how to modify this data on the server, updating, adding, and deleting records in the database. You may want to go look at your application server's class file (or CFC) now to familiarize yourself with the methods it contains before looking at the code to call these methods. If you installed the files, you can look at the source code on your server. Otherwise, you can right-click the SWF in the browser, select View Source, and browse to the appropriate PHP class, Java class, or CFC.

Using the DataGrid to update data

One way to let users update the data is to make the DataGrid editable and then to send the changes to the server. You make the DataGrid editable by setting its editable property to true and then registering to listen for itsgridItemEditorSessionSave event which is broadcast when the user makes changes to a cell value.

<s:DataGrid id="empDg" dataProvider="{employees}" editable="true" gridItemEditorSessionSave="empDg_gridItemEditorSessionSaveHandler(event)" ...>

Inside the handler, you need to send the modified Employee instance to the server: call the updateEmployee()method and pass to it the selected item in the DataGrid.

employeeService.updateEmployee(employee);

For ColdFusion, you need to modify this slightly. When you pass an object to a Flash Remoting request, it is treated as a group of named arguments and passed to the CFC method as individual arguments, not as a single object argument. To actually pass a single object as an argument, you must create an Object instance with the name of the argument expected by the CFC, in this case an argument called item, and pass that to the server-side method. The {} here are are an ActonScript short hand notation for creating an Object; multiple name/value pairs would be separated by commas.

employeeService.updateEmployee({item:employee});

In this case, you're not going to do anything after the data is successfully updated so you don't need to specify a CallResponder to handle the results.

In this application, updates are sent to the server every time the user changes data in one DataGrid cell. If a lot of changes are going to be made, you may want to wait and submit all changes to the server at once.

Using a form to update data

Only some of the employee data is displayed in the DataGrid, so you may also want to provide a form for the user to modify all of the employee data.
When an employee is selected and the EmployeeDetails state displayed, an update button is enabled.

<s:Button id="updateBtn" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate" label="Update" enabled.EmployeeAdd="false" enabled.EmployeeUpdate="false" click="updateBtn_clickHandler(event)" .../>

When the user clicks this button, the application switches to its EmployeeUpdate state:

protected function updateBtn_clickHandler(event:MouseEvent):void{ currentState="EmployeeUpdate"; }

... that has a Form containing one TextInput control for each of the employee properties that can be updated.

<s:Form includeIn="EmployeeAdd,EmployeeUpdate" defaultButton="{button}"...> <s:FormItem label="Last Name"> <s:TextInput id="lastnameTextInput" text="{employee.lastname}"/> </s:FormItem> <s:FormItem label="First Name"> <s:TextInput id="firstnameTextInput" text="{employee.firstname}"/> </s:FormItem> <!-- more FormItem controls --> <s:FormItem> <s:Button id="button" label="Add" click="button_clickHandler(event)" label.EmployeeUpdate="Update"/> </s:FormItem> </s:Form>

When the user clicks this button in the Form container, the employee object is updated with the values the user entered in the input controls and then passed to the data service's updateEmployee() method.

protected function button_clickHandler(event:MouseEvent):void { employee.lastname = lastnameTextInput.text; employee.firstname = firstnameTextInput.text; employee.title = titleTextInput.text; //code to set the rest of the properties if(employee.id==0){ //for Java and PHP createEmployeeResult.token = employeeService.createEmployee(employee); //for CF, createEmployeeResult.token = employeeService.createEmployee({item:employee}); } else{ //for Java and PHP updateEmployeeResult.token = employeeService.updateEmployee(employee); //for CF, updateEmployeeResult.token = employeeService.updateEmployee({item:employee}); } }

Similar functionionality will be used to add a new employee next, so this function has been written to handle both cases. If an existing employee is being updated, employee.id will be non-zero, so the server-sideupdateEmployee() method is called. Otherwise, the createEmployee() method is called. As before, the code for ColdFusion is slightly different to pass an object to a server-side method.

In this case, we do want to do something after the data has successfully been sent to the server, so a new CallResponder is defined with a result handler:

<s:CallResponder id="updateEmployeeResult" result="updateEmployeeResult_resultHandler(event)"/>

... and the service call assigned to the CallResponder's token property.

updateEmployeeResult.token=employeeService.updateEmployee(employee);

In the result handler, the application switches to its EmployeeDetails state and shows the details for the modified employee.

protected function updateEmployeeResult_resultHandler(event:ResultEvent):void { currentState="EmployeeDetails"; }

Using the form to add data

Similar code is used to add a new employee to the database. When an employee is selected, an add button is enabled.

<s:Button id="addBtn" label="Add" click="addBtn_clickHandler(event)" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate,Employees" enabled.EmployeeAdd="false" enabled.EmployeeUpdate="false" .../>

When the user clicks this button, the application switches to its EmployeeAdd state, which shows the same form as used to update an employee, but now the submit button is labeled Add instead of Update.

protected function addBtn_clickHandler(event:MouseEvent):void { currentState="EmployeeAdd"; employee=new Employee(); }

Using the form to add data

Similar code is used to add a new employee to the database. When an employee is selected, an add button is enabled.

<s:Button id="addBtn" label="Add" click="addBtn_clickHandler(event)" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate,Employees" enabled.EmployeeAdd="false" enabled.EmployeeUpdate="false" .../>

When the user clicks this button, the application switches to its EmployeeAdd state, which shows the same form as used to update an employee, but now the submit button is labeled Add instead of Update.

protected function addBtn_clickHandler(event:MouseEvent):void { currentState="EmployeeAdd"; employee=new Employee(); }

The employee object is also set equal to a new Employee instance (employee could currently contain the employee selected in the DataGrid) so the input controls in the Form container that are bound to it will all be set to the Employee class's default values.

The same handler is called when the user clicks the button in the form:

<s:FormItem> <s:Button id="button" label="Add" click="button_clickHandler(event)" label.EmployeeUpdate="Update"/> </s:FormItem>

... which populates employee with the data from the input controls and now in this case, employee.id will be zero so employee is passed to the data service's createEmployee() method.

protected function button_clickHandler(event:MouseEvent):void { employee.lastname = lastnameTextInput.text; employee.firstname = firstnameTextInput.text; employee.title = titleTextInput.text; //code to set the rest of the properties if(employee.id==0){ //for Java and PHP createEmployeeResult.token = employeeService.createEmployee(employee); //for CF, createEmployeeResult.token = employeeService.createEmployee({item:employee}); } else{ //for Java and PHP updateEmployeeResult.token = employeeService.updateEmployee(employee); //for CF, updateEmployeeResult.token = employeeService.updateEmployee({item:employee}); } }

To handle results, a new CallResponder is defined with a result handler:

<s:CallResponder id="createEmployeeResult" result="createEmployeeResult_resultHandler(event)"/>

... and the service call assigned to the CallResponder's token property.

createEmployeeResult.token=employeeService.createEmployee(employee);

After the data is added successfully to the database, the EmployeeDetails state is shown with the details for this new employee.

protected function createEmployeeResult_resultHandler(event:ResultEvent):void { currentState="EmployeeDetails"; // more code }

At this point the new employee is saved in the database, but not in the collection of data being displayed in the DataGrid. You need to assign the newly generated id to employee and add employee to the data displayed in the DataGrid.

If you look in the TestDrive server-side service file, you will see that the createEmployee() method returns an integer equal to the id of the new employee inserted in the database. The data returned from a server-side method call is stored in the result property of the event object that is passed to the result event handler. The idproperty of employee is data typed as an integer and the result property of the event object is data typed as a general Object, so you have to cast event.result to an integer to set id equal to it.

employee.id=event.result as int;

You use the addItem() method to add the new employee to the employees ArrayCollection.

employees.addItem(employee);

Note: In this example, you are writing code to update both the server-side data (stored in the database) and the client-side data (stored in the DataGrid dataProvider). Flash Builder also has a data management feature you can use to help synchronize client and server-side data.

Then, you select it in the DataGrid:

empDg.setSelectedIndex (employees.getItemIndex(employee));

... and then scroll to it so it is displayed:

empDg.ensureCellIsVisible(empDg.selectedIndex);

The result event handler for adding an employee appears as shown here.

protected function createEmployeeResult_resultHandler(event:ResultEvent):void { currentState="EmployeeDetails"; employee.id=event.result as int; employees.addItem(employee); empDg.setSelectedIndex(employees.getItemIndex(employee)); empDg.ensureCellIsVisible(empDg.selectedIndex); }

Deleting data

The last thing to look at is how to delete an employee from the database. The process is very similar to those for adding and updating. When an employee is selected, a delete button is enabled.

<s:Button id="deleteBtn" click="deleteBtn_clickHandler(event)" enabled.EmployeeAdd="false" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate" label="Delete" enabled.EmployeeUpdate="true"/>

When the user clicks this button, the server-side deleteEmployee() method is called.

protected function deleteBtn_clickHandler(event:MouseEvent):void { deleteEmployeeResult.token = employeeService.deleteEmployee(employee.id); }

To handle results, a new CallResponder is defined with a result handler:

<s:CallResponder id="deleteEmployeeResult" result="deleteEmployeeResult_resultHandler(event)"/>

... and the service call assigned to the CallResponder's token property.

deleteEmployeeResult.token=employeeService.deleteEmployee(employee.id);

The server-side method expects one argument, the id of the employee to delete.

In the result handler, the employee is removed from the employees ArrayCollection using its removeItemAt()method and the application is switched to its Employees state (there is no longer any employee selected to show details for).

protected function deleteEmployeeResult_resultHandler(event:ResultEvent):void { employees.removeItemAt(empDg.selectedIndex); currentState="Employees"; }
:
Posted by 라면스프
2011. 11. 1. 09:17

[FLEX]플래시(Flash) 소켓(Socket) 레퍼런스 Enjoy/FLEX2011. 11. 1. 09:17




패키지 :loadClassListFrame('class-list.html')">flash.net
클래스 public class Socket
상속 Socket Inheritance EventDispatcher Inheritance Object
구현 IDataInputIDataOutput

언어 버전:  ActionScript 3.0
런타임 버전:  AIR 1.0, Flash Player 9

Socket 클래스는 ActionScript 코드를 활성화하여 소켓 연결을 만들고 원시 이진 데이터를 읽고 쓸 수 있도록 합니다. XMLSocket과 유사하지만, 수신된 또는 전송된 데이터의 형식을 지정하지는 않습니다.

소켓 클래스는 이진 프로토콜을 사용하는 서버와의 작업에서 유용합니다.

Socket 클래스의 메서드를 사용하려면 우선 생성자인 new Socket을 사용하여 Socket 객체를 만들어야 합니다.

local-with-filesystem 샌드박스의 SWF 파일은 소켓을 사용할 수 없습니다.

대상 호스트의 소켓 정책 파일은SWF 파일에서 소켓 연결을 만들 수 있는 호스트 및 가능한 대상 포트를 지정합니다. Flash Player의 버전이 올라가면서소켓 정책 파일에 대한 보안 요구 사항이 보다 엄격해졌습니다. 모든 버전의 Flash Player에서 소켓 정책 파일을 사용하는것이 좋습니다. 소켓 정책 파일이 필수적인 경우도 있습니다. 따라서 XMLSocket 객체를 사용할 때는 필요한 경우 대상호스트가 소켓 정책 파일을 제공하는지 확인해야 합니다.

다음 목록에서는 여러 버전의 Flash Player에서 소켓 정책 파일에 대한 요구 사항을 보여 줍니다.

  • Flash Player 9.0.124.0 이상에서는 모든 Socket 연결에 소켓 정책 파일이 필요합니다. 즉, 연결하는 포트에관계없이 대상 호스트에 소켓 정책 파일이 있어야 하며, SWF 파일을 제공하는 해당 호스트의 포트에 연결하는 경우에도마찬가지입니다.
  • Flash Player 9.0.115.0 이전 버전에서는 1024보다 낮은 포트 번호에 연결하거나 SWF 파일을 제공하는 호스트와 다른 호스트에 연결하려는 경우 대상 호스트에 소켓 정책 파일이 있어야 합니다.
  • Flash Player 9.0.115.0에서는 소켓 정책 파일이 필수적이지 않지만 대상 호스트에서 소켓 정책 파일을 제공하지 않으면 Flash Debug Player를 사용할 때 경고가 표시됩니다.

보안과 관련된 자세한 내용은 다음을 참조하십시오.

  • 보안 장(ActionScript 3.0 프로그래밍 설명서) 및 LiveDocs의 최신 의견
  • Flash Player 개발자 센터 항목: 보안

예제 보기



Public 속성
 속성다음에 의해 정의됨
    bytesAvailable : uint
[읽기 전용] 입력 버퍼에서 읽을 수 있는 데이터 바이트 수입니다.
Socket
    connected : Boolean
[읽기 전용] 이 소켓 객체가 현재 연결되어 있는지 여부를 나타냅니다.
Socket
  Inherited constructor : Object
지정된 객체 인스턴스의 클래스 객체 또는 생성자 함수에 대한 참조입니다.
Object
    endian : String
데이터의 바이트 순서를 나타냅니다. flash.utils.Endian 클래스에서 Endian.BIG_ENDIAN 또는 Endian.LITTLE_ENDIAN 상수 값을 가질 수 있습니다.
Socket
    objectEncoding : uint
객체를 쓰거나 읽을 때 사용되는 AMF 버전을 제어합니다.
Socket
  Inherited prototype : Object
[정적] 클래스 또는 함수 객체의 프로토타입 객체에 대한 참조입니다.
Object
    timeout : uint
연결을 기다릴 시간(밀리초)를 나타냅니다.



[보안정책 참고용] 
Flash Socket(소켓) Policy(보안) 정책
 
http://cafe.naver.com/q69/117152 http://www.jcraft.com/jhttptunnel/index.html

 
:
Posted by 라면스프

출처 : http://joongang.joinsmsn.com/article/aid/2011/11/01/6201181.html?cloc=nnc

노후 갉아먹는 은행 연금의 불편한 진실
 

#1 회사원 강인규(45)씨는 얼마 전 신한은행에서 날아온 ‘신탁재산운용보고서’를 보고 가슴이 철렁했다. 노후 대비와 절세를 위해 2005년부터 월 25만원씩 넣고 있는 안정형 연금신탁의 올 수익률이 1.13%에 불과했기 때문이다. 강씨는 “은행 정기예금에 들어도 4% 안팎의 금리를 주는데 어떻게 운용했길래 수익률이 이런지 이해가 되지 않는다”며 “만기가 10여 년 남았는데 지금이라도 보험사나 자산운용사 상품으로 갈아타야겠다”고 말했다.

 #2 1994년 한 시중은행 개인연금신탁에 가입한 이경자(56)씨는 지난 7월 첫 연금을 받아보고 눈앞이 막막해졌다. 10년간 나눠받는 월 연금액이 102만원에 불과했기 때문이다. 은행에선 “글로벌 금융위기 이후 저금리가 지속돼 최근 4년간 수익률이 연 3%대에 머물렀다”고 설명했다. 이씨는 남은 금액을 앞당겨 찾아 타 금융권의 상품에 넣을 계획이다.

 대표적인 노후대비 상품인 은행 연금상품이 오히려 고객의 노후를 갉아먹고 있다. 수익률이 형편 없고, 그마저 연도별로 편차가 극심하다. 운용실력이 없거나 운용에 별 신경을 쓰지 않는다는 말이다. 그런데도 은행들은 채권형 펀드와 비슷한 수수료를 꼬박꼬박 떼가고 있다.

은행 연금상품은 연말정산 때 연 72만원의 소득공제 혜택을 주고 수익에 대해 전액 비과세하는 ‘개인연금신탁(구 개인연금)’과 연 400만원을 소득공제 해주되 수익의 일부에 과세하는 ‘연금저축신탁(신 개인연금)’ 등 두 가지다. 구 개인연금은 2000년 이후 판매가 중단됐고 현재는 신 개인연금만 가입할 수 있다.

 연금상품의 수익률은 한숨이 나올 지경이다. 가장 많이 판매된 국공채형을 기준으로 한 최근 3년 수익률은 연평균 3%대에 불과하다. 9월 말을 기준으로 기업은행과 국민은행·신한은행 정도만 4%를 겨우 넘겼다. 산업은행(2.06%)·SC제일은행(2.52%)·씨티은행(3.31%)·하나은행(3.4%) 등은 정기예금의 세후 수익률(약 3.6%)에도 못 미치는 성적을 내고 있다. 신 개인연금은 사정이 더 나쁘다. 올해 국공채형 평균 수익률이 2.77%에 머물렀다. 한 시중은행의 연금팀장은 이에 대해 “연금형 신탁상품은 90% 이상을 채권에 주로 투자하는데 시장 금리 자체가 낮아 운용을 아무리 잘해도 수익률이 낮을 수밖에 없다”고 설명했다. 하지만 같은 기간 채권수익률(KIS채권종합지수)은 은행의 운용 수익률보다 한참 높다. <그래픽 참조>

 은행들은 수익률이 낮은 대신 ‘안정적’이라는 것을 장점으로 내세우고 있다. 채권으로 주로 운용하다 보니 고수익보다는 꾸준한 수익을 목표로 한다는 것이다. 하지만 이 말을 믿기엔 수익이 너무 들쭉날쭉하다. 올해 성과가 가장 좋은 기업은행의 구 개인연금은 2008~2009년엔 업계에서 가장 저조한 연2%의 실적을 기록했다. 반대로 산업은행의 구 개인연금 평균배당률은 2008년 4.5%에서 2010년 2.1%로 반 토막이 났다. “투자한 채권을 발행한 회사가 부도나는 바람에 손실을 입었다”는 게 은행 측의 해명이다.

신 개인연금 역시 마찬가지다. 국민은행의 국공채형 1호의 수익률은 2008년 7%대에서 2009년 2%대, 지난해 4%, 올해 2%로 오락가락하고 있다. 신 개인연금에 가입한 회사원 서진원(49)씨는 “작은 차이에도 연금수령액에는 상당한 차이가 나지 않겠느냐”며 “더 운용을 잘하는 곳으로 옮기고 싶어도 은행마다 수익률이 들쭉날쭉해 선택하기가 어렵다”고 말했다.

 고객이 답답해도 은행은 느긋하다. 수익이 아니라 신탁자산의 일정 비율을 떼는 수수료(신탁보수율) 구조 때문이다. 현재 은행들은 상품의 수익률과 관계없이 해마다 원금의 1% 가량을 챙겨가고 있다.

고객의 일반 채권형 펀드의 신탁보수와 똑같은 수준이다. 이런 구조에선 고객의 수익률이 1% 높아져도 은행이 추가로 얻을 수 있는 수수료 수입은 0.1%에 불과하다. 은행으로선 열심히 운용할 필요를 굳이 느끼지 못하는 것이다. 조연행 금융소비자연맹 부회장은 “위험이 전혀 없는 정기예금 금리에도 못 미치는 실적을 내면서 꼬박꼬박 수수료를 챙기는 건 은행의 도덕적 해이”라고 지적했다. 이장혁(경영학) 고려대 교수도 “낮은 수익성과 높은 수수료는 국가가 세금 혜택을 통해 국민에게 보장하려는 노후를 중간에서 가로채는 셈”이라고 비판했다.

 이렇다 보니 은행 개인연금의 인기도 떨어지고 있다. 개인연금 시장은 2006년 이후 해마다 평균 12%가량의 고성장을 계속하고 있다. 하지만 은행 개인연금은 같은 기간 중 11조560억원에서 11조3200억원으로 사실상 제자리걸음을 했다. 보험과 자산운용사의 개인연금이 두세 배 커진 것과는 대조적이다. 박덕배 현대경제연구원 연구위원은 “은행의 연금상품은 원금을 안전하게 보관하는 것 외에는 의미가 없게 됐다”며 “은행이 노력하지 않아도 수수료는 챙길 수 있는 구조를 바꿀 필요가 있다”고 지적했다.


나현철·김혜미 기자.
:
Posted by 라면스프
2011. 10. 10. 13:21

[ORACLE] 경과된 시간 날짜 계산 Enjoy/ORACLE2011. 10. 10. 13:21

날짜와 날짜 사이 경과 시 분 초 구하는 예제.

select TRUNC((to_date('20111010100203','yyyymmddhh24miss')-to_date('20111009090000', 'yyyymmddhh24miss'))*24) || ' hour ' || 

       TRUNC(mod((to_date('20111010100203','yyyymmddhh24miss') - to_date('20111009090000', 'yyyymmddhh24miss'))*24,1)*60) || ' minute ' ||

       TRUNC(round(mod((to_date('20111010100203','yyyymmddhh24miss') - to_date('20111009090000', 'yyyymmddhh24miss'))*24*60,1)*60)) || ' second '

from dual
;

아래는 참고한 사이트


출처 : http://cafe.naver.com/coolkkm1/19



- 시간구하기

select (to_date('1800', 'hh24mi') - to_date('0900', 'hh24mi'))*(24*60*60 )
 from dual;

to_date 로 계산후

(24 -- 시간표시

*60 -- 분표시

*60 ) -- 초표시

 

- 현재시간에 시간 추가하기

select sysdate,sysdate+1/(24*60)*10 from dual

 

sysdate+1은 1일 이후입니다.

그래서 1/(24*60)은 1분입니다.

10을 마지막에 곱하면 10분이죠 ^^

일 가(감) 산 SYSDATE + 1

시간 가(감) 산 SYSDATE + 1/24

분 가(감) 산 SYSDATE + 1/24/60

초 가(감) 산 SYSDATE + 1/24/60/60

 

-- 날자와 날짜사이의 시간 구하기
select to_date('2005050309','yyyymmddhh')-to_date('2005050409', 'yyyymmddhh'))*24
from dual;
;
                               
-- 날짜에 시간더하기
select to_char(to_date('200305021120', 'yyyymmddhh24mi'),  'yyyymmddhh24mi'),
to_char(to_date('200305021120', 'yyyymmddhh24mi') + (115/1440), 'yyyymmddhhmi') from dual;

 

-- 날짜수 구하기
select
  to_date('20050301', 'yyyymmdd')+1 - to_date('20050225', 'yyyymmdd')
from dual;
->여기서 하루치를 더한거는 그마지막 날을 포함하기 위해 하루를 더해야한다

 

-- 개월수 구하기
select months_between(to_date('20050131', 'yyyymmdd'), to_date('20010201', 'yyyymmdd')) from dual;

 

-- 그달의 마지막 날짜 구하기
select to_char(last_day(to_date('20040201','yyyymmdd')), 'yyyymmdd')
from dual;

select to_char(last_day(to_date('20040201','yyyymmdd')), 'mm')
from dual;

select to_char(last_day(to_date('20040201','yyyymmdd')), 'dd')
from dual;

 

-- 하루를 더추가하고 2달 뒤의 일자구하기
select to_char(add_months(to_date('20050201','yyyymmdd')+1, 2), 'yyyymmdd')
from dual;

 

-- 하루를 더추가하고 2달 앞의 일자구하기
select to_char(add_months(to_date('20050201','yyyymmdd')+1, 2), 'yyyymmdd')
from dual;


-- 해달일부터 2달 뒤의 일자구하기
select to_char(add_months(to_date('20050201','yyyymmdd'),2), 'yyyymmdd')
from dual;

 

- months_between : 두날짜간의 달수 구하기

select  months_between (to_date('20050201','yyyymmdd'), to_date('20050101', 'yyyymmdd'))
from dual;

 

- next_day 특정날자에서 가장가까운 요일의 날자 찾기

select next_day(to_date('20050101','yyyymmdd'), '일') from dual

 

TRUNC 함수의 제2 인수에'day'를 이용하면…….

SQL> select TRUNC(SYSDATE,'day') from dual;

TRUNC(SY
--------
05-02-13
리스트 4 이번 주의 주처음의 날을 취득

 

이러한 방법으로 간단하게 주의 처음의 날을 취득할 수 있습니다. 물론 SYSDATE 함수 대신에, SYSTIMESTAMP 함수를 사용할 수도 있습니다.다만, DATE형으로 변환되는 것은 기억해 둘 필요가 있습니다.

날짜 데이터로 TRUNC 함수를 사용하는 경우, 제2 인수에는'day'외에도 몇개인가 지정할 수 있습니다.메뉴얼을 확인하삼!!

 

TRUNC 함수를 사용한 샘플 SQL를  1개들어 둡니다.제목은 「이번 달의 제n○요일을 취득한다」

select decode(TRUNC(get_date,'mm'),TRUNC(SYSDATE,'mm'),get_date,null)
from (
select decode(TRUNC(TRUNC(TRUNC(SYSDATE,'mm'),'day') + :youbi -1,'mm')
             ,TRUNC(SYSDATE,'mm')
             ,TRUNC(TRUNC(SYSDATE,'mm'),'day') + :youbi -1
             ,TRUNC(TRUNC(SYSDATE,'mm'),'day') + :youbi -1 + 7)
      + (:nambanme - 1) * 7 get_date
from dual)
리스트 5 이번 달의 제n○요일을 취득한다

 

- sysdate = 19950725

-  round(sysdate, 'month') -> 19950801

-  round(sysdate,'year') -> 19960101

-  trunc(sysdate, 'month') -> 1950701

-  trunc(sysdate, 'year') -> 19950101

 

- 형식

 scc , cc : 세기 표현

 year : 년도를 영어로 표현

yyyy, yyy, yy, y : 년도를 자릿수로 자른다

bc, ad : 서기 등으로 표시

q : 분기 표시

mm : 두자리로 월표시

month: 영어로 표시

mon: 영어로 3자리로 월표시

rm: 로마자로 표시 i, ii. xi

ww: 1년기준 몇째주 표시

w:한달기준 몇째주 표시

ddd: 365(1년기준 ) 의 몇째 일

dd: 날짜를 두자리로 표시

d: 요일을 숫자로 표시

dy : 요일 한자리로 표시

day: 요일 표시

am, pm, a.m. , p.m. : 오전오후 표시

hh, hh12 : 12시 기준으로 표시

hh24 : 24시 기준으로 표시

/, "of" : 날짜의 중간에 문자 표시 -> to_char(to_date('19951201', 'yyyymmdd'),'yyyy "of" mm/dd')

spth : 날짜를 영문 서수로 표시

sp : 날짜를 영문 숫자로 표시

 





출처 : http://blog.naver.com/uhjinmo/80021617480


-- 두 날짜(date type)사이의 시분초 계산하기

-- 한 레코드에 속하지 않은 각각의 Attribute인 경우를 가정함

 

-- 간단히 시간계산은

 

-- 첫째 방법
select (A.endtime - B.starttime) * (24*60*60)
from (select endtime
        from iptimetable where marketclass = 1
        ) A
     , (select starttime
        from iptimetable where marketclass = 2
        ) B     ;

 

-- 두번째 방법
select to_char((A.endtime - B.starttime) * (24*60*60),'099999')
from (select endtime
        from iptimetable where marketclass = 1
        ) A
     , (select starttime
        from iptimetable where marketclass = 2
        ) B     ;

 

-- 시분초로 변환
select trunc(mod((A.endtime - B.starttime)*24,1)*60) || ' 분 ' ||
trunc(round(mod((A.endtime - B.starttime)*24*60,1)*60)) || ' 초 '
from (select endtime
        from iptimetable where marketclass = 1
        ) A
     , (select starttime
        from iptimetable where marketclass = 2
        ) B     ;

 

-- 일,시간,분,초로 표현
select trunc(A.endtime - B.starttime) || ' day ' ||
trunc(mod((A.endtime - B.starttime),1)*24) || ' hour ' ||
trunc(mod((A.endtime - B.starttime)*24,1)*60) || ' minute ' ||
trunc(round(mod((A.endtime - B.starttime)*24*60,1)*60)) || ' second '
from (select endtime
        from iptimetable where marketclass = 1
        ) A
     , (select starttime
        from iptimetable where marketclass = 2
        ) B     ;

 

-- 또 다른 표현

SELECT FLOOR((to_time - from_time)*24) hh, 
( (to_time - from_time)*24 - FLOOR((to_time - from_time)*24) )*60 mm 
FROM (SELECT to_date('17:00','hh24:mi') to_Time, to_date('8:30','hh24:mi') from_Time FROM dual)

 

:
Posted by 라면스프
2011. 9. 28. 15:12

파탸야 뭄 아러이 It's Me2011. 9. 28. 15:12


 

태국

아시아

기간:2010.09.16 ~ 2010.09.23 (7박 8일)

컨셉:어슬렁어슬렁 대충 다니는 여행

경로:방콕파타야

 

TIP  
 

노선 성태우를 이용해서 다녀와보세요. 센트럴 비치와는 또다른 파타야의 풍경을 볼 수 있답니다.

 

파타야의 나끄아 비치에 있는 해산물 레스토랑 << 뭄 아러이 >>

 

인터넷 검색을 해보니 "구석에 있는 맛있는 집"이라는 뜻을 품은 이름이라고...

방콕에서 3박을 마치고, 파타야로 와서 첫식사는 이 구석을 찾아가보기로 했다.

파타야에서는 성태우택시를 타면 어디든지 쉽게 갈 수 있지만, 현지 교통 시스템상 택시가 버스처럼도 사용이 가능하므로,

노선 성태우를 이용해서 가기로 했다.

물론 가격은 얼마 차이 안난다...100밧과 20밧의 차이? ...

둘이가면 1,6백원과 4천원이지만, 현지에서는 걍 현지사람처럼 해보고 싶은 오기가 생기더라는...

 

돌핀상 근처 우드랜드 앞에서는 나끄아 방향으로 가는 성태우가 많이 서있다..

"뭄아러이"..외치니 20밧을 부르고, 노선성태우가 가는 곳은 아닌 듯 하나, 20밧 내면 그냥 약간 멀리 뭄아러이까지 가주는 듯 했다.

뭐 노선의 제일 끝에서 내려서 걸어가도 그닥 먼거리는 아니므로...

 

롱비치 호텔을 지나...

 

커다란 쏘니 간판을 지나 돌핀상에서부터 약 15분 정도 가다보면 좀 큰 세븐일레븐이 코너에 있다.

원래 노선은 저곳을 순환하는 듯 하나,

친절한 우리 아저씨는 약 5분 정도 더 가서 뭄아러이까지 데려다 주시더라는...

 

<<뭄아러이 정문>>

뭄아러이의 저녁 노을에 대한 이야기를 익히 들어본지라, 해지는 뭄아러리 앞에서 부랴부랴 입장.

 

식당은 겉으로 보는 것보다 큰 규모였고, 들어가니 한가운데 저렇게 나무들로 인테리어가 되어 있으며,

누군가가 수영을 하기는 하는 곳인지 궁금한 수영장이 꽤 멋드러지게 나무의 조명들을 반사해서 새로운 조명을 만들어 준다...

 

일단 테이블에서 음식을 주문하고, 얼음 동동 맥주 한모금한 다음 주변을 둘러보니..

 




역시 소문듣던대로 노을이 끝내준다. 2009년에 가본 캐비지 앤 콘톰에서 바라본 노을보다 더 낫다..

잔잔하게 들리는 파도소리는 베이스 뮤직으로 깔리고...
이젠 정말 휴가온 거 같다...이럴려고 돈 버는 구나...열심히 돈 벌어야지...하는 생각이 마구마구 들더라는...^^


새우 요리와 똠양꿍, 흰밥, 볶음밥 골고루 시켰는데,

맛도 괜찮고 가격도 저렴하다....오래되서 기억은 정확히 안나지만 각 요리당 200밧이 좀 넘었던 것 같다...

앞에 갔던 크레페 & 코 보다는 훨씬 저렴했던 걸로 ..

 

바닷바람 솔솔 부는 풍경 멋진 곳에서 맥주 한잔 마시고 맛있는 해산물 요리와,,,맛있는 똠양이랑.....

완전 행복 만취였던 저녁.

 

 

 

뭄아러이가 워낙 구석에 있다보니 성태우 잡기가 쉽지는 않은 듯 하고..

물론 기다리다가 들어오는 성태우를 타면 된다는 이야길 들었지만, 무작정 기다리기도 어정쩡해서 그냥 슬슬 걸어가보기로 했다.

 

이런 다리를 건너다보면, 한쪽은 바다 한쪽은 민가인듯...불빛들이 보인다...

 

그런데 어디 골목선가 들려오는 풍악(?) 소리...

작은 마을 축제(?)를 열고 있었는데, 가수들이 한창 공연중이었고 사람들은 작은 관중석에 앉아서 구경중이고...

이 게이 가수들 뒤타임에 뭔가 공연이 있는 듯 하던데, 너무 노래 길게 하셔셔 그냥 여기까지만 보고 다시 가던 길을...

카오산에서 판다는 연탄토스트...예상치 못하게 여기서 만나니 반갑더라는..

 뭄아러이에서 이미 배터지게 잡수고 나온뒤라 맛보지는 못하고..

 

이방인인 우리를 향해 환한 미소를 지어주시는 어여뿐 파타야 소녀..

 

여행은 역시 미처 기대하지 못한 소소한 사건에서서 더 큰 기쁨을 맛볼 수 있는 것 같다...

뭄아러이의 저녁 노을도 좋았지만, 파탸야 센트럴 비치와는 다른 분위기의 또 다른 파타야의 일면을 볼 수 있어서 더욱 좋았던 밤..

 

오늘 문득..그 밤이...그 밤의 시원한 바람이..새로운 경험으로 들떴던 기분이...그리워진다...

:
Posted by 라면스프
2011. 9. 28. 15:09

파타야 뭄 아러이 It's Me2011. 9. 28. 15:09

* 이 때만 해도...펜 따위는 없었기 때문에 사진이 아주 구리고....
사진이 구리다 보니...찍기도 싫었고.... 찍기 싫으니 가방에서 꺼내지도 않았고...
꺼내지도 않으니..구경하기만 바빴고... 사실 새로운 세상에 정신이 없어서 사진 찍는걸 깜빡하기도 했다.
그러므로 4월에 배낭여행가서 멋진 사진을 찍어올것을 기대하며....

*이 여행기는 정보 따위 아무것도 없으며 그냥 잊지 않기위해 혼자 위안삼는 후기 일 뿐임을 거듭 강조합니다.
있을지 없을지 모를 정보는 색칠해놨어요~ 

2009.08.24 파타야의 밤

태국을 오면서 다짐한게 있다. 해산물 비린내나도록 먹기!!! ㅎㅎ
앞서 말했듯이 이번여행은 휴가를 내서 온거므로 휴양이 목적!!!! 돈 생각 안하고 그냥 막 먹기로했다.

파타야에서 유명한 '뭄 아러이'라는 레스토랑이 있다. 2곳에 위치하고 있는데
나끌르아 지역쪽은 야외 레스토랑이어서 바로 옆에 바다를 보며 식사를 할 수 있다. 그러므로 노을이 질 때 
가면 사이드 자린 하나도 없을 정도...그리고 싸이삼에 하나 더 있지만 여긴 바다는 볼 수 없다.
그럼 답은 나왔다. 바다가 있는 나끌르아로!!! 북파타야에서 멀지 않은 곳에 있었으므로 쉽게 갈 수 있었다.
자주 본 아주머니 택시를 타고 갔다. 150밧



쏨땀 + 깡텃끄라티엠 + 똠양꿍 + 맥주 라지~~~ 825밧

쏨땀은 파파야로 만든 태국식 샐러드이다. 파파야의 씹는 맛이 좋다.
그리고 깡텃끄라티엠은 돌가재 튀김이다..마늘향이 나는게 아주 굿!! 살도 오동통했다.
똠양꿍은 다들 알다시피 세계 3대 스프중 하나이고, 맵고 시고 톡 쏘면서도 향기로운 맛이 일품이다. 해장에도 굿...

뭄아러이에서 쏭테우를 불러줘서 150밧에 숙소로 다시 돌아왔다.
파타야엔 버스가 없으니 택시도 150, 쏭테우도 150.. 기본요금처럼 썼다..

숙소에 올라가니 침대위에 티파니쇼 표가 있었다.



낫티투어에 전화 했을 때 한국어 되는 분으로 소개시켜 준다고 해서 그거 또한 정말 감사했는데
표만 보내주셔도 될것을 삐뚤삐뚤 그려서 보내준 약도에 또 한번 감동 받았다. 타지에서 느끼는 정이란....ㅎ
버즈님 만세!!!!

티파니쇼장은 우드랜드와 가까운 곳에 있어서 걸어갔다.
금방 공연이 마쳤는지 밖에 사람들이 몰려있었다. 우왕...진짜 이쁜 언니들!!!!! 음..오빤가;;뭐지;;;



공연 중엔 사진을 찍을 수 없고 공연이 끝나고 나면 팁을 주고 이렇게 같이 사진을 찍을 수 있다.
팁은 최저 40밧이었던 걸로 기억되는데 남녀 할것없이 많은 사람들이 같이 사진을 찍는다. 언니들의 호객행위도 있고..

공연을 보면서 완벽한 몸매에 도자기 피부에다가 얼굴까지 이쁜 언니들이 춤을 추는 것을 보자니
아오 초라해지는 내자신...난 참 열심히 박수 쳤었다..;;
중간중간 관광객을 위해 한국공연 (아리랑, 필승코리아, 소핫등의 공연), 중국공연(전통노래)등의 공연도 있었다.
소핫 부르는 언니들 참 오글오글;;;

오늘은 파타야의 마지막 밤이니 워킹스트리트로!!! 말로만 듣던 밤문화;; 
쏭테우를 타고 로얄가든 플라자까지 갔다. 150밧.

천천히 걸어서 워킹까지 가는 도중 에라 모르겠다 병이 도져서 칵테일 카를 보고 그냥 털썩 앉아버렸다.
칵테일 바케스로 주세욤~~~ 200밧에 엄청난 양의 칵테일을 먹을 수 있다..(할아버지 추천....이름은..잊어버림)
파타야는 그래도 레알 바케스는 아니고 큰 유리잔에 넣어줬다. 음 뭔가 양주같이 럭셔리해..;;



한 잔 하고 워킹스트리트까지 또 걸었다. 모르는 길을 쨋든 걸어서 찾는거니 지치는건 어쩔 수가 없는 듯...
뿅! 워킹보다 삼성이 눈에 더들어와;;; 여긴 오디야~~~
옴마 골목을 들어가니;;; 어디서 구했는지 모를 야한 옷을 입고 호객행위를 하고...눈을 마주치면 안돼;;;;;
어려보이는 언니들..(?)도 다 야한옷...ㅠ 아저씨들은 클럽에 오라고 손짓하고 외쿡 할아버지들이 바글바글....



그렇게 앞만 보고 걸어걸어 선착장까지 걸어버렸다....
난...경주마처럼 앞만 보고 가니 잘 걷는구나...라고 느낀 파타야의 밤;;;
:
Posted by 라면스프
2011. 9. 28. 14:46

파타야 지도 It's Me2011. 9. 28. 14:46





A4사이즈에 두부분으로 나누어 인쇄하고 싶으시면 

아래 파일을 각각 프린트 하세요.

용지방향은 가로로 해주세요.






[이 게시물은 요술왕자님에 의해 2011-08-04 18:51:02 지역/일반정보에서 복사 됨]
:
Posted by 라면스프