2014年10月12日日曜日

groovyとDocker Remote APIでcontainerを一覧表示する

groovyとDocker Remote APIでcontainerを一覧表示するには、以下のようなコードを実行します。

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

def host = "192.168.1.215" // replace this
def port = 4243

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {

  def method = new HttpGet(
    "http://${host}:${port}/containers/json?all=1"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

  def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
  for(container in json){
    println "-------"
    println "Container ID:${container.Id}"
    println "names:${container.Names}"
    println "image:${container.Image}"
    println "ports:${container.Ports}"
    println "status:${container.Status}"
  }
}
Docker Remote APIを使用可能にする方法
ubuntuの場合、/etc/default/dockerに以下のように記述します。
DOCKER_OPTS="-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock -d"
そのあと、dockerを再起動します。
sudo service docker restart

動作環境
Docker 1.2.0

2014年10月11日土曜日

groovyとSqoop REST APIでconnectorを一覧表示する

groovyとSqoop REST APIでconnectorを一覧表示するには、以下のようなコードを実行します。

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

def host = "localhost"
def port = 12000
def httpclient = new DefaultHttpClient()

def method = new HttpGet("http://${host}:${port}/sqoop/v1/connector/all")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
//println json
for(conn in json.all){
  println "id:${conn.id}, name:${conn.name}, class:${conn.class}"
}
動作環境
Cloudera CDH 5.1.2

2014年10月10日金曜日

groovyとZooKeeperで、指定のznodeが存在するか確認する

groovyとZooKeeperで、指定のznodeが存在するか確認するには、以下のサンプルコードのようにexistsメソッドを使用します。

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

def zk = new ZooKeeper("localhost:2181", 3000, null)
try
{
  if( zk.exists("/not_exist", false) == null ){
    println "not exist"
  }
  if( (stat = zk.exists("/zookeeper", false)) != null ){
    println "exists"
  }
}
finally
{
  zk.close()
}
動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6

2014年10月9日木曜日

SwingBuilderでラベル内のアイコンに対するテキスト位置を設定する

SwingBuilderでラベル内のアイコンに対するテキスト位置を設定するには、以下のコードのようにhorizontalTextPosition, verticalTextPositionを使用します。

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

sb = new SwingBuilder()
sb.edt {
  frame(
    title: "example : text position",
    show: true,
    resizable: true,
    pack: true,
    defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE
  ){
    label(text:"left", icon:imageIcon(file:"e:/icons/home.png"),
      horizontalTextPosition: JLabel.LEFT, constraints: BorderLayout.WEST
    )
    label(text:"top", icon:imageIcon(file:"e:/icons/plane.png"),
      horizontalTextPosition: JLabel.CENTER,
      verticalTextPosition: JLabel.TOP, constraints: BorderLayout.NORTH
    )
    label(text:"right", icon:imageIcon(file:"e:/icons/mobile2.png"),
      horizontalTextPosition: JLabel.RIGHT, constraints: BorderLayout.EAST
    )
    label(text:"bottom", icon:imageIcon(file:"e:/icons/computer.png"),
      horizontalTextPosition: JLabel.CENTER,
      verticalTextPosition: JLabel.BOTTOM, constraints: BorderLayout.SOUTH
    )
  }
}
実行時画面

動作環境
groovy 2.2.2, JDK 1.7 update55

2014年10月7日火曜日

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 HttpDelete("http://${host}:${port}/api/queues/%2f/${queue}")
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年10月6日月曜日

Apache TikaでWORDファイル等からテキストを抽出する

Apache TikaでWORDファイル等からテキストを抽出する Apache TikaでWORDファイル等からテキストを抽出するには、以下のサンプルコードのようにTikaクラスのparseToStringメソッドを使用します。
@Grab(group='org.apache.tika', module='tika-core', version='1.5')
@Grab(group='org.apache.tika', module='tika-parsers', version='1.5')
import org.apache.tika.*

// テキストの抽出
println new Tika().parseToString(new File("test.doc"))

2014年10月5日日曜日

groovyでCloudera Managerに登録されているホストを一覧表示する

groovyでCloudera Managerに登録されているホストを一覧表示するには、以下のようなコードを実行します。

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

def host = "192.168.1.240" // replace this
def port = 7180
def user = "admin"
def password = "admin"

def httpclient = new DefaultHttpClient()
httpclient.getCredentialsProvider().setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, password)
)

def method = new HttpGet("http://${host}:${port}/api/v7/hosts")
def response = httpclient.execute(method)
println response.getStatusLine().getStatusCode()

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
for(item in json.items){
  println "hostname:${item.hostname}"
  println "IP Address:${item.ipAddress}"
  println "Rack ID:${item.rackId}"
}
参考情報
/hosts - Cloudera Manager API v7