ラベル ApacheHttpClient の投稿を表示しています。 すべての投稿を表示
ラベル ApacheHttpClient の投稿を表示しています。 すべての投稿を表示

2014年12月5日金曜日

WebHDFSのREST APIでファイルのタイプ・サイズ・オーナーなどの情報を取得する

WebHDFSのREST APIでファイルのタイプ・サイズ・オーナーなどの情報を取得するには、以下のようなコードを実行します。

サンプルプログラム
@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.206.132" // replace this
def port = 50070
def path = "/user/hadoop25b"
def file = "01_2012.csv"
def user = "hadoop25b"

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {

  def method = new HttpGet(
    "http://${host}:${port}/webhdfs/v1${path}/${file}?op=GETFILESTATUS&user.name=${user}"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

  def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
  def status = json.FileStatus
  println "type:${status.type}"
  println "length:${status.length}"
  println "owner:${status.owner}"
  println "group:${status.group}"
  println "permission:${status.permission}"

}
動作環境
Hadoop 2.5.0

2014年11月28日金曜日

groovyから気象情報APIを使用して、経度・緯度から気象情報を求める

groovyから気象情報APIを使用して、経度・緯度から気象情報を求めるには、以下のようなコードを実行します。

サンプルコード
@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 groovy.json.*

def appid = "your-app-id"
// 緯度経度
def coordinates = "139.75363355,35.69400229"

def httpclient = new DefaultHttpClient()
def method = new HttpGet("http://weather.olp.yahooapis.jp/v1/place?appid=${appid}&output=json&coordinates=${coordinates}")
def response = httpclient.execute(method)
println response.getStatusLine().getStatusCode()

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
// タイプ、日時、降水強度(mm/h)
json.Feature.Property.WeatherList.Weather[0].each {
  println "${it.Type}:${it.Date}:${it.Rainfall}"
}
関連情報
YOLP(地図):気象情報API - Yahoo!デベロッパーネットワーク

2014年11月21日金曜日

groovyからYahoo!リバースジオコーダAPIを使用して、経度・緯度から住所を求める

groovyからYahoo!リバースジオコーダAPIを使用して、経度・緯度から住所を求めるには、以下のようなコードを実行します。

サンプルコード
@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 groovy.json.*

def appid = "your-app-id"
def lon = 139.75363355
def lat = 35.69400229

def httpclient = new DefaultHttpClient()
def method = new HttpGet("http://reverse.search.olp.yahooapis.jp/OpenLocalPlatform/V1/reverseGeoCoder?appid=${appid}&output=json&lat=${lat}&lon=${lon}")
def response = httpclient.execute(method)
println response.getStatusLine().getStatusCode()

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
// 住所
println json.Feature.Property.Address[0]
関連情報
YOLP(地図):Yahoo!リバースジオコーダAPI - Yahoo!デベロッパーネットワーク

2014年11月18日火曜日

groovyとRabbitMQのHTTP APIを使用して、userを削除する

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

サンプルコード
@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 {
  // ユーザの削除
  def newUser = "user1"
  def method = new HttpDelete("http://${host}:${port}/api/users/${newUser}")
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年11月11日火曜日

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

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

サンプルコード
@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 {
  // ユーザの作成
  def newUser = "user1"
  def method = new HttpPut("http://${host}:${port}/api/users/${newUser}")
  def json = new JsonBuilder()
  json (
    password:"user1", tags:"administrator"
  )
  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()

  // パーミッションの設定
  def method2 = new HttpPut("http://${host}:${port}/api/permissions/%2f/${newUser}")
  json (
    configure:".*", write:".*", read:".*"
  )
  method2.setHeader("Content-Type", "application/json; charset=utf-8")
  method2.setEntity(new StringEntity(json.toString(), "UTF-8"))
  response = httpclient.execute(method2, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年11月4日火曜日

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

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

サンプルコード
@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 = "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/users")
response = httpclient.execute(method)

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

2014年10月30日木曜日

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 clusterName = "cluster"

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

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

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
for(item in json.items){
  println "name:${item.name}"
  println "health summary:${item.healthSummary}"
  println "service state:${item.serviceState}"
  println "----"
}
参考情報
/clusters/{clusterName}/services - Cloudera Manager API v7

2014年10月28日火曜日

groovyとRabbitMQのHTTP APIを使用して、exchangeを削除する

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

2014年10月21日火曜日

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.*
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 {
  // exchangeの作成
  def exchange = "exchange1"
  def method = new HttpPut("http://${host}:${port}/api/exchanges/%2f/${exchange}")
  def json = new JsonBuilder()
  json (
    type:"direct", auto_delete:false, durable:true, internal:false
  )
  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年10月14日火曜日

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.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/queues")
response = httpclient.execute(method)

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

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