Groovy 使用自定义路由启动内存中的http服务器

import org.simpleframework.http.Request
import org.simpleframework.http.Response
import org.simpleframework.http.core.Container
import org.simpleframework.transport.connect.Connection
import org.simpleframework.transport.connect.SocketConnection

class HttpContainer implements Container {

	Connection connection

	def setup(){
		connection = new SocketConnection(this);
		SocketAddress address = new InetSocketAddress(13080);
		connection.connect(address);
		this
	}

	public void handle(Request request, Response response) {
		PrintStream body = response.getPrintStream();
		long time = System.currentTimeMillis();
		response.set("Content-Type", "text/xml;charset=utf-8");
		response.set("Server", "Apache-Coyote/1.1");
		response.setDate("Date", time);

		def text = simpleRoute(request)
		body.println(text);
		body.close();
	}

	def simpleRoute(request){
		switch(request.target){
			case "/some/url/file":
			return new File('src/test/resources/file').text

			case "/some/url/hello":
			return 'hello'

			default: throw new RuntimeException("no route found")
		}
	}

	def close(){
		connection.close()
	}
}

Groovy JAX-RS服务,用于在groovy中代理和验证HTTP请求

import javax.ws.rs.Path
import javax.ws.rs.POST
import javax.ws.rs.FormParam

@Path("/proxy")
public class Proxy {
  @POST
  @Path("basic_auth/")
  public String basic_auth(@FormParam("url") String url, @FormParam("login") String login,
                      @FormParam("password") String password) {
    def encoded = "$login:$password".getBytes().encodeBase64().toString()
    def c= new URL(url).openConnection()
    c.setRequestProperty("Authorization", "Basic $encoded")
    return c.content.text
  }
}

Groovy 控制台输入在groovy中读取

System.in.withReader {
    println "Test: "
    carrier = it.readLine()
}

Groovy Groovy Swing Explorer文件删除处理程序

import java.awt.datatransfer.*;
import java.awt.dnd.*;

public class TFileDropHandler
{	
	// TFileDropHandler.groovy
	// Laurence Toenjes - 2010-08-18
	// Based on 1999 example from Cay Horstmann found at
	// http://java.itags.org/java-core-gui-apis/33457/
	
	// dropped files closure example: { files -> println files };
	def TFileDropHandler( aSwingControl, Closure a_onDroppedFiles )
	{   // ctor
		def dropTarget = new DropTarget( aSwingControl, new TFileDropTargetListener( a_onDroppedFiles ) )
		aSwingControl.setDropTarget( dropTarget )
	}
	
	// --------------------------------------------------------
	class TFileDropTargetListener implements DropTargetListener 
	{
		def Closure onDroppedFiles =  null // our callback event
		public TFileDropTargetListener( a_onDroppedFiles ) { // ctor
					 onDroppedFiles = a_onDroppedFiles }
			
		public void dragEnter(DropTargetDragEvent event) {}	
		public void dragExit(DropTargetEvent event) {}
		public void dropActionChanged(DropTargetDragEvent event) {}
		public void dragOver(DropTargetDragEvent event) {
			// provide visual feedback
			event.acceptDrag(DnDConstants.ACTION_COPY);
		}
		
		public void drop(DropTargetDropEvent event) {
			if ( (event.getSourceActions() & DnDConstants.ACTION_COPY) != 0 ) {
				event.acceptDrop(DnDConstants.ACTION_COPY);
			}
			else {
				event.rejectDrop();
				return; // !!!!!!!!!!!!!!!!!!!!!
			}
			Transferable transferable = event.getTransferable();
			DataFlavor[] flavors = event.getCurrentDataFlavors();
			for (int i = 0; i < flavors.length; i++) {
				DataFlavor dataFlavor = flavors[i];
				try {
					// file flavor
					if ( dataFlavor.equals( DataFlavor.javaFileListFlavor ) ) {
						java.util.List fileList = (java.util.List) transferable.getTransferData(dataFlavor);					
						def files = []	
						fileList.each { files << it }
						this?.onDroppedFiles( files )
						event.dropComplete(true);
						return;
					}	
				} 
				catch(Exception e) {
						event.dropComplete(false);
						return;
					}
			} // end for
			event.dropComplete(false);		
		} // end drop
	}
	// --------------------------------------------------------
	
	public static void main(String[] args) {
		// simple example
		def f = new javax.swing.JFrame()
		f.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE )
		f.size = [400,300]
		def ta = new javax.swing.JTextArea()
		f.add( ta )
		
		new TFileDropHandler( ta,  { files -> 
			files.each { 
				ta.append("${it}\n")
				println it
			} 
		} )
		
		f.show()
	}
}

Groovy Groovy中的var_dump

import org.apache.commons.lang.builder.ReflectionToStringBuilder

variable= new ComplexObject()
println new ReflectionToStringBuilder( variable).toString()

Groovy Bootstrap中的Grails环境

switch (GrailsUtil.environment) {
   case "development":
      ...
      break
   case "production":
      ...
      break
}

Groovy Compete.com Webstats Scrape Groovy

import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.BrowserVersion

def domainList = (new File("/root/Desktop/Morningstar/AlexaTop3000.txt")).readLines()
def outFile = new File("/root/Desktop/Morningstar/CompeteStats3000.csv")
outFile.delete()
def wc = new WebClient( BrowserVersion.FIREFOX_3_6 )

domainList.each {
  def domainName = it.trim()
  println domainName
  def url = "http://siteanalytics.compete.com/export_csv/${domainName}/"
  def page = wc.getPage( url )
  def pageLines = page.getContent().split("\n")

  def lineCount = 0
  pageLines.each { line ->
   if ( lineCount > 3 ) {
     outFile.append( "\"${domainName}\",${line}\n" )
   }
   lineCount++
  }
  sleep( 400 )
}

Groovy Groovy嵌入式Apache FTP服务器示例

#!/usr/bin/env groovy

// file: FtpSvr.groovy

/*
	Laurence Toenjes Jan 12, 2013
	
	Standalone Groovy ftp server script (no jars to download if Groovy is 
	properly installed).  
	
	The default user is guest with password of guest
	and the ftp home/base directory is the home folder of the account
	running this script.
	A root account is also created with the ftp home/base dir set to /
	and the password is root (for root to fully work you would obviously
	have to run it under an account with expanded file permissions).
	
	Optional command line args:
		arg0 defaults to port 8021.
		arg1 (ftp base dir) defaults to the home directory of the user running this script.
*/

// See http://mina.apache.org/ftpserver/ for more details.

// for OS X/*nix
//   don't forget to do: chmod +x FtpServer.groovy
//   also run as sudo ./FtpSvr.groovy for when using a port number < 1024

@Grapes([
	  @Grab(group='org.apache.ftpserver', module='ftpserver-core', version='1.0.6')
	, @Grab(group='ch.qos.logback', module='logback-classic', version='1.0.9')
])

import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.FtpServer;

import org.apache.ftpserver.listener.ListenerFactory;

import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.BaseUser;

import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.ftplet.Authority;

import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.Properties;

public class FtpSvr {
	
	def go(String[] args) {
		String ftpUsersPropFileName = "FtpSvrUsers.properties"
		int    defaultPort = 8021

		String userHome = System.properties.'user.home';
		String homeDir = args.size()>=2 ? args[1].replace('~', userHome) : userHome ;
		assert new File(homeDir).exists();

		def gi = groovy.inspect.swingui.ObjectBrowser.&inspect; // for debug

		int port = args.size()>=1 ? args[0].toInteger() : defaultPort ;
		println "### ftp port   : $port"
		println "### ftp homeDir: $homeDir"
		println ''

		// the basics
		// FtpServerFactory serverFactory = new FtpServerFactory();
		// FtpServer server = serverFactory.createServer();
		// server.start();

		// setup users

		PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();

		def myusersPropsFile = new File( ftpUsersPropFileName );
		if ( !myusersPropsFile.exists() ) {
			myusersPropsFile.createNewFile();
		}

		userManagerFactory.setFile( myusersPropsFile );
		userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());

		UserManager um = userManagerFactory.createUserManager();

		def users = []
		users << [ uid:'guest', pwd:'guest', home:homeDir ]
		users << [ uid:'root' , pwd:'root' , home:'/'     ]

		def addUser = { map ->
			BaseUser user = new BaseUser();
			user.setName( map.uid );
			user.setPassword( map.pwd );
			user.setHomeDirectory( map.home );
			
			List<Authority> auths = new ArrayList<Authority>();
			Authority auth = new WritePermission();
			auths.add(auth);
			user.setAuthorities(auths);
			// gi user;
			// gi user.getAuthorities();
			um.save(user);
		}

		users.each { itUserMap -> addUser( itUserMap ) }

		FtpServerFactory serverFactory = new FtpServerFactory();

		serverFactory.setUserManager( um );

		ListenerFactory factory = new ListenerFactory();
				
		// set the port of the listener
		factory.setPort( port );

		// replace the default listener
		serverFactory.addListener("default", factory.createListener());

		// start the server
		FtpServer server = serverFactory.createServer(); 

		// groovy.inspect.swingui.ObjectBrowser.inspect( server );
		// groovy.inspect.swingui.ObjectBrowser.inspect( server.userManager );
		// gi server.userManager.getAllUserNames() as List;
			
		server.start();
	}
	
	public static void main(String[] args) {
		def mo = new FtpSvr();
		mo.go(args)
	}
}

Groovy Groovy Gradle - 在没有安装SVN的情况下执行SVN命令。

/*
	File  : helperSvn.gradle
	Author: Laurence Toenjes
	Date  : 3/31/2013
	
	Example of how to use:
		1. Put this file in the same directory as your build.gradle file.
		
		2. Near the very top of your build.gradle source file add this line: 
			apply from: 'helperSvn.gradle'
			
		3. You can now do svn commands like:
		
			doSvnMain( 'export', 'http://svn.codehaus.org/gmod/gsql/tags/gsql-1.5.0/', 'build/svnExport' );
			
			doSvnMain( 'help' );
			
			... etc. ...
			
			Note: each command line arg you would normally supply to a svn command should be an arg passed to doSvnMain
				  (since we are not using the OS shell you should probably not have to double quote any of the args).
*/

import org.tmatesoft.svn.cli.SVN;

buildscript {
	repositories { mavenCentral() }
	dependencies { classpath( 'org.tmatesoft.svnkit:svnkit:1.7.8', 'org.tmatesoft.svnkit:svnkit-cli:1.7.8' ) }
}

project.ext.SVN = SVN; /* for certain scenarios might be useful to share this project var */

def _disableSystemExitCall = {
	System.setSecurityManager(
		new SecurityManager() {
			@Override public void checkPermission(java.security.Permission perm) {}
			@Override public void checkExit(int status) { throw new SecurityException(); }
		}	
	);
};

def _enableSystemExitCall = { System.setSecurityManager(null); };

/* for certain scenarios might be useful to share these closures with build */
project.ext.disableSystemExitCall = _disableSystemExitCall;
project.ext.enableSystemExitCall  = _enableSystemExitCall;

/* key method/closure - used as: doSvnMain( 'your', 'svn', 'args', 'go', 'here' ); */
project.ext.doSvnMain = { String... aSvnArgs ->
	_disableSystemExitCall(); /* stop SVN.main from doing a System.exit call */
	try {
		SVN.main( aSvnArgs as String[] );
	} finally {
		_enableSystemExitCall();
	}
} ;

Groovy 删除所有文件和子目录

def c
c = {println "Dir ${it.canonicalPath}"; it.eachDir(c); it.eachFile{println "File ${it.canonicalPath}"; it.delete()}}
c new File("test")