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'
}
torsdag 16 januari 2014
Meaning of your lastname with Groovy
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)