2014年9月30日火曜日

groovyとRabbitMQのHTTP APIを使用して、queueを作成する

groovyとRabbitMQのHTTP APIを使用して、queueを作成するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.*
import org.apache.http.client.methods.*
import org.apache.http.client.protocol.*
import org.apache.http.impl.auth.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import org.apache.http.conn.*
import org.apache.http.*
import groovy.json.*

ConnectionKeepAliveStrategy ckas = new ConnectionKeepAliveStrategy() {
  public long getKeepAliveDuration(HttpResponse response, HttpContext context)
  {
    HeaderElementIterator it = new BasicHeaderElementIterator(
      response.headerIterator(HTTP.CONN_KEEP_ALIVE))
    while(it.hasNext()){
      HeaderElement he = it.nextElement()
      if( he.value != null && he.param.equalsIgnoreCase("timeout") ){
        try
        {
          return Long.parseLong(he.value) * 1000
        }
        catch(NumberFormatException nfex){}
      }
    }
    return 30 * 1000
  }
}
def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"

CredentialsProvider credsProvider = new BasicCredentialsProvider()
credsProvider.setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)
AuthCache authCache = new BasicAuthCache()
HttpHost targetHost = new HttpHost(host, port, "http")
BasicScheme basicAuth = new BasicScheme()
authCache.put(targetHost, basicAuth)
HttpClientContext context = HttpClientContext.create()
context.setCredentialsProvider(credsProvider)
context.setAuthCache(authCache)

CloseableHttpClient httpclient = HttpClients.custom()
  .setKeepAliveStrategy(ckas)
  .build()
httpclient.withCloseable {
  // queueの作成
  def queue = "test_queue1"
  def method = new HttpPut("http://${host}:${port}/api/queues/%2f/${queue}")
  def json = new JsonBuilder()
  json (
    auto_delete:false, durable:true
  )
  method.setHeader("Content-Type", "application/json; charset=utf-8")
  method.setEntity(new StringEntity(json.toString(), "UTF-8"))
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年9月29日月曜日

SwingBuilderでラベルにツールチップを設定する

SwingBuilderでラベルにツールチップを設定するには、以下のコードの様にtoolTipTextを使用します。
サンプルコード
import java.awt.*
import javax.swing.*
import groovy.swing.*

sb = new SwingBuilder()
sb.edt {
  frame(
    title: "example - label with tooltip",
    show: true,
    resizable: true,
    pack: true,
    defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE
  ){
    label(text:"Sample label",
      // フォント
      font: new Font("Arial", Font.BOLD, 40),
      constraints: BorderLayout.CENTER,
      toolTipText: "サンプルのツールチップ"
    )
  }
}
実行時画面

動作環境
groovy 2.2.2, JDK 1.7 update55

2014年9月26日金曜日

Apache TikaでファイルのMIMEタイプを検出する

Apache TikaでファイルのMIMEタイプを検出するには、以下のコードのようにTikaクラスのdetectメソッドを使用します。
@Grab(group='org.apache.tika', module='tika-core', version='1.5')
import org.apache.tika.*

// MIMEタイプの検出
println new Tika().detect(new File("./home.png"))
// -> image/png

println new Tika().detect(new File("./test.xlsx"))
// -> application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

2014年9月25日木曜日

groovyとOpenWeatherMapで現在の天気を取得する

groovyとOpenWeatherMapで現在の天気を取得するには、以下のコードのようにqパラメータに都市名、国コードとunitsパラメータにmetricを指定します。
import groovy.json.*

def appkey = "<your-api-key>"
def url = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units=metric&APPID=${appkey}"

json = new URL(url).getText("UTF-8")
slurper = new JsonSlurper()
data = slurper.parseText(json)
println "経度/緯度:${data.coord.lon}, ${data.coord.lat}"
println "天気:" + data.weather.collect { it.main }.join(",")
println "温度:${data.main.temp}"
println "気圧:${data.main.pressure}"
println "湿度:${data.main.humidity}"
println "風速:${data.wind.speed}"
println "風向:${data.wind.deg}"

2014年9月23日火曜日

groovyとRabbitMQのHTTP APIを使用して、erlangのバージョン情報を取得する

groovyとRabbitMQのHTTP APIを使用して、erlangのバージョン情報を取得するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.entity.*
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import groovy.json.*

def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"
def httpclient = new DefaultHttpClient()
httpclient.getCredentialsProvider().setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)

def method = new HttpGet("http://${host}:${port}/api/overview")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
println json
println "----"
println "erlang_full_version:${json.erlang_full_version}"
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年9月22日月曜日

groovy、RabbitMQとMQTTプラグイン、Pahoを使用して、メッセージの送信と受信をおこなう

groovy、RabbitMQとMQTTプラグイン、Pahoを使用して、メッセージの送信と受信するには、以下のようなコードを実行します。

サンプルコード(受信)
@GrabResolver(name='paho-rel', root='https://repo.eclipse.org/content/repositories/paho-releases/')
@Grab(group='org.eclipse.paho', module='mqtt-client', version='0.4.0')
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.*

def host = "192.168.1.219" // replace this
def broker = "tcp://${host}:1883"
def clientId = "groovySubscriber"
def persistence = new MemoryPersistence()

def client = new MqttClient(broker, clientId, persistence)
def opts = new MqttConnectOptions()
//opts.setKeepAliveInterval(30)
opts.setCleanSession(true)
client.connect(opts)

client.setCallback(new MqttCallback(){
  void connectionLost(Throwable cause){
    println "connection lost."
    println cause
    cause.printStackTrace()
    System.exit(1)
  }
  void deliveryComplete(IMqttDeliveryToken token){
    println "completed delivery."
  }
  void messageArrived(String topic, MqttMessage message){
    println "received: ${new String(message.getPayload(), "UTF-8")}"
  }
})

client.subscribe("topic/test")
System.console().readLine 'please press enter\n'
client.disconnect()
サンプルコード(送信)
@GrabResolver(name='paho-rel', root='https://repo.eclipse.org/content/repositories/paho-releases/')
@Grab(group='org.eclipse.paho', module='mqtt-client', version='0.4.0')
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.*

def host = "192.168.1.219" // replace this
def broker = "tcp://${host}:1883"
def clientId = "groovyPublisher"
def persistence = new MemoryPersistence()

def client = new MqttClient(broker, clientId, persistence)
def opts = new MqttConnectOptions()
//opts.setKeepAliveInterval(30)
opts.setCleanSession(true)
client.connect(opts)

def message = new MqttMessage("サンプル".getBytes("UTF-8"))
message.setQos(0)
def topic = client.getTopic("topic/test")
def token = topic.publish(message)
token.waitForCompletion()
client.disconnect()
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

SwingBuilderでディレクトリ選択ダイアログを使用する

SwingBuilderでディレクトリ選択ダイアログを使用するには、以下のコードの様にfileChooserを使用します。
サンプルコード
import javax.swing.*
import groovy.swing.*

sb = new SwingBuilder()
def dlg = sb.fileChooser(dialogTitle:"select a directory.",
  fileSelectionMode: JFileChooser.DIRECTORIES_ONLY)

if( dlg.showOpenDialog() == JFileChooser.APPROVE_OPTION ){
  println dlg.selectedFile.toString()
} else {
  println "cancelled."
}

動作環境
groovy 2.2.2, JDK 1.7 update55

2014年9月19日金曜日

Apache Commons CSVとgroovyで、CSVデータの各列の最小長・最大長・平均長を求める

Apache Commons CSVとgroovyで、CSVデータの各列の最小長・最大長・平均長を求めるには、以下のコードを実行します。
import org.apache.commons.csv.*
import java.text.*

def records = 0
def ct = [:].withDefault { [min:Integer.MAX_VALUE, max:0, sum:0] }
def fmt = CSVFormat.EXCEL
  .withHeader()
def parser = fmt.parse(new FileReader("export.csv"))
for(record in parser){
  parser.getHeaderMap().each { key, index ->
    def len = record.get(index).size()
    ct[key].min = ct[key].min < len ? ct[key].min:len
    ct[key].max = ct[key].max > len ? ct[key].max:len
    ct[key].sum += record.get(index).size()
  }
  records++
}

def df = new DecimalFormat("#.#")
ct.each { key, value ->
  println "${key} : min${value.min} - max${value.max}, \
avg:${df.format(value.sum/records)}"
}
println "total records:${records}"

2014年9月18日木曜日

Apache Commons CSVとSwingBuilderでCSVデータを読み込み、テーブルに表示する

Apache Commons CSVとSwingBuilderでCSVデータを読み込み、テーブルに表示するには、以下のコードを実行します。

import javax.swing.*
import groovy.swing.*
import org.apache.commons.csv.*

def fmt = CSVFormat.EXCEL.withHeader()

println "file:${args[0]}"
def parser = fmt.parse(new FileReader(args[0]))
def data = []
parser.iterator().each { data.add(it.toMap()) }

sb = new SwingBuilder()
sb.edt {
  frame(
    title: args[0],
    show: true,
    resizable: true,
    size: [300, 100],
    defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE
  ){
    scrollPane(){
      table(){
        tableModel(list: data){
          parser.getHeaderMap().each { key, index ->
            propertyColumn( header:key, propertyName: key, editable: false )
          }
        }
      }
    }
  }
}

2014年9月17日水曜日

groovyとRabbitMQのHTTP APIを使用して、exchangeを一覧表示する

groovyとRabbitMQのHTTP APIを使用して、exchangeを一覧表示するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.entity.*
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import groovy.json.*

def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"
def httpclient = new DefaultHttpClient()
httpclient.getCredentialsProvider().setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)

def method = new HttpGet("http://${host}:${port}/api/exchanges")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
println json
println "----"
for(exchange in json){
  println "[${exchange.name}]:type=${exchange.type}"
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年9月16日火曜日

groovyとHBaseで、テーブルを一覧表示する

groovyとHBaseで、テーブルを一覧表示するには、以下のコードのようにlistTableNamesを使用します。

サンプルコード
@Grab(group='org.apache.hbase', module='hbase-client', version='0.98.5-hadoop2')
@Grab(group='org.apache.hbase', module='hbase-common', version='0.98.5-hadoop2')
@Grab(group='org.apache.hadoop', module='hadoop-client', version='2.5.0')
import org.apache.hadoop.hbase.*
import org.apache.hadoop.hbase.client.*

def config = HBaseConfiguration.create()
config.set(HConstants.ZOOKEEPER_QUORUM, "localhost")
config.set(HConstants.ZOOKEEPER_CLIENT_PORT, "2181")
def conn = HConnectionManager.createConnection(config)
conn.withCloseable {
  for(tname in conn.listTableNames()){
    println tname.nameAsString
  }
}
動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6, HBase0.98.5

groovyとApache Phoenixでテーブル内を全件表示する

Apache Phoenixを使用することで、HBaseをバックエンドとして通常のSQLと同じようにテーブル内を全件表示する事ができます。

サンプルコード
import groovy.sql.Sql
import java.sql.*

sql = Sql.newInstance(
  "jdbc:phoenix:localhost",
  "",
  "",
  "org.apache.phoenix.jdbc.PhoenixDriver")

query = """
select * from STOCK_SYMBOL
"""
sql.eachRow(query){ row ->
  println row
}
クライアント設定
phoenix-4.1.0-bin.tar.gzを解凍しphoenix-4.1.0-bin/hadoop2/phoenix-4.1.0-client-hadoop2.jarを~/.groovy/libなどにコピーします。

動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6, hbase 0.98.5, phoenix 4.1.0

2014年9月15日月曜日

groovyでPocketのエクスポートデータをCSV形式に変換する

Pocketでは、保存したページを以下のページからHTML形式でエクスポートすることができます。

Pocketのエクスポート用ページ
https://getpocket.com/export/

エクスポートデータをCSV形式に変換するには、以下のコードを実行します。
@Grab(group='org.jsoup', module='jsoup', version='1.7.3')
import org.jsoup.*
import org.jsoup.select.*
import org.apache.commons.csv.*

doc = Jsoup.parse(new File("ril_export.html").getText("UTF-8"))

def fmt = CSVFormat.EXCEL
  .withHeader("time_added", "title", "url", "tags")
  .withQuoteMode(QuoteMode.NON_NUMERIC)
def printer = new CSVPrinter(new FileWriter("ril_export.csv"), fmt)

for(link in Selector.select("a", doc)){
  def time_added = new Date(Long.parseLong(link.attr("time_added"))*1000).format("yyyy/MM/dd HH:mm:ss")
  def title = link.text()
  def url = link.attr("href")
  def tags = link.attr("tags")
  printer.printRecord([time_added, title, url, tags])
}
printer.flush()
printer.close()

2014年9月14日日曜日

SwingBuilderでラベルの水平方向アライメントを設定する

SwingBuilderでラベルの水平方向アライメントを設定するには、以下のコードのようにhorizontalAlignmentを使用します。

サンプルコード
import java.awt.*
import javax.swing.*
import groovy.swing.*

sb = new SwingBuilder()
sb.edt {
  frame(
    title: "example - horizontal alignement",
    show: true,
    resizable: true,
    pack: true,
    defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE
  ){
    label(text:"left", horizontalAlignment: JLabel.LEFT,
      constraints: BorderLayout.NORTH
    )
    label(text:"center", horizontalAlignment: JLabel.CENTER,
      constraints: BorderLayout.CENTER
    )
    label(text:"right", horizontalAlignment: JLabel.RIGHT,
      constraints: BorderLayout.SOUTH
    )
  }
}
実行時画面

動作環境
groovy 2.2.2, JDK 1.7 update55

groovyとZooKeeperで、znodeを一覧表示する

groovyとZooKeeperで、指定パスのznodeを一覧表示するには、以下のコードを実行します。

サンプルコード
@Grab(group='org.apache.zookeeper', module='zookeeper', version='3.4.6')
import org.apache.zookeeper.*

def zk = new ZooKeeper("localhost:2181", 3000, null)
try
{
  for(child in zk.getChildren("/", false)){
    println child
  }
}
finally
{
  zk.close()
}
動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6

2014年9月12日金曜日

Raspberry pi上のgroovyでメモリサイズ・メモリ使用量・フリーサイズを取得する

Raspberry pi上のgroovyでメモリサイズ・メモリ使用量・フリーサイズを取得するには、以下のコードのようにSystemInfoのgetMemoryTotal()とgetMemoryUsed(), getMemoryFree()を使用します。

@Grab(group='com.pi4j', module='pi4j-core', version='0.0.5')
import com.pi4j.system.*

println "total memory:${SystemInfo.getMemoryTotal()/1024/1024}M"
println "used memory:${SystemInfo.getMemoryUsed()/1024/1024}M"
println "free memory:${SystemInfo.getMemoryFree()/1024/1024}M"
実行結果
total memory:437.49609375M
used memory:422.93359375M
free memory:14.5625M

2014年9月11日木曜日

Apache Commons CSVとgroovyでヘッダー行付きのCSVデータを書き込む

Apache Commons CSVとgroovyでヘッダー行付きのCSVデータを書き込むには、以下のコードのようにwithHeaderでヘッダー情報を指定します。

import org.apache.commons.csv.*

def data = [
  [100, "テスト"],
  [200, "サンプル"]
]

def fmt = CSVFormat.EXCEL
  .withHeader("id", "category")
  .withQuoteMode(QuoteMode.NON_NUMERIC)
def printer = new CSVPrinter(new FileWriter("test.csv"), fmt)
printer.printRecords(data)
printer.flush()
printer.close()

2014年9月8日月曜日

groovyとApache OpenNLPで英語をトークン化する

groovyとApache OpenNLPで英語をトークン化するには、以下のコードの様にSimpleTokenizerを使用します。
import opennlp.tools.tokenize.*

def text = """The Apache OpenNLP library is a machine learning based toolkit for
the processing of natural language text."""

for(token in SimpleTokenizer.INSTANCE.tokenize(text)){
  println token
}

2014年9月5日金曜日

Raspberry pi上のgroovyでOS名称・バージョンを取得する

Raspberry pi上のgroovyでOS名称・バージョンを取得するには、以下のコードのようにSystemInfoのgetOsName()とgetOsVersion()を使用します。

@Grab(group='com.pi4j', module='pi4j-core', version='0.0.5')
import com.pi4j.system.*

println "OS name:${SystemInfo.getOsName()}"
println "OS version:${SystemInfo.getOsVersion()}"
実行結果
OS name:Linux
OS version:3.12.22+

2014年9月4日木曜日

Apache Commons CSVとgroovyでタブ区切りのCSVデータを読み込む

Apache Commons CSVとgroovyでタブ区切りのCSVデータを読み込むには、以下のコードのようにwithDelimiter()を使用します。

import org.apache.commons.csv.*

def fmt = CSVFormat.EXCEL
  .withHeader()
  .withDelimiter((char)'\t')
for(record in fmt.parse(new FileReader("tab-sep-data.csv"))){
  for(value in record){
    println value
  }
  println "----"
}