@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()
torsdag 18 september 2014
Hazelcast and Groovy
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())
Prenumerera på:
Inlägg (Atom)