Wednesday, September 5, 2007

JAVA Strengths

JAVA Strengths

Java is an excellent programming language. For most programming it's better than older programming languages like C or C++.

  1. Productivity The top reason Java has become popular is because of the increased productivity of Java programmers. It is claimed, and my experience is in agreement, that Java programmers have about double the productivity of C/C++ programmers.
  1. GUI Java a good, portable library for a Graphical User Interface (GUI). Most programming languages supply only a text mode interface.
  • Internet Java lets you easily use the Internet. Most languages were designed before the Internet was born!
  1. Portability Java programs can run on many different machines (Intel, Sparc, PowerPC, ...) and many different operating systems (Windows, Unix, Macintosh, ...). You can move a C program if it is written very carefully, but it is usually difficult or impossible. In contrast, it easy to move most Java programs.
  1. Reliability Java programs are more reliable because Java doesn't have very dangerous things like C/C++'s pointer arithmetic. Java also checks array bounds and other error-prone operations. Memory management is much safer because Java does automatic garbage collection.
  1. Libraries Java has a very large number of packages which extend the language. Therefore it is unnecessary to call the operating system directly.
  1. OOP Object-oriented programming features (inheritance, encapsulation, and polymorphism) make many programs, especially large programs, easier to write.
Large Programs Java supports large programming projects with object-oriented programming, packages, and components (JavaBeans).

Tuesday, September 4, 2007

Buffer overflows likely to be around for another decade

Buffer overflows likely to be around for another decade

By Edward Hurley, News Writer

Few classes of security flaws in software cause as many headaches as buffer overflows. Yet given the present programming paradigm, buffer overflows will be around for some time to come, experts say.

Buffer overflows in both Unix and Windows systems were common occurrences in the recently released SANS/FBI Top 20 List of Web vulnerabilities. Buffer overflows open gaping holes that attackers can exploit, as the recent Slapper worm showed. The worm took advantage of a buffer overflow in OpenSSL running on Linux Apache Web servers to set up peer-to-peer networks and to commandeer other computers for possible use in launching distributed denial-of-service attacks.

Often buffer overflow vulnerabilities are hard to find in the minutiae of computer code. Additionally, the nature of the popular C programming language makes them an easy programming error to make, experts said.

In essence, a buffer overflow occurs when too much data is stuffed into a memory space. They are common in applications written in C.

Gerhard Eschelbeck, vice president of engineering at Redwood Shores, Calif.-based Qualys Inc., compares buffer overflows to people filling in handwritten forms that allow one space for each letter of a person's name. A buffer overflow is similar to what happens when the writer does not having enough blocks for one's last name, he said.

The extra "letters" or data aren't lost but written into other places in memory. This could cause the application to act oddly or shut down, creating a denial-of-service condition. It can also allow an attacker to run malicious code on the system. "The code looks the same to the computer," Eschelbeck said.

Buffer overflows can occur in both the stack and heap areas of memory. Stack memory is a pool that all programs can share. When a buffer overflow occurs, the extra data is put into stack memory, much like a card is added to a deck, said Ted Doty, director of product management at Waltham, Mass.-based Okena Inc. The system doesn't realize that data may be malicious.

Buffer overflows in heap memory are similar, except that heap memory is specifically allocated to a program, Doty said.

Buffer overflows are hard to find, and that's why many make their way into finished software products. Basically, one has to squeeze large amounts of data into every area of a program that can accept it to find them, Doty said.

Once an attacker is able to find a buffer overflow, exploiting it is often quite simple.

Finding buffer overflows is especially hard in large server applications that may have as many as 40 million lines of code, Doty said. Software vendors are under too much pressure to get new versions out to market to audit every line of code, he added.

At their most basic, buffer overflow vulnerabilities are programming errors. Error-checking for a too-long string of data wasn't included in the program.

One reason for this is that the C programming language doesn't have boundary checking. It's assumed that someone programming in C would include error-checking in their code, Doty said.

Other languages such as Perl and Java have the utility, hence buffer overflows don't occur, Eschelbeck said. On the other hand, Perl and Java don't offer access to the system that is as deep as some programs need. "The C programming language is very powerful. You can go as deep as you need," he said.

Better programmer training and education would minimize buffer overflows. Certain C functions such as string copy need to be avoided in order to minimize buffer overflows. There are code-auditing tools that look for such flaws, but they are still pretty early in their development, Eschelbeck said.

Software users, however, need to keep on buffer overflows in the applications they run. This means keeping tabs on advisories released by the Computer Emergency Response Team at Carnegie Mellon University or by vendors. Installing the released patches is also a must.

While they occur in many applications, buffer overflows are most damaging in core infrastructure such as domain name servers and Web servers.

Even if all programs started today were written buffer-overflow free, the vulnerabilities will continue to be found for the next few years because of the millions of lines of code that have not been audited. "There's no doubt in my mind that we'll be dealing with buffer overflows for at least the next 10 years," Eschelbeck added.

Monday, September 3, 2007

Looking up an EJB home with JNDI

Example: Looking up an EJB home with JNDI

Most applications that use JNDI run in a container. Some do not. The name used to look up an object depends on whether or not the application is running in a container. Sometimes it is more convenient for an application to use a corbaname URL as the lookup name. Container-based JNDI clients and thin Java clients can use a corbaname URL.

The following examples show how to perform JNDI lookups from different types of applications.

JNDI lookup from an application running in a container

Applications that run in a container can use java: lookup names. Lookup names of this form provide a level of indirection such that the lookup name used to look up an object is not dependent on the object's name as it is bound in the name server's name space. The deployment descriptors for the application provide the mapping from the java: name and the name server lookup name. The container sets up the java: name space based on the deployment descriptor information so that the java: name is correctly mapped to the corresponding object.

The following example shows a lookup of an EJB home. The actual home lookup name is determined by the application's deployment descriptors. The enterprise bean (EJB) resides in an EJB container, which provides an interface between the bean and the application server on which it resides.

// Get the initial context as shown in a previous example
...
// Look up the home interface using the JNDI name
try {
java.lang.Object ejbHome =
initialContext.lookup(
"java:comp/env/com/mycompany/accounting/AccountEJB");
accountHome = (AccountHome)javax.rmi.PortableRemoteObject.narrow(
(org.omg.CORBA.Object) ejbHome, AccountHome.class);
}
catch (NamingException e) { // Error getting the home interface
...
}

JNDI lookup from an application that does not run in a container

Applications that do not run in a container cannot use java: lookup names because it is the container which sets the java: name space up for the application. Instead, an application of this type must look the object up directly from the name server. Each application server contains a name server. System artifacts such as EJB homes are bound relative to the server root context in that name server. The various name servers are federated by means of a system name space structure. The recommended way to look up objects on different servers is to qualify the name so that the name resolves from any initial context in the cell. If a relative name is used, the initial context must be the same server root context as the one under which the object is bound. The form of the qualified name depends on whether the qualified name is a topology-based name or a fixed name. Examples of each form of qualified name follow.

  • Topology-based qualified names

    Topology-based qualified names traverse through the system name space to the server root context under which the target object is bound. A topology-based qualified name resolves from any initial context in the cell.

    Single server
    The following example shows a lookup of an EJB home that is running in the single server, MyServer, configured in the node, Node1.
    // Get the initial context as shown in a previous example
    // Using the form of lookup name below, it doesn't matter which
    // server in the cell is used to obtain the initial context.
    ...
    // Look up the home interface using the JNDI name
    try {
    java.lang.Object ejbHome = initialContext.lookup(
    "cell/nodes/Node1/servers/MyServer/com/mycompany/accounting/AccountEJB");
    accountHome = (AccountHome)javax.rmi.PortableRemoteObject.narrow(
    (org.omg.CORBA.Object) ejbHome, AccountHome.class);
    }
    catch (NamingException e) { // Error getting the home interface
    ...
    }
  • Fixed qualified names

    If the target object has a cell-scoped fixed name defined for it, you can use its qualified form instead of the topology-based qualified name. Even though the topology-based name works, the fixed name does not change with the specific cell topology or with the movement of the target object to a different server. An example lookup with a qualified fixed name is shown below.

    // Get the initial context as shown in a previous example
    // Using the form of lookup name below, it doesn't matter which
    // server in the cell is used to obtain the initial context.
    ...
    // Look up the home interface using the JNDI name
    try {
    java.lang.Object ejbHome = initialContext.lookup(
    "cell/persistent/com/mycompany/accounting/AccountEJB");
    accountHome = (AccountHome)javax.rmi.PortableRemoteObject.narrow(
    (org.omg.CORBA.Object) ejbHome, AccountHome.class);
    }
    catch (NamingException e) { // Error getting the home interface
    ...
    }

JNDI lookup with a corbaname URL

A corbaname can be useful at times as a lookup name. If, for example, the target object is not a member of the federated name space and cannot be located with a qualifiied name, a corbaname can be a convenient way to look up the object. A lookup with a corbaname URL follows.

// Get the initial context as shown in a previous example
...
// Look up the home interface using a corbaname URL
try {
java.lang.Object ejbHome = initialContext.lookup(
"corbaname:iiop:someHost:2809#com/mycompany/accounting/AccountEJB");
accountHome = (AccountHome)javax.rmi.PortableRemoteObject.narrow(
(org.omg.CORBA.Object) ejbHome, AccountHome.class);
}
catch (NamingException e) { // Error getting the home interface
...
}

Sunday, September 2, 2007

EJB and the limitation

According to EJB specification, EJB can not directly use file. So we have to find a way to read/write file indirectly. There are some solution for this.
1. We can use RMI technology.
2. We can use JCA to read file.

Solution 1:

RMI is the way to read file. It is also easy to implemented. All we have to do is make a server which provide a service: read/write file. EJB will implement a client to communicate with this server. All data when read/write file between the EJB and RMi Server is in byte array. But one of the drawback is that RMI is so heavy and big.

Solution 2:
The J2EE Connector architecture is based on the technologies defined and standardized in the Java 2 Platform, Enterprise Edition (J2EE) and is part of the J2EE platform.

As more businesses move towards an e-business strategy, integration with existing enterprise information systems (EIS) becomes the key to success. Enterprises with successful e-businesses need to integrate their existing EIS systems with new web-based applications. They also need to extend the reach of their EIS systems to support business-to-business (B2B) transactions.

Before the the J2EE Connector architecture was defined, no specification for the Java platform addressed the problem of providing a standard architecture for integrating heterogeneous EIS systems. Most EIS vendors and application server vendors use non-standard vendor-specific architectures to provide connectivity between application servers and enterprise information systems. The following diagram illustrates the complexity of a heterogenous environment.



The Java 2 Platform, Enterprise Edition provides containers for client applications, web components based on Servlets and JavaServer Pages (JSP) technologies, and Enterprise JavaBeans (EJB) components. These containers provide deployment and runtime support for application components. They also provide a federated view of the services provided by the underlying application server for the application components.

Containers run on existing systems: web servers for the web containers, application servers, transaction processing (TP) monitors, and database systems for EJB containers. This enables enterprises to leverage both the advantages of their existing systems and those with J2EE technology. Enterprises can write (or rewrite) new applications using J2EE technology capabilities and can also encapsulate parts of existing applications with Enterprise JavaBeans or JavaServer Pages (JSP) technologies.

Enterprise applications access functions and data associated with applications running on EISs. Application servers extend their containers and support connectivity to heterogeneous EISs. Enterprise tools and Enterprise Application Integration (EAI) vendors add value by providing tools and frameworks to simplify the EIS integration task.

The J2EE Connector architecture defines a standard architecture for connecting the J2EE platform to heterogeneous EIS systems. Examples of EIS systems include ERP, mainframe transaction processing, database systems, and legacy applications not written in the Java programming language. By defining a a set of scalable, secure, and transactional mechanisms, the J2EE Connector architecture enables the integration of EISs with application servers and enterprise applications.

The J2EE Connector architecture enables an EIS vendor to provide a standard resource adapter for its EIS. The resource adapter plugs into an application server, providing connectivity between the EIS, the application server, and the enterprise application. If an application server vendor has extended its system to support the J2EE Connector architecture, it is assured of seamless connectivity to multiple EISs. An EIS vendor needs to provide just one standard resource adapter which has the capability to plug in to any application server that supports the J2EE Connector architecture.

Multiple resource adapters (that is, one resource adapter per type of EIS) are pluggable into an application server. This capability enables application components deployed on the application server to access the underlying EIS systems.

Now all we have is implemented ResourceAdapter to provide a File Service to EJB. It is so tricky. But it works.

Friday, August 24, 2007

How to validate JAXP 1.3

How to use JAXP to validate a xml file against schema.
File NewXMLSchema.xsd is a resource.
File NewXMlSchema.xml is a xml file which we need to validate against schema NewXMlSchema.xsd

package validator;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class JAXPValidation {
public JAXPValidation() {
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(this.getClass().getResource("NewXMLSchema.xsd"));
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler(){

public void error(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}

public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}

public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
throw exception;
}
});
URL url = this.getClass().getResource("NewXMlSchema.xml");
InputStream stream = url.openStream();
StreamSource source = new StreamSource(stream);
validator.validate(source);
System.out.println("validate sucessfully");
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

static public void main(String[] args) {
new JAXPValidation();
}
}

Tuesday, August 21, 2007

How to validate request in jax-ws


JAX-WS has the hole in validate soap request. But we can work around by using SoapHandler and JAXP to validate soap request.
As we can see from the picture from the left, we have 2 chance to validate request:
SOAPHandler and LogicalHandler. We use SOAPHandler if we want to validate soap header and soap body and use logicalhandler to validate soap body.

In method: handleMessage() in class SOAPHanlder, we can easily get the raw soap message by using: SOAPMessageContext and write them to ByteArrayOutputStream. After we got the xml string, we can use JAXP to validate the request. Detail in how to implement the idea will be presented in next post.

Sunday, August 19, 2007

Default Password List for Routers

To know the default password list for router, please refer to this url:

http://www.phenoelit-us.org/dpl/dpl.html

Thursday, August 16, 2007

How to deploy an FTP server with FileZilla

Today, i meet a problem with ftp server. I will share my experience with you about it.

Download FTP Server at:
http://filezilla.sourceforge.net/
Download FTP Client at:
http://filezilla.sourceforge.net

Setup FileZilla server:
1.Run installer.
2.If you are behind the router, remember to open 2 port at router: port 20, 21.
By opening these 2 ports, the users from internet can access to server. If your server is behind the firewall, you have to let firewall also open 2 ports 20,21 .
3. Next, please refer to this document:
http://filezilla.sourceforge.net/documentation/

Hope this post will help you in setup ftp server: FileZilla.

Saturday, July 21, 2007

Java classloader

The Java platform was designed to be robust, secure, and extensible in order to support the mobility of code and data. The Java ClassLoader in the Java Virtual Machine (JVM) is a key component in the realization of these goals.

The JVM is responsible for loading and executing code on the Java platform. It uses a ClassLoader to load Java classes into the Java runtime environment. ClassLoaders are architected so that at start-up the JVM doesn't need to know anything about the classes that will be loaded at runtime. Almost all Java-based containers such as EJB or servlet containers implement custom ClassLoaders to support features like hot deployment and runtime platform extensibility. An in-depth understanding of ClassLoaders is important for developers when implementing such Java-based containers.

For enterprise developers who develop components that are deployed on these containers, this knowledge will help you understand how the container works and with debugging problems. This article presents the Java ClassLoader architecture and discusses the implications of ClassLoaders on platform security and extensibility as well as a method to implement user-defined ClassLoaders.

The smallest unit of execution that gets loaded by a ClassLoader is the Java class file. A class file contains the binary representation of a Java class, which has the executable bytecodes and references to other classes used by that class, including references to classes in the Java API. Stated simply, a ClassLoader locates the bytecodes for a Java class that needs to be loaded, reads the bytecodes, and creates an instance of the java.lang.Class class. This makes the class available to the JVM for execution. Initially when a JVM starts up, nothing is loaded into it. The class file of the program being executed is loaded first and then other classes and interfaces are loaded as they get referenced in the bytecode being executed. The JVM thus exhibits lazy loading, i.e., loading classes only when required, so at start-up the JVM doesn't need to know the classes that would get loaded during runtime. Lazy loading plays a key role in providing dynamic extensibility to the Java platform. The Java runtime can be customized in interesting ways by implementing a custom ClassLoader in a program, as I'll discuss later.

Java 2 ClassLoader Delegation Model
Multiple instances of ClassLoaders exist in the Java 2 runtime, each loading classes from different code repositories. For instance, Java core API classes are loaded by the bootstrap (or primordial) ClassLoader. Application-specific classes are loaded by the system (or application) ClassLoader. In addition, an application can define its own ClassLoaders to load code from custom repositories. Java 2 defines a parent-child relationship between ClassLoaders. Each ClassLoader except the bootstrap ClassLoader has a parent ClassLoader, conceptually forming a treelike structure of ClassLoaders. The bootstrap ClassLoader is the root of this tree and thus doesn't have a parent. The relationship is depicted in Figure 1.

The following is a high-level class-loading algorithm executed by a ClassLoader when a client requests it to load a class:
1. A check is performed to see if the requested class has already been loaded by the current ClassLoader. If so, the loaded class is returned and the request is completed. The JVM caches all the classes that are loaded by a ClassLoader. A class that has previously been loaded by a ClassLoader is not loaded again.
2. If the class is not already loaded, the request is delegated to the parent ClassLoader, before the current ClassLoader tries to load it. This delegation can go all the way up to the bootstrap ClassLoader, after which no further delegation is possible.
3. If a parent fails to return a class because it was unable to load it, the current ClassLoader will then try to search for the requested class. Each ClassLoader has defined locations where it searches for classes to load. For instance, the bootstrap ClassLoader searches in the locations (directories and zip/jar files) specified in the sun.boot.class.path system property. The system ClassLoader searches for classes in the locations specified by the classpath (set as the java.class.path system property) command-line variable passed in when a JVM starts executing. If the class is found, it's loaded into the system and returned, completing the request.
4. If the class is not found, a java.lang.ClassNotFoundException is thrown.

Implementing a Java 2 Custom ClassLoader
As mentioned earlier the Java platform allows an application programmer to customize the classloading behavior by implementing a custom ClassLoader. This section shows how.

ClassLoaders (all but the bootstrap ClassLoader, which is implemented in native code in the JVM) are implemented by extending the java.lang.Class Loader class. The following code shows the relevant methods of the Java 2 ClassLoader API:

1. public abstract class ClassLoader extends Object {
2. protected ClassLoader(ClassLoader parent);
3. protected final Class defineClass(
4. String name,byte[] b,int off,int len)
5. throws ClassFormatError
5. protected Class findClass(String
7. className) throws ClassNotFoundException
6. public class loadClass(String className)
7. throws ClassNotFoundException
8.}

Each ClassLoader is assigned a parent when it's created, as per the parent-delegation model. Clients invoke the loadClass method on an instance of a ClassLoader to load a class. This initiates the classloading algorithm as explained earlier. Prior to Java 2, the loadClass method in the java.lang.ClassLoader class was declared abstract, requiring custom ClassLoaders to implement it when extending the java.lang.ClassLoader class. Implementing the loadClass method is rather complicated, so this has been changed in Java 2. With the introduction of the ClassLoader parent delegation model, java.lang.ClassLoader has an implementation of the loadClass method, which is essentially a template method that executes the classloading algorithm. The loadClass method invokes the findClass method (introduced in Java 2) in Step 3 of the classloading algorithm. Custom ClassLoaders should override this method to provide a custom way of locating and loading a Java class. This greatly simplifies the implementation of a custom ClassLoader. Listing 1 shows some code from the CustomClassLoader.java class (the complete source code can be downloaded from www.sys-con.com/java/sourcec.cfm), which loads classes from a repository specified in the constructor.

The findClass method invokes loadFromCustomRepository that searches for the given class in the repository and, if found, reads and returns the bytecodes for the class. The raw bytecodes for the class are passed into the defineClass method implemented in the java.lang.ClassLoader class, which returns an instance of the java.lang.Class object. This makes a new class available to a running Java program. The defineClass method also ensures that a custom ClassLoader does not redefine core Java API classes by loading them from a custom repository. A SecurityException is thrown if the class name passed to defineClass begins with "java".

It should be noted that at start-up, the JVM doesn't need to know anything about the class represented by the string passed into the loadClass method. A subsequent section shows how a program can use the CustomClassLoader.

Deviations from the Java 2 Delegation Model
The Java 2 delegation model cannot be followed in all situations. There are cases in which ClassLoaders have to diverge from the Java 2 model. For instance, the servlet specification recommends (section 9.7) that a Web application ClassLoader be implemented so that classes and resources packaged in the Web application archive are loaded in preference to classes and resources residing in container-wide JAR files. To meet this recommendation, a Web application ClassLoader should search for classes and resources in its local repository first, before delegating to a parent ClassLoader, thus deviating from the Java 2 delegation model. This recommendation makes it possible for Web applications to use different versions of classes/resources than those being used by a servlet container. For example, a Web application might be implemented using features available in a newer version of an XML parser than the one being used by a servlet container.

A Web application ClassLoader that meets the recommendation of the servlet specifications can be implemented by overriding the loadClass method of the java.lang.Classloader class. The loadClass method of such a custom ClassLoader may look similar to Listing 2.

Applications of ClassLoaders
ClassLoaders provide some powerful features that can be utilized in Java programs. This section discusses a few ways in which they can be used.

Hot Deployment
Upgrading software in a running application without restarting it is known as hot deployment. For a Java application, hot deployment means upgrading Java classes at runtime. ClassLoaders play an important role in Java-based application servers to achieve hot deployment. This feature is exploited in most Java-based application servers like EJB servers and servlet containers. A ClassLoader cannot reload a class that it has already loaded, but using a new instance of a ClassLoader will reload a class into a running program. The following code from TestCustomLoader.java illustrates how hot deployment may be achieved in a Java application:

1. ClassLoader customLoader = new
2. CustomClassLoader(repository);
3. loadAndInvoke(customLoader,classToLoad);
4. System.out.println("waiting.Hit
5. Enter to continue");
6. System.in.read();
7. customLoader = new CustomClassLoader
8. (repository);
9. loadAndInvoke(customLoader,classToLoad);

An instance of the CustomClassLoader is created to load classes from a repository specified as a command-line parameter. loadAndInvoke loads a class, HelloWorld, also specified as a command-line parameter, and invokes a method on its instance, which prints a message on the console. While the program is waiting for user input at line 6, the HelloWorld class can be changed (by changing the message that gets printed on the console) and recompiled. When the program continues execution, a new instance of CustomClassLoader is created at line 7. When loadAndInvoke executes line 9, it loads the updated version of HelloWorld and a new message is printed on the console.

Modifying Class Files
A ClassLoader searches for bytecodes of a class file in the findClass method. After the bytecodes have been located and read into the program, they may be modified before invoking defineClass. For example, extra debugging information may be added to the class file before invoking defineClass. Class file data for some secure applications may be stored encrypted in a repository; the findClass method can decrypt the data before invoking defineClass. A program can generate the bytecodes on the fly instead of retrieving them from a repository. This forms the basis of JSP technology.

ClassLoaders and Security
Since a ClassLoader is responsible for bringing code into the JVM, it's architected so that the security of the platform may not be compromised. Each ClassLoader defines a separate namespace for the classes loaded by it, so at runtime a class is uniquely identified by its package name and the ClassLoader that loaded it. A class is not visible outside its namespace; at runtime there's a protective shield between classes existing in separate namespaces. The parent delegation model makes it possible for a ClassLoader to request classes loaded by its parent, thus a ClassLoader doesn't need to load all classes required by it.

The various ClassLoaders that exist in a Java runtime have different repositories from which they load code. The idea behind separating repository locations is that different trust levels can be assigned to the repositories. The Java runtime libraries loaded by the bootstrap ClassLoader have the highest level of trust in the JVM. The repositories for user-defined ClassLoaders have lower levels of trust. Furthermore, ClassLoaders can assign each loaded class into a protection domain that defines the permissions assigned to the code as it executes. To define permissions on code based on the system security policy (an instance of java.security.Policy), a custom ClassLoader should extend the java.security.SecureClassLoader class and invoke its defineClass method that takes a java.security.CodeSource object as a parameter. The defineClass method of SecureClassLoader gets the permissions associated with the CodeSource from the system policy and defines a java.security.Protection Domain based on that. A detailed discussion of the security model is beyond the scope of this article. Further details can be obtained from the book Inside the Java Virtual Machine by Bill Venners.

Summary
ClassLoaders offer a powerful mechanism by which the Java platform can be extended in interesting ways at runtime. Custom ClassLoaders can be used to achieve functionality not normally available to a running Java program. Some of these applications have been discussed in this article. ClassLoaders play an important role in some of the technologies offered by current J2EE platforms. For further details about the Java classloading mechanism, read Inside the Java Virtual Machine.

Friday, July 20, 2007

How to create rss link for google blogspot ?

RSS Feeds from Xanga and Blogspot

Recently got a few friends who are blogging on Xanga and Blogspot. As someone who likes to read blog yet lazy to visit them one by one, I usually just subscribe to their RSS and wait for news to arrive at my doorstep (or better know as Outlook). However, I cannot find any [XML] or [RSS] icon in both the blog sites. I quick search in goggle reveals 2 ways which I can feed the blogs

Xanga:

there is a free service @
http://www.ephemeraleuphoria.com/xanga/rss.php?username=

Simply change the field to the username of the blog you wish to feed from Xanga


Blogspot
:

Blogspot default feed through atom, which the RSS aggregator I using (you subscribe) do not support.
Therefore I used this free service from 2rss to convert the feeds to atom before subscibing to them

http://www.2rss.com/software.php?page=atom2rss


Lastly, there are some who simply dun support RSS feeds. I therefore use watchthatpage instead, which is recommended by icelava

Friday, July 13, 2007

JAXB tutorial and tip

JAXB is used for mapping xml to java classes.

To generate java class from xml we use xjc.

Command: xjc -d sourcefolder schema.

Tip: Do not try to use parameter: -p in command line. This will make all class in the same package.
It results in namespace will be removed because of JAXB optimization. I've got a problem because it.

Unmarshalling:
JAXBContext context = JAXBContext.newInstance("enter generated packagename here");
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.unmarshal(new FileInputStream(fileName));

Marshalling:
JAXBContext context = JAXBContext.newInstance("enter generated packagename here");
JAXBElement root = soapFactory.createEnvelope(rootElement);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(root, System.out);

Saturday, July 7, 2007

How to configure pom file to use jaxws library and wsimport plugins maven

First: you should point out the plugin repository to download jaxws-maven-plugin

[pluginRepository]
Repository url: http://download.java.net/maven/2
[/pluginRepository]


Second:
Chose the repository for downloading jaxws library:

[repository]
[id]java net repository[/id]
[name]java net name[/name]
[url]https://maven-repository.dev.java.net/repository[/url]
[layout]legacy[/layout]
[/repository]


Third:
Chose the plugin jaxws-maven-plugin

[plugin]
[groupId]org.codehaus.mojo[/groupId]
[artifactId>jaxws-maven-plugin[/artifactId]
[version]1.3[/version]
[executions]
[execution]
[goals]
[goal]wsimport[/goal]
[/goals]
[/execution]
[/executions]
[configuration]
[sourceDestDir]
${basedir}/src/main
[/sourceDestDir]
[verbose]true[/verbose]
[packageName]com.example.myschema[/packageName]
[target]2.1[/target]
[/configuration]


[dependencies]
[dependency]
[groupId]com.sun.xml.ws[/groupId]
[artifactId>jaxws-tools[/artifactId[
[version]2.1.1[/version]
[/dependency]
[dependency]
[groupId]javax.xml.bind[/groupId]
[artifactId]jaxb-api[/artifactId]
[version] 2.1[/version]
[/dependency]
[/dependencies]
[/plugin]

Configure plugins jaxws-maven-plugin with jdk1.6

Today, i will write about how to use plugins jaxws-maven-plugin with jdk 1.6.
The prolem is : JDK 1.6 shipped with jaxws 2.0. But if you want to use jaxws-maven-plugin with latest jaxws library 2.1, you will meet the error:

JAXB 2.0 API is being loaded from the bootstrap classloader, but this RI (from jar:file:/C:/Documents and Settings/Administrator.HOME/.m2/repository/com/sun/xml/bind/jaxb-impl/2.1.3/jaxb-impl-2.1.3.jar!/com/sun/xml/bind/v2/model/impl/ModelBuilder.class) needs 2.1 API. Use the endorsed directo
ry mechanism to place jaxb-api.jar in the bootstrap classloader. (See http://java.sun.com/j2se/1.5.0/docs/guide/standards/)

This error occurred because jaxb 2.0 was loaded instead of your jaxb 2.1.

Solution:
First: you should find where is your java-home.
Second: go to ${java-home}/jre/lib and create folder: endorsed.
In this folder(endorsed) you copy your jaxb-api and jaxws-api (version 2.1 not 2.0)

Now done!
Test: mvn jaxws:wsimport and see the result.

Sunday, July 1, 2007

Elipse and SVN

Subclipse is the plugin for eclipse. This plugin provides eclipse the SVN capability.

Home page for subclipse:
http://subclipse.tigris.org/

Eclipse update site URL: http://subclipse.tigris.org/update_1.2.x
We use this URL for update plugin automatically.

Maven tutorial

Today, i will make a tut about maven.

Definition about maven:

Maven was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. There were several projects each with their own Ant build files that were all slightly different and JARs were checked into CVS. We wanted a standard way to build the projects, a clear definition of what the project consisted of, an easy way to publish project information and a way to share JARs across several projects.

The result is a tool that can now be used for building and managing any Java-based project. We hope that we have created something that will make the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project.

Home page: http://maven.apache.org/index.html

Step 1: Download maven from home page.

Step 2: configure setting.xml in folder maven/conf

Tag localRepository : is used to set the folder where maven will downloaded all library and find them when build project.

Tag Proxy: is used when you are behind the network proxy.

Step 3: Set up project layout.












After create the folder for our project. We have to create pom file for them.
At the folder project. We have a top pom file pom.xml.
At the folder modules, we also have a pom.xml file.
At module1, module2, we also have a pom.xml file.

Using tag modules and module to show which one will be compiled next.

[modules]
[module] modules [/module]
[/modules]

Using repository tag to show which repository maven used to get library:

[repositories]
[repository]

[/repository]
[/repositories]

Using dependency tag to show which library you used in the project.
[dependencies]
[dependency]
[/dependency]
[/dependencies]

Tuesday, June 5, 2007

JAX-WS and how to send SOAP Header

When i do my project, i met a problems. How can i add soap header to soap messages. The webservice is developed with JAX-WS library.

I really don't know why jax-ws does not implements such a method to add soap header from the implementation of web-service. We have to use another way to do that: Soap Handler. A Soap Handler is called before the implementation of webservice called. So we used them to send soap header.

for example:
we have a webservice with one function: sayHello(). They function required that its response and request come along with a soap header. It should contains the value of session.

[soap:header]
[session] 12424512[/session]
[/soap:header]
[soap:body]
[sayhelloresponse] .... [/sayhelloresponse]
[/soap:body]

How we add soap:header??

Step to do:
in the class implement the function sayHello()

@Resource
WebServiceContext wsContext

void sayHello(){
MessageContext message = wsContext.getMessage();
message.put("session", 245235); //this will put the value to the context of the //webservice
}

In the soap handler, we get the value we store in the context of webservice. and put to soap handler. Only in soap handler, we have a chance to create soap header. So that why we have to do in this way.

public class SOAPLoggingHandler implements
SOAPHandler {
...

public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean)
smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

if (outboundProperty) {
MessageContext context = smc.getMessageContext();;
String session = context.get("Session");
SOAPMessage soapMessage = smc.getMessage();
//Add header to soapmessage. Using function of soap message like
//GetElementHeader, GetHeader ... I am not remember exactly. I will update this soon.
}
return true;
}

public boolean handleFault(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}

public void close(MessageContext messageContext) {
}
}

Friday, June 1, 2007

JBoss and Log4j

JBoss and Log4j come together will make the stupid things. JBoss make all logs of user application come to its log file and prohibit the user using trace log. It is terrible. In my project, i have to define my own log file which separated with the system log. But this task take me 2 days. What a terrible. Now i find 2 solution.
First one: Remove all the trace log and define new appender and category in log4j.xml in folder conf of jboss. It will make the log of application come to new place.
Seconde one:
Using RepositorySelector with ServletListener or Listener to use your own log. As my research in internet, i found that this is the clean solution of separate logger with jboss logger.
All you need for the second solution is:

  1. Log4j.jar in WEB-INF.
  2. Your own lof4j.xml file( you can mimic the log4j.xml of jboss)
  3. 2 file followings.
  4. Configure web.xml to ensure servlet or servlet listener to run first to make log initialize or you will get error.

/***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/

package org.jboss.repositoryselectorexample;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.RepositorySelector;
import org.apache.log4j.spi.RootCategory;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;

/**
* This RepositorySelector is for use with web applications. It assumes that
* your log4j.xml file is in the WEB-INF directory.
*
* @author Stan Silvert
*/
public class MyRepositorySelector implements RepositorySelector
{
private static boolean initialized = false;
private static Object guard = LogManager.getRootLogger();

private static Map repositories = new HashMap();
private static LoggerRepository defaultRepository;

/**
* Register your web-app with this repository selector.
*/
public static synchronized void init(ServletConfig config)
throws ServletException {
if( !initialized ) // set the global RepositorySelector
{
defaultRepository = LogManager.getLoggerRepository();
RepositorySelector theSelector = new MyRepositorySelector();
LogManager.setRepositorySelector(theSelector, guard);
initialized = true;
}

Hierarchy hierarchy = new Hierarchy(new RootCategory(Level.DEBUG));
loadLog4JConfig(config, hierarchy);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
repositories.put(loader, hierarchy);
}

public static synchronized void removeFromRepository() {
repositories.remove(Thread.currentThread().getContextClassLoader());
}

// load log4j.xml from WEB-INF
private static void loadLog4JConfig(ServletConfig config,
Hierarchy hierarchy)
throws ServletException {
try {
String log4jFile = "/WEB-INF/log4j.xml";
InputStream log4JConfig =
config.getServletContext().getResourceAsStream(log4jFile);
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(log4JConfig);
DOMConfigurator conf = new DOMConfigurator();
conf.doConfigure(doc.getDocumentElement(), hierarchy);
} catch (Exception e) {
throw new ServletException(e);
}
}

private MyRepositorySelector() {
}

public LoggerRepository getLoggerRepository() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
LoggerRepository repository = (LoggerRepository)repositories.get(loader);

if (repository == null) {
return defaultRepository;
} else {
return repository;
}
}
}

/***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/

package org.jboss.repositoryselectorexample;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
* This servlet demonstrates initialization of a RepositorySelector so that
* logging can be done on a per-app basis.
*
* @author Stan Silvert
*/
public class Log4JServlet extends HttpServlet {

private static Logger LOG;

private String servletName;
private MyObject myObj; // can't initialize until init() method called

/** Initializes the servlet.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.servletName = config.getServletName();


MyRepositorySelector.init(config);

// note that we can't call Logger.getLogger() until
// MyRepositorySelector.init() is called. For all other classes in the
// webapp, you can call Logger.getLogger() at any time.
this.LOG = Logger.getLogger(Log4JServlet.class);

// the same goes for the Logger.getLogger() method in MyObject
this.myObj = new MyObject(this.servletName);
}

/** Destroys the servlet.
*/
public void destroy() {
MyRepositorySelector.removeFromRepository();
}

/**
* Processes requests for both HTTP GET and POST
* methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/*");
PrintWriter out = response.getWriter();

LOG.error("TEST FROM THE SERVLET: " + this.servletName);
myObj.foo();
out.println("");
out.close();
}

/** Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Log4JServlet";
}

}


/***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/

package org.jboss.repositoryselectorexample;

import org.apache.log4j.Logger;

/**
* This just shows another object besides the servlet within the same
* web app.
*
* @author Stan Silvert
*/
public class MyObject {

// note that this can not be static because MyObject is referenced in
// the servlet before the RepositorySelector is initialized. For other
// classes, it would be OK to make this static.
private final Logger LOG = Logger.getLogger(MyObject.class);

private String servletName;

public MyObject(String servletName) {
this.servletName = servletName;
}
public void foo() {
LOG.info("Message from MyObject: " + this.servletName);
}
}

JMock and how to use.

Today i use JMock for my projects. I should say that it is a good tool for testing.
But finding how to use it makes me crazy. But now i have just resolved all my problems.
It related to the jax-ws mock object. JAX-WS uses the abstract instead of the interface so
it makes using jmock is difficult task. But thanks for new lib JMock 2.x, it support abstract class also concrete class. Following is sample of using jmock for jax-ws soap handler for the unit test purpose.

Step to use:
Using the latest lib JMock 2.x lib

Import org.jmock.Expectations;
import org.jmock.integration.junit3.MockObjectTestCase;
import org.jmock.lib.legacy.ClassImposteriser;

protected final void setUp() throws Exception {
super.setUp();
setImposteriser(ClassImposteriser.INSTANCE);
soapHandlerImpl = new SoapHandlerImpl();
}

public final void testHandleMessage(){
//create mock object
final SOAPMessageContext smc = mock(SOAPMessageContext.class);
final SOAPHeader mockSoapHeader = mock(SOAPHeader.class);
final SOAPMessage mockSoapMessage1 = mock(SOAPMessage.class);
final SOAPMessage mockSoapMessage2 = mock(SOAPMessage.class);
final SOAPHeaderElement mockSoapHeaderElement =
mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapSessionIDHashTag =
mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapFromTag = mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapFromTo = mock(SOAPHeaderElement.class);

//Make the expectation. Please remember that the expectation have to be
//correct or the exception occur. The exception message is not useful to resolve
checking(new Expectations() {
{
one(smc).get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
will(returnValue(true));
}
}); //simulate function getmessage for soapmessage.

//call function to test with mock parameter.
soapHandlerImpl.handleMessage(smc) ;
}
Some note:
To make the test run with out exception, we have to define how many mock object you need in the function. You should also count the number of function of mock object which will be called and the data for each calls. All of them have to be explicit define or you will got an exception in unit test.
I wrote this to remind me the problems when i do my project in company. I met a lot of prolems with that.

Wednesday, May 16, 2007

sitemap

http://thegioitinhoccuatoi.blogspot.com/

Study and Works

Now i am very tired because i have to study and work full time at the same time. Stress !!!! Work very hard but money is so little. I know people in in USA which do same job have the salary greater 10 times than mine. That is why i have to work more to find out changes to get higher salary and position. Studying at university. It required that i have to spent many time for research. Now i wished a day have 48hours. :D.

Tryyyyyyyyyy your best! I think i will be succeeded.

Vertu -- The most expesive phone



Vertu Diamond Cellphone is the world most expensive phone, with a price tag of 1 million Euro, only 3 of these made are available. For the moment, only 2 has been grabbed, one by a russian tycoon and the other by a Hong Kong tycoon. The “Piece Unique” handmade phone is constructed out of solid gold, is studded with diamonds and comes with a customized insurance policy. The phone has entered the Guinness Book of World Records as the expensive cell phone ever sold in the world. One million euro for a phone is crazy, some people ARE crazy!

Nokia N95 -- the modern and expensive phone

Wiith HSDPA technology which is 3 times faster than the 3G technology, Nokia N95 is the most prolific mobile phone from Nokia. The mobile phone is a camera mobile phone with imaging capability of 5 mega pixels. The sharpness and richness of colours brings something extra that other mobile phones cannot derive.
The most astounding feature of Nokia N95 is the technology that comes with it. In addition, the powerful camera which is included in the mobile phone gives you an imaging capability other mobile phones cannot give. The internal memory size of the mobile phone too is of great comfort to those who wish to store more images, video or music. Technology which runs Nokia N95 is S60 software on Symbian OS. Along with the various possibilities like mobile blogging, direct connection to TV, video calls, visual radio and faster internet connectivity this mobile phone brings out the best experience a latest mobile phone can give you.

Built-in GPS is another feather in the cap in Nokia N95. Inclusion of this technology in the mobile phone lets you find help in distress. Whether you wish to play Java™ enabled games, listen and watch stream music, all can be done with the aid of this mobile phone. As the mobile phone support a number of network types you can carry this around anywhere in the world and still stay connected. For connectivity and sharing Nokia N95 comes with latest technology. It is enabled with UPnP, Integrated wireless LAN, IrDA and Bluetooth™ technology which makes it universally acceptable in connectivity and sharing of data.

Apple iPhone


With screen size of 3.5 inches and resolution of 320×480 at 160 ppi, Apple iPhone is a communication device sporting some of the latest technology. The weight of this device is 135 grams and overall dimensions are 115×61×11.6 mm. Included in this device is a 2.0 megapixels digital camera. The input method supported by Apple iPhone is multi-touch technology.

Apple iPhone
Apple iPhone Dimensions : 104 x 50 x 16.4 mm
Weight : 93 g
Stand-by: 264 hrs


The operating system that runs Apple iPhone is OS X from Apple. This communication device supports wireless data transfer with the usage of technologies like Wi-Fi, EDGE and Bluetooth 2.0. It is a quad-band mobile phone supporting GSM 850/900/1800/1900 MHz. The storage capacity of Apple iPhone is 4GB or 8GB depending upon the need choice of the user.

With talk time of up to 5 hours and audio playback time of up to 16 hours, this is a communication device, which would let a user enjoy these functionalities too. Apple iPhone would be sporting a full QWERTY keyboard, which would let a user type in messages or emails easily. In addition, the keyboard would be supported by predictive text, saving time for a user of this device.

Bluetooth™ technology would also be present in Apple iPhone. It will empower a user to connect to other Bluetooth™ enabled devices with the aid of this mobile phone. However, the most prolific feature of Apple iPhone is the inclusion of various sensors to aid a user in clicking images, saving power and to enrich the user experience. As soon as a user picks up the phone and takes it near ears, one of its sensors detects the proximity of the device to the ear and switches off the display thus saving power consumption.

Synchronization of data with your PC or other devices too would be possible with the help of this device. Making calls, voicemails, SMS and clicking pictures and video clips would be possible with this futuristic mobile phone, Apple iPhone. Order and buying this mobile phone would be easy as Mobile Phone Shop UK accepts online booking of this communication device. Book your order now and have it in your hand when it is released in the market.

Nokia N75



Service Provider:
AT&T Wireless, Cingular Wireless
Operating System: Symbian OS
Screen Size: 2.4 inches
Screen Details: 2.4", 320x240 TFT main screen; 1.4", 160x128 front screen
Camera: Yes
Megapixels: 2
Bluetooth: Yes
Web Browser: Yes
Network: GSM, UMTS
Bands: 850, 900, 1800, 1900
High-Speed Data: GPRS, EDGE, UMTS
Special Features: Music

Nokia's first US 3G phone, in fact Nokia's first US flip smart phone, and AT&T's first 3G Symbian OS phone, the glamorous Nokia N75 has been the subject of many hopes and dreams in the seven months since it was first announced. It's beautiful and powerful to be sure, but poor battery life makes me worry you won't be able to get the use you want out of it.

MOTORAZR2V8 phone. Nice phone


MOTORAZR2 V8 brings the revolutionary RAZR form to a new level of sophistication. It takes the impossibly sleek RAZR profile and makes it even slimmer. It packs a powerhouse of features into a strong stainless steel structure. All told, the phone that has forever captivated is now about to mesmerize.

Certain mobile phone features are dependent on the capabilities and settings of your service provider’s network. Additionally, certain features may not be activated by your service provider, and/or their network settings may limit the feature’s functionality. Always contact your service provider about feature availability and functionality. All features, functionality and other product specifications are based upon the latest available information and are believed to be accurate; however such product specifications are subject to change without notice or obligation.

Supports the following Bluetooth profiles: A2DP, AVRCP, GAVDP, generic access, hands-free, headset, dial-up networking, object push, file transfer, generic object exchange, basic imaging (sending/receiving images supported only), basic printing (in the following applications: Phonebook, Datebook, Picture Viewer and Messaging).

Wednesday, May 9, 2007

About traditional vietnames costume


ao tu than 1
AO TU THAN

The "ao dai" ("flowing tunic") has been the traditional dress for Vietnamese women long, long ago. There are many different kinds of ao dai: the four-part flowing tunic had two equal front flaps that women tied together, while the five-part flowing tunic had an additional small front flap that buttoned up onto the right side of the dress.

Different regions of the country have their own styles of flowing tunic. In the north, Vietnamese women usually wear the four-part flowing tunic, refers to as "Ao Tu Than", with a long skirt. The hat is called "Non Quai Thao".

On the right, instead of wearing "non quai thao", Nothern women just simply wear a scarf as a variety.

ao tu than 2


ao dai 1
Student Uniform

In the Central Region, and in the South of Vietnam, "ao dai" is worn. It is a long flowing tunic that consists of only 2 parts and is worn over a loose-fitting pair of either white, black, or colored pants. However, the white pants are usually preferred over the others. The dress splits into a front and back panel from the waist down. It is also buttoned down on the 1eft side to the waist. There are many stylish variations in color and collar design.

White, or violet ao dai is also worn by Vietnamese students as their uniforms.

The cone-shaped hat is called "non la". Non la in these two pictures is more for posing and decorating. In reality, non la is more functional than decorative. It is used indeed like a hat to protect one from the heat and the sun in everyday life situation. However, in weddings (brides), festivals, or any formal event, a headdress (a diadem - as in the middle picture) is usually preferred. Note: neither non la, nor the headdress is required to be worn with ao dai.



Ao Dai with headdress
ao dai 2
Ao Dai with Non La


Men Attire


Anyone who has seen the exquisite costumes worn by Vietnamese women will recognize similarities in the traditional dress of the male. Men costumes are worn with the conventional snug collar and buttoned down on the 1eft side to the waist, with no crease in front or back. The male dress extends only to the knees and is more loose-fitting.

There are many variations on the basic theme. At the top of the list is the elaborate dress of the emperor and the mandarins. Their rank was shown in the display of color in the brocade and embroideries. Gold brocade with embroidered dragons was for the emperor only. Gold is the national color and the dragon heads the fabulous mythical animal world. Purple is the color reserved for high-ranking court mandarins, while blue is for those of lower rank.

Costumes worn for religious ceremonies also have their special colors. Dresses for ceremonial occasions usually have very wide and ample sleeves. Wedding dresses are similar to the popular fashions, and the color is usually purple or blue brocade. Dresses for mourning have frayed fringes or a line up the back and may be either black or white in color.

Monday, February 19, 2007

Definition of "TET" holiday

Read it to find out more about "TET" holiday

http://en.wikipedia.org/wiki/T%E1%BA%BFt

Component in "TET" holiday



Cay neu is a bamboo pole (New Year's Tree) stripped of its leaves except for a tuft on top. Red paper is used to decorate the tree, which is planted outside the house during the Tet holiday. The cay neu has Taoist origins and holds talismanic objects that clang in the breeze to attract good spirits and repel evil ones. On the very top, they frequently place a paper symbol of yin and yang, the two principal forces of the universe. Sometimes a colorful paper carp flag will fly from the top. The carp (or sometimes a horse) is the vehicle on which the Kitchen God travels to make his report. This tree is more common in the countryside now than in the city. It is ceremonially removed after the seventh day of Tet.

Vietnamese Peach Blossoms (Hoa Dao)


According to Vietnamese legend, once upon a time, in the East of the Soc Son Mountain, North Vietnam, existed a gigantic peach tree. The tree was so huge that its shadow extended through out a large area of land. Up on the tree, lived two powerful deities, Tra and Uat Luy. They protected the people of the land in the surrounding areas from the devils. The devils were so afraid of these two deities that even the sight of the peach tree haunted them.

However, at the end of every lunar year, these two deities had to fly back to heaven for an annual meeting with the Jade Emperor. During this time, the devils took advantage of this opportunity to harass the peaceful inhabitants. To fight the battle against these devils, people came up with the ideas of display a branch of the Peach tree in the house to scare away the devils. Since then it becomes a custom of the North Vietnamese to have a branch of a Peach tree during Tet season to protect themselves against the Satan soldiers. Those who don't have Peach tree can draw the figures of the two deities, Tra and Uat Luy, on red paper, and display them in front of the house.


Hoa Mai

While Peach tree is preferred in the North, Hoa Mai is more commonly used for this ceremony in the South because of the warm weather. Hoa Mai is a small, yellow flowering plant that is used for decoration during Tet with the meanings of prosperity and well-being for the family. The value of these flowers is determined by the number of petals - the more petals, the more expensive the flower.



Kumquat Trees

Kumquat trees about two or three feet tall are carefully selected and prominently displayed during Tet. To carefully choose a kumquat bush, the buyer must pay attention to the symmetrical shape, to the leaves and to the color and shape of the fruit. The bushes have been precisely pruned to display ripe deep orange fruits with smooth clear thin skin shining like little suns or gold coins on the first day of the lunar new year. Other fruits must still be green to ripen later. This represents the wish that wealth will come to you now and in the future. The leaves must be thick and dark green with some light green sprouts. The fruits represent the grandparents, the flowers represent parents, the buds represent children and the light green leaves represent grandchildren. The tree thus symbolizes many generations. Guests will caress the light green leaves about to sprout and compliment the discerning host who chose so carefully.

The "Mam Ngu Qua"

The "five-fruit tray" on the ancestral altar during the Tet holiday symbolizes the admiration and gratitude of the Vietnamese to Heaven and Earth and their ancestors, and demonstrates their aspiration for a life of plenty. As one theory goes, the five fruits are symbolic of the five basic elements of oriental philosophy: metal, wood, water, fire, and earth. Some people believe that the five fruits are symbols of the five fingers of a man's hand that is used to produce physical wealth for his own use and to make offerings to his ancestors. However, in a simpler way, the five fruits represent the quintessence that Heaven and Earth bless humans. This is one of the general perceptions of life of the Vietnamese, which is "When taking fruit, you should think of the grower". Today, the tray may contain five or more fruits, in the form of a pyramid like before or in an different shape. Regardless, it is still called the Mam Ngu Qua, the five-fruit tray.

Fire Crackers


The most exciting element in the celebration of Tet is the lighting of trang phao (fire crackers). These explosions are believed to drive off ghosts and evil spirits and leave good luck in their place. As thousands of households simultaneously partake in this fantastic part of Tet, the level of volume and excitement rises to a fury. This level of emotion is the most memorable part of Tet and also the part which makes it such a marvelous experience. However, firecrackers are no longer used as the government banned them in 1995.






Banh Chung


It is a square cake, wrapped in banana leaves and tied with laces of flexible bamboo slivers. It is a very rich food for the interior contains a filling of bean paste to which may be added small bits of pork meat, both fat and lean. This filling, which is amply seasoned, is pressed between layers of glutinous rice. Its square shape is considered a symbol of the thankfulness of the Vietnamese people for the great abundance of the Earth, which has supplied them with nutritious food throughout the four seasons of the year.

Cau Doi (Parallels)



Composing, challenging and displaying parallels represents an elegant cultural activity of the Vietnamese. On the occasion of Tet, parallels are written on red paper and hung on both sides of the gate, the pillars or the ancestral altar. Each pair of parallels has an equal number of words with contrasting or corresponding meanings and lines of verses. They show a keen intelligence, perception of nature and social life, uphold morality and a yearning for the well-being of all people. The red is symbolic of auspicious and powerful vitality, according to popular belief. Mingling with the green of the banh chung, the pink of the peach blooms, the yellow of the hoa mai, and the red of the parallels is sure to make the Spring warmer and cozier.

Xin Xam


After Giao Thua, the last day of the lunar calendar year, many Buddhists go to their favorite pagoda to pray for a good year and to get a fortune reading for the whole year. Each person will get a chance to shake the tube that contains reading sticks, until one stick falls out of the tube. In the case that many sticks drop out of the tube, that person will have to repeat the process. Afterwards, usually the monks will translate the meanings of the reading.

"Nguyen Hue" Street , the beautiful street in viet nam, in the January 1st , lunar year









Picture of the "TET" holiday in viet nam

HAPPY VIET NAM NEW YEAR

Happy new year to you, my family, my dear friend. We call this day is "Tet" holiday, and i want to tell all of you about "TET" holiday in viet nam.
WELCOME YOU TO VIET NAM

Before "TET" holiday



Some days before Tet Ong Tao (on the 23rd of the twelfth moon), people start their preparations for the Kitchen God's journey to the Heaven to make his report to the Jade Emperor. This report includes the year's activities of the household in which he has lived. A farewell and thank-you dinner is given to the Kitchen God at Tet Ong Tao. The Kitchen God will need a week for his mission to Heaven.

After the Kitchen God has gone to the Heaven, preparations for the New Year festivities begin in enthusiasm. The week before New Year's Eve is called a period of "Tat Nien". Tat Nien (literally meaning the end or "to extinguish the year") is the celebration of the last session of a period, such as the last class of school, the last day in the office, even the last bath, all with parties and great ceremonies.

Some families set up a Tet tree outside the house in the week before New Year's Eve. The Tet tree, called cay neu, is a bamboo pole stripped of its leaves except for a tuft on top. It is supposed to ward off the evil spirits during absence of the Spirit of the Kitchen God.

Sweeping and scrubbing must be done during this time as tradition discourages it during the Tet holiday. Two items required for the proper enjoyment of Tet are peach flower branches and kumquat trees. Throughout the country, on bicycles of roving vendors, flowers create great splashes of color. In the north, the soft rose-colored dao peach flowers decorate homes and offices while the bright golden yellow branches of the hoa mai are preferred in the south.

Kumquat trees, about two or three feet tall, are carefully selected and prominently displayed. To carefully choose a kumquat tree, the buyer must pay attention to the symmetrical shape, to the leaves and to the color and shape of the fruit. The bushes have been precisely pruned to display ripe deep orange fruits with smooth clear thin skin shining like little suns or gold coins on the first day. Other fruits must still be green to ripen later. This represents the wish that wealth will come to you now and in the future.

When Tet is approaching, crowds of shoppers at the markets become thicker and more frantic each night, holding up traffic as they jostle each other to reach the counters with the best buys. Prices are a bit higher, but thriftiness is not considered a virtue at Tet.

While shoppers roam the streets, banh chung patties wrapped in leaves are steaming in giant vats. After being boiled until the outside of banh chung has taken on a lovely light green tinge, it is taken out of the vats and cooled. Banh chung will be eaten and used as offerings to worship ancestors during Tet.

Before the New Year's Eve, shops, stalls and restaurants are locked, leaving a notice hung on the door announcing the date of reopening. Special dishes must be completed to serve the family and its guests for the first three days of the new year.

Google