2009年6月22日 星期一

java XML 寫入

轉貼幾篇在java 讀取 xml 的文章

1. 用jdom來創建xml文件

2. Java XML API 漫谈

以下是我修改後的範例

包含新增 、刪除、列出所有



//-------------------------------------------------
// JDOM sample
//-------------------------------------------------

import java.io.*;

import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;





public class myCreate {

public myCreate() {



// 要寫入的文字
String[] strChapter = { "XML sample ", "write XML", "what is XML", "control XML", "check XML", "transfare XML" };


//建立jdom的 document 的 element
Element elmtRoot = new Element("Article");

// 建立jdom的 document "Article" 下
Document docJDOM = new Document(elmtRoot);

//新增 子 element 在

for(int i=0; i<6; elmtchapter =" new" style="color: rgb(0, 153, 0);">//刪除 子節點 by index, 此例是第4個
List lstChapter = elmtRoot.getChildren("Chapter");
lstChapter.remove(4);



//刪除2 特定名稱
int x=-1;
for(int i=0;i // 列出所有
for(int i=0;i//新增2

Element elmtChapter = new Element("Chapter");

elmtChapter.addContent("TEst");

elmtChapter.setAttribute("sort", "9");

elmtRoot.addContent(elmtChapter);



//輸出xml檔, 寫入 myJDOM.xml

OutputXML(docJDOM, "myJDOM.xml");

}



private void OutputXML(Document docXML, String strFilename) {

XMLOutputter fmt = new XMLOutputter();

try {

// fmt.setFormat(newFormat)();

//fmt.setNewlines(true);


FileWriter fwXML = new FileWriter(strFilename);

fmt.output(docXML, fwXML);

fwXML.close();

}

catch (IOException e) {

e.printStackTrace();

}

}



public static void main(String[] args) {

myCreate myCreate1 = new myCreate();

}

}

2009年6月6日 星期六

Java Native Interface 實做 傳java 函數

以下是我參考 的文章
hello world的話就參考下面的文章就好,這裡我是自己在寫出另一個範例
教學
http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=3997


Thinking in Java, 2nd edition, Revision 9

參數教學

http://dev.kanngard.net/Permalinks/ID_20050509144235.html

實作環境
ms XP

前置環境
  • 確定 java 有無安裝
關於這點可以參考java world "swanky "兄的文章
  • 確定 設定好 java path
  • 安裝 vc 環境
java lib 移到vc 的 lib

vc lib 位置
ex.
vs 2008 C:\Program Files\Microsoft Visual Studio 9.0\VC\lib
vc 6 C:\Program Files\Microsoft Visual Studio\VC98\Include

java 位置
C:\Program Files\Java\jdk1.6.0_11\lib jdk1.6.0_11 隨版本不同

步驟
1. 建立java file
2. 編譯出class 檔 ex. javac classname .java
3. 編譯出head 檔 給c, c++ 使用 ex javah -jni classname
4. 建立vc 專案 for dll
5. 複製 head 檔到vc 專案
6. 建立dll


建立java file
//-----------------------------------------------------------------------
// UseObjects.java
//-----------------------------------------------------------------------

class javaAddClass {
private int c;
public void setc(int varc){ this.c=varc;}
public int getc(){return this.c;}
public void add(int a, int b) { this.c = a+b; }
}

public class jniDemo {

// 宣告要傳給dll用的obj
private native void addObject(javaAddClass obj);

static {
// 讀取dll名稱
System.loadLibrary("jniDemo");
// Linux hack, if you can't get your library // path set in your environment: // System.load( //"/home/bruce/tij2/appendixb/UseObjImpl.so");
}


// 主程式
public static void main(String[] args) {

// 宣告新的物件
jniDemo app = new jniDemo();
javaAddClass jAddObj = new javaAddClass();

// 設定參數
jAddObj.setc(2);

// 呼叫dll
app.addObject(jAddObj);

// 測試有無執行dll,顯示變更後的值
System.out.println("Java: " + jAddObj.getc());
}
}


編譯出class 檔
javac UseObjects .
java

編譯出head 檔
javah -jni UseObjects

建立vc 專案 for dll, 並複製 head 檔到vc 專案
建立方式有很多文章 搜尋 vc dll 就很多了
以下轉貼兩篇
http://genewince.blogspot.com/2008/03/visual-c-dll-gene.html
http://www.functionx.com/visualc/libraries/staticdll.htm

附上DEMO 的 head檔和c檔

head 檔不用改,由java產生的複製
//-----------------------------------------------------------------------
// jniDemo.h
//-----------------------------------------------------------------------
* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class jniDemo */

#ifndef _Included_jniDemo
#define _Included_jniDemo
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: jniDemo
* Method: addObject
* Signature: (LjavaAddClass;)V
*/
JNIEXPORT void JNICALL Java_jniDemo_addObject
(JNIEnv *, jobject, jobject);

#ifdef __cplusplus
}
#endif
#endif




//-----------------------------------------------------------------------

// jniDemo.cpp

//-----------------------------------------------------------------------

//: appendixb:UseObjImpl.cpp //# Tested with VC++ & BC++. Include path must //# be adjusted to find the JNI headers. See //# the makefile for this chapter (in the //# downloadable source code) for an example.

// jniDemo.cpp : Defines the exported functions for the DLL application. //

#include "stdafx.h"
#include "jniDemo.h"

extern "C" JNIEXPORT void JNICALL Java_jniDemo_addObject
(JNIEnv * env, jobject, jobject obj) {

// get class and name jAddClass
jclass jAddClass = env->GetObjectClass(obj);

// get function [ GetFieldID(class name, function name, type) ]
// java code : private int c

jfieldID jobjC = env->GetFieldID(
jAddClass, "c", "I");

// get function [ GetFieldID(class name, function name, type) ]
// java code : public void setc(int varc){ this.c=varc;}

jmethodID jobjSetc = env->GetMethodID(
jAddClass, "setc", "(I)V");

// get function [ GetFieldID(class name, function name, type) ]
// java code : public int getc(){return this.c;}

jmethodID jobjGetc = env->GetMethodID(
jAddClass, "getc", "()I");

// get function [ GetFieldID(class name, function name, type) ]
// java code : public void add(int a, int b) { this.c = a+b; }

jmethodID jobjAddc = env->GetMethodID(
jAddClass, "add", "(II)V");

// get value
int value = env->GetIntField(obj, jobjC);
printf("the C is : %d\n", value);

// call set function
env->CallVoidMethod(obj, jobjSetc, 5);
// call get function
int value2 = (int) env->CallObjectMethod(obj, jobjGetc);
printf("after set the C is : %d\n", value2);

// call add function
env->CallVoidMethod(obj, jobjAddc, 5, 6);
// call get function
int value3 = (int) env->CallObjectMethod(obj, jobjGetc);
printf("after add the C is : %d\n", value3);
}

建立dll
build 後,將dll移到java檔的位置,在執行
java UseObjects
即可
結果如下


2009年6月3日 星期三

JNative DEMO 實做

參考了一下 平乐天地的文章


我的環境如下
以下分兩個階段

1. dll 建立
透過 vc6 建立,過程同平乐天地的文章

建立專案

add.h:
#define DLLEXPORT extern "C" _declspec(dllexport)
DLLEXPORT int addTest(int a, int b);
DLLEXPORT char* getString();

add.cpp:
#include "add.h";
int addTest(int a, int b)
{
return a+b;
}
char* getString()
{
char* test = "this is test";
return test;
}

DLL 建立可參考這兩篇文章
http://hi.baidu.com/44997/blog/item/dcf47b59198b2d2a2934f0e1.html
http://blog.csdn.net/askAloe/archive/2006/09/08/1192522.aspx

2. java 端讀取 dll

以下是我修改後的範例
編譯前記得匯入jnative.jar



import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;


public class LoadDllDemo {


public static final String GetString() throws NativeException,IllegalAccessException
{
JNative n = null;
String str=null;

try {

// 取得dll JNative(dll位址, 函數名稱);
n = new JNative("add.dll", "getString");

// 設定回傳質類型
n.setRetVal(Type.STRING);

// 使用方法
n.invoke();

// 取得回傳值
str=n.getRetVal();

return str;

} finally {
if (n != null)
// relase
n.dispose();
}

}


public static final int addTest(int a, int b) throws NativeException,IllegalAccessException
{
JNative n = null;
int x=0;

try {

// 取得dll JNative(dll位址, 函數名稱);
n = new JNative("add.dll", "addTest");

// 設定回傳質類型
n.setRetVal(Type.INT);

// 設定傳入參數 setParameter(位置, 類型 , 值)
// 值 必須是 string
n.setParameter(0, Type.INT, ""+a);
n.setParameter(1, Type.INT, ""+b);

// 使用方法
n.invoke();

// 取得回傳值
x=Integer.parseInt(n.getRetVal());

return x;

} finally {
if (n != null)
// relase
n.dispose();
}

}




public static void main(String[] args) throws NativeException, IllegalAccessException{

System.out.println("LoadDllDemo 的 String : ");
System.out.println(LoadDllDemo.GetString());
System.out.println("------------------------------------------------- ");
System.out.println("LoadDllDemo 的 addTest function : 5+7= ");
System.out.println(LoadDllDemo.addTest(5,7));

}
}

2009年6月2日 星期二

GAE&JDO by XMLHttpRequest()

基本上 和

Google App Engines Datastore with JDO ( GAE&JDO 1/7)) 這篇類似

不過在index.html 方面改用 XMLHttpRequest 呼叫server

範例網站 http://6.latest.catontest.appspot.com/


例子這裡就簡單的介紹三個功能
  1. 新增
  2. 查詢所有
  3. 和更新三個功能

js 檔案格式如下

//-----------------------------------------------------
// 宣告 set httprequest by explorer
//-----------------------------------------------------
XmlsReq = false;
if(window.XMLHttpRequest) {
XmlsReq = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
XmlsReq = new ActiveXObject("Msxml2.XMLHTTP"); // ie
} catch(e) {
XmlsReq = new ActiveXObject("Microsoft.XMLHTTP"); // ie
}
}


//----------------------------------------------------------
// 新增 PostHttpRequestAdd()
//----------------------------------------------------------
function PostHttpRequestAdd() {
// servlet name 記得要在web.xml 設定
var uri='add';

// 連接成功傳回訊息
XmlsReq.onreadystatechange=function() {
if (XmlsReq.readyState==4 && XmlsReq.status == 200) {
alert(XmlsReq.responseText);
}

}

// 取得輸入檔案的值
var aUserName = document.getElementById('aUserName').value;
var aUserPassword =document.getElementById('aUserPassword').value;
var aUserContent= document.getElementById('aUserContent').value;

// 設定要傳到server的值
var param = "aUserName="+aUserName+"&aUserPassword="+aUserPassword+"&aUserContent="+aUserContent;

// 以POST 方式 像server 傳送資料
XmlsReq.open("POST",uri,true);
XmlsReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XmlsReq.send(param);
}


2. 查詢所有

//----------------------------------------------------------
// 新增 GetHttpRequestShow()
//----------------------------------------------------------
function GetHttpRequestShow() {
// servlet name 記得要在web.xml 設定
var uri='show';

// 連接成功傳回訊息
XmlsReq.onreadystatechange=function() {
if (XmlsReq.readyState==4 && XmlsReq.status == 200) {
alert(XmlsReq.responseText);
}
}

// 以GET方式 像server 傳送資料
XmlsReq.open("GET",uri,true);
XmlsReq.send(null);
}


//----------------------------------------------------------
// 新增 PostHttpRequest()
//----------------------------------------------------------
function PostHttpRequest() {
// servlet name 記得要在web.xml 設定
var uri='update';

// 連接成功傳回訊息
XmlsReq.onreadystatechange=function() {
if (XmlsReq.readyState==4 && XmlsReq.status == 200) {
alert(XmlsReq.responseText);
}

}

// 取得輸入檔案的值
var uUserName = document.getElementById('uUserName').value;
var uUserPassword =document.getElementById('uUserPassword').value;
var uUserContent= document.getElementById('uUserContent').value;

// 設定要傳到server的值
var param = "uUserName="+uUserName+"&uUserPassword="+uUserPassword+"&uUserContent="+uUserContent;


// 以POST 方式 像server 傳送資料
XmlsReq.open("POST",uri,true);
XmlsReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XmlsReq.send(param);
}



三個功能的 server 端 檔案如下


//-----------------------------------------------------
// add.java
//-----------------------------------------------------
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdo.cookie.example.PMF;
import jdo.cookie.example.User;

@SuppressWarnings("serial")
public class add extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {

/// get content
String UserName = req.getParameter("aUserName");
String UserPassword = req.getParameter("aUserPassword");
String UserContent = req.getParameter("aUserContent");

System.out.println(UserName);

/// Set new user
User newUesr=new User(UserName,UserPassword,UserContent );

/// Get Persistence Manager
PersistenceManager pm = PMF.get().getPersistenceManager();

/// check the name is already exist
String query = "select from " + User.class.getName() + " where Name == "+ "'"+UserName+"'";
List UserAll = (List) pm.newQuery(query).execute();

/// declare the output function,
/// out.println the html code in the client browser
PrintWriter out = resp.getWriter();

if(UserAll.isEmpty()){
out.println(newUesr.GetName());
/// add user in data store
pm.makePersistent(newUesr);
out.println("Success");
}
else
{
out.println("already exist");
}

}


}

//-----------------------------------------------------
// show.java
//-----------------------------------------------------

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdo.cookie.example.PMF;
import jdo.cookie.example.User;

@SuppressWarnings("serial")
public class show extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {


/// set response type
resp.setContentType("text/plain");

/// get Persistence Manager
PersistenceManager pm = PMF.get().getPersistenceManager();

/// set query String
String query = "select from " + User.class.getName() ;

/// start query
List userAll = (List) pm.newQuery(query).execute();

/// declare the output function,
/// out.println the html code in the client browser
PrintWriter out = resp.getWriter();

/// check the data is exist or not
if(userAll.isEmpty()){
out.println("no data exist");
}
else
{
/// print all data name and content
for (User g : userAll) {
resp.getWriter().println(g.GetName()+" :"+" Content ="+g.GetContent());
}
}

}
}



//-----------------------------------------------------
// update .java
//-----------------------------------------------------
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdo.cookie.example.PMF;
import jdo.cookie.example.User;

public class update extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {

/// set response type
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("UTF-8");

/// get content
String UserName = req.getParameter("uUserName");
String UserPassword = req.getParameter("uUserPassword");
String UserContent = req.getParameter("uUserContent");

System.out.println(UserName);

/// get Persistence Manager
PersistenceManager pm = PMF.get().getPersistenceManager();

/// check the name is already exist
String query = "select from " + User.class.getName() + " where Name == "+ "'"+UserName+"'";
List UserAll = (List) pm.newQuery(query).execute();

/// declare the output function,
/// out.println the html code in the client browser
PrintWriter out = resp.getWriter();

/// declare Transaction when you update
Transaction tx = pm.currentTransaction();

try {

tx.begin();

/// get the User you want update
Iterator iter=UserAll.iterator();
User my_obj=(User)iter.next();

if (my_obj.GetPassword().equals(UserPassword))
{

my_obj.SetContent(UserContent); // Change the value
out.println("OK");
/// must be commit or will be do nothing
tx.commit();
}

}
catch (Exception e)
{
/// when no this data
if (tx.isActive())
{
out.println("sorry retry again");
tx.rollback();
}
}


}


}

Java Native Interface 使用c,c++ 函式 在java

想利用 c,c++ 編輯好得方法在 java 有很多方法



Java Native Interface(jni


  • 文章
http://java.sun.com/j2se/1.4.2/docs/guide/jni/

http://blog.ring.idv.tw/comment.ser?i=127

http://enijmax.2y.idv.tw/linux/CLib_Jni.html


JNative : 直接使用dll 的函數
  • download
http://sourceforge.net/projects/jnative/
  • 文章
http://blog.yam.com/gonex/article/16647453

轉貼 eclipse 編譯 c++

基本上步驟

安裝以下軟體
1. eclipse 平台
2. eclipse dct
3. MinGW

注意 mingw 要設定path

其他參考文件
http://nknush.kh.edu.tw/~johnsirhp/Eclipse+CDT+MinGW.htm

關於c 的編譯環境 eclipse 也有提供 專門 for c ide

http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/ganymede/SR2/eclipse-cpp-ganymede-SR2-win32.zip