티스토리 툴바



개발노트/XML2012/01/27 17:46
String t_xmlStr =           
   "<root>" +           
   "<item value=\"돈까스\">" +
   "<item value=\"순대국\">" +
   "<item value=\"짜장면\">" +
   "</item></item></item></root>";
   
  DocumentBuilderFactory t_dbf = null;       
  DocumentBuilder t_db = null;       
  Document t_doc = null;       
  NodeList t_nodes = null;       
  Node t_node = null;       
  Element t_element = null;       
  InputSource t_is = new InputSource();        
  try{           
   t_dbf = DocumentBuilderFactory.newInstance();           
   t_db = t_dbf.newDocumentBuilder();           
   t_is = new InputSource();           
   t_is.setCharacterStream(new StringReader(t_xmlStr));           
   t_doc = (Document) t_db.parse(t_is);           
   t_nodes = t_doc.getElementsByTagName("item");            
   for (int i = 0, t_len = t_nodes.getLength(); i < t_len; i ++){              
    t_element = (Element)t_nodes.item(i);                
    System.out.println(t_element.getAttribute("value"));   
    collection.add(new personVO(t_element.getAttribute("value"), t_element.getAttribute("value"), t_element.getAttribute("value")));
   }       
  }catch (Exception e){           
   e.printStackTrace();       
  }
Posted by WebProgrammer 1010
개발노트/Java2012/01/27 14:50

jar 파일 생성 시 MANIFEST.MF 작성

JAVA 2009/03/05 08:56
파일 위치 및 명령어 실행 위치 현황
D:\Java_EXE \
└Genealogy2 \ ←명령어 실행 위치
└data
└lib ← swt.jar 위치
META-INF (folder)
└src ← 실행 파일 위치(package)

● META-INF 폴더는 root 폴더 바로 아래에 만든다.
( src 등 기타 위치에 생성하는 건 의미없다.
eclipse에서 export를 통해 jar를 만들 때 root 폴더가 아닌 곳에 만든 manifest.mf를 참조할 경우
eclipse가 root 폴더 아래 새로 만들기 때문에 실행 파일 설정이 정상적으로 이뤄지지 않는다. )

root\META-INF 밑에 MANIFEST.MF 만들어서 아래 내용 추가하고, Export 할 때 manifest.mf를 추가해 준다. (eclipse에서 작업해야 Resource is out of sync ~~~ 안 뜬다. 뜨면 한 번 열어서 읽어 준다.)

MANIFEST.MF 파일 내용
Manifest-Version: 0.1
Class-Path: lib/swt.jar
Main-Class: src.ManageGenealogy


Class-Path: lib/swt.jar ← jar 파일 내부 폴더에 둔다.
그 외 참조할 class가 있으면 그 위치를 적어준다. 구분자는 ' '
이 예제의 경우, swt.jar 를 제외한 모든 class가 메인 클래스와 같은 src 하부에 있어서 추가없음.
Class-Path는 72자까지만 됨.
Class-Path는 외부 경로(local)만 가능함. Jar 내부나, Internet 등으로 접근하는 Jar는 참조할 수 없음.
(-> 내가 만든 jar 안에 내가 참조할 외부 jar를 넣고, Class-Path에 잡아주어도 참조하지 못한다.
참조하려면 1. 참조할 jar를 풀어서 내 jar 안에 넣고, sealed 처리하던가
2. 외부에 참조할 jar를 위치시키고 class-path에 경로를 잡아준다.

Main-Class: src.ManageGenealogy ← 실행 파일 경로 및 파일 명
jar 파일을 실행 가능하게 만든다.
실행 명령어 : java -jar Genealogy.jar

※ 주의사항 :
1. MANIFEST.MF 내에서 다른 class, directory, jar를 참조할 때는 경로 정보를 입력할 때 '/'를 사용한다.
(경우에 따라서 '\'를 쓰게 되는 경우도 있으니 아래 Exception 발생 시 경로를 수정해 볼 것.
Exception in thread "main" java.lang.NoClassDefFoundError: aaa/bbb/ccc )
2. 각 'attirbute :' 다음에 공백 한 칸 둘 것. (ex 'Class-Path: ')
3. Main-Class attribute 다음에 carrage return(엔터) 하나 둘 것. 안 그러면 실행 시 main class를 인식 못 함.

참조 : http://www.ibm.com/developerworks/kr/library/j-jar/index.html
http://java.sun.com/docs/books/tutorial/deployment/jar/basicsindex.html
http://blog.naver.com/echris7?Redirect=Log&logNo=140012585340
관련 글 : http://digicom.tistory.com/165
---------------------------------------------------------------------------------------------------

...


Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:45
:http://xstream.codehaus.org/tutorial.html <- 참조

Serializing an object to XML

Let's create an instance of Person and populate its fields:

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

Now, to convert it to XML, all you have to do is make a simple call to XStream:

String xml = xstream.toXML(joe);

The resulting XML looks like this:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

It's that simple. Look at how clean the XML is.

Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:43

ThoughtWorks에서 만든 Xstream을 활용한다.
Xstream 최대의 장점은 초 간단...
얼마나 간단하면 튜토리얼이 Two Minute Tutorial 이다.
클래스 패스에 xstream-xxx.jar를 넣고.. 다음 코드를 실행하면..
XStream xstream = new XStream();
Person joe = new Person();
joe.setAge(30);
joe.setName("Joe");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
System.out.println(xml);
출력 내용은.. 간단하기 이를데 없다.. 만족.. ^^
<object.Person>
<name>Joe</name>
<age>30</age>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
</object.Person>
object.Person은 좀 보기 싫어.. 별칭(alias)를 준다.
XStream xstream = new XStream();
xstream.alias("person", Person.class);
Person joe = new Person();
joe.setAge(30);
joe.setName("Joe");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
System.out.println(xml);
그럼.. 출력은 내 스타일(?)로 변모...
<person>
<name>Joe</name>
<age>30</age>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
</person>
null값을 갖는 속성은 어찌 되는가?
XStream xstream = new XStream();
xstream.alias("person", Person.class);
Person joe = new Person();
// joe.setAge(30);
joe.setName("Joe");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
출력이 안되는군.
<person>
<name>Joe</name>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
</person>
XML을 자바 객체로..
XStream xstream = new XStream();
xstream.alias("person", Person.class);
String xml =
"<person>" +
"<name>Joe</name>" +
"<fax>" +
"<code>123</code>" +
"<number>9999-999</number>" +
"</fax>" +
"<phone>" +
"<code>123</code>" +
"<number>1234-456</number>" +
"</phone>" +
"</person>" ;
Person joe = (Person)xstream.fromXML(xml);
alias 처리를 포함해도 세 문장이면 되는구만.
단.. 자바 객체 변환(Deserializing)시에는 xpp.jar(xstream zip 파일의 lib에 있음)가 필요하다.
Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:29

JAXB를 활용한 Java 객체의 XML 자동 변환

Using JAXB for XML data binding

자바 SE 6에서 JAXB(Java Architecture for XML Binding)를 사용하여 JAVA -> XML 변환하는 테스트 샘플을 만들어 보았습니다. 물론 XStream으로도 가능합니다.

1. JAXB란?
JAXB를 사용하면 XML과 자바 간에 쉽게 앞뒤로 이동할 수 있습니다. JAXB 구현은 XML 스키마를 받아 해당 스키마에 매핑되는 자바 클래스를 생성하는 스키마 컴파일러를 제공합니다. XML 문서의 데이터는 JAXB의 바인딩 런타임 프레임워크를 통해, 스키마 컴파일러가 생성한 클래스에 자동으로 바인딩될 수 있습니다. 이 작업을 언마샬링(Unmarshalling)이라고 합니다. 언마샬링되면 필요에 따라 콘텐츠를 Java로 조작하거나 수정할 수 있습니다. JAXB는 자바 개체에서 XML 인스턴스 문서로 데이터를 쓸(마샬링할) 수도 있습니다.

2. 샘플 소스
*. Person bean 객체
package client;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "person")
public class Person
{
private String firstName;
private String lastName;
private Family family;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Family getFamily() {
return family;
}

public void setFamily(Family family) {
this.family = family;
}
}

*. Family bean 객체
package client;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;

public class Family
{
private String description;
@XmlElementWrapper(name = "persons")
@XmlElement
private List<Person> members = new ArrayList<Person>();


public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public List<Person> getMembers() {
return members;
}
}

*. Java객체를 Xml로 변환하는 클라이언트 샘플
package client;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBClient
{
public static void main(String[] args) {
JAXBContext context = null;
List<Person> list = null;
Person person1 = null;
Person person2 = null;
Family family = null;
Marshaller marshaller = null;

try {
context = JAXBContext.newInstance(Person.class);
list = new ArrayList<Person>();

person1 = new Person();
family = new Family();

family.setDescription("Family Mimul");
person1.setFirstName("IlDong");
person1.setLastName("Hong");
person1.setFamily(family);
list.add(person1);

person2 = new Person();
person2.setFirstName("LeeDong");
person2.setLastName("Hong");
person2.setFamily(family);
list.add(person2);

// Marshal 객체를 XML로 변환
// Unmarshal the objects from XML

marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);

marshaller.marshal(person2, System.out);

} catch (JAXBException e) {
e.printStackTrace();
}
}
}


3. 실행 결과
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<person>
<family>
<persons/>
<description>Family Mimul</description>
</family>
<firstName>LeeDong</firstName>
<lastName>Hong</lastName>
</person>
Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:09

How to create XML file in Java – (JDOM Parser)
Published: August 4, 2011 , Updated: August 4, 2011 , Author: mkyong

In this example, we show you how to use JDOM parser to create document, element and attribute in a XML file.

1. XML File

At the end of this example, following XML file will be created.

File : file.xml

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>199999</salary>
  </staff>
  <staff id="2">
    <firstname>low</firstname>
    <lastname>yin fong</lastname>
    <nickname>fong fong</nickname>
    <salary>188888</salary>
  </staff>
</company>

3. JDOM Example

JDOM example to create above XML file.

import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
 
public class WriteXMLFile {
	public static void main(String[] args) {
 
	  try {
 
		Element company = new Element("company");
		Document doc = new Document(company);
		doc.setRootElement(company);
 
		Element staff = new Element("staff");
		staff.setAttribute(new Attribute("id", "1"));
		staff.addContent(new Element("firstname").setText("yong"));
		staff.addContent(new Element("lastname").setText("mook kim"));
		staff.addContent(new Element("nickname").setText("mkyong"));
		staff.addContent(new Element("salary").setText("199999"));
 
		doc.getRootElement().addContent(staff);
 
		Element staff2 = new Element("staff");
		staff2.setAttribute(new Attribute("id", "2"));
		staff2.addContent(new Element("firstname").setText("low"));
		staff2.addContent(new Element("lastname").setText("yin fong"));
		staff2.addContent(new Element("nickname").setText("fong fong"));
		staff2.addContent(new Element("salary").setText("188888"));
 
		doc.getRootElement().addContent(staff2);
 
		// new XMLOutputter().output(doc, System.out);
		XMLOutputter xmlOutput = new XMLOutputter();
 
		// display nice nice
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("c:\\file.xml"));
 
		System.out.println("File Saved!");
	  } catch (IOException io) {
		System.out.println(io.getMessage());
	  }
	}
}
Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:07
How to modify XML file in Java – (JDOM Parser)
Published: April 3, 2010 , Updated: August 4, 2011 , Author: mkyong

JDOM XML parser example to modify an existing XML file :

  1. Add a new element
  2. Update existing element attribute
  3. Update existing element value
  4. Delete existing element

1. XML File

See before and after XML file.

File : file.xml – Original XML file.

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>5000</salary>
  </staff>
</company>

Later, update above XML file via JDOM XML Parser.

  1. Add a new “age” element under staff
  2. Update the staff attribute id = 2
  3. Update salary value to 7000
  4. Delete “firstname” element under staff

File : file.xml – Newly modified XML file.

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="2">
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>7000</salary>
    <age>28</age>
  </staff>
</company>

2. JDOM Example

JDOM parser to update or modify an existing XML file.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
 
public class ModifyXMLFile {
	public static void main(String[] args) {
 
	  try {
 
		SAXBuilder builder = new SAXBuilder();
		File xmlFile = new File("c:\\file.xml");
 
		Document doc = (Document) builder.build(xmlFile);
		Element rootNode = doc.getRootElement();
 
		// update staff id attribute
		Element staff = rootNode.getChild("staff");
		staff.getAttribute("id").setValue("2");
 
		// add new age element
		Element age = new Element("age").setText("28");
		staff.addContent(age);
 
		// update salary value
		staff.getChild("salary").setText("7000");
 
		// remove firstname element
		staff.removeChild("firstname");
 
		XMLOutputter xmlOutput = new XMLOutputter();
 
		// display nice nice
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("c:\\file.xml"));
 
		// xmlOutput.output(doc, System.out);
 
		System.out.println("File updated!");
	  } catch (IOException io) {
		io.printStackTrace();
	  } catch (JDOMException e) {
		e.printStackTrace();
	  }
	}
}

Posted by WebProgrammer 1010
개발노트/XML2012/01/26 13:06

How to read XML file in Java – (JDOM Parser)
Published: December 21, 2009 , Updated: August 4, 2011 , Author: mkyong

JDOM is, quite simply, a Java representation of an XML document. JDOM provides a way to represent that document for easy and efficient reading, manipulation, and writing. It has a straightforward API, is a lightweight and fast, and is optimized for the Java programmer. It’s an alternative to DOM and SAX, although it integrates well with both DOM and SAX.

JDOM, Java XML parser, is more user friendly in the way of accessing the XML document.

In this example, we show you how to use JDOM to read a XML file, and print out each element orderly.

1. Download the JDOM library

JDOM is not like SAX or DOM, which bundled in JDK. To use JDOM, you need to download the library manually.

Get JDOM from JDOM official site or declares following dependency if you are using Maven.

    <dependency>
	<groupId>jdom</groupId>
	<artifactId>jdom</artifactId>
	<version>1.1</version>
    </dependency>

2. XML File

XML file as following

<?xml version="1.0"?>
<company>
	<staff>
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff>
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>

3. Java File

Use JDOM parser to parse above XML file.

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
 
public class ReadXMLFile {
	public static void main(String[] args) {
 
	  SAXBuilder builder = new SAXBuilder();
	  File xmlFile = new File("c:\\file.xml");
 
	  try {
 
		Document document = (Document) builder.build(xmlFile);
		Element rootNode = document.getRootElement();
		List list = rootNode.getChildren("staff");
 
		for (int i = 0; i < list.size(); i++) {
 
		   Element node = (Element) list.get(i);
 
		   System.out.println("First Name : " + node.getChildText("firstname"));
		   System.out.println("Last Name : " + node.getChildText("lastname"));
		   System.out.println("Nick Name : " + node.getChildText("nickname"));
		   System.out.println("Salary : " + node.getChildText("salary"));
 
		}
 
	  } catch (IOException io) {
		System.out.println(io.getMessage());
	  } catch (JDOMException jdomex) {
		System.out.println(jdomex.getMessage());
	  }
	}
}

Output

First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000
Posted by WebProgrammer 1010

JavaBeans as datasource in JasperReports

JasperReports is very flexible report generation tool on both beginner as well as enterprise level. It supports many data access mechanisms for retrieving data and rendering to the report like SQL, EJBQL, HSQL, XML, JavaBeans, XPath etc. But here our main focus is on the usage of JavaBeans.

I have divided the whole task of report generation into certain activities as shown below:
1. Create a simple Java Class (JavaBean) with properties and their accessors and mutators.
2. Design a report either manually or you can use IDE like iReports for that, I have used iReports.
3. Compile the report using Java and run it to test whether its working or not.

We will start with step 1:
Create a simple Java Class thats a simple POJO(Plain Old Java Object) its contains the data for the report. You can take any entity for that, I am here taking a simple entity Student and creating a Java file shown below with the name Student.java.

package beansforjasper;

public class Student
{
private String name;
private String roll_no;
private String fathers_name;
private String studying_in;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll_no() {
return roll_no;
}
public void setRoll_no(String roll_no) {
this.roll_no = roll_no;
}
public String getFathers_name() {
return fathers_name;
}
public void setFathers_name(String fathers_name) {
this.fathers_name = fathers_name;
}
public String getStudying_in() {
return studying_in;
}
public void setStudying_in(String studying_in) {
this.studying_in = studying_in;
}
}

In addition to the above code we have to add a static method that returns a collection. This will be used as datasource for report. I have made a simple static method as follows:


public static Collection getStudentList()
{
Vector students = new Vector();
try
{
Student student = new Student();
student.setRoll_no("101");
student.setName("Steve");
student.setFathers_name("Jack");
student.setStudying_in("I-A");
students.add(student);
student = new Student();
student.setRoll_no("102");
student.setName("Mark");
student.setFathers_name("Henry");
student.setStudying_in("I-A");
students.add(student);
}
catch(Exception ex)
{
System.out.println(ex);
}
return students;
}


Thats all for as far as datasource for report is concerned.


Step 2 (The iReports part):
Create a new report in iReports as show in diagram 1.

Diagram 1

Now create a new datasource by clicking on "Report Datasources" button on toolbar. You will see a window showing the tabular representation of the all existing datasources. Now click on "New" button and you will see datasource types as shown in Diagram 2 below:

Diagram 2

Now select JavaBean set datasource and click on the "Next" button. This will take you to a new window, that will ask you for name, fully qualified class name of the factory class that will generate set and of course the static method thats going to return either Collection or Array of JavaBeans. Be care full to select the radio button specific to the return type of your static method. This is shown in Diagram 3 below:

Diagram 3

After doing all this work when you click on "Test" button an error will be generated, this is mainly because the class path is not set for our "Student.class" file. To set classpath follow steps below:
1. Goto Tools(Menu)>>Options
2. Select iReport tab and then select "Classpath" tab now click on "Add Folder" if you have only class file and add directory containing it else "Add JAR" if you have distributable jar file.

After the classpath is set Now its time to add data fields so that these can be used in our report.
In order to do that Right click the Report Node(Root Node) in the "Report Inspector" and choose "Edit Query" from popup menu. A window will appear choose "JavaBean Datasource" tab in that window as shown below:

Diagram 4

Provide the fully qualified class name of the JavaBean and click on "Read Attributes" you will see all the fields that this class contains. Select the fields that you want to make available for the report and then click on "Add Selected Fields".

I have created a simple design just to show you how easy it is to create reports with iReport. My sample is shown as Diagram 5.

Diagram 5


This is actually an attemp to show how JavaBeans can be used as datasource for the JasperReports.
Here I have used iReport 3.7.2.

On clicking the preview its generates preview as as shown below in Diagram 6.

Diagram 6

Step 3(Compilation and Test using Java)
To test this demo using a Java program we can use the following code:


public static void main(String[] str)
{
try
{
JasperReport jasperReport = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
jasperDesign = JRXmlLoader.load("<Path of Report>");
jasperReport = JasperCompileManager.compileReport(jasperDesign);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(beansforjasper.Student.getStudentList()));
JasperExportManager.exportReportToPdfFile(jasperPrint,"StudentInfo.pdf");
JasperViewer.viewReport(jasperPrint);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex);
}
}


This will generate a "StudentInfo.pdf" file and will invoke Jasper report viewer that will show you the generated report.

Remember to put the dependencies at the classpath while running the above program.
Posted by WebProgrammer 1010


Posted by WebProgrammer 1010