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
Related
In build.gradle I Know you can do this
ext {
dbUsername = System.getenv("DB_USER").toString()
dbPassword = System.getenv("DB_PASS").toString()
libsUserNameNew = System.getenv("LIBS_USERNAME_NEW").toString()
libsPassNew = System.getenv("LIBS_PASS_NEW").toString()
gitShortTag = System.getenv("SHORT_SHA").toString()
repoName = System.getenv("REPO_NAME").toString()
group = "app.test.customerservicepoc"
mainClass = "app.test.customerservicepoc.CustomerServicePOC"
}
How can I achieve the same using build.gradle.kts
This is what I have tried
var dbUsername =""
var dbPassword =""
var LibsUserNameNew = ""
var LibsPassNew = ""
var gitShortTag = ""
var repoName = ""
and then
ext {
dbUsername = System.getenv("DB_USER").toString()
dbPassword = System.getenv("DB_PASS").toString()
kyoskLibsUserNameNew = System.getenv("LIBS_USERNAME_NEW").toString()
LibsPassNew = System.getenv("LIBS_PASS_NEW").toString()
gitShortTag = System.getenv("SHORT_SHA").toString()
repoName = System.getenv("REPO_NAME").toString()
group = "app.test.mms"
}
during build I end up getting errors
What went wrong: 945 Cannot invoke "String.toString()" because the return value of
"org.gradle.internal.classpath.Instrumented.getenv(String, String)" is
null
I am migrating the project to kotlin gradle, how can I define the variables in kotlin gradle?
Well, the issue is shown in the other question, System.getenv is a static java method that doesn't guarantee the nullability of the returned String. In Kotlin, this is a compilation error. So what the compiler is telling you is "I cannot guarantee that calling toString() on the returned string won't crash with a NullPointerException because the JVM method getenv doesn't guarantee it". I'd argue that you don't need the toString() call at all.
lateinit var db: String
// or
var db: String? = null //this can now be null
//then
ext {
db = System.getenv("YOUR_DB") ?: "" //UPDATE: you also need this since getenv can return null, or you need to make the variable `String?`
//or
db = System.getenv("YOUR_DB") ?: "" // since it can be null, set some fallback, like empty or null
}
This should work no problem.
UPDATE
I've created a new empty android project with compose (which uses build.gradle.kt instead of groovy), and added this:
lateinit var something1: String
var something2: String? = null
ext {
something1 = System.getenv("something") ?: ""
something2 = System.getenv("something2") ?: ""
}
It compiled no problem. (And I'd assume it would work if the environment variables were set).
BUILD SUCCESSFUL in 25s
Update 2 a real test
I've actually done this
lateinit var something1: String
var something2: String? = null
ext {
something1 = System.getenv("SHELL") ?: ""
something2 = System.getenv("SHELL") ?: ""
}
tasks.register("printSomething") {
println("Something 1 is $something1")
println("Something 2 is $something2")
}
Then I ran ./gradle printSomething
And here's the result:
I tried to convert a java file to kotlin file but i'm getting this error : An annotation argument must be a compile-time constant
#StringDef(
BillingEnum.ALL,
BillingEnum.PAID,
BillingEnum.PENDING,
BillingEnum.OVERDUE,
BillingEnum.OPEN,
BillingEnum.DELETED
)
annotation class BillingEnum {
companion object {
var ALL = ""
var PAID = "paid"
var PENDING = "pending"
var OVERDUE = "overdue"
var OPEN = "open"
var DELETED = "deleted"
}
}
Before it looked like this:
#StringDef({
BillingEnum.ALL,
BillingEnum.PAID,
BillingEnum.PENDING,
BillingEnum.OVERDUE,
BillingEnum.OPEN,
BillingEnum.DELETED
})
public #interface BillingEnum {
String ALL = "";
String PAID = "paid";
String PENDING = "pending";
String OVERDUE = "overdue";
String OPEN = "open";
String DELETED = "deleted";
}
You must write
annotation class BillingEnum {
companion object {
const val ALL = ""
const val PAID = "paid"
const val PENDING = "pending"
const val OVERDUE = "overdue"
const val OPEN = "open"
const val DELETED = "deleted"
}
}
I am trying to get references/paths where some AEM tags are used.
I tried with this:
import org.apache.sling.api.resource.Resource
import com.day.cq.tagging.Tag
import com.day.cq.tagging.TagManager
import org.apache.sling.api.resource.ResourceResolver
import java.lang.Thread.*;
import javax.jcr.Node;
def tagpath = "/etc/tags";
def delay = 10 ; //in Milliseconds.
def query = getAllTags(tagpath)
def result = query.execute()
def rows = result.rows
def unusedTags = 0
rows.each { row ->
Resource res = resourceResolver.getResource(row.path)
if(res!=null){
Tag tag = res.adaptTo(com.day.cq.tagging.Tag)
Node tempNode = res.adaptTo(javax.jcr.Node);
TagManager tm = resourceResolver.adaptTo(com.day.cq.tagging.TagManager);
FindResults fr = tm.findByTitle(tag.title)
RangeIterator rangeIterator = fr.resources; -> this throws Cast Exception
//how to get paths of results (content) from fr to see where is this tag used
Thread.currentThread().sleep((long)(delay));
}
}
def getAllTags(tagpath) {
def queryManager = session.workspace.queryManager
def statement = "/jcr:root"+tagpath+"//element(*, cq:Tag)"
def query = queryManager.createQuery(statement, "xpath")
}
Now I am interested in how to get results from fr variable. Should I somehow adapt it to the Resource class or how can I get path to the assets/pages this returns?
FindResults findByTitle(String) - Searches for all content that is tagged with a tag that contains the given title as tag title.
import org.apache.sling.api.resource.Resource
import com.day.cq.tagging.Tag
import com.day.cq.tagging.TagManager
import com.day.cq.tagging.TagManager.FindResults
import org.apache.sling.api.resource.ResourceResolver
import java.lang.Thread.*;
import javax.jcr.Node;
import javax.jcr.RangeIterator;
def tagpath = "/etc/tags";
def query = getAllTags(tagpath)
def result = query.execute()
def rows = result.rows
def counter = 1;
def tagTitles = ["tag1", "tag2", "tag3"]
rows.each { row ->
Resource res = resourceResolver.getResource(row.path)
if(res!=null){
Tag tag = res.adaptTo(com.day.cq.tagging.Tag)
Node tempNode = res.adaptTo(javax.jcr.Node);
TagManager tm = resourceResolver.adaptTo(com.day.cq.tagging.TagManager);
tagTitles.each { tagTitle ->
if(tag.title.equalsIgnoreCase(tagTitle)){
counter++;
try{
FindResults fr = tm.findByTitle(tag.title);
Iterator rangeIterator = fr.resources;
if(rangeIterator.size() != 0){
println("Tag: " + tagTitle);
println("-- References: ");
println();
fr = tm.findByTitle(tag.title);
rangeIterator = fr.resources;
rangeIterator.each { resource ->
println(resource.path);
}
}
else{
println("REFERENCES NOT FOUND FOR: " + tagTitle);
}
} catch(MissingMethodException ex){
println("Title not found in tag list: " + tagTitle);
println(ex);
}
}
}
}
}
println("List lenght: " + tagTitles.size());
println("Number of tags with given title found: " + counter);
def getAllTags(tagpath) {
def queryManager = session.workspace.queryManager
def statement = "/jcr:root"+tagpath+"//element(*, cq:Tag)"
def query = queryManager.createQuery(statement, "xpath")
}
This is the solution. Since Groovy doesn't work with RandeIterator, I started using its parent class Iterator.
------ EDIT ------
I do not consider this as full answer since I don't know exact reason
for Groovy not to recognise this as a RangeIterator, so if someone can
answer that, please do.
Also, does this fr = tm.findByTitle(tag.title); get only references of tag with given title, or also references of his children?
There is a Cast Exception as the class returned is not an Iterator. It is a RangeIterator this class extends from iterator and provides some extra methods that can be useful.
It would be best if you use
RangeIterator rangeIterator = fr.resources
Then you can normally inherit hasNext next methods
In this case this is RangeIterator of Resource so you can obtain the path by calling the getPath method on each of the elements.
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)
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