Groovy Goodness Notebook Sample

Download Groovy Goodness Notebook Sample

Post on 23-Dec-2015

13 views

Category:

Documents

4 download

Embed Size (px)

DESCRIPTION

Test

TRANSCRIPT

  • Groovy Goodness Notebook

    Hubert A. Klein Ikkink (mrhaki)

    This book is for sale at http://leanpub.com/groovy-goodness-notebook

    This version was published on 2013-12-12

    This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process.Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and manyiterations to get reader feedback, pivot until you have the right book and build traction once you do.

    2012 - 2013 Hubert A. Klein Ikkink (mrhaki)

    http://leanpub.com/groovy-goodness-notebookhttp://leanpub.comhttp://leanpub.com/manifesto

  • Tweet This Book!

    Please help Hubert A. Klein Ikkink (mrhaki) by spreading the word about this book on Twitter!

    The suggested tweet for this book is:

    I just bought Groovy Goodness Notebook with Groovy Goodness blog posts bundled into one book.#groovy @mrhaki

    The suggested hashtag for this book is #groovygoodnessnotebook.

    Find out what other people are saying about the book by clicking on this link to search for this hashtagon Twitter:

    https://twitter.com/search?q=#groovygoodnessnotebook

    http://twitter.comhttps://twitter.com/search?q=%23groovygoodnessnotebookhttps://twitter.com/search?q=%23groovygoodnessnotebook

  • This book is dedicated to my lovely family. I love you.

  • Contents

    Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Working with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Setting Date and Calendar Values with Subscript Operators . . . . . . . . . . . . . . . . . . . . 2Convert Date to java.sql.Timestamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Convert Date to Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Format Dates with TimeZone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Parse Date.toString() Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Use the set Method to Define a Date or Calendar Value . . . . . . . . . . . . . . . . . . . . . . 5Create New Date from Old Date with Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Create New Date or Calendar from Existing and Set Property Value . . . . . . . . . . . . . . . 6Clear Time Portion of a Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Date and Time Durations and the TimeCategory . . . . . . . . . . . . . . . . . . . . . . . . . . 7Loop Through Date and Calendar Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Check if Maps are Equal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Sorting a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Turn a List into a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Complex Keys in Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Use inject Method on a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Intersect Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Subtracting Map Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Process Map Entries in Reverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Getting a Submap from a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Grouping Map Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Get Value from Map or a Default Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Map with Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Determine Min and Max Entries in a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

  • Dates

    Working with Dates

    Thanks to Groovys extensions to the JDK Date classes we can work with dates more easily. For examplewe can now add and subtract days with the plus() and minus() methods. And because this methods aremapped to the operators + and - we can write dense code.

    Also the next() and previous() methods are implemented so we can use the ++ and -- operators to getto a next or previous day. We can even use the subscript operator ([]) to get date fields, because of thegetAt() method Groovy adds to the Date class.

    The Date class also contains parse() and format() methods to convert string to a date and to format adate into a string.

    // Date.parse() to convert String to Date.

    date = new Date().parse('yyyy/MM/dd', '1973/07/09')

    // We can use [] or getAt() to get date fields.

    assert 1973 == date[Calendar.YEAR]

    assert 6 == date[Calendar.MONTH]

    assert 9 == date.getAt(Calendar.DATE)

    dateNext = date.clone()

    datePrevious = date.clone()

    // We can use the + and - operators to add or

    // subtract days.

    nextDay = date + 1 // Or date.plus(1)

    previousDay = date - 1 // Or date.minus(1)

    // ++ operator to move one day ahead.

    dateNext++ // Or dateNext.next()

    assert dateNext == nextDay

    // -- operator to move one day back.

    datePrevious-- // Or datePrevious.previous()

    assert datePrevious == previousDay

    otherDate = new Date().parse('yyyy/MM/dd', '1973/07/21')

    // Dates can be used in ranges.

    assert 12 == (otherDate..

  • Dates 2

    // Date.format() uses java.text.SimpleDateFormat.

    assert '9 July, 1973' == date.format("d MMMM, yyyy")

    assert '7/9/73' == date.getDateString()

    Original blog post written on August 31, 2009

    Setting Date and Calendar Values with Subscript Operators

    In Groovy 1.7.3 we have some new ways to set the value of Date or Calendar objects. We can for exampleuse the subscript operators (getAt() and putAt() methods) to define values for fields or get the valuefrom a field. The fields are the Calendar constants like Calendar.YEAR, Calendar.DATE.

    import static java.util.Calendar.*

    def date = new Date()

    // Set value with subscript operator

    date[YEAR] = 2010

    date[MONTH] = JUNE

    date[DATE] = 14

    assert 110 == date.year

    assert 5 == date.month

    assert 14 == date.date

    // Get value with subscript operator

    assert 2010 == date[YEAR]

    assert JUNE == date[MONTH]

    assert 14 == date[DATE]

    def cal = Calendar.instance

    // Set value with subscript operator

    cal[YEAR] = 2000

    cal[MONTH] = DECEMBER

    cal[DATE] = 25

    assert '2000-12-25' == cal.format('yyyy-MM-dd')

    assert 2000 == cal[YEAR] // Get value with subscript operator

    Original blog post written on June 14, 2010.

    Convert Date to java.sql.Timestamp

    Groovy adds many methods to standard Java classes we can use in our code. To convert a simple Dateobject to a java.sql.Timestamp we can simply use the toTimestamp() method on a Date object.

    http://mrhaki.blogspot.com/2009/08/groovy-goodness-working-with-dates.htmlhttp://mrhaki.blogspot.com/2010/06/groovy-goodness-setting-date-and.html

  • Dates 3

    import static java.util.Calendar.*

    // Create date object with specific year, month and day.

    def date = new Date()

    date.clearTime()

    date.set year: 2010, month: AUGUST, date: 10

    // Convert to java.sql.Timestamp.

    def sqlTimestamp = date.toTimestamp()

    assert 'java.sql.Timestamp' == sqlTimestamp.class.name

    assert '2010-08-10 00:00:00.0' == sqlTimestamp.toString()

    Original blog post written on August 30, 2010.

    Convert Date to Calendar

    In Groovy version 1.7.6 we can convert a Date to a Calendar with the toCalendar() method. ThetoCalendar() method is added to the Date class by Groovy.

    import static java.util.Calendar.*

    def date = new Date()

    date.set year: 2010, month: 11, date: 16

    def calendar = date.toCalendar()

    assert calendar[YEAR] == 2010

    assert calendar[MONTH] == Calendar.DECEMBER

    assert calendar[DATE] == 16

    assert calendar.format('dd-MM-yyyy') == '16-12-2010'

    assert calendar in Calendar

    Original blog post written on December 16, 2010.

    Format Dates with TimeZone

    Since Groovy 1.8.3 we can use an extra TimeZone parameter with the format() method of the Date class.This can be used to print a date/time for a particular timezone.

    http://mrhaki.blogspot.com/2010/08/groovy-goodness-convert-date-to.htmlhttp://mrhaki.blogspot.com/2010/12/groovy-goodness-convert-date-to.html

  • Dates 4

    import static java.util.Calendar.*

    def timeZone = TimeZone.getTimeZone('Europe/Amsterdam')

    def otherTimeZone = TimeZone.getTimeZone('Australia/Canberra')

    def cal = Calendar.instance

    cal.set(year: 2011, month: OCTOBER, date: 20, hourOfDay: 12, minute: 30)

    def date = cal.time

    def dateFormat = 'yyyy/MM/dd HH:mm'

    assert date.format(dateFormat, timeZone) == '2011/10/20 12:30'

    assert date.format(dateFormat, otherTimeZone) == '2011/10/20 21:30'

    Original blog post written on October 20, 2011.

    Parse Date.toString() Value

    With Groovy 1.8.4 we can parse the output of the Date.toString() method back to a Date with theparseToStringDate() method. For example we get the String value of a Date from an external sourceand want to parse it to a Date object. The format of the String must have the pattern EEE MMM ddHH:mm:ss zzz yyyy with the US Locale. This is used by the toString() method of the Date class.

    import static java.util.Calendar.*

    // Create date 10 November 2011.

    def cal = Calendar.getInstance(TimeZone.getTimeZone('Europe/Amsterdam'))

    def date = cal.time

    date.clearTime()

    date[YEAR] = 2011

    date[MONTH] = NOVEMBER

    date[DATE] = 10

    // Get toString() value.

    def dateToString = date.toString()

    assert dateToString == 'Thu Nov 10 00:00:00 CET 2011'

    // Replace Nov for Dec in string and 10 for 24.

    dateString = dateToString.replace('Nov', 'Dec').replace('10', '24')

    // Use parseToStringDate to get new Date.

    def newDate = Date.parseToStringDate(dateString)

    assert newDate[MONTH] == DECEMBER

    assert newDate[DATE] == 24

    assert newDate[YEAR] == 2011

    Original blog post written on November 10, 2011.

    http://mrhaki.blogspot.com/2011/10/groovy-goodness-format-dates-with.htmlhttp://mrhaki.blogspot.com/2011/11/groovy-goodness-parse-datetostring.html

  • Dates 5

    Use the set Method to Define a Date or Calendar Value

    In a previous post we learned about the new subscript operator support in Groovy 1.7.3 for setting Dateor Calendar values. But we have other new ways in Groovy 1.7.3: we can use a set() method to set thevalues. The method accepts a Map with the following keys: year, month, date, hourOfDay, minute andsecond. The keys are used to set the according values of the Date or Calendar object.

    import static java.util.Calendar.*

    def cal = Calendar.instance

    cal.set(year: 2010, month: JULY, date: 9)

    assert 'Birthday @ 2010-7-9' == 'Birthday @ ' + cal.format('yyyy-M-d')

    assert FRIDAY == cal[DAY_OF_WEEK]

    def date = new Date()

    date.set(hourOfDay: 12, minute: 0, second: 0, year: 2010, month: JUNE, date: 1)

    assert '12:00:00' == date.format('HH:mm:ss')

    assert 2010 == date[YEAR]

    assert JUNE == date[MONTH]

    assert 1 == date.getAt(DATE)

    Original blog post written on June 14, 2010.

    Create New Date from Old Date with Updates

    Groovy 1.7.3 adds the updated() method to the Date and Calendar classes. We pass a Map as parameterto this method to define which fields are updated. The fields that are not mentioned are unchanged. Theresult is a new Date or Calendar object, our original object stays the same.

    import static java.util.Calendar.*

    def cal = Calendar.instance

    cal[MONTH] = DECEMBER

    def calNextMonth = cal.updated(month: cal[MONTH] + 1, year: 2012)

    assert JANUARY == calNextMonth[MONTH]

    assert 2013 == calNextMonth[YEAR]

    def date = new Date()

    date.set(year: 2011, month: MAY, date: 5)

    def dateTenYearsAgo = date.updated(year: date[YEAR] - 10)

    assert '2011-5-5' == date.format('yyyy-M-d')

    assert '2001-5-5' == dateTenYearsAgo.format('yyyy-M-d')

    Original blog post written on June 14, 2010.

    http://mrhaki.blogspot.com/2010/06/groovy-goodness-use-set-method-to.htmlhttp://mrhaki.blogspot.com/2010/06/groovy-goodness-create-new-date-from.html

  • Dates 6

    Create New Date or Calendar from Existing and Set Property Value

    Since Groovy 2.2 we can create a new Date or Calendar object from an existing Date and Calendarobject and directly change property values. We must use the copyWith() method and we pass a mapwith property names and values as an argument. The newly created object will have the old values forproperties from the original object and the properties set in the map are overridden.

    The following code shows the new copyWith() method:

    import static java.util.Calendar.NOVEMBER

    // Create original date.

    def date = new Date().clearTime()

    date.set(year: 2013, month: NOVEMBER, date: 18)

    // Use copyWith to get new Date and

    // immmediatelly set year to 2014.

    def yearLater = date.copyWith(year: 2014)

    assert yearLater.format('dd-MM-yyyy') == '18-11-2014'

    // Also works for Calendar.

    def cal = Calendar.instance

    cal.set(year: 2013, month: NOVEMBER, date: 10)

    // Create new Calendar with new date value.

    def newCalendar = cal.copyWith(date: 18)

    assert newCalendar.format('dd-MM-yyyy') == '18-11-2013'

    Code written with Groovy 2.2.

    Original blog post written on November 18, 2013.

    Clear Time Portion of a Date

    Working with dates in Groovy is easy. We get a lot of extra functionality compared to the standard JavaDate class. One of the extra methods added to the Date class since Groovy 1.6.8 is clearTime(). WithclearTime() we reset the time portion of a date to 12 oclock midnight. This makes it easier to comparedates if we only are interested in the date, month, year parts.

    http://mrhaki.blogspot.com/2013/11/groovy-goodness-create-new-date-or.html

  • Dates 7

    // Create new date.

    def d = new Date(year: 2010, month: Calendar.JULY, date: 1,

    hours: 7, minutes: 12, seconds: 0)

    assert '7/1/10 7:12:00 AM' == d.dateTimeString

    // Reset time portion of the date.

    d.clearTime()

    assert '7/1/10 12:00:00 AM' == d.dateTimeString

    Original blog post written on July 1, 2010.

    Date and Time Durations and the TimeCategory

    Groovy has some elegant ways to work with date and time values. One of them is the support of durations.We can define a duration to denote a certain time amount, like 7 days, 2 hours and 50 minutes. We canuse these durations to add or subtract them from date and time objects.

    The TimeCategory provides an even Groovier way to work with durations. We can use constructs like7.days + 12.minutes to create a duration. When we read this code it is just like reading English text.Here is some sample code:

    import groovy.time.*

    // Define period of 2 years, 3 months, 15 days, 0 hours,

    // 23 minutes, 2 seconds and 0 milliseconds.

    def period = new DatumDependentDuration(2, 3, 15, 0, 23, 2, 0)

    assert '2 years, 3 months, 15 days, 23 minutes, 2.000 seconds' ==

    period.toString()

    def year2000 = new Date(100, 0, 0) // Jan 1, 2000

    assert '14 Apr 2002 22:23:02 GMT' == (period + year2000).toGMTString()

    // Define time period of 5 hours, 54 minutes and 30 milliseconds.

    def time = new TimeDuration(5, 54, 0, 30)

    assert '5 hours, 54 minutes, 0.030 seconds' == time.toString()

    use (TimeCategory) {

    assert peri...

Recommended

View more >