import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class EncryptionUtil {
/**
* String to hold name of the encryption algorithm.
*/
public static final String ALGORITHM = "RSA";
private static final int MAX_LENGTH = 16384;
/**
* String to hold the name of the private key file.
*/
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
/**
* String to hold name of the public key file.
*/
public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
/**
* Generate key which contains a pair of private and public key using 16384
* bytes. Store the set of keys in Prvate.key and Public.key files.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws FileNotFoundException
*/
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
//MAXIMUM KEY LENGTH
keyGen.initialize(MAX_LEGTH);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The method checks if the pair of public and private key has been generated.
*
* @return flag indicating if the pair of keys were generated.
*/
public static boolean areKeysPresent() {
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists()) {
return true;
}
return false;
}
/**
* Encrypt the plain text using public key.
*
* @param text
* : original plain text
* @param key
* :The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
/**
* Decrypt text using private key.
*
* @param text
* :encrypted text
* @param key
* :The private key
* @return plain text
* @throws java.lang.Exception
*/
public static String decrypt(byte[] text, PrivateKey key) {
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
}
try {
// Check if the pair of keys are present else generate those.
if (!EncryptionUtil.areKeysPresent()) {
// Method generates a pair of keys using the RSA algorithm and stores it
// in their respective files
EncryptionUtil.generateKey();
}
final String originalText = "In practice, we need to store the public and private keys somewhere. Typically, the private key will be placed on our server, and the public key distributed to clients. To store the key, we simply need to pull out the modulus and the public and private exponents, then write these numbers to some file (or put in whatever convenient place).";
ObjectInputStream inputStream = null;
// Encrypt the string using the public key
inputStream = new ObjectInputStream(new FileInputStream(EncryptionUtil.PUBLIC_KEY_FILE));
final PublicKey publicKey = (PublicKey) inputStream.readObject();
final byte[] cipherText = EncryptionUtil.encrypt(originalText, publicKey);
// Decrypt the cipher text using the private key.
inputStream = new ObjectInputStream(new FileInputStream(EncryptionUtil.PRIVATE_KEY_FILE));
final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
final String plainText = EncryptionUtil.decrypt(cipherText, privateKey);
// Printing the Original, Encrypted and Decrypted Text
System.out.println("Original: " + originalText);
System.out.println("Encrypted: " +cipherText.toString());
System.out.println("Decrypted: " + plainText);
} catch (Exception e) {
e.printStackTrace();
}
tisdag 14 oktober 2014
RSA Example...
Etiketter:
Big Keys,
Decryption,
Encryption,
Groovy,
Java,
RSA
torsdag 18 september 2014
Hazelcast and Groovy
@Grapes(
@Grab(group='com.hazelcast', module='hazelcast-all', version='3.2.5')
)
import com.hazelcast.core.Hazelcast
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.query.SqlPredicate
import java.util.Map
import java.util.Queue
//Bean to store
class Customer implements Serializable
{
static final long serialVersionUID = 423248904328809L;
def name;
//numeric values have to be declared with right type here
Integer internalId;
def birthDate;
}
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance()
Map customers = hazelcastInstance.getMap( "customers" )
customers.put(1, new Customer(internalId:10001, name:'Luis Dinkel', birthDate:'1976-01-23'))
customers.put(2, new Customer(internalId:10111, name:'Logan Askim', birthDate:'1971-11-13'))
def cust = customers.values(new SqlPredicate("internalId>10000 AND name LIKE '%Lui%'"));
println(cust.name)
hazelcastInstance.shutdown()
onsdag 17 september 2014
RestService with Springboot and Groovy
To test this you have to install GVM follow the instruction for your environment, I use Cygwin and GVM, when you have GVM up and running, install Springboot on GVM:
gvm install springboot
//Place this groovy-file in /cygwin/home/your_username
//To kick on the service open cygwin or another terminal and write:
//spring run your_file_name.groovy
//Now the service is started, open a browser and test the service, f.e: http://localhost:8080/greeting/John
@Grab("org.grails:gorm-hibernate4-spring-boot:1.0.0.RC1")
@Grab("com.h2database:h2:1.3.173")
import grails.persistence.*
import org.springframework.http.*
import org.springframework.web.bind.annotation.*
import static org.springframework.web.bind.annotation.RequestMethod.*
@RestController
class Application {
@RequestMapping("/greeting")
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name)
{
return "greeting "+name
}
@RequestMapping("/greeting/{name}")
public String greeting2(@PathVariable("name") String name)
{
return "greeting "+name
}
@RequestMapping(value = '/person/add/{birthDate}/{firstName}/{lastName}', method = GET)
ResponseEntity addPerson(@PathVariable("birthDate") String birthDate,
@PathVariable("firstName") String firstName,
@PathVariable("lastName") String lastName)
{
Person.withTransaction
{
def p = new Person(firstName: firstName, lastName:lastName,birthDate:birthDate).save()
if(p)
{
return new ResponseEntity("OK", HttpStatus.CREATED )
}
else
{
return new ResponseEntity("BAD",HttpStatus.BAD_REQUEST)
}
}
}
@RequestMapping(value="/person/findByFirstName/{lang}/{value}", method = GET)
String findByFirstName(@PathVariable("lang") String lang, @PathVariable("value") String value) {
def salutation = getSalutation(lang)
def p = Person.findByFirstName(value)
return p ? "${salutation} ${p.firstName} ${p.lastName} !" : "Person not found"
}
private String getSalutation(String lang)
{
def salutation = 'Hello'
if(lang.equals("sv"))
{
salutation = 'Hej'
}
else if (lang.equals("it"))
{
salutation = 'Salve'
}
return salutation
}
}
@Entity
class Person {
String firstName
String lastName
String birthDate
}
Etiketter:
Groovy,
H2,
Hibernate,
In-memory DB,
Micro Framework,
REST,
Spring,
Web Service
söndag 14 september 2014
Low Cost Jaxb Validator
package nap.util.jaxb;
import java.lang.reflect.Field;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import org.apache.log4j.Logger;
/**
* minimal consideration of JAXB annotation
*/
public class JaxbValidator
{
private static final Logger LOG = Logger.getLogger(JaxbValidator.class);
private static StringBuilder errors = new StringBuilder();
private static String message;
/**
* Enforce 'required' attibute.
*
* Requires either no security manager is used or the default security
* manager is employed.
*
* @throws SchemaValidationException
* @see {@link Field#setAccessible(boolean)}.
*/
public static void validateRequired(T target) throws SchemaValidationException
{
try
{
Class targetClass = target.getClass();
Field[] fields = targetClass.getDeclaredFields();
for (Field field : fields)
{
XmlElement annotation = field.getAnnotation(XmlElement.class);
if (annotation != null && annotation.required())
{
try
{
field.setAccessible(true);
if (field.get(target) == null)
{
if (errors.length() != 0)
{
errors.append(" ");
}
message = String.format("%s: required field '%s' is null.", targetClass.getCanonicalName(), field.getName());
LOG.warn(message);
errors.append(message);
}
}
catch (IllegalArgumentException e)
{
LOG.warn(field.getName(), e);
}
catch (IllegalAccessException e)
{
LOG.warn(field.getName(), e);
}
}
if (field.getType().getCanonicalName().equals(List.class.getCanonicalName()))
{
field.setAccessible(true);
List list = (List) field.get(target);
for (Object obj : list)
{
validateRequired(obj);
}
}
}
if (errors.length() != 0)
{
throw new SchemaValidationException(message);
}
}
catch (IllegalArgumentException e)
{
throw new SchemaValidationException(message);
}
catch (IllegalAccessException iae)
{
throw new SchemaValidationException(message);
}
}
static class SchemaValidationException extends Exception
{
private static final long serialVersionUID = 1787869622725094010L;
SchemaValidationException(String msg)
{
super(msg);
}
}
}
fredag 12 september 2014
Embed Derby DB in Groovy
@Grapes([
@Grab(group='org.apache.derby', module='derby', version='10.10.1.1'),
@GrabConfig(systemClassLoader=true)
])
import groovy.sql.*
import java.sql.*
import java.sql.DriverManager
protocol = 'jdbc:derby:'
def props = new Properties()
props.put('user', 'user1')
props.put('password', 'user1')
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver())
//DriverManager.registerDriver()
def sql = Sql.newInstance("${protocol}derbyDB;create=true", props)
/* Creating table, adding few lines, updating one */
sql.execute('create table people(id int, name varchar(40), second_name varchar(40), phone varchar(30), email varchar(50))')
println("Created table 'people'")
sql.execute("insert into people values (1,'John', 'Doe', '123456','johndoe@company.com')")
sql.execute("insert into people values (2,'Bill', 'Brown', '324235','billbrown@company.com')")
sql.execute("insert into people values (3,'Jack', 'Daniels', '443323','jackdaniels@company.com')")
println('Inserted people')
sql.execute("update people set phone='443322', second_name='Daniel''s'where id=3")
println('Updated person')
/* Simple query */
def rows = sql.rows('SELECT * FROM people ORDER BY id')
rows.each {println it}
/* Dropping table 'people' */
sql.execute('drop table people')
println ("Table 'people' dropped")
try{
DriverManager.getConnection('jdbc:derby:;shutdown=true')
}
catch (SQLException se){
gotSQLExc = true
}
println('Finish!')
torsdag 11 september 2014
How to parse JSon with Groovy
The Slurper:
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper();
/*
Read the JSON from the file system
*/
def jsonSlurper = new JsonSlurper()
def reader = new BufferedReader(new FileReader("c:/tmp/users.json"))
def parsedData = jsonSlurper.parse(reader)
def usersList = []
parsedData.each {
entry,value ->
println value
def user = new User(id:value.id,
screenName:value.screenName,
name:value.name,
url:value.url,
followersCount:value.followersCount,
friendsCount:value.friendsCount,
favouritesCount:value.favouritesCount,
statusesCount:value.statusesCount)
usersList.add(user)
}
usersList.each {aUser -> println aUser.name}
The Bean:
class User{
def id
def screenName
def name
def url
def followersCount
def friendsCount
def favouritesCount
def statusesCount
def String toString(){
return "Name: "+this.name+
" ScreenName:"+this.screenName+
" Followers: "+this.followersCount+
" Friends: "+this.friendsCount+
" Favourites: "+this.favouritesCount+
" Statuses: "+this.statusesCount+"
" URL: "+this.url
}
}
The json file:
{
"users": [
{
"followersCount": 2000,
"id": "293939",
"favouritesCount": null,
"friendsCount": 2000,
"url": null,
"screenName": "ALAN000",
"name": "Alan",
"statusesCount": 1900
},
{
"followersCount": 1000,
"id": "393939",
"favouritesCount": null,
"friendsCount": 2030,
"url": null,
"screenName": "ALF2000",
"name": "Alfred",
"statusesCount": 900
},
{
"followersCount": 3020,
"id": "493939",
"favouritesCount": null,
"friendsCount": 2200,
"url": null,
"screenName": "ANNA000",
"name": "Anna",
"statusesCount": 910
}
]
}
Generated with this code:
def user1 = new GroovyUser(id:"293939",name:"Alan",screenName:"ALAN000",followersCount:2000,friendsCount:2000,statusesCount:1900)
def user2 = new GroovyUser(id:"393939",name:"Alfred",screenName:"ALF2000",followersCount:1000,friendsCount:2030,statusesCount:900)
def user3 = new GroovyUser(id:"493939",name:"Anna",screenName:"ANNA000",followersCount:3020,friendsCount:2200,statusesCount:910)
def users = [user1, user2,user3]
def jsonBuilder = new groovy.json.JsonBuilder(users:users)
println(jsonBuilder.toPrettyString())
def file = new File("c:/tmp/users.json")
file.write(jsonBuilder.toPrettyString())
fredag 14 mars 2014
Groovy HTTPBuilder POST: JIRA API
How to create a Rest client to
import groovyx.net.http.HttpResponseDecorator;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.entity.StringEntity;
import groovy.json.JsonSlurper;
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
@Grapes([
@Grab(group = 'org.codehaus.groovy.modules.http-builder',
module = 'http-builder', version = '0.5.1'),
@GrabExclude('org.codehaus.groovy:groovy')
])
//Your Jira api url
def jiraApiUrl = 'localhost:8989/rest/api/2/'
//Your user and password
def basic = 'Basic ' +
'user:password'.bytes.encodeBase64().toString()
//New issue to add
def msg= '''
{
"fields": {
"project": {
"id": "10000"
},
"summary": "something's test www",
"issuetype": {
"id": "10000"
},
"assignee": {
"name": "luigi"
},
"labels": [
"bugfix",
"blitz_test"
],
"timetracking": {
"originalEstimate": "10",
"remainingEstimate": "5"
},
"environment": "environment",
"description": "description",
"duedate": "2011-03-11",
"customfield_10007": "Epic Name is required."
}
}
'''
def bodyMap= new JsonSlurper().parseText(msg)
println bodyMap
//Url and path
def myClient = new groovyx.net.http.HTTPBuilder('http://'+jiraApiUrl+'issue/')
//Proxy to use Fiddler
myClient.setProxy('localhost', 8888, 'http')
results = myClient.request(POST, JSON) { req ->
req.addHeader('Authorization', basic)
req.addHeader('Content-Type' ,'application/json')
req.addHeader("accept", "application/json");
requestContentType = JSON
body = bodyMap
println req.getAllHeaders()
response.success = { resp, reader ->
println "SUCCESS! ${resp.statusLine}"
}
response.failure = { resp ->
println "FAILURE! ${resp.properties}"
}
}
Groovy RestClient GET; JIRA API
How to create a Rest client to
import groovyx.net.http.RESTClient;
import groovyx.net.http.HttpResponseDecorator;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequestInterceptor;
import groovy.json.JsonSlurper;
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
@Grapes([
@Grab(group = 'org.codehaus.groovy.modules.http-builder',
module = 'http-builder', version = '0.5.1'),
@GrabExclude('org.codehaus.groovy:groovy')
])
def jiraApiUrl = 'http://localhost:8989/rest/api/2/'
def jiraClient = new RESTClient(jiraApiUrl)
def basic = 'Basic ' +
'user:password'.bytes.encodeBase64().toString()
jiraClient.client.addRequestInterceptor(
new HttpRequestInterceptor() {
void process(HttpRequest httpRequest,
HttpContext httpContext) {
httpRequest.addHeader('Authorization', basic)
}
})
def serverInfo = jiraClient.get(path: 'issue/SPACE-4')
println serverInfo.data
def slurp =
new JsonSlurper().parseText(serverInfo.data.toString())
println slurp.fields.description
måndag 3 mars 2014
Modular Groovy Scripting
First we create an abstract class like this:
package test
public abstract class IncludeScript extends Script {
def includeScript(scriptClass) {
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(new File(scriptClass));
def scriptInstance = clazz.newInstance()
scriptInstance.metaClass = this.metaClass
scriptInstance.binding = new ConfigBinding(this.getBinding().callable)
scriptInstance.&run.call()
}
}
Compile the IncludeScript.groovy with groovyc and add the class-file to your classpath.
Second we create something to test on like:
service{
endpoint ="http://mysite.se/Service"
port=4322
user="admin"
password="YmlsbDR5b3U="
}
//----------------------------------------------------------------------------------------
//Copy the code above to a file and name it to ServiceConfig.groovy
//----------------------------------------------------------------------------------------
import test.IncludeScript
class SecurityConfig extends IncludeScript {
def run() { // normal contents of a config file go in here
security {
includeScript( "c:\\tmp\\ServiceConfig.groovy" )
active = true
}
}
}
//----------------------------------------------------------------------------------------
//Copy the code above to a file and name it to what you want, I named my to prop.groovy
//----------------------------------------------------------------------------------------
Now we test our modularity...
def conf = new ConfigSlurper().parse( new File("c:\\tmp\\prop.groovy").toURL() )
println conf.security.service.password
println conf.security.active
torsdag 16 januari 2014
Meaning of your lastname with Groovy
import org.htmlcleaner.*
@Grapes(
@Grab(group='net.sourceforge.htmlcleaner', module='htmlcleaner', version='2.2')
)
def name ='russo';
def url = new URL('http://www.ancestry.com/name-origin?surname='+name)
// Clean any messy HTML
def cleaner = new HtmlCleaner()
def node = cleaner.clean(url)
// Convert from HTML to XML
def props = cleaner.getProperties()
def serializer = new SimpleXmlSerializer(props)
def xml = serializer.getXmlAsString(node)
//println xml
// Parse the XML into a document we can work with
def records = new XmlSlurper(false,false).parseText(xml)
def div = records.'**'.findAll{
it.@class.text()=='familyNameMeaning'
}
Infinite List with Groovy used as object factory
class LazyList {
def head
private Closure tail
LazyList(def head, Closure tail) { this.head=head; this.tail=tail }
def LazyList getTail() { tail ? tail.call() : null }
def List getFirst(n) {
def result = []; def current = this
n.times { result.add(current.head); current = current.tail }
result
}
def LazyList filter(Closure matchExpr) {
if (matchExpr(head))
return matchExpr.owner.prepend(head, { getTail().filter(matchExpr) })
else
return getTail().filter(matchExpr)
}
}
// general purpose lazy list function
def prepend(val, Closure c) { new LazyList(val, c) }
class User
{
def age = 0
def id = 0
def name = 'default '
User plus(def i)
{
def p = 'and marc son bert wick ness ton shire step ley ing sley up down jack ly rex sum brown'.split()
def q = 'Lord Lady Viscount Baronet Marquis Sir Captain Admiral'.split()
def random = q[new Random().nextInt(q.size())] + ' ' + (0..1).collect { p[new Random().nextInt(p.size())] }.join('').capitalize() + ' ' + (0..1).collect { p[new Random().nextInt(p.size())] }.join('').capitalize()
new User(age:this.age+i,id:this.id+i,name:random)
}
String toString()
{
name+' '+age+' '+id
}
}
// now define and use infinite streams
def userFactory(n) { prepend(n, { userFactory(n+1) }) }
def listOfUsers = userFactory(new User().plus(1))
def ten = listOfUsers.getFirst(10)
println ten
def evennumbers =listOfUsers.filter{ it.age % 2 == 0 }
println evennumbers.getFirst(10)
Generate QRCode with Groovy
import com.google.zxing.*
import com.google.zxing.qrcode.*
import com.google.zxing.qrcode.decoder.*
import com.google.zxing.client.j2se.*
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.awt.*
//fix zxing dependency
@Grapes(
@Grab(group='com.google.zxing', module='javase', version='2.2')
)
def QRCODE_IMAGE_HEIGHT = 300
def QRCODE_IMAGE_WIDTH = 300
//path where you want to save qrcode
def IMAGE_PATH = "C:/Users/luma/Google Drive/apps/"
def hints = new HashMap()
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H)
def qrWriter = new QRCodeWriter()
//Add your data instead of http://capatosta.se/
def matrix = qrWriter.encode("http://capatosta.se/",
BarcodeFormat.QR_CODE,
QRCODE_IMAGE_WIDTH,
QRCODE_IMAGE_HEIGHT,
hints)
def image = MatrixToImageWriter.toBufferedImage(matrix)
//Read a logo gif to add QRCode image
def overlay = ImageIO.read(new File(IMAGE_PATH, "capa.gif"))
//Calculate the delta height and width
def deltaHeight = image.height - overlay.height
def deltaWidth = image.width - overlay.width
//Draw the new image
def combined = new BufferedImage(QRCODE_IMAGE_HEIGHT, QRCODE_IMAGE_WIDTH, BufferedImage.TYPE_INT_ARGB)
def g = (Graphics2D)combined.getGraphics()
g.drawImage(image, 0, 0, null)
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f))
g.drawImage(overlay, (int)Math.round(deltaWidth/2), (int)Math.round(deltaHeight/2), null)
def imageFile = new File(IMAGE_PATH, "qrcode_logo2.png")
ImageIO.write(combined, "PNG", imageFile)
println "Generating QRCode ================================="
println "Image width,height: ${image.width},${image.height}"
println "Overlay width,height: ${overlay.width},${overlay.height}"
println "Delta width,height: $deltaWidth, $deltaHeight"
println "QRCode saved to: ${imageFile.absolutePath}"
println "DONE!! ================================="
Groovy and Strings
//GString supports Variable Interpolation; $var eller ${var}
def var = "HI"
//Slashy String will result in a GString so supports variable interpolation
def slashyString = /Test \/ "slashy" 'string!' $var/
//Single Quote String is an java.lang.String so doesn't support variable interpolation
def singleQuoteString = 'Test / "single" \'quote string\' $var'
//Double Quote String will result in a GString so supports variable interpolation
def doubleQuoteString = "Test / \"single\" 'double quote string' $var"
println slashyString.class
println singleQuoteString.class
println doubleQuoteString.class
//Multiline Strings
slashyString = /
Test
\/ "slashy"
'string!'
${var}
/
singleQuoteString = '''
Test
/ "single"
\'quote string\'
${var}
'''
doubleQuoteString = """
Test /
\"single\"
'double quote string'
${var}
"""
println slashyString
println singleQuoteString
println doubleQuoteString
//GString will execute embedded Closure
def user = new Expando(name: 'mrhaki', email: 'mail@email.com')
def s = "...."
//GStrings will execute embedded Closure
def directEval = "Current name value is ${user.name} and email is ${user.email}."
def lazyEval = /Current name value is ${ -> user?.name } and email is ${s=user.email }./
user.name = 'changed username'
user.email = 'changed email'
println directEval
println lazyEval
println s
DAO to Service
Compile and run separatelly!
//JAVA BEAN, Expando Bean works bad without binding of CXF
package test;
public class Customer
{
private int id;
private String lastname;
private String firstname;
private String city;
public int getId()
{
return this.id;
}
public void setId(int paramInt)
{
this.id = paramInt;
}
public String getLastname()
{
return this.lastname;
}
public void setLastname(String paramString)
{
this.lastname = paramString;
}
public String getFirstname()
{
return this.firstname;
}
public void setFirstname(String paramString)
{
this.firstname = paramString;
}
public String getCity()
{
return this.city;
}
public void setCity(String paramString)
{
this.city = paramString;
}
}
//Groovy DAO
package test
//In-memory DB
@Grab(group='com.h2database', module='h2', version='1.3.168')
import groovy.sql.Sql
class CustomerDAO
{
private def sql
public CustomerDAO()
{
init()
}
private void init()
{
sql = Sql.newInstance("jdbc:h2:mem:db1", "sa", "sa", "org.h2.Driver")
sql.execute("""CREATE TABLE Customers
(
id int,
lastname varchar(255),
firstname varchar(255),
city varchar(255)
);
""")
sql.execute("""INSERT INTO CUSTOMERS (id, lastname, firstname, city) VALUES (1,'Enrot','Tommy','Stavanger');""")
println sql.rows("select * from CUSTOMERS")
}
Boolean addCustomer(Integer id, String lastname, String firstname, String city)
{
def r = sql.execute("""INSERT INTO CUSTOMERS (id, lastname, firstname, city)
VALUES ($id, $lastname, $firstname, $city); """)
return r==null?false:true;
}
Customer getCustomerByLastname(String lastname)
{
GroovyRowResult res = sql.firstRow("select id,lastname,firstname,city from CUSTOMERS WHERE lastname=$lastname")
println res.containsKey('id')
println res.id+", "+res.lastname+", "+res.firstname+", "+res.city
return new Customer(id:res.id,lastname:res.lastname,firstname:res.firstname,city:res.city)
}
}
//Kick on WS
@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSServer
def server = new WSServer()
server.setNode("test.CustomerDAO", "http://localhost:6999/CustomerService")
server.start()
Generating Barcode in PDF with Groovy
import com.lowagie.text.pdf.BarcodePDF417
import com.lowagie.text.pdf.BarcodePostnet
import com.lowagie.text.pdf.PdfContentByte
import com.lowagie.text.pdf.PdfWriter
@Grapes(
@Grab(group='com.lowagie', module='itext', version='4.2.1')
)
// step 1: creation of a document-object
def document = new Document()
try
{
// step 2:
// we create a writer
def writer = PdfWriter.getInstance(document,new FileOutputStream("/barcode.pdf"))
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
def cb = writer.getDirectContent()
// EAN 13
document.add(new Paragraph("Barcode TEST"))
document.add(createBarcodeEAN("5704420001016",cb))
} catch (DocumentException de) {
println(de.getMessage())
} catch (IOException ioe) {
println(ioe.getMessage())
}
// step 5: we close the document
document.close()
/* Creating a barcode image using Barcode 128 for myText*/
Image createBarcode128(String myText, PdfContentByte cb )
{
Barcode128 code128 = new Barcode128()
code128.setCode(myText)
code128.setBarHeight(35f)
code128.setInkSpreading(0.6f)
Image myBarCodeImage128 = code128.createImageWithBarcode( cb, null, null)
return myBarCodeImage128
}
Image createBarcodeEAN(String myText, PdfContentByte cb )
{
BarcodeEAN code128 = new BarcodeEAN();
code128.setCodeType(Barcode.EAN13)
code128.setCode(myText)
code128.setGuardBars(false)
Image myBarCodeImage128 = code128.createImageWithBarcode( cb, null, null)
return myBarCodeImage128
}
Groovy Presentation - Svenska
Prenumerera på:
Inlägg (Atom)