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();
}
Visar inlägg med etikett Groovy. Visa alla inlägg
Visar inlägg med etikett Groovy. Visa alla inlägg
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
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!')
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
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
onsdag 6 november 2013
Groovy Web Service
It's very simple to create a web service with Groovy, look a this:
Now you can test this with SoapUI or with this code:
@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSServer
import java.security.SecureRandom
import java.math.BigInteger
class UtilsService
{
double add(double arg0, double arg1)
{
return (arg0 + arg1)
}
double square(double arg0)
{
return (arg0 * arg0)
}
String randomPassword()
{
SecureRandom random = new SecureRandom()
return new BigInteger(130, random).toString(32)
}
long random()
{
Random random = new Random();
long randInt = random.nextLong()
if (randInt < 0)
{
randInt = randInt*-1L;
}
return randInt;
}
String randomPhrase()
{
String[] randomStrings = new String[4];
Random random = new Random();
for(int i = 0; i < randomStrings.length; i++)
{
char[] word = new char[random.nextInt(8)+3];
// words of length 3 through 10. (1 and 2 letter words are boring.)
for(int j = 0; j < word.length; j++)
{
word[j] = (char)(99 + random.nextInt(26));
}
randomStrings[i] = new String(word);
}
String words = "";
for(String word:randomStrings)
{
words+= word+" ";
}
return words.trim();
}
}
def server = new WSServer()
//Start your service
server.setNode("UtilsService", "http://localhost:6980/UtilsService")
server.start()
Now you can test this with SoapUI or with this code:
@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient
def proxy = new WSClient("http://localhost:6980/UtilsService?WSDL", this.class.classLoader)
proxy.initialize()
result = proxy.add(23.88, 24.88)
println "You are sum is: "+result
Simple currency converter in Groovy Swing Style
Simple currency converter in Groovy Swing Style:
@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient
class TryIt
{
groovy.swing.SwingBuilder swing = new groovy.swing.SwingBuilder()
def proxy = new WSClient("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL", TryIt.class.classLoader)
def currency = ['USD', 'EUR', 'CAD', 'GBP', 'AUD', 'SGD','SEK','DKK','NOK']
def rate = 0.0
def exc = 1.0
void main()
{
proxy.initialize()
def refresh = swing.action(
name:'Refresh',
closure:this.&refreshText,
mnemonic:'R'
)
def frame = swing.frame(title:'Currency Demo')
{
panel
{
label 'Currency rate from '
comboBox(id:'from', items:currency)
label ' to '
comboBox(id:'to', items:currency)
label ' rate '
textField(id:'currency', columns:10, rate.toString(),editable:false)
label ' exchange '
textField(id:'exchange', columns:10, exc.toString())
button(text:'Go !', action:refresh)
}
}
frame.pack()
frame.show()
}
def refreshText(event)
{
rate = proxy.ConversionRate(swing.from.getSelectedItem(), swing.to.getSelectedItem()) swing.currency.text = rate
swing.exchange.text = rate*Double.parseDouble(swing.exchange.text)
}
}
new TryIt().main()
Extract input tags from a web page
If you need to extract a specific html-tag from a web page you can do so:
@Grapes( @Grab('org.jsoup:jsoup:1.6.1'))
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
//Get a web page
Document doc = Jsoup.connect("https://biglietti.italotreno.it/Booking_Acquisto_Ricerca.aspx").get()
def results = doc.select("input")
for (Element src : results)
{
if (src.tagName().equals("input"))
{
println("tag name: "+
src.tagName()+" id: "+src.attr("id")+" type: "+src.attr("type")+" name: "+ src.attr("name"));
}
}
Simple Groovy Scheduler
How to write a simple scheduler in Groovy? Here you are:
Attetion: If you run this code as is, to stop the script you have to kill the GroovyConsole!
class GroovyTimerTask extends TimerTask {
Closure closure
void run()
{
closure()
}
}
class TimerMethods
{
static TimerTask runEvery(Timer timer, long delay,
long period, Closure codeToRun)
{
TimerTask task = new GroovyTimerTask(closure: codeToRun)
timer.schedule task, delay, period
task
}
}
use (TimerMethods)
{
def timer = new Timer()
def task = timer.runEvery(1000, 5000)
{
println "Task executed at ${new Date()}."
}
println "Current date is ${new Date()}."
}
Attetion: If you run this code as is, to stop the script you have to kill the GroovyConsole!
Prenumerera på:
Inlägg (Atom)