ByteBuffer to String

from java 2008/09/30 13:18
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("aabcde".getBytes());
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String s = new String(bytes);

위가 아니라 아래처럼 해야 됩니다. ^^;;

ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("aabcde".getBytes());
byte[] bytes = new byte[buffer.position()];
buffer.flip();       
buffer.get(bytes);
String s = new String(bytes);
System.out.println(s);
public int byteArrayToInt(byte [] b) {
return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF);
}


public byte[] intToByteArray(int value) {
  return new byte[] {(byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value};
}


'java' 카테고리의 다른 글

Get and put unsigned values to a ByteBuffer  (0) 2008/10/07
ByteBuffer to String  (2) 2008/09/30
Convert int -> byte array and byte array -> int  (0) 2008/09/30
POJO와 관련된 용어들..  (1) 2008/09/24
File 내용 추가하기..  (0) 2008/09/24
Tag // byte array, int, java
아래 내용은 http://www.javabeat.net/tips/139-struts-10-vs-struts-20.html의 내용입니다.

Difference between Struts 1.0 and Struts 2.0

In the following section, we are going to compare the various features between the two frameworks. Struts 2.0 is very simple as compared to struts 1.0,1.1, few of its excelent features are:

1.Servlet Dependency

Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2.0, Actions are not container dependent because they are made simple POJOs. In Struts 2.0, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2.0 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2.Action classes

Programming the abstract classes instead of interfaces is one of design issues of struts 1.0 framework that has been resolved in the Struts 2.0 framework. Struts 1.0 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2.0 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2.0 , Actions are not container dependent because they are made simple POJOs. Struts 2.0 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts 2.0 Action object.

3.Validation

Struts 1.0 and Struts 2.0 both supports the manual validation via a validate method. Struts 1.0 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2.0 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4.Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1.0 Actions and requires extra care to develop. However in case of Struts 2.0, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5.Testability

Testing Struts 1.0 applications are a bit complex. A major hurdle to test Struts 1.0 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2.0 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6.Harvesting Input

Struts 1.0 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input. However Struts 2.0 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in Struts 2.0, Action properties can be accessed from the web page via the taglibs. Struts 2.0 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7.Expression Language

Struts 1.0 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2.0 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

8.Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2.0 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9.Type Conversion

Usually, Struts 1.0 ActionForm properties are all Strings. Struts 1.0 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2.0 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10.Control Of Action Execution

Struts 1.0 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2.0 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.


'apache project > struts 2.x' 카테고리의 다른 글

Struts 1.0 Vs Struts 2.0  (0) 2008/09/26
struts2 dtd 파일입니다.  (0) 2008/04/28
struts2 아키텍처 입니다.  (0) 2008/03/02
.action 확장자를 원하는 형태로 바꿔보자...  (0) 2008/03/02

POJO와 관련된 용어들..

from java 2008/09/24 21:54
POJO(Plain Old Java Object)가 몬지 확실히 알고 갑시다.. ㅋㅋ
아래는 미물의 개발 세상님의 블로그에서 발췌한 내용입니다.

*  VO - Value Object.
 테이블에 매핑되는 레퍼 클래스로서 값을 표현하는 객체로서 고유의 identity를 갖지 않는것을 말한다. 그리고 속성에 따라 정의된 객체이고 pass by value로 넘겨지게 되므로  원격 호출이 아닌 로컬 호출이 된다.
* PO - Persistence Object.
 database identity를 포함하고 있는 객체, 캐싱됨.
* BO - Business Object
 Data source에 접근하여 데이트를 얻거나 저장하는 것을 목표로하고 비즈니스 로직을 포함하고 있는 객체이다. .Business Object는 Session Bean, Entity Bean 또는 별도의 Java Object로 구현된다.
* TO - Transfer Object
 Client가 사용하기 위해 데이터 전송에 사용될 조합된 객체. Value  Object와 유사함.
* POJO - Plain Ordinary Java Object
 원격 콤포넌트가 아닌 로컬 Object이고 더이상 EJB 콘테이너에 의존하지 않고 콘테이너 외부에서 단위 테스트가 가능하고 DTO(Data Transfer Object)로도 사용 가능한 것이라고 할까요.


위키피디아에서 정의한 내용을 살펴보면...

Contextual variations
As of November 2005, the term "POJO" is mainly used to denote a Java object which does not follow any of the (major) Java object models, conventions, or frameworks such as EJB.

All Java objects are POJOs, therefore ideally speaking a POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

Extend prespecified classes, as in
public class Foo extends javax.servlet.http.HttpServlet{ ...Implement prespecified interfaces, as in
public class Bar implements javax.ejb.EntityBean{ ...Contain prespecified annotations, as in
@javax.ejb.Entitypublic class Baz{ ...However, due to technical difficulties and other reasons, many software products or frameworks described as POJO-compliant actually still require the use of prespecified annotations for features such as persistence to work properly.


결국 POJO는 간단하게 Getter, Setter 메쏘드등을 가지고 있는 Java Object라고 보면 되겠습니다.
http://c2.com/cgi/wiki?PlainOldJavaObject 의 글도 참고해 보세요.. ^^

'java' 카테고리의 다른 글

ByteBuffer to String  (2) 2008/09/30
Convert int -> byte array and byte array -> int  (0) 2008/09/30
POJO와 관련된 용어들..  (1) 2008/09/24
File 내용 추가하기..  (0) 2008/09/24
SocketChannel에서 read()시에 계속 0을 리턴할 경우..  (0) 2008/09/23
Tag // java, POJO

File 내용 추가하기..

from java 2008/09/24 15:34
간단하게 아래의 코드로 File의 내용을 추가합니다.

try
{
//ask user for file name to write to

FileWriter out = new FileWriter("out.txt", true);
BufferedWriter writer = new BufferedWriter(out, 64); // buffersize를 줘서 성능을 높이자..
writer.write("fooooooooooooooooooooooo~~");
writer.newLine();
writer.flush();
writer.close();
}

위의 FileWriter out = new FileWriter("out.txt", true); 에서 out.txt 파일이 없을경우 생성을 한다고 합니다. ^^
FileWriter의 생성자의 true 인자를 통해서 파일에 추가를 하시고, BufferedWriter는 buffersize를 줘서 성능을 높이시면 됩니다.  ^^



Selector를 통해서 클라이언트 SocketChannel을 등록하고 read 이벤트가 발생할 경우, 폴링을 하면서 read를 하지만 계속 0을 리턴하는 경우가 있습니다.. 그럴경우, read(ByteBuffer buffer)의 buffer의 position을 잘못 세팅했을 경우 발생을 합니다. 어떻게 보면 쉬운 버그이지만, 쉽게 찾아지지가 않는 다는.. ^^;;

'java' 카테고리의 다른 글

POJO와 관련된 용어들..  (1) 2008/09/24
File 내용 추가하기..  (0) 2008/09/24
SocketChannel에서 read()시에 계속 0을 리턴할 경우..  (0) 2008/09/23
Selector 및 SelectionKey 클래스 내용..  (0) 2008/09/05
this keyword 의미  (0) 2008/08/25

Reactor나 Proactor 패턴을 구현하기 위한 핵심 클래스가 select()를 지원하는 Selector 클래스와 이벤트 키를 가지고 있는  SelectionKey 클래스 입니다. 따라서, 위의 2개 클래스는 명확하게 알아둘 필요가 있습니다.

Selector 클래스의 주요 메서드

public static Selector open () : selector를 얻는다.
public abstract void close () : selector를 닫는다. 이때 selector가 관리중인 SelectionKey들도 모두 닫힌다.
public abstract boolean isOpen () : selector가 닫혔는지 아닌지 여부를 리턴.
public abstract Set keys () : 채널이 등록될때 생성된 SelectionKey를 java.util.Set객체로 리턴한다. Set안에 SelectionKey들이 전부 들어 있다.
public abstract Set selectedKeys () : selector가 선택한 SelectionKey를 java.util.Set객체로 리턴한다. 이들은 등록된 SelectionKey들 중에서 해당 동작(ops)이 일어난 SelectionKey들을 가리키는 것이다. 이들은 select()메서드나 selectNow()메서드가 호출된 다음에 Set 객체에 채워진다.
public abstract int select () :
public abstract int selectNow () :
-> 둘다 등록된 SelectionKey들 중에서 해당 동작(ops)이 일어난 SelectionKey들을 SelectionKey 리스트에 포함시키는 메서드로서 실제 해당 동작이 일어난 SelectionKey의 개수를 리턴한다. 이 둘의 차이점은 우선 select()인 경우 해당 동작이 일어난 SelectionKey가 하나라도 생시지 않으면 그 상태에서 블로킹이 된다. 그러나 selectNow()는 당장 해당 동작이 일어난 SelectionKey가 없어도 곧바로 리턴이 된다.
public abstract Selector wakeup () : select()가 블로킹되었을때 이를 깨워주는 메서드이다. 이때 SelectionKey의 Set에 SelectionKey가 추가되었는지 안되었는지는 알 수 없다.

SelectionKey 클래스의 주요 메서드

public static final int OP_ACCEPT
public static final int OP_CONNECT
public static final int OP_READ
public static final int OP_WRITE
위의 변수들은 비트값을 가진 int형 데이터로서 각각이 or연산에 의해 합해져서 어떤 동작들이 가능하거나 관심 있는지를 나타내게 된다.
public abstract int interestOps () : 해당 동작을 위의 값들로 리턴한다. 예를 들어 OP_READ|OP_WRITE 값이 리턴되었다면 읽는 것과 쓰는 동작을 취한다는 뚯이 된다. 그래서 읽거나 쓰거나 하는 동작이 취해지면 Selector에 의해 선택될 수 있게 된다.
public abstract SelectionKey interestOps (int ops) : 이는 위와는 반대로 해당 동작을 지정한다.
public final boolean isAcceptable ()
public final boolean isConnectable ()
public final boolean isReadable ()
public final boolean isWritable ()
 
public final Object attach (Object ob) : 채널 등록시 함께 등록될 객체(채널에 관한 정보를 담고 있는 객체)를 지정해준다. 이는 SelectableChannel클래스의 register ()메서드에서 인자 하나를 추가해서 지정해주는 것과 같다.
public final Object attachment () : attach()메서드나 register()로 추가로 지정된 객체를 리턴한다.
public abstract SelectableChannel channel () : 연결된 SelectableChannel 인스턴스를 리턴한다.
public abstract Selector selector () : 연결된 Selector 인스턴스를 리턴한다.

무료로 쉽게 사용할 수 있는 플래시 차트 라이브러리 입니다.
이름은 오픈 플래시 차트이고, 주소는 http://teethgrinder.co.uk/open-flash-chart/index.php 입니다.
자바로  프로젝트를 진행하면서, JFreeChart나 Cewolf를사용했었는데, 플래시 차트가 더 손쉬을거 같습니다.

사용자 삽입 이미지
사용자 삽입 이미지
사용자 삽입 이미지

'tools' 카테고리의 다른 글

Another java decompiler  (0) 2010/01/13
eclipse에서 ant로 javadoc task 에러  (0) 2009/06/11
무료 플래시 차트 'Open Flash Chart'..  (0) 2008/09/04
eclipse에서 cvs 연결끊기..  (0) 2008/08/27
FF VS IE 웹 개발 디버깅 툴  (0) 2008/08/13
IBM의 developWorks에서 안영회님께서 OSGI 개발에 대해서 강의하는 두번째 동영상 자료입니다.

Tag // IBM, OSGi