writning the data into the database using xml file in groovy - groovy

import groovy.sql.Sql
class come {
static main(args) {
def sql = Sql.newInstance("jdbc:mysql://localhost/test", "root","nayeem","com.mysql.jdbc.Driver")
assert(sql)
sql.execute('drop table if exists customers')
sql.execute(
'''create table customers(
CustomerID bigint(20) not null auto_increment,
CustomerName varchar(50) not null,
ContactName varchar(50) not null,
Address varchar(50) not null,
city varchar(25) not null,
PostalCode bigint(20) not null,
Country varchar(20) not null,
primary key(CustomerID))''')
def i=1
def key1= new XmlSlurper().parse('E:/kha.xml')
assert(key1)
//key1.each{println it}
for (p in { vars -> customers
} ){
println 'Hai'
println("->$i")
def CustomerID=p.CustomerID.text();
println("->$CustomerID")
def CustomerName=p.CustomerName.text();
println("->$CustomerName")
def ContactName=p.ContactName.text();
println("->$ContactName")
def Address=p.Address.text();
println("->$Address")
def array=[] as String
def city=p.city.text();
println("->$city")
def PostalCode=p.PostalCode.text();
println("->$PostalCode")
def Country=p.Country.text();
println("->$Country")
def key2="insert into customers values($CustomerID,$CustomerName,$ContactName,$Address,$city,$PostalCode,$Country)"
sql.execute(key2)
i++
}
def list=sql.rows"select * from customers"
println ''
println '------reading data--------'
println list
}
}
i am getting groovy.lang.MissingPropertyException: No such property: CustomerID for class: come please give me reply

Related

Print the specific field from list

Please help to print the assetNumber. Need to search for specific assetname and print its associated assetNumber using list in groovy.
Currently, it does not print value. It struck once search criteria is entered.
class Main
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
List list = new ArrayList()
Asset asset = new Asset()
def name
def assetNumber
def assigneeName
def assignedDate
def assetType
String userInput = "Yes"
while(userInput.equalsIgnoreCase("Yes"))
{
println "Enter the asset details:"
asset.name = br.readLine()
asset.assetNumber= Integer.parseInt(br.readLine())
asset.assigneeName = br.readLine()
asset.assignedDate = Date.parse('dd/MM/yyyy', br.readLine())
list.add(asset)
println "Do you want to continue(yes/no)"
userInput = br.readLine()
}
println "Enter the asset type:"
assetType = br.readLine()
println "Asserts with type "+assetType+":"
def items = list.findAll{p->p.name == assetType }
items.each { println it.assetNumber }
}
}
class Asset
{
def name
def assetNumber
def assigneeName
def assignedDate
}
You are overwriting the value in your Asset object, then adding the same object to the list every time
If you create a new asset inside the loop (rather than outside it), it should work...
Something like this:
import groovy.transform.*
class Main {
static main(args) {
def console = System.console()
def list = []
while (true) {
def name = console.readLine 'Enter the asset name:'
def number = console.readLine 'Enter the asset number:'
def assignee = console.readLine 'Assignee name:'
def date = console.readLine 'Date (dd/MM/yyyy):'
list << new Asset(
name: name,
assetNumber: Integer.parseInt(number),
assigneeName: assignee,
assignedDate: Date.parse('dd/MM/yyyy', date)
)
if ('Y' != console.readLine('Enter another (y/n):')?.take(1)?.toUpperCase()) {
break
}
}
def type = console.readLine 'Enter the asset type:'
println "Assets with type $type:"
list.findAll { p -> p.name == type }
.each { println it.assetNumber }
}
#Canonical
static class Asset {
def name
def assetNumber
def assigneeName
def assignedDate
}
}

Compare all Fields of an Object

In our Integration Tests we wan't to compare every field of an Object returned by an Rest Controller with an object constructed in the test.
This example illustrates the problem:
class RestIntegrationTest extends Specification {
def "Should return contracts"() {
when:
def actual = callRestController()
then:
// compare all fields of actual with "contract"
actual == new Contract(
number: "123",
signDate: "2017-04-01",
address: new Address(
name: "Foobar",
street: "Foostreet",
city: "Frankfurt",
zip: "60486"
),
persons: [new Person(name: "Christian")]
)
}
def callRestController() {
return new Contract(
number: "123",
signDate: "2017-04-01",
address: new Address(
name: "Foobar",
street: "Wrong Street",
city: "Frankfurt",
zip: "60486"
),
persons: [new Person(name: "Frank")]
)
}
static class Contract {
String number
String signDate
Address address
Person[] persons
}
static class Address {
String name
String street
String city
String zip
}
static class Person {
String name
}
}
As output we like expect something like this:
address.street "Wrong Street" != "Foostreet"
persons[0].name "Christian" != "Frank"
Breaking the assert into multiple "==" lines would lead into the correct output, but that will be not handy since some objects are quite huge.
You can try the groovy's #EqualsAndHashCode:
import groovy.transform.EqualsAndHashCode
#EqualsAndHashCode
static class Address {
String name
String street
String city
String zip
}
You can use unitils assertReflectionEquals
http://unitils.sourceforge.net/tutorial-reflectionassert.html
It's not comprehensive but may be sufficient for your needs:
def compareFields( obj1, obj2, propName = null ) {
obj1.properties.each {
if ( it.value instanceof Object[] ) {
def obj2Len = obj2."${it.key}".length
it.value.eachWithIndex { collObj, idx ->
if ( idx + 1 <= obj2Len )
compareFields( collObj, obj2."${it.key}"[idx], "${it.key}[${idx}]" )
}
}
if ( !it.value.class.getCanonicalName().contains( 'java' ) ) {
compareFields( it.value, obj2."${it.key}", it.key )
}
if ( it.value.class.getCanonicalName().contains( 'java' ) &&
it.key != 'class' &&
it.value <=> obj2."${it.key}") {
println "${propName ? "$propName." : ''}${it.key}: '${it.value}' != '" + obj2."${it.key}" + "'"
}
}
}

slick: nested (embedded) classes DRY

If can define nested classes (embedded in JPA) following learning slick2 like this:
case class Person(name: Name, address: Address)
case class Name(given: String, family: String)
case class Address(street: String, city: String)
class Directory(tag: Tag) extends Table[Person](tag, "directory") {
def givenName = column["String"] ( "given_name" )
def familyName = column["String"] ( "family_name" )
def street = column["String"] ( "street" )
def city = column["String"] ( "city" )
def * = (name, address) <> (Person.tupled, Person.unapply)
def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
def address = (street, city) <> (Address.tupled, Address.unapply)
}
I would not like to write the definition of street, city and address in every table I embed Adress. I would like to write something like below, but this does not compile for the obvious reasons, because column is a method on Table etc... Is it possible to reuse column definitions somehow?
object Adresses {
def street = column["String"] ( "street" )
def city = column["String"] ( "city" )
def address = (street, city) <> (Address.tupled, Address.unapply)
}
class Directory(tag: Tag) extends Table[Person](tag, "directory") {
def givenName = column["String"] ( "given_name" )
def familyName = column["String"] ( "family_name" )
def * = (name, Adresses.address) <> (Person.tupled, Person.unapply) //address from Adresses
def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
}
You can make Adresses a trait that inherits from the class Table (yep that works).
trait Adresses[T] extends Table[T]{
def street = column["String"] ( "street" )
def city = column["String"] ( "city" )
def address = (street, city) <> (Address.tupled, Address.unapply)
}
class Directory(tag: Tag) extends Table[Person](tag, "directory") with Adresses[Person] {
def givenName = column["String"] ( "given_name" )
def familyName = column["String"] ( "family_name" )
def * = (name, address) <> (Person.tupled, Person.unapply) //address from Adresses
def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
}

Grails 2.1 How Can i add value in join table

I create 2 tables one Category and one Manufacturer, and There relationship is Many-to-Many,
So i use a join table,
I insert values into two tables individually. Now i want to join two table by their id, but i cannot do, Can you help me....
When i try to insert value in join table give an exception, here is the exception:
Cannot invoke method addToManufacturers() on null object. Stacktrace follows:
java.lang.NullPointerException: Cannot invoke method addToManufacturers() on null object
here is my domain class for Category
static hasMany = [manufacturers: Manufacturer]
static constraints = {
name blank: false, size: 0..60, unique: false
}
static mapping = {
table 't01i001'
id column: 'f_category_id'
name column: 'f_name', length: 30
version column: 'f_revision'
manufacturers joinTable: [name: 't01j001', key: 'k_category_id', column: 'k_manufacturer_id']
}
here is my domain class for manufacturer
static belongsTo = Category
static hasMany = [categories: Category]
static constraints = {
name blank: false, size: 0..60, unique: false
}
static mapping = {
table 't01i002'
id column: 'f_manufacturer_id'
name column: 'f_name', length: 30
version column: 'f_revision'
categories joinTable: [name: 't01j001', key: 'k_manufacturer_id', column: 'k_category_id']
}
add my controller where i try to insert
def manuInsertInCat(){
def message, flag,count=0,categories = []
int catid = params.containsKey("catid") ? params.catid : '0'
int manuid = params.containsKey("manuid") ? params.manuid : '0'
def category = Category.get(catid);
def manufacture = Manufacturer.get(manuid)
category.addToManufacturers(manufacture)
message = "Successfully Loaded"
count++
flag =true
render Category.getJsonData(categories, count, flag, message)
}
At last i complete my job by this process its works fine.
def catInsertInManu(){
def message, flag,count=0,manufacturers = []
String catid = params.containsKey("catid") ? params.catid : '0'
String manuid = params.containsKey("manuid") ? params.manuid : '0'
def category = Category.get(catid)
def manufacture = Manufacturer.get(manuid)
manufacture.addToCategories(category)
def m01i001001s = []
manufacture.categories.each{ cat ->
m01i001001s << [id:cat.id, name:cat.name]
}
manufacturers << [id: manufacture.id, name:manufacture.name, m01i001001s:m01i001001s]
message = "Successfully Loaded"
count++
flag =true
render Manufacturer.getJsonData(manufacturers, count, flag, message)
}

groovy change bean variables using properties

Is there a way in groovy to do something like:
class Person{
def name, surname
}
public void aMethod(anoherBean){
def bean = retrieveMyBean()
p.properties = anoherBean.properties
}
The property properties is final, is there another way to do this shortcut?
properties is a virtual property; you have to call the individual setters. Try this:
def values = [name: 'John', surname: 'Lennon']
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
Or, using MOP:
Object.class.putAllProperties = { values ->
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
}
Person p = new Person();
p.putAllProperties [name: 'John', surname: 'Lennon']
[EDIT] To achieve what you want, you must loop over the properties. This blog post describes how to do that:
def copyProperties(def source, def target){
target.metaClass.properties.each{
if (source.metaClass.hasProperty(source, it.name) && it.name != 'metaClass' && it.name != 'class')
it.setProperty(target, source.metaClass.getProperty(source, it.name))
}
}
If you don't have any special reason then just use named parameters
def p = new Person(name: 'John', surname: 'Lennon')
After question being updated
static copyProperties(from, to) {
from.properties.each { key, value ->
if (to.hasProperty(key) && !(key in ['class', 'metaClass']))
to[key] = value
}
}

Resources