월별 글 목록: 2008년 9월월

ByteBuffer to String

아래 예는 ByteBuffer를 String으로 변환하는 예제이다.

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);

Convert int -> byte array and byte array -> int

아래 예는 int를 byte array 그리고 byte array를 int로 변환하는 예제이다.

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};
}

Struts 1.0 Vs Struts 2.0

아래 내용은 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.

 

POJO와 관련된 용어들..

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 의 글도 참고해 보세요.. ^^

File에 내용 추가하기..

간단하게 아래의 코드로 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();
		} catch (IOException e) {
			e.printStackTrace();
		}

위의 FileWriter out = new FileWriter(“out.txt”, true); 에서 out.txt 파일이 없는 경우에 파일은 생성한다. FileWriter 생성자에서 true 인자를 사용해서 파일에 추가하고, BufferedWriter는 buffersize를 설정해서 성능을 높일 수 있다. ^^