Visar inlägg med etikett In-memory DB. Visa alla inlägg
Visar inlägg med etikett In-memory DB. Visa alla inlägg

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 }

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 16 januari 2014

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()