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