Archive for the ‘groovy’ Category

[groovy] shell script 처럼 바로 쓰기

2016/05/02

from http://smplnote.tistory.com/305

배경 :

1. shell script 짜는 것보다 자바 코딩이 더 쉽다. (사실은 그루비가.. )

2. 컴파일은 하기 싫다.

준비사항 :

1. jdk가 설치되어야함 (대부분 있음)

2. groovy-all-X.X.X.jar 를 준비할것

3. groovy 문법을 모르면 java 문법이라도 알고 있어야 함.

방법 :

1. 대신 실행해줄 쉘을 만든다.

touch groovy.sh

#/bin/sh

JAVA_HOME=/usr/local/java/jdk1.6.0_30

CP=/groovy/groovy-all-2.0.0.jar:.

echo $1 run

$JAVA_HOME/bin/java -classpath $CP groovy.ui.GroovyMain  $1

/// window version

@echo off
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_80

set LIB_PATH=groovy/lib
set CP=%LIB_PATH%\groovy-all-1.8.9.jar;.

echo %1 run

“%JAVA_HOME%/bin/java” -classpath %CP% groovy.ui.GroovyMain  %1

# 실행모드 변경

chmod 744 groovy.sh

2. groovy example

# ls 명령을 실행한 결과를 출력해주는…

touch hello.groovy

import java.util.*;

class HelloGroovy{

public static void main(String[] args) {

println args.length

def result = “ls”.execute().text;

println result

}

}

주의사항 :

1. 지나치게 중독되지 말 것.

2. 뭔가 안될 경우 classpath 설정을 확인할 것

 

Advertisements

jenkins cli를 java에서 사용하기

2015/11/13

Jenkins Command Line Interface (https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI
)

ref :
http://www.javacodegeeks.com/2012/08/hooking-into-jenkins-hudson-api-part-2.html
http://www.javacodegeeks.com/2012/08/hooking-into-jenkins-hudson-api-part-1.html

example

import hudson.cli.CLI

arguments.add("list-jobs");
final ByteArrayOutputStream output = new ByteArrayOutputStream()
int exit_code = cli.execute(arguments,System.in,output,System.err);
output.toString().split("\\n").each{
	print "build name : ${it}"
}
cli.close()

[link] GVM on Windows

2014/12/29

1) powershell 을 이용한 해결방식

from : http://paweloczadly.github.io/dev/2014/07/02/gvm-on-windows/

1) check version : 3+

$PSVersionTable.PSVersion

2) check module

3) import module

> but…

경고: This command is not available in offline mode. 메세지가 나오면서 실패함.

2) gravy

https://github.com/enterprise-grails/gravy

java에서 groovy sql 사용하기

2013/02/04

왜 : 신입사원이 JDBC 프로그래밍 문서를 보고 있는게 왠지 마음이 안좋았다.

미션 : SQL 처리를 좀더 쉽게, JNDI 사용도 가능하게…

ibatis나 hibernate 등 별도의 framework을 사용하면 좋긴한데,
모르는 라이브러리들은 왜이리 산처럼 쌓이는건지?, 그리고 framework 환경 구성하고, 학습하는데도 좀 시간이…

이런 부담을 포기하면, 자바 개발자들은 순수한(?) JDBC 프로그래밍의 세계로 들어가야 합니다.
물론… 기본으로 돌아가는 것의 중요함을 모르는 바는 아니지만, 게으름의 충동이…

그래서 groovy.sql.Sql 의 힘을 써보기로 했습니다.
(아예 groovy를 쓰면 더 좋겠으나 이건 ‘영어가 편하니 영어로 대화하자’ 라고 말하는 격.. )

어쨌거나, Sql 클래스에는 여러가지 메소드를 제공하지만 Closure 를 사용하는 것은 익숙한 java 개발 방식이 아니므로
여기서는 제외.

1. 필요 라이브러리
Sql library : grooyv-all-*.jar
vendor jdbc library : ojdbc*(oracle) 또는 mysql* 같은 벤더가 제공하는 jdbc library
vendor jndi library : clientcontainer.jar(jeus) 같은 벤더가 제공하는 client에서 jndi 접속용 library

2. 파일 소스
import groovy.sql.GroovyRowResult;
import groovy.sql.Sql;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class SqlToy {
public static void main(String[] args) throws Exception {
// jdbc 직접 연결
Sql sql = Sql.newInstance(“jdbc:oracle:thin:@localhost:1521:XE”, “system”, “**”, “oracle.jdbc.OracleDriver”);
// jndi 사용 연결
///// Sql sql = new Sql(lookup(“yourDS”));

// select example
String query = “select * from board where name = ?”;
for(GroovyRowResult row : sql.rows(query, new Object[]{“smpl”})){
System.out.println(row.get(“description”) );
}

// update example
sql.executeUpdate(“update board set comment = ? where name=? “, new Object[]{“comment”,”smpl”});

// select 1 row example
GroovyRowResult result = sql.firstRow(“select comment from board where name = ? and comment= ?”,
new Object[]{name,”comment”});
System.out.println(“selected comment = ” + result.get(“comment”));

sql.close();
}
// jeus jndi lookup
static DataSource lookup(String jndiname) throws Exception{
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, “jeus.jndi.JEUSContextFactory”);
env.put(Context.URL_PKG_PREFIXES, “jeus.jndi.jns.url”);
env.put(Context.PROVIDER_URL, “127.0.0.1:9736”);
Context ctx = new InitialContext(env);
return (DataSource)ctx.lookup(jndiname);
}
}

[groovy/grails] make grails web service client (using wslite)

2012/09/25

– prepare

install grails 2.1.1 ( or groovy-grails-tool-suite-3.1.0.M1-e4.2 )

1. install ws-lite plugin ( current 0.7.1)

grails install-plugin wslite

2. add wslite bean
edit conf/spring/resources.groovy

httpClient(wslite.http.HTTPClient){
 // ....
}
soapClient(wslite.soap.SOAPClient){
 serviceURL = "http://blah.com/wsdl.."
 httpClient = ref('httpClient')
} 

3. create ws client service class

class WSClientService{
def soapClient
     def submit(service, act, body){
         def action = "http://your-soap-namespace/${service}/${act}"
def writer = new StringWriter()
         def soap = new MarkupBuilder(writer)
         soap.mkp.xmlDeclaration(version:'1.0', encoding:'UTF-8')
         soap."soap-env:Envelope"(  ["xmlns:soap-env":"http://schemas.xmlsoap.org/soap/envelope",  "xmlns:tns" : "http://your-soap-namespace/${service}/"] ){
"soap-env:Header"([:], {} )  // set header
"soap-env:Body"([:]){  "tns:${action}"( body )   }

def sendstring = writer.toString()
def response = soapClient.send(SOAPAction: action, sendstring)
return response."*"."*" // extract real soap object root
}
}

5. create controller class

class WsController{
WSClientService wsClientService
def index(){
def parameter = { // this is closure
id( params.id)
}

def response = wsClientService.submit("ServiceName", "ActionName", parameter);
render response as XML
}

cf) if you use grails2.1.1, then you can’t use converters plugin. -> installation fail  ( so, you can’t use ” as XML” sentence )

spring Restful api documentation

2012/08/24

[purpose]
– make RESTful API Documentation
– Using Spring framework
– autogenerate

[Review solutions]
SPRINGDOCLET : javadoc style로 rest api user document 로는 부족함

RESTDOCLET : 목적에 부합
maven plugin, web application type
param description not support, rest error code not support
controller에 정의한 mapping 미인식

WSDOC : simple 충분하지않음 rest error, param description nor support

SWAGGER : spring 지원 불충분, 복잡…

[try – restdoclet]
– fail maven setting
– use library
– process : java source ->; xml using xmldoc ->; xml using jibx ->; html using template
– preperation
spring restful application source & libraries
library :
rsetdoclet lib : restdoclet-doclet-2.2.0.jar, restdoclet-plugin-2.2.0.jar, jibx-run-1.2.1.jar, from https://oss.sonatype.org/index.html#nexus-search;classname~RESTdoclet
spring lib : spring-web-3.0.5.RELEASE.jar, spring-context-3.0.5.RELEASE.jar, commons-lang-2.6.jar,
javadoc lib : tools.jar,
ant lib : ant-launcher.jar, ant.jar
etc : commons-collections-3.2.jar, log4j-1.2.15.jar,

thanks iggroup restdoclet! https://github.com/IG-Group/RESTdoclet

demo.groovy

import groovy.text.SimpleTemplateEngine
import org.apache.commons.collections.CollectionUtils
import org.jibx.runtime.JiBXException
import com.iggroup.oss.restdoclet.doclet.XmlDoclet
import com.iggroup.oss.restdoclet.doclet.type.*
import com.iggroup.oss.restdoclet.doclet.util.*
import com.iggroup.oss.restdoclet.plugin.io.*
import com.iggroup.oss.restdoclet.plugin.util.ServiceUtils
import com.sun.tools.javac.util.*
import com.sun.tools.javac.util.Options
import com.sun.tools.javadoc.*
class demo {
	static def SERVICES_TEMPLATE = "src/main/resources/services.jsp";
	static def SERVICE_TEMPLATE = "src/main/resources/service.jsp";
	def reportDir, restsrcDir , packageNames = [] , appname = "" , version
	static main(args) {
		def me = new demo();
		me.restsrcDir = "my-rest-web/src/main/java"
		me.reportDir = "my-rest-web/doc/restdoc"
		me.packageNames = {"com.my.rest"}
		me.appname =  ["APPLICATION":"my-rest" ]
		me.version = ["version":1.0, timestamp:new Date()]
		
		me.makexmldoc()
		me.build();
	}
	def ant = new AntBuilder()
	def controllers = []// ArrayList<;Controller>; 
	def outputDirectory = "my-rest";

	// gathering Controller.java files ( except Sample)
	def getRestControllers(){
		def list = []
		new File(restsrcDir).eachFileRecurse {
			if(it.name.endsWith("Controller.java")){ list.add(it) }
		}
		return list;
	}
	
	def makexmldoc(){
	    ant.mkdir(dir:reportDir);
		Context context = new Context();
		Options compOpts = Options.instance(context);
		compOpts.put("-sourcepath", new File(restsrcDir).absolutePath);
		compOpts.put("-classpath", getClassLibs());
		
		def javaNames = new ListBuffer<;String>;();
		getRestControllers().each{ javaNames.append(it.getPath()); }
		def subPackages = new ListBuffer<;String>;();
		for (String packageName : packageNames) {
			subPackages.append(packageName);
		}
		new Messager(context,"application")
		JavadocTool javadocTool = JavadocTool.make0(context);
		def rootDoc = javadocTool.getRootDocImpl( "", "utf-8",
                    new ModifierFilter(ModifierFilter.ALL_ACCESS),
                    javaNames.toList(), new ListBuffer<;String[]>;().toList(),
                    false, subPackages.toList(), new ListBuffer<;String>;().toList(),
                    false, false, true);
		
		new XmlDoclet().start(rootDoc);
		def myDir = "target/restdoc"
		ant.mkdir(dir:myDir)
		new ControllerUriAppender().add(rootDoc, myDir);
	}
	def build()   {
		def myDir = "target/restdoc"
	    javadocs(myDir);
	    services(myDir);
	}

	def javadocs(rootDir){
		new File(rootDir).eachFileRecurse {
			if(it.name.endsWith(Controller.FILE_SUFFIX)){
				final Controller cntrl = JiBXUtils.unmarshallController(it);
				if (!controllers.contains(cntrl)) { controllers.add(cntrl); }
			}
		}
	}
	
	def services(baseDirectory)  {
	   def services = new ArrayList<;Service>;();
	   def uriMethodMappings = [:]
	   def uriControllerMappings = new HashMap<;String, Controller>;();
	   def multiUriMappings = new HashMap<;String, Collection<;Uri>;>;();
	   for (Controller controller : controllers) {
		  for (Method method : controller.getMethods()) {
			 def uris = method.getUris();
			 if (!uris.isEmpty()) {
				String multiUri = uris.join(", ")
				multiUriMappings.put(multiUri, uris);
				def methodList = uriMethodMappings.get(multiUri);
				if (methodList == null) {
				   methodList = new ArrayList<;Method>;();
				   uriMethodMappings.put(multiUri, methodList);
				}
				methodList.add(method);
				uriControllerMappings.put(multiUri, controller);
			 }
		  }
	   }
 
	   int identifier = 1;
	   for (String uri : uriControllerMappings.keySet()) {
		  Controller controller = uriControllerMappings.get(uri);
		  ArrayList<;Method>; matches = uriMethodMappings.get(uri);
		  Service service = new Service(identifier, multiUriMappings.get(uri), new Controller(
				controller.getType(), controller.getJavadoc(), matches));
		  services.add(service);
		  generateServiceHtml( appname, version, service)
		  identifier++;
	   }
 
	   Services list = new Services();
	   for (Service service : services) {
		  org.apache.commons.collections.Predicate predicate = new ControllerTypePredicate(service.getController().getType());
		  if (CollectionUtils.exists(list.getControllers(), predicate)) {
			 ControllerSummary controller = (ControllerSummary) CollectionUtils.find(list.getControllers(), predicate);
			 controller.addService(service);
		  } else {
			 ControllerSummary controller = new ControllerSummary(service.getController().getType(), service.getController().getJavadoc());
			 controller.addService(service);
			 list.addController(controller);
		  }
	   }
		def toFile = reportDir+"/services.html"
		generateHtml(toFile, ["param" : appname,  "props":version, "services":list.getServices()], SERVICES_TEMPLATE);
	}
	
	def generateServiceHtml(  param, props, svc){
		def toFile = reportDir+"/service-" + svc.identifier  + ".html"
		generateHtml(toFile, ["param" : param,  "props":props, "service":svc], SERVICE_TEMPLATE);
	}
	
	def generateHtml(def toFile, def binding, def templateFile, encoding = "UTF-8"){
		def reader = new File(templateFile).newReader();
		def template = new SimpleTemplateEngine().createTemplate(reader).make(binding);
		new File(toFile).write(template.toString(), encoding)
	}

	// for javadoc compile
	def getClassLibs(){
		return [ "../my-rest/WEB-INF/lib/commons-logging.jar", "../my-rest/WEB-INF/lib/spring-XXXX-X.X.X.RELEASE.jar"
			// ...  other libraries
			].join(";")
	}
}

ControllerUriAppender.groovy ( for controller’s uri appending)

import static com.iggroup.oss.restdoclet.doclet.util.AnnotationUtils.*
import static com.iggroup.oss.restdoclet.doclet.util.JiBXUtils.marshallController
import groovy.util.slurpersupport.GPathResult
import groovy.xml.*
import org.springframework.web.bind.annotation.RequestMapping
import com.iggroup.oss.restdoclet.doclet.type.Controller
import com.sun.javadoc.*
class ControllerUriAppender {
	def add(RootDoc rootDoc, outputpath){
		for (ClassDoc classDoc : rootDoc.classes()) {
			if (isAnnotated(classDoc, org.springframework.stereotype.Controller.class)) {
			   AnnotationValue value = elementValue(	classDoc, RequestMapping.class, "value")
			   def rooturi  = value.toString().replaceAll(""","");
			   def xmlname = classDoc.qualifiedName().replace('.' as char, File.separatorChar) + Controller.FILE_SUFFIX
			   def root = new XmlSlurper().parse(new File(xmlname));
			   if(value!=null){
				   root.method.each{ mtd ->;
					   def mtdname = mtd.name.toString()
					   if(mtdname.endsWith("Null")||mtdname.endsWith("Error")){ // remove null filter mapping
						   mtd.replaceNode{}
					   }else{
						   if(mtd.uri==""){
							   mtd.javadoc + { 
								   uri {
									   uri(rooturi)
									   deprecated(false)
									   type("java.lang.String")
								   }
							   }
						   }else{
						   		mtd.uri.uri = rooturi + mtd.uri.uri
						   }
						   
						   def mtddoc = classDoc.methods().find { //// add parameter comment
							   it.name().equals(mtdname) 
						   }
						   
						   mtd."request-param".each{ rqparam ->;
							   if(rqparam.javadoc==""){
								   def paramdoc = mtddoc.paramTags().find{ paramtag ->;
									   paramtag.parameterName().equals(rqparam.name)
								   }
								   rqparam.type + {
									   javadoc(paramdoc?.parameterComment() )
								   }
							   }
						   }

						   // response-param exception javadoc 추가.
						   mtd."response-param".each{ rpparam ->;
							   if(rpparam.name.equals("Exception")){
								   def exceptiondoc = mtddoc.throwsTags().find{ paramtag ->;
									   paramtag.exceptionName() .equals(rpparam.name.toString())
								   }
								   if(rpparam.javadoc==""){
									   rpparam.type + {
										   javadoc(exceptiondoc?.exceptionComment() )
									   }
								   }
							   }
						   }
					   }
				   }
			   }
			   def outputBuilder = new StreamingMarkupBuilder()
			   outputBuilder.encoding ="UTF-8"
			   def result = outputBuilder.bind{ 
				   mkp.xmlDeclaration()
				   mkp.yield root 
			   }
			   def ant = new AntBuilder()
			   def myDir = outputpath + "/"+xmlname
			   ant.touch(file:myDir, mkdirs:true, verbose:false)
			   def fwriter = new FileWriter(myDir  );// .write(result);
			   XmlUtil.serialize(result, fwriter)
			   fwriter.close();
			}
		 }
	}
}

template : services.jsp

<;div class="projectDetails">;

   <;h1 class="mainHeading">;
      <;span class="title">;RESTdoclet for:<;/span>;
      <;span class="application">;
         <;em>;<;span class="application">;${param["APPLICATION"]}<;/span>;<;/em>;
      <;/span>;
   <;/h1>;

   <;h3>;
      <;span class="version">;Version: <;em>;${props.version}<;/em>;<;/span>;
      <;span class="timestamp">;Creation: <;em>;${props.timestamp}<;/em>;<;/span>;
   <;/h3>;
<;/div>;

<;div class="services">;
<;!-- 
   <;div class="sourceControlLocation">;
      Under version control at <;a href="${props.scmUrl}">;${props.scmUrl}<;/a>;
   <;/div>;
 -->;
   <;table class="topLevel">;
      <;thead>;
      <;tr>;
         <;th>;URI<;/th>;
         <;th>;Actions<;/th>;
      <;/tr>;
      <;/thead>;
      <;tbody>;<;% services.each{ service ->; %>;
            <;tr>;
               <;td class="uri">;<;%  service.uris.each{ urix ->; %>;
                     <;div class="active">;
                        <;a href="service-${service.identifier}.html">;${urix.uri}<;/a>;
                     <;/div>;<;% } %>;<;/td>;
               <;td>;
                  <;table class="methods">;
                     <;% service.methods.each{ method->; %>;
                        <;tr>;
                           <;td class="requestMethod">;${method.requestMethod}<;/td class="javadoc">;
                           <;td class="javadoc">;${method.javadoc}<;/td>;
                        <;/tr>;<;% } %>;
                  <;/table>;
               <;/td>;
            <;/tr>;
      <;% }  %>;
      <;/tbody>;
   <;/table>;
<;/div>;

template service.jsp

<;div class="projectDetails">;
   <;h1 class="mainHeading">;
      <;span class="title">;RESTdoclet for:<;/span>;
      <;em>;<;a href="services.html">;${param["APPLICATION"]}<;/a>;<;/em>;
      <;% service.uris.each{ urix ->; %>;
         <;span class="path">;
            <;em>;${urix.uri}<;/em>;
         <;/span>;
      <;% } %>;
   <;/h1>;

   <;h3>;
      <;span class="version">;Version: <;em>;${props.version}<;/em>;<;/span>;
       <;span class="timestamp">;Creation: <;em>;${props.timestamp}<;/em>;<;/span>;
   <;/h3>;
<;!-- 
   <;h2 class="javaClass">;Java Class: <;em>;${service.controller.type}<;/em>;<;/h2>; -->;
<;/div>;

<;% service.controller.methods.each{ method->; %>;
   <;div class="method">;
      <;h3 class="httpMethod">;${method.requestMethod}<;/h3>;
      <;p class="methodJsDoc">;${method.javadoc}<;/p>;
      <;% if(method.pathParams.size()>;0 || method.restParams.size() >;0 || method.requestParams.size()>;0 ){ %>;
         <;div class="input">;
            <;h3>;Request input<;/h3>;
            <;table class="topLevel methodDetails">;
               <;thead>;
               <;tr>;
                  <;th>;Name<;/th>;
                  <;th>;Description<;/th>;
                  <;th>;Param Type<;/th>;
               <;/tr>;
               <;/thead>;
               <;tbody>;
               <;% method.pathParams.each{ parameter->; %>;
                  <;tr>;
                     <;td class="name">;
                           ${parameter.type} ${parameter.name}
                     <;/td>;
                     <;td class="javadoc">;
                           ${parameter.javadoc}
                     <;/td>;
                     <;td class="path">;
                        Path (Mandatory)
                     <;/td>;
                  <;/tr>;
               <;% } %>;
               <;% method.restParams.each{ parameter->; %>;
                  <;tr>;
                     <;td class="name">;
                           ${parameter.type} ${parameter.name}<;/td>;
                     <;td class="javadoc">;
                           ${parameter.javadoc}<;/td>;
                     <;td class="path">;
                        REST
                     <;/td>;
                  <;/tr>;
               <;% } %>;
			<;% method.requestParams.each{ parameter->; %>;
                  <;tr>;
                     <;td class="name">;
                           ${parameter.type} ${parameter.name}<;/td>;
                     <;td class="javadoc">;
                           ${parameter.javadoc}<;/td>;
                     <;td class="path">;
                        Request
                        <;% if(parameter.required){ %>;
                           (Mandatory)
                        <;% }else{ %>;
                           (Optional)
                        <;% } %>;
                        <;% if(parameter.defaultValue){ %>;
                           (Default=${parameter.defaultValue})
                        <;% } %>;
                     <;/td>;
                  <;/tr>;
               <;% } %>;
               <;/tbody>;
            <;/table>;
         <;/div>;
      <;% } %>;
	<;% if( method.responseParams.size()>;0){ %>;
         <;div class="response">;
            <;h3>;Response contents<;/h3>;
            <;table class="topLevel methodDetails">;
               <;thead>;
               <;tr>;
                  <;th class="type">;Response Type<;/th>;
                  <;th class="description">;Description<;/th>;
               <;/tr>;
               <;/thead>;
               <;tbody>;
               <;% method.responseParams.each{ parameter->; %>;
                  <;tr>;
                     <;td class="type">;${parameter.type}<;/td>;
                     <;td class="javadoc">;${parameter.javadoc}<;/td>;
                  <;/tr>;
               <;% } %>;
               <;/tbody>;
            <;/table>;
         <;/div>;
      <;% } %>;
   <;/div>;
<;% } %>;

ref) http://mestachs.wordpress.com/2012/08/06/rest-api-documentation/