Groovy/Grails - Jollyday CalenderUtil - No signature of method - java

I have a little problem with my project:
URI
/TimeKeeper/calendar/show
Class
groovy.lang.MissingMethodException
Message
No signature of method: static de.jollyday.util.CalendarUtil.create() is applicable for argument types: (java.util.GregorianCalendar) values:
[java.util.GregorianCalendar[time=1406897280000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=31,WEEK_OF_MONTH=0,DAY_OF_MONTH=1,DAY_OF_YEAR=213,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=48,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=3600000]] Possible solutions: create(), create(java.util.Calendar), create(int, de.jollyday.config.Fixed), create(int, int, int), create(int, int, int, org.joda.time.Chronology), grep()
And thats my code where the exception is thrown:
import static java.util.Calendar.*
import de.jollyday.*
import de.jollyday.util.*
class DayReport {
def day
def records
def getHolidayName() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def holidays = m.getHolidays(day.get(YEAR), 'nw')
holidays.find {
CalendarUtil.create(day) == it.date
}?.description
}
def isHoliday() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def create = CalendarUtil.create(day)
println "DayReport isHoliday: ${create.getClass()}"
m.isHoliday(create, 'nw')
}
...
Can somebody tell me what is wrong?
Thanks :)

def getHolidayName() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def holidays = m.getHolidays(day.get(YEAR), 'nw')
holidays.find {
new LocalDate(day.getTime()) == new LocalDate(it.date)
}?.description
}
def isHoliday() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def localDate = new LocalDate(day.getTime())
println "localDate: " + localDate
m.isHoliday(localDate, 'nw')
}
That's the solution

Related

Copy object properties to another object in Groovy

I was using a funky way to do it suggested in:
https://stackoverflow.com/a/9072974/4470135
So my code is:
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.properties*.keySet()
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
What I get when I try to call a method that should convert an Entity into a Dto is:
No signature of method: java.util.ArrayList.keySet() is applicable
for argument types: () values: []\nPossible solutions: toSet(),
toSet(), set(int, java.lang.Object), set(int, java.lang.Object),
get(int), get(int)
UPDATE:
My source is a Serializable bean with fields:
private String passengerName;
#NotNull
#Size(min = 5, max = 40)
private String destination;
#NotNull
private String departureDate;
My target is a JPA Entity with the same fields, but with an additional #Id field and a slightly different date representation:
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
ZonedDateTime departureDate
The code is working, however, there are corner cases where it may break.
To fix this replace the property access properties with the method call getProperties(), which might be enough for your case. To cover all cases, you will need to write code for special cases (see bottom)
Working example for the original version
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.properties*.keySet()
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
def a = new Expando()
a.foo = "foo"
a.bar = "bar"
def b = new Expando()
b.baz = "baz"
b.bar = "old"
copyProperties(a, b)
println b
Example causing problems
If the parameters have a property called properties I get the same exception you got (if the value is a List):
def c = new Expando()
c.properties = []
c.bar = "bar"
def d = new Expando()
d.baz = "baz"
d.bar = "old"
copyProperties(c, d)
println d
What works in both cases:
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.getProperties()*.keySet()
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
Not that here I used an explicit call to getProperties rather than just accessing the properties property.
We can still break this
def e = new Object() {
// causes same Exception again
def getProperties() {
return []
}
def bar = "bar"
}
def f = new Expando()
f.baz = "baz"
f.bar = "old"
copyProperties(e, f)
You can fix the last example for e by using the metaClass explicitly
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.getMetaClass()*.properties*.name
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
However, that will fail due to f.
Handle special cases
def getProperties(Expando obj) {
return obj.getProperties().keySet()
}
def getProperties(Object obj) {
return obj.getMetaClass()*.properties*.name
}
def copyProperties(source, target) {
def (sProps, tProps) = [source, target].collect {getProperties(it)}
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
Here we give objects that need a special treatment what they need ;)
Note that this only works like this for groovy with #CompileDynamic as the decision which getProperties implementation is called will be made at runtime. The alternative is a check with instanceof for all the cases.
User user = User.findById('1')
User copyUser = new User()
InvokerHelper.setProperties(copyUser, user.properties)

Set a customField Value in JIRA with Groovy JAVA

Ok Maybe I am just really new at this, but I am trying to use this code and it is not updating the custom field value.
Any idea why not? I am guessing its an over sight n my end. Any help is greatly appreciated
def rush = getCustomFieldValue("Rush?")
if (rush=="Yes") {
def cal = new java.util.GregorianCalendar();
cal.setTimeInMillis(customField.setCustomFieldValue("Rush Date", getTime()));
return new java.sql.Timestamp(cal.getTimeInMillis());
}
else {
return null
}
solved
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.customfields.manager.OptionsManager
def componentManager = ComponentManager.instance
def optionsManager = ComponentManager.getComponentInstanceOfType(OptionsManager.class)
def customFieldManager = componentManager.getCustomFieldManager()
def cf = customFieldManager.getCustomFieldObjectByName("Rush?")
def rush = issue.getCustomFieldValue(cf)
def paymentDate = new Date()
if (rush?.value=="Yes"){
if (paymentDate){
def cal = new java.util.GregorianCalendar();
cal.setTimeInMillis(paymentDate.getTime());
cal.add(java.util.Calendar.DAY_OF_MONTH, 0);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
else {
return null
}}
Your snippet, as it stands, fails to me with the following error:
Caught: groovy.lang.MissingMethodException: No signature of method: Custom.getTime() is applicable for argument types: () values: []
That getTime() over there is not being invoked from any object. I guess you want only to setCustomFieldValue in customField, thus, cal.setTimeInMillis()ยน is not needed:
def customField
customField = [
'Rush?':'Yes',
setCustomFieldValue : { field, value -> customField[field] = value }
]
getCustomFieldValue = { customField[it] }
def rush = getCustomFieldValue("Rush?")
def cal = new java.util.GregorianCalendar()
def parseRush = {
if (rush=="Yes") {
customField.setCustomFieldValue("Rush Date", cal.getTime())
return new java.sql.Timestamp(cal.getTimeInMillis())
}
else {
return null
}
}
assert parseRush() == new java.sql.Timestamp(cal.timeInMillis)
assert customField['Rush Date'] == cal.time

Getting a substring using method does not work

I am trying to introduce a method in my program which should result into a substring. I wrote the following code but why would not this work?
class testmethod {
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
println $sname
def shortname(Longname)
{
shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
}
First of all the code should be(for better readability) :-
def shortname(String Longname) not def shortname(Longname).
Also shortname1 = Longname.substring(0, Longname.indexOf('.')) in this shortname1 is not defined.
Moreover you can try :-
def shortname(String Longname)
{
String[] shortnameArr = Longname.split("\\.");
return shortnameArr[0];// will return TEST
}
You're mixing both script and class concepts of the Groovy in one single piece of code.
Just remove the class definition and $ sign to use the script way:
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
println sname
def shortname(Longname)
{
shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
Or add class initialization and local variable declaration to use the class way:
class testmethod {
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
def shortname(Longname)
{
def shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
}
def tc = new testmethod()
println tc.sname

How would I import tables into another class (/object??) so I can run queries on it in the other class/object? [slick 3.0][scala]

I have two tables defined in a
class Patients(tag: Tag) extends Table[(String, String, Int, String)](tag, "Patientss") {
def PID = column[String]("Patient Id", O.PrimaryKey)
def Gender = column[String]("Gender")
def Age = column[Int]("Age")
def Ethnicity = column[String]("Ethnicity")
def * = (PID, Gender, Age, Ethnicity)
}
val patientsss = TableQuery[Patients]
class DrugEffect(tag: Tag) extends Table[(String, String, Double)](tag, "DrugEffectss") {
def DrugID = column[String]("Drug ID", O.PrimaryKey)
def PatientID = column[String]("Patient_ID")
def DrugEffectssss = column[Double]("Drug Effect")
def * = (DrugID, PatientID, DrugEffectssss)
def Patient = foreignKey("Patient_FK", PatientID, patientsss)(_.PID)
}
val d_effects = TableQuery[DrugEffect]
I fill in the tables in this particular object/class as well.
I was wondering how I could call the filled in tables in another object so I can access both DrugEffect and Patients as a class, and then run queries on the table itself?
I hope I'm making myself clear, I don't really have a clue about what I'm doing
What I mean by running queries is something like this:
val q1 = for {
c <- patientsss if (c.Age === 20 && c.Gender === "F")
s <- d_effects if (s.DrugEffectssss > 10.0)
} yield (c.PID, s.DrugID)
but in an object defined in a different file
You need the DB API and the table in the separate class. You can do something like:
import tables.Tables
class SeparateClass extends HasDatabaseConfig[JdbcProfile] {
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
import driver.api._
def get(id: Long) = {
db.run(Tables.DrugEffect.d_effects.filter(_.id === id).result)
}
}

working with java iterators in Scala

Im trying to iterate over a java util.iterator with Scala but am having trouble with casting the objects to the correct class.
I get the error:
type mismatch; found: java.util.Iterator[?0] where type ?0
required : java.util.iterator[net.percederberg.mibble.MibSymbol]
val iter:util.Iterator[MibSymbol] == mib_obj.getAllSymbols.iterator()
the code looks like following:
import java.io.File
import java.util
import net.percederberg.mibble._
import scala.collection.immutable.HashMap
import scala.collection.JavaConversions._
object Bacon {
def main(args:Array[String]) {
println("hello")
val mib_obj:Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
val iter:util.Iterator[MibSymbol] = mib_obj.getAllSymbols.iterator()
while(iter.hasNext()) {
var obj:MibSymbol = iter.next()
println(obj.getName())
}
}
def loadMib(file: File): Mib = {
var loader: MibLoader = new MibLoader()
loader.addDir(file.getParentFile())
return loader.load(file)
}
}
Use an explicit typecast asInstanceOf[Iterator[MibSymbol]]:
def main(args: Array[String]) {
println("hello")
val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
val x = mib_obj.getAllSymbols.iterator()
val iter: util.Iterator[MibSymbol] = x.asInstanceOf[Iterator[MibSymbol]]
while (iter.hasNext()) {
var obj: MibSymbol = iter.next()
println(obj.getName())
}
}
def loadMib(file: File): Mib = {
var loader: MibLoader = new MibLoader()
loader.addDir(file.getParentFile())
return loader.load(file)
}
NOTE: In absence of runtime type information, this may fail.
EDIT1: You can also use a for comprehension:
val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
for ( obj <- mib_obj.getAllSymbols) {
println(obj.asInstanceOf[MibSymbol].getName())
}
import scala.collection.JavaConversions._ does all the magic for you. You only need to ensure that the types are correct.

Categories