顯示具有 HTTP request 標籤的文章。 顯示所有文章
顯示具有 HTTP request 標籤的文章。 顯示所有文章

2011年1月4日 星期二

Java Http post with SSLSocket

使用 SSL 的 程式碼如下



import java.net.*;
import java.security.Security;
import java.io.*;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


try {
String xmldata = "xx";

//Create socket
String hostname = "xxx.appspot.com";
int port = 443;
InetAddress addr = InetAddress.getByName(hostname);

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sock = (SSLSocket) factory.createSocket(hostname, port);




//Send header
String path = "/test";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Host: deltapowermeter.appspot.com\r\n");
wr.write("Connection: close\r\n");
wr.write("Content-Type: application/xml\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();

// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null)
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}

Java Http post with Socket

程式碼如下


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

try {
String xmldata ="QQ";

//Create socket
String hostname = "xxx.appspot.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);


//Send header
String path = "/powermeter/event";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Host: deltapowermeter.appspot.com\r\n");
wr.write("Connection: close\r\n");
wr.write("Content-Type: application/xml\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();

// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null)
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
System.out.println("ASS");
}

2010年8月30日 星期一

轉貼 FileUpload google app engine java(图片上传实例demo)

google appengine 可以用來儲存相當多的資料,不同於文字,若要儲存圖片的話就比較麻煩一些


以下轉貼自 http://mimaiji.appspot.com/article?method=view&id=9001


程式碼簡單分成四個部份

1. 圖片物件 Photo.java



import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Blob;


@PersistenceCapable(identityType = IdentityType.APPLICATION,detachable="true")
public class Photo {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;

@SuppressWarnings("unused")
@Persistent
private String photoID;


@SuppressWarnings("unused")
@Persistent
private Blob photoO;


public Photo(Blob ObjBlob)
{
this.photoO = ObjBlob;
}



public Blob getPhoto() {
return this.photoO;
}

public Long getId() {
return this.id;
}


}






2. 資料存取物件 PhotoDao.java





import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class PhotoDao {
private static PhotoDao _instance = null;

public static PhotoDao getInstance() {
if (_instance == null) {
_instance = new PhotoDao();
}
return _instance;
}

public String insertPhoto(Photo photo) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(photo);
} finally {
pm.close();
}
return photo.getId().toString();
}


public Photo getById(Long id) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Photo.class);
query.setFilter("id == idParam");
query.declareParameters("Long idParam");
List photo = null;
try {
photo = (List) query.execute(id);
if (photo.isEmpty()){
return null;
}else{
return (Photo) photo.get(0);
}

} finally {
query.closeAll();
}
}
}





3. PhotoServlet.java, Servlet 的設定,
3-1.這個例子要 import Apache 的 "
commons-fileupload" 和 "commons-io"
3-2. 下載完解壓縮, eciplse 專案中 加入 external jar, 如圖


3-3. 兩個 jar 要放在 \war\lib 中

3-4. code




import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;

public class PhotoServlet extends HttpServlet{
/*display image*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String id = req.getParameter("id");
Photo photo = PhotoDao.getInstance().getById(Long.parseLong(id));
Blob b = photo.getPhoto();
resp.setContentType("image/jpeg;charset=utf-8");
resp.getOutputStream().write(b.getBytes());
resp.getOutputStream().close();
}
/*upload image and add to datastore*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
try {
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
// Handle form field
} else {
Blob bImg = new Blob(IOUtils.toByteArray(stream));
Photo photo = new Photo(bImg);
String pid = PhotoDao.getInstance().insertPhoto(photo);
req.setAttribute("Pid", pid);
resp.getWriter().write("Success "+ photo.getId());
}

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

}

}





4. 在 web.xml 設定 servelt 的路徑






<servlet>
<servlet-name>PhotoServlet</servlet-name>
<servlet-class>ppp.com.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PhotoServlet</servlet-name>
<url-pattern>/PhotoServlet</url-pattern>
</servlet-mapping>




附註: 要將資料抓到程式中的話
可以利用 HTTP GET 的方式,來取得圖片的 Stream


例如 C# 為例將資料存成 BitmapImage


private void GetHTTPRequest(string URL)
{
/// try send message to the web, if success show that the connect correct
try
{
/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);

/// Set values for the request back
req.Method = "GET";

BitmapImage Bi = new BitmapImage();

Bi.BeginInit();

/// Set Bi source from MemoryStream
Bi.StreamSource = req.GetResponse().GetResponseStream();

Bi.EndInit();

IMG.Source = Bi;

}

catch{
Console.WriteLine("Error");
}
}

2009年11月12日 星期四

使用 Google protrol to get the google api in C# with Google Site data api

在這個範例 中 使用 Google protocol 去取得 google site data 的資訊

所使用的語言是 C#, java的版本之前在其他文章有寫過


Http Post requset with java:
使用 java http post 取得 google account (AuthSub)

Http Get request with java:
使用 java http Get( by AuthSub) 取得 google document list





主要分成3個部份

1. SetProxyServer (有經過proxy 才要設 )
code 如下

/**
* @name SetProxyServer
*
* Set the Proxy Server if have Proxy Server
*
* @param req [in] - the http web request
*/
public void SetProxyServer(HttpWebRequest req)
{

IWebProxy iProxy = WebRequest.DefaultWebProxy;

/// potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;
req.Proxy = iProxy;
}






2.
取得 google api 的要驗證碼( 使用 http post), 這裡我是使用client login的方法

輸入以下三種資訊
Account: google 帳號
Password: google 帳號的密碼
Service Type: google api 的 類型 這裡使用 google site 類型為 "jotspot" (其他類型 )

code 如下



/**
* @name GetGoogleLoginAuth
*
* Get the google client login auth token
*
* @param Account [in] - the google account
* @param Password [in] - the google account password
* @param ServiceType [in] - the google api type
*
* @return the google client login auth
*/
public string GetGoogleLoginAuth(string Account, string Password, string ServiceType)
{
/// Declare the return valure
string GoogleLoginAuth="";

/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");

/// Set proxy
this.SetProxyServer(req);

/// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string strNewValue = "accountType=HOSTED_OR_GOOGLE"+
"&Email=" + Account +
"&Passwd=" + Password +
"&service=" + ServiceType +
"&source=Gulp-CalGulp-1.05";

/// Set the request value
req.ContentLength = strNewValue.Length;


/// Write the request
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();


/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();


/// Split string and set token
/// there are tree type in the return value
/// SID, LSID and Auth
string[] parts = strResponse.Split('=');

/// Save the auth token, auth token is in last part of string parts[]
GoogleLoginAuth = parts[parts.Length - 1];

/// Close the stream reader
stIn.Close();


return GoogleLoginAuth;
}




3. RetrievalContentFeed , 利用 http get 取得google site 的資訊
主要實做 google guide 的範例

輸入兩個 資訊
a. url: http(s)://sites.google.com/feeds/content/site/siteName

site 網域名稱 如 example.com
siteName 網頁名稱 如 myCoolSite

b. token 剛取得的 auth token


附註:
要 傳送出以下的訊息
GET /feeds/content/site/siteName HTTP/1.1
Host: sites.google.com
GData-Version: 1.0
Authorization: GoogleLogin auth= yourAuthToken

在c # 這裡是用 HttpWebRequest.Headers.Add 來附加訊息
此外 Host 不需在設定, 因為 會從 url 取得
所以要附加的資訊就只有
GData-Version 和 Authorization

看下面的code 會更瞭解, code 如下


/**
* @name RetrievalContentFeed
*
* Get the google client login auth token
*
* @param URL [in] - the google api Url
* @param Token [in] - the google client login token
*
*
* @return Content Feed
*/
public string RetrievalContentFeed(string URL, string Token)
{
/// Declare the return valure
string Feed = "";

/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://sites.google.com/feeds/content/hh-mud.com/touch-teach");

/// Set proxy
this.SetProxyServer(req);

/// Set values for the request back
req.Method = "GET";

/// Set the Head value
req.Headers.Add("GData-Version:1.0");
req.Headers.Add("Authorization: GoogleLogin auth=" + Token);


/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
Feed = stIn.ReadToEnd();

stIn.Close();

return Feed;
}


2009年9月4日 星期五

C sharp 使用 httpRequest 取得 google Auth token

直接使用Google api 來登入 Google 的服務 雖然很方便, 但是每用一次就必須重新驗證一次, 若有要使用很多服務的話也是一件蠻麻煩的事。

所以 Google 提供了一種 ClientLogin 方式的驗證, 讓使用者只要取得一次驗證碼, 之後就不必一直作驗證的動作

以下 是官方的 說明網站

java 範例之前寫過了 見 使用 java http post 取得 google account (AuthSub)

這裡就說明 C# 的方法

輸入 帳號、 密碼即可

會得到 strResponse 如圖, 但我們只要 auth 的驗證碼就好



所以在此用 Split('=') 的方法找出 需要的字串



/**
* @name GetGoogleAuth
*
* Get Google Auth code
* @return string Auth
*/
public string GetGoogleAuth(string Account, string Password)
{
string Auth="";

try
{
/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");

/// Set proxy
SetProxyServer(req);

/// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string strNewValue = "accountType=HOSTED_OR_GOOGLE&Email=" + Account +
"&Passwd=" + Password +
"&service=cl&source=Gulp-CalGulp-1.05";
req.ContentLength = strNewValue.Length;


/// Write the request
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();

/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();

/// Split string and set token
string[] parts = strResponse.Split('=');

/// Save the Auth Token
/// Auth Token id in the last string
GoogleAuthToken= parts[parts.Length - 1];

stIn.Close();
Auth = GoogleAuthToken;
}
catch
{
Auth = "";
}

return Auth;

}




/**
* @name SetProxyServer
*
* Set the Proxy Server if have Proxy Server
*
*/
public void SetProxyServer(HttpWebRequest req)
{

IWebProxy iProxy = WebRequest.DefaultWebProxy;
/// potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;
req.Proxy = iProxy;
}

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


}


}

2009年5月20日 星期三

Login Data with JDO ( GAE&JDO 7/7)

Modify 3 point
  • 1 Modify index html
這裡幾個地方要加入

getCookie(c_name) 取得cookie
deleteCookie(c_name) 刪除 cookie
initial() 起始設定
logoutfunction() 登出函式

並加入以下的html
------------------------------------------------------------------------
< tr>
< td colspan="2" style="font-weight:bold;">Login function:< /td>
< /tr>
< tr>
< td>
< form id=frmLogin method=get action="login" >
< span id="tobeVisible" >Enter your message ulen!

請輸入姓名:
< input type=text name="lUserName">
請輸入Password:
< input type=text name="lUserPassword">
< input type=submit value="確定">
< /span>
< /form>
< input id=logout type=submit value="logout" onclick='logoutfunction()'>

< /td>
< /tr>
--------------------------------------------------------------------------------------


修改完的 index.html
  • 2 Add servlet function
在 src/jdo.cookie.example/ 下 (jdo.cookie.example( 是package name))
撰寫 java serverlet function login.java
  • 3 Web.xml
修改 位於 war\WEB-INF\lib的 web.xml 如連結 再中間加入下一段XML
設定servlet的位置名稱

----------------------------------這裡是XML--------------------------

< servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdo.cookie.example.
login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
login</servlet-name>
<url-pattern>/
login</url-pattern>
</servlet-mapping>

----------------------------------這裡是XML--------------------------

2009年5月19日 星期二

Delete Data with JDO ( GAE&JDO 6/7)

Modify 3 point
  • 1 Modify index html

delete function:



刪除資料 有此姓名才可以刪除!!!!!

<form method="post" action="delete">
請輸入姓名:
<input name="dUserName" type="text">
<input value="確定" type="submit">
</form>





注意 form method=post action="delete"
  • 2 Add servlet function
在 src/jdo.cookie.example/ 下 (jdo.cookie.example( 是package name))
撰寫 java serverlet function delete.java
  • 3 Web.xml
修改 位於 war\WEB-INF\lib的 web.xml 如連結 再中間加入下一段XML
設定servlet的位置名稱

----------------------------------這裡是XML--------------------------

< servlet>
<servlet-name>
delete</servlet-name>
<servlet-class>jdo.cookie.example.
delete</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
delete</servlet-name>
<url-pattern>/
delete</url-pattern>
</servlet-mapping>

----------------------------------這裡是XML--------------------------

Update Data with JDO ( GAE&JDO 5/7)

Modify 3 point
  • 1 Modify index html

Update function:



姓名密碼相符才可以修改!!!!!


<form method="post" action="update">
請輸入姓名:
<input name="uUserName" type="text">
請輸入Password:
<input name="uUserPassword" type="text">
請輸入要修改的 Content:
<input name="uUserContent" type="text">
<input value="確定" type="submit">
</form>



注意 form method=post action="update"
  • 2 Add servlet function
在 src/jdo.cookie.example/ 下 (jdo.cookie.example( 是package name))
撰寫 java serverlet function update.java

這裡是用了 PersistenceManager 的方法 update

這裡有說明的文章 http://blog.csdn.net/wafd/archive/2004/01/02/17757.aspx
  • 3 Web.xml
修改 位於 war\WEB-INF\lib的 web.xml 如連結 再中間加入下一段XML
設定servlet的位置名稱

----------------------------------這裡是XML--------------------------

< servlet>
<servlet-name>update</servlet-name>
<servlet-class>jdo.cookie.example.
update</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
update</servlet-name>
<url-pattern>/
update</url-pattern>
</servlet-mapping>

----------------------------------這裡是XML--------------------------

List Data with JDO ( GAE&JDO 4/7)

Modify 3 point
  • 1 Modify index html

Show all user:


<form method="get" action="show">
<input value="顯示所有使用者" type="submit">
</form>

注意 form method=get action="show"
  • 2 Add servlet function
在 src/jdo.cookie.example/ 下 (jdo.cookie.example( 是package name))
撰寫 java serverlet function show.java
  • 3 Web.xml
修改 位於 war\WEB-INF\lib的 web.xml 如連結 再中間加入下一段XML
設定servlet的位置名稱

----------------------------------這裡是XML--------------------------
< servlet>
<servlet-name>show</servlet-name>
<servlet-class>jdo.cookie.example.show</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>show</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>

----------------------------------這裡是XML--------------------------

Add Data with JDO ( GAE&JDO 3/7)

Modify 3 point
  • 1 Modify index html

加入如以下的欄位

<form method="get" action="add">
請輸入姓名:
<input name="aUserName" type="text">
請輸入Password:
<input name="aUserPassword" type="text">
請輸入Content:
<input name="aUserContent" type="text">
<input value="確定" type="submit">

這裡 form method="get" action="add"
  • 2 Add servlet function
在 src/jdo.cookie.example/ 下 (jdo.cookie.example( 是package name))
撰寫 java serverlet function Add.java
  • 3 Web.xml
修改 位於 war\WEB-INF\lib的 web.xml 如連結 設定servlet的位置名稱

定義JDO type ( GAE&JDO 2/7)

在 eclipse 建立專案

  • 1. 建立新的APP Project


  • 2. 設定專案名稱及package 的名稱,這裡不討論gwt 所以把他勾掉不使用


  • 3.新增 Custom class 在 src/jdo.cookie.example/ 下
(jdo.cookie.example( 是package name))

Ex User.java
Inlcuded attributes
-----------------------------------------------------
Id
Password
Content

  • 4. Set Persistence Manager 在 src/jdo.cookie.example/ 下
PMF.java

See more in Using the Datastore with JDO

Google App Engines Datastore with JDO ( GAE&JDO 1/7))

做了一個小的範例

Using Google App Engine’s Datastore with JDO
Include
  • update
  • Add
  • List
  • delete
  • login Using Cookie in the java servlet

環境

  • JDK
  • Eclipse
  • Google App Engine Plug-in for Eclipse

由於敘述過多,所以在多分六個步驟

Setp

相關文章


完成範例網址
http://4.latest.catontest.appspot.com/index.html

2009年5月13日 星期三

java upload file to google document and set share friend

有時候要上傳檔案又要設定分享的朋友, 但分享再往頁上設定還真的給他有點慢 ,所以就寫了一個程式來加速吧


需要的liberaey
google data api for java


要使用的話要修改幾個部份
1. 分享朋友清單
2. 使用者id
3. 使用者password
4. file 位置

在結束時我有列出 新檔案的url 方便直接去找

使用 java http Get( by AuthSub) 取得 google document list

這個範例是利用http get 的 request 取得google document 的文件清單的XML

code 如下



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;


public class RetrievingListDocumentDemo {


public static void main(String[] args) {

/// Set information
String UesrName="XXXX@gmail.com";
String Password="yourPassword";
String ServiceType="writely"; ///ServiceType see more in http://code.google.com/intl/zh-TW/apis/gdata/faq.html#clientlogin


/// Get Authorization
String Authorization;
Authorization=GetSub(UesrName,Password,ServiceType);

System.out.println("Auth is ");

/// split the message get the code
/// 原始碼= "Auth=................."
/// 將分割為兩段 "Auth="+"...............",取得後面的驗證碼
String[] Authw= Authorization.split("=");
System.out.println(Authw[1]);




URL url;

try {

/// Set url
url = new URL("http://docs.google.com/feeds/documents/private/full");

/// Open Connect
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
/// Set Request method and property
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "GoogleLogin auth="+Authw[1]);
conn.setRequestProperty("GData-Version", "2.0");

/// print sent respond code
/// 列出連線的回應碼如 200 OK
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());

/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;

while ((line = rd.readLine()) != null) {
/// Process line...
/// line recode the response XML
System.out.println(line);

}
rd.close();


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



}




/*
* 輸入使用者名稱(email)、密碼以及服務類型
* 取得 Auth 的驗證碼
*
*/
public static String GetSub(String UesrName, String Password, String ServiceType) {


/// Set String record auth
String Authorization="";

try {
/// Construct data
String data = "accountType=HOSTED_OR_GOOGLE"+
"&Email="+UesrName+
"&Passwd="+Password+
"&service="+ServiceType+
"&source=Gulp-CalGulp-1.05";



/// Open Connect
URL url = new URL("https://www.google.com/accounts/ClientLogin");
URLConnection conn = url.openConnection();

/// setDoOutput=true than can write message to sent request
conn.setDoOutput(true);
/// write message to the request
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
int lineNumber=0;

while ((line = rd.readLine()) != null) {
/// Process line...
lineNumber++;
///System.out.println(line);
/// 第3行才是Auth
if(lineNumber==3)
Authorization=line;

}

wr.close();
rd.close();



} catch (Exception e) {
}
return Authorization;

}


}

2009年5月12日 星期二

使用 java http post 取得 google account (AuthSub)

透過輸入 google 帳號 或 google app 的帳號,控制再網頁上的資訊,包含新增、刪除、修改、讀取已有服務的內容
輸入的資訊有兩項,就是帳號和密碼

Sample Request by java


如果想要送的訊息如下
POST /accounts/ClientLogin HTTP/1.0
Content-type: application/x-www-form-urlencoded

accountType=HOSTED_OR_GOOGLE&Email=jondoe@gmail.com&Passwd=north23AZ&service=cl&
source=Gulp-CalGulp-1.05


可以使用以下的java code 去取得


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;


public class ClientLoginDemo {


public static void main(String[] args) throws IOException {


/// Set information
String UesrName="yourgmail@gmail.com"; ///must be set your gmail
String Password="yourcode"; ///must be set your gmail password
String ServiceType="cl"; ///ServiceType see more in http://code.google.com/intl/zh-TW/apis/gdata/faq.html#clientlogin



/// Construct data
String data = "accountType=HOSTED_OR_GOOGLE"+
"&Email="+UesrName+
"&Passwd="+Password+
"&service="+ServiceType+
"&source=Gulp-CalGulp-1.05";



URL url;
try {
url = new URL("https://www.google.com/accounts/ClientLogin");

/// Open Connect
URLConnection conn = url.openConnection();

/// setDoOutput=true than can write message to sent request
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;

while ((line = rd.readLine()) != null) {
// Process line...
System.out.println(line);

}
wr.close();
rd.close();


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

}


ClientLogin Response

成功的話回應如下

HTTP/1.0 200 OK
Server: GFE/1.3
Content-Type: text/plain

SID=DQAAAGgA...7Zg8CTN
LSID=DQAAAGsA...lk8BBbG
Auth=DQAAAGgA...dk3fA5N

上面的ClientLoginDemo 所印出的回應就包含 SID,LSID,Auth 三個回傳值
其中 Auth 的回傳值 可以用這個登入其他的google服務