@Grab(group='org.jsoup', module='jsoup', version='1.6.1') import org.jsoup.* // htmlを取得してtitleを取得 println Jsoup.connect("http://groovy.codehaus.org").get().title()
動作環境
groovy 1.8.2, JDK6 Update27, jsoup 1.6.1
groovyのTipsを書いていきます。
@Grab(group='org.jsoup', module='jsoup', version='1.6.1') import org.jsoup.* // htmlを取得してtitleを取得 println Jsoup.connect("http://groovy.codehaus.org").get().title()
@Grab(group="javax.mail", module="mail", version="latest.integration") import java.security.* import java.util.* import javax.mail.* import javax.mail.internet.* import javax.activation.* smtpHost = "smtp.gmail.com" smtpPort = "465" Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()) Properties props = new Properties() props.put("mail.smtp.host", smtpHost) props.put("mail.smtp.port", smtpPort) props.put("mail.smtp.auth", "true") props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory") props.put("mail.smtp.socketFactory.fallback", "false") Session session = Session.getDefaultInstance(props, [ getPasswordAuthentication: { return new PasswordAuthentication("youraccount@gmail.com", 'yourpassword') } ] as Authenticator ) Message msg = new MimeMessage(session) msg.setFrom(new InternetAddress( "youraccount@gmail.com","youraccount@gmail.com","iso-2022-jp")) msg.setRecipients(Message.RecipientType.TO, "recipient@gmail.com") msg.setSubject("添付ファイルサンプル","iso-2022-jp") multipart = new MimeMultipart() // 本文のパートを作成 bp1 = new MimeBodyPart() bp1.setText("添付ファイルのサンプル","iso-2022-jp") multipart.addBodyPart(bp1) // 添付ファイルのパートを作成 bp2 = new MimeBodyPart() fds = new FileDataSource("SF.JPG") bp2.setFileName(MimeUtility.encodeWord(fds.getName())) bp2.setDataHandler(new DataHandler(fds)) multipart.addBodyPart(bp2) msg.setContent(multipart) Transport.send(msg)
@Grab(group='org.jsoup', module='jsoup', version='1.6.1') import org.jsoup.* // htmlを取得してtextに変換 println Jsoup.connect("http://groovy.codehaus.org").get().text()
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([country:"Japan", store:"store_A", sales:100]) col.insert([country:"Japan", store:"store_B", sales:120]) col.insert([country:"Japan", store:"store_C", sales:170]) col.insert([country:"United States", store:"store_D", sales:80]) col.insert([country:"United States", store:"store_E", sales:200]) col.insert([country:"United States", store:"store_F", sales:190]) col.insert([country:"United States", store:"store_G", sales:100]) // MapReduceで国ごとの売上を取得 println col.mapReduce( /* map */ "function(){ emit(this.country, {total_sales:this.sales}); }", /* reduce */ """function(key, values){ var total = 0; for(var vi = 0;vi<values.length;vi++){ total += values[vi].total_sales; } return {total_sales: total}; }""", /* outputTarget */"mr_result", /* query */ new BasicDBObject() ) // 結果を表示 db.mr_result.find().each { println it }
import javax.xml.transform.* import org.xmldb.api.* // eXistに接続 db = Class.forName("org.exist.xmldb.DatabaseImpl").newInstance() DatabaseManager.registerDatabase(db) col = DatabaseManager.getCollection( "xmldb:exist://localhost:8080/exist/xmlrpc/db", "admin", "admin"); // XQueryを実行 query = ''' for $c in //country[population_growth < 0] order by $c/name return <country> {$c/name, $c/population_growth} </country> ''' service = col.getService("XQueryService", "1.0") service.setProperty(OutputKeys.INDENT, "yes") service.setProperty(OutputKeys.ENCODING, "UTF-8") compiled = service.compile(query) result = service.execute(compiled) // 結果を取得 results = result.getIterator() while(results.hasMoreResources()){ res = results.nextResource() if( res.getResourceType().equals("XMLResource") ){ println(res.getContent()) } } col.close()
@Grab(group="javax.mail", module="mail", version="latest.integration") import java.security.* import java.util.* import javax.mail.* import javax.mail.internet.* import groovy.xml.* smtpHost = "smtp.gmail.com" smtpPort = "465" Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()) Properties props = new Properties() props.put("mail.smtp.host", smtpHost) props.put("mail.smtp.port", smtpPort) props.put("mail.smtp.auth", "true") props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory") props.put("mail.smtp.socketFactory.fallback", "false") Session session = Session.getDefaultInstance(props, [ getPasswordAuthentication: { return new PasswordAuthentication("youraccount@gmail.com", 'yourpassword') } ] as Authenticator ) Message msg = new MimeMessage(session) msg.setFrom(new InternetAddress( "youraccount@gmail.com","youraccount@gmail.com","iso-2022-jp")) msg.setRecipients(Message.RecipientType.TO, "recipients@gmail.com") msg.setSubject("HTMLメールサンプル","iso-2022-jp") import groovy.xml.* def writer = new StringWriter() def html = new MarkupBuilder(writer) html.doubleQuotes = true html.html { body { p { mkp.yield("HTMLメールサンプル") br() a(href:"http://groovyarekore.blogspot.com", "groovyあれこれ") } } } msg.setContent(writer.toString(), "text/html; charset=iso-2022-jp") Transport.send(msg)
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([country:"Japan", store:"store_A", sales:100]) col.insert([country:"Japan", store:"store_B", sales:120]) col.insert([country:"Japan", store:"store_C", sales:170]) col.insert([country:"United States", store:"store_D", sales:80]) col.insert([country:"United States", store:"store_E", sales:200]) col.insert([country:"United States", store:"store_F", sales:190]) col.insert([country:"United States", store:"store_G", sales:100]) // MapReduceで国ごとの店舗数を取得 println col.mapReduce( /* map */ "function(){ emit(this.country, {count:1}); }", /* reduce */ """function(key, values){ var total = 0; for(var vi = 0;vi<values.length;vi++){ total += values[vi].count; } return {count: total}; }""", /* outputTarget */"mr_result", /* query */ new BasicDBObject() ) // 結果を表示 db.mr_result.find().each { println it }
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["sales"].drop() // コレクションにオブジェクトを挿入する col = db["sales"] col.insert([sku:"001", total_sales:100]) col.insert([sku:"002", total_sales:120]) col.insert([sku:"003", total_sales:170]) col.insert([sku:"004", total_sales:80]) col.insert([sku:"005", total_sales:200]) // between 90 and 190相当の検索を実行 for(obj in col.find([total_sales:['$gte':90, '$lte':190]])){ println obj } println "-----" // Javascript Expressionで同様の検索 for(obj in col.find( [$where:"this.total_sales >= 90 && this.total_sales <= 190"])){ println obj }
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("perftest") // 事前に領域を割り当て(sizeはバイト) db.createCollection("salesdata", [size: 40*1024*1024]) println "storage size:" + db.salesdata.getStats().storageSize println "total index size:" + db.salesdata.getStats().totalIndexSize
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([store:"store_A", "sales_timestamp":new GregorianCalendar(2011, 7, 10, 12, 11, 30).getTime(), sales:100]) col.insert([store:"store_B", "sales_timestamp":new GregorianCalendar(2011, 7, 10, 18, 31, 15).getTime(), sales:100]) col.insert([store:"store_C", "sales_timestamp":new GregorianCalendar(2011, 7, 10, 19, 11, 10).getTime(), sales:100]) col.insert([store:"store_A", "sales_timestamp":new GregorianCalendar(2011, 7, 11, 10, 17, 45).getTime(), sales:100]) col.insert([store:"store_C", "sales_timestamp":new GregorianCalendar(2011, 7, 11, 11, 10, 5).getTime(), sales:100]) for(obj in db.command( [group : [ ns:"stores", '$keyf': """ function(obj){ return {"dt":obj.sales_timestamp.getFullYear() + "/" + (obj.sales_timestamp.getMonth() + 1) + "/" + obj.sales_timestamp.getDate() }; } """, initial:[scount:0], '$reduce': "function(obj,prev){ prev.scount++; }" ] ]).retval) { println obj["dt"] + " - number of stores:${obj.scount}" }
@Grab(group="javax.mail", module="mail", version="latest.integration") import java.security.* import java.util.* import javax.mail.* import javax.mail.internet.* smtpHost = "smtp.gmail.com" smtpPort = "465" Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()) Properties props = new Properties() props.put("mail.smtp.host", smtpHost) props.put("mail.smtp.port", smtpPort) props.put("mail.smtp.auth", "true") props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory") props.put("mail.smtp.socketFactory.fallback", "false") Session session = Session.getDefaultInstance(props, [ getPasswordAuthentication: { return new PasswordAuthentication("youraccount@gmail.com", 'yourpassword') } ] as Authenticator ) Message msg = new MimeMessage(session) msg.setFrom(new InternetAddress( "youraccount@gmail.com","youraccount@gmail.com","iso-2022-jp")) msg.setRecipients(Message.RecipientType.TO, "recipient_address@gmail.com") msg.setSubject("Disk Free Space","iso-2022-jp") content = "path : free / total size \n" File.listRoots().each{ content += it.getAbsolutePath() + " : " + String.format("%8.2f", it.getFreeSpace()/1024/1024/1024) + "(G) / " + String.format("%8.2f", it.getTotalSpace()/1024/1024/1024) + "(G)\n" } msg.setText(content, "iso-2022-jp") Transport.send(msg)
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([country:"Japan", store:"store_A", sales:100]) col.insert([country:"Japan", store:"store_B", sales:120]) col.insert([country:"Japan", store:"store_C", sales:170]) col.insert([country:"United States", store:"store_D", sales:80]) col.insert([country:"United States", store:"store_E", sales:200]) col.insert([country:"United States", store:"store_F", sales:190]) col.insert([country:"United States", store:"store_G", sales:100]) // 国ごとの店舗数を取得 for(obj in col.group(/* key */new BasicDBObject([country:true]), /* condition */new BasicDBObject(), /* initial */new BasicDBObject([scount:0, ssum:0]), /* reduce */"function(obj,prev){ prev.scount++; prev.ssum += obj.sales;}", /* finalize */"function(obj){ obj.savg = obj.ssum / obj.scount;}" )){ println obj["country"] + " - sales average:${obj.savg}" }
@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([country:"Japan", store:"store_A", sales:100]) col.insert([country:"Japan", store:"store_B", sales:120]) col.insert([country:"Japan", store:"store_C", sales:170]) col.insert([country:"United States", store:"store_D", sales:80]) col.insert([country:"United States", store:"store_E", sales:200]) col.insert([country:"United States", store:"store_F", sales:190]) col.insert([country:"United States", store:"store_G", sales:100]) // 国ごとの店舗数を取得 for(obj in col.group(/* key */new BasicDBObject([country:true]), /* condition */new BasicDBObject(), /* initial */new BasicDBObject([scount:0]), /* reduce */"function(obj,prev){ prev.scount++; }" )){ println obj["country"] + " - number of stores:${obj.scount}" }