2010年7月23日金曜日

groovyとgdata-java-clientでGoogle Documents内の指定した名前のスプレッドシートをコピーする

groovyとgdata-java-clientでGoogle Documents内の指定した名前のスプレッドシートをコピーするには、以下のコードを実行します。

import com.google.api.client.googleapis.*
import com.google.api.client.googleapis.auth.clientlogin.*
import com.google.api.data.docs.v3.*
import com.google.api.data.docs.v3.atom.*
import com.google.api.client.xml.atom.*
import com.google.api.client.util.*

// エントリ
public class Entry
{
@Key
String title
@Key
String id
}

// リンク
public class Link
{
@Key("@rel")
String rel
@Key("@type")
String type
@Key("@href")
String href
}

// フィード
public class Feed
{
@Key
String title
@Key
List<Link> link
@Key
List<Entry> entry
}

// Parser設定
GoogleTransport transport = new GoogleTransport()
transport.applicationName = "yourcorp-yourapp-1.0"
transport.setVersionHeader(GoogleDocumentsList.VERSION)
ap = new AtomParser()
ap.namespaceDictionary = GoogleDocumentsListAtom.NAMESPACE_DICTIONARY
transport.addParser(ap)

username = "youraccount@gmail.com"
password = 'yourpassword'

// 認証
cl = new ClientLogin()
cl.authTokenType = GoogleDocumentsList.AUTH_TOKEN_TYPE
cl.username = username
cl.password = password
cl.authenticate().setAuthorizationHeader(transport)

// 指定した名前のスプレッドシートを検索する
docname = "さんぷる1"
requrl = "https://docs.google.com/feeds/default/private/full/-/spreadsheet" +
"?title=${URLEncoder.encode(docname, 'UTF-8')}&title-exact=true"
while(requrl != null){
request = transport.buildGetRequest()
request.url = requrl
feed = request.execute().parseAs(Feed.class)
println "feed title:" + feed.title
for(item in feed.entry){
// 指定した名前のスプレッドシートが見つかったのでコピーする
request = transport.buildPostRequest()
request.url = "https://docs.google.com/feeds/default/private/full/"
content = new AtomContent()
content.entry = new Entry()
content.entry.title = "コピーしたさんぷる1"
content.entry.id = "https://docs.google.com/feeds/default/private/full/" +
"${item.id.substring(item.id.indexOf("spreadsheet%3A"))}"
println content.entry.id
content.namespaceDictionary = GoogleDocumentsListAtom.NAMESPACE_DICTIONARY
request.content = content;
request.execute().parseAsString()
}
// 100個以上の文書の場合
requrl = null
for(link in feed.link){
if( link.rel == "next" ){
requrl = link.href
}
}
}


動作環境
groovy 1.7.2, JDK6 Update20, gdata-java-2.2.1-alpha

関連情報
gdata-java-client
http://code.google.com/p/gdata-java-client/

0 件のコメント:

コメントを投稿