PageRenderTime 69ms CodeModel.GetById 43ms RepoModel.GetById 0ms app.codeStats 0ms

/scripts/_Ulc.groovy

http://github.com/canoo/grails-ulc
Groovy | 288 lines | 221 code | 37 blank | 30 comment | 38 complexity | c5b5dbb411e662c2c527ed1036484cb9 MD5 | raw file
  1. /*
  2. * Copyright 2009-2010 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /**
  17. * @author ulcteam
  18. */
  19. import java.text.DateFormat
  20. import java.text.SimpleDateFormat
  21. import groovy.swing.SwingBuilder
  22. import java.util.concurrent.CountDownLatch
  23. import javax.swing.JFrame
  24. import grails.util.GrailsNameUtils
  25. import org.springframework.core.io.support.PathMatchingResourcePatternResolver
  26. dateFormat = new SimpleDateFormat('yyyy-MM-dd')
  27. parseLicenseText = { text ->
  28. def moduleType = ''
  29. def productVersion = ''
  30. def licenseName = ''
  31. def license = []
  32. def licenses = [:]
  33. text.eachLine { line ->
  34. if(line == '--- START MODULE ---') {
  35. license = []
  36. licenseName = ''
  37. moduleType = ''
  38. productVersion = ''
  39. }
  40. license << line
  41. if(line =~ /module-type=/) {
  42. moduleType = line.substring('module-type='.length())
  43. }
  44. if(line =~ /product-version=/) {
  45. productVersion = line.substring('product-version='.length())
  46. }
  47. if(moduleType && productVersion) {
  48. productVersion = productVersion.collect([]){c -> c =~/[0-9]/ ? c : ''}.join()
  49. if(productVersion.length() == 2) productVersion += '0'
  50. productVersion = productVersion.padLeft(4, '0')
  51. licenseName = moduleType +'-'+productVersion
  52. }
  53. if(line == '--- END MODULE ---' && licenseName) {
  54. licenses[licenseName] = license.join('\n')
  55. }
  56. }
  57. licenses
  58. }
  59. checkLicense = {
  60. downloadLicenseIfNeeded()
  61. checkLicenseExpirationDate()
  62. }
  63. downloadLicenseIfNeeded = {
  64. if(checkExistingLicense()) return
  65. if(checkLicenseToken()) return
  66. checkEvalLicense()
  67. }
  68. checkLicenseExpirationDate = {
  69. File developerLicense = ulcLicenseDir.listFiles().find{it.name =~ /^DEVELOPER-\d{4}\.lic$/}
  70. Properties license = readLicenseText(developerLicense.text)
  71. Date dateShipped = dateFormat.parse(license['date-shipped'])
  72. int period = license.get('evaluation-period')?.toInteger() ?: 0i
  73. Date expirationDate = dateShipped + period
  74. Date today = new Date()
  75. Date warningDate = expirationDate - 6
  76. expirationDate.clearTime()
  77. warningDate.clearTime()
  78. today.clearTime()
  79. // license has expired (check for evaluation only!)
  80. if(period != 0) {
  81. if(today.after(expirationDate)) {
  82. showLicenseExpiredWindow(expirationDate)
  83. } else if(today.after(warningDate)) {
  84. File ulcWarningCheck = new File(System.getProperty('user.home'), '.ulc-check')
  85. if(ulcWarningCheck.exists()) {
  86. Date when = dateFormat.parse(ulcWarningCheck.text.trim())
  87. when.clearTime()
  88. if(when == today) return
  89. }
  90. ulcWarningCheck.text = dateFormat.format(today)
  91. int days = today - warningDate
  92. showLicenseWarningWindow(days)
  93. } // OK!
  94. }
  95. }
  96. checkExistingLicense = {
  97. File userHome = new File(System.getProperty('user.home'))
  98. List ulcDirs = []
  99. userHome.eachDir{ if(it.name =~ /^.ulc-\d.\d[\.\d]?/) ulcDirs << it}
  100. // has license?
  101. if(!ulcDirs) return false
  102. // sort by version
  103. ulcDirs.sort { (it.name =~ /(\d\.\d(\.\d)?)/)[0][1] }
  104. // pick latest one
  105. def candidateUlcLicenseDir = ulcDirs[-1]
  106. // check if version >= 7.0
  107. String version = (candidateUlcLicenseDir.name =~ /(\d.\d(\.\d)?)/)[0][1]
  108. if(version < '7.0') return
  109. ulcLicenseDir = candidateUlcLicenseDir
  110. true
  111. }
  112. checkLicenseToken = {
  113. ant.input(addProperty: "access.token", message: "Do you have a license access token? If so please enter it or type [ENTER] to proceed:")
  114. def token = ant.antProject.properties."access.token"
  115. if(!token?.trim()) return false
  116. def text = null
  117. try {
  118. text = "https://ulc.canoo.com/rest/license/promoCore/$token".toURL().text
  119. println 'Access token verified.'
  120. } catch(x) {
  121. // if(x.message =~ /.*HTTP response code: 500.*/)
  122. // any error means no valid token or already used
  123. println 'Access token is invalid or it has expired.'
  124. return false
  125. }
  126. downloadLicense(text)
  127. true
  128. }
  129. checkEvalLicense = {
  130. String text = 'https://ulc.canoo.com/rest/license/eval/ULC%20Core'.toURL().text
  131. println 'Downloading evaluation license...'
  132. downloadLicense(text)
  133. }
  134. downloadLicense = { text ->
  135. Map<String, String> licenses = parseLicenseText(text)
  136. String version = ''
  137. // search for core license
  138. for(key in licenses.keySet()) {
  139. if(key =~ /DEPLOYMENT-(\d+)/) {
  140. Properties p = readLicenseText(licenses[key])
  141. version = (String) p.get('product-version')
  142. break
  143. }
  144. }
  145. ulcLicenseDir = new File(System.getProperty('user.home'), ".ulc-${version}")
  146. ulcLicenseDir.mkdirs()
  147. licenses.each { k, v ->
  148. File licenseFile = new File(ulcLicenseDir.absolutePath, "${k}.lic")
  149. licenseFile.text = v
  150. }
  151. }
  152. readLicenseText = { String text ->
  153. Properties p = new Properties()
  154. p.load(new StringReader(text))
  155. p
  156. }
  157. showLicenseExpiredWindow = { expirationDate ->
  158. CountDownLatch latch = new CountDownLatch(1i)
  159. def swing = new SwingBuilder()
  160. swing.edt {
  161. frame(title: 'Canoo RIA Suite License EXPIRED!', pack: true, visible: true, resizable: false,
  162. defaultCloseOperation: JFrame.DISPOSE_ON_CLOSE, id: 'frame',
  163. locationRelativeTo: null, windowClosed: { latch.countDown() }) {
  164. borderLayout()
  165. scrollPane(constraints: CENTER, preferredSize: [400, 250]) {
  166. textArea(editable: false, wrapStyleWord: true, lineWrap: true, text: "Your license has expired on ${dateFormat.format(expirationDate)}.\n\nWe urge you to get in touch with a Canoo sales representative to find out more about the different licensing options available for Canoo RIA Suite. Or you can click the 'Buy now' button.\n\n You can contact Canoo by sending a message to sales@canoo.com")
  167. }
  168. panel(constraints: SOUTH) {
  169. gridLayout(cols: 2, rows: 1)
  170. button('Buy now', actionPerformed: { openURL('http://www.canoo.com/ulc/') })
  171. button('Close', actionPerformed: {frame.dispose()})
  172. }
  173. }
  174. }
  175. latch.await()
  176. }
  177. showLicenseWarningWindow = { int days ->
  178. CountDownLatch latch = new CountDownLatch(1i)
  179. def swing = new SwingBuilder()
  180. swing.edt {
  181. frame(title: 'Canoo RIA Suite License Check', pack: true, visible: true, resizable: false,
  182. defaultCloseOperation: JFrame.DISPOSE_ON_CLOSE, id: 'frame',
  183. locationRelativeTo: null, windowClosed: { latch.countDown() }) {
  184. borderLayout()
  185. scrollPane(constraints: CENTER, preferredSize: [400, 250]) {
  186. textArea(editable: false, wrapStyleWord: true, lineWrap: true, text: "Your license will expire in ${days} day${days == 1? '': 's'}.\n\nWe encourage you to get in touch with a Canoo sales representative to find out more about the different licensing options available for Canoo RIA Suite. Or you can click the 'Buy now' button.\n\n You can contact Canoo by sending a message to sales@canoo.com")
  187. }
  188. panel(constraints: SOUTH) {
  189. gridLayout(cols: 2, rows: 1)
  190. button('Buy now', actionPerformed: { openURL('http://www.canoo.com/ulc/') })
  191. button('Close', actionPerformed: {frame.dispose()})
  192. }
  193. }
  194. }
  195. latch.await()
  196. }
  197. generateApplicationsFile = { destination ->
  198. Properties applications = new Properties()
  199. def pathResolver = new PathMatchingResourcePatternResolver(getClass().classLoader)
  200. pathResolver.getResources("file://${basedir}/src/**/*UlcConfiguration.xml".toString()).each { cfg ->
  201. String className = new XmlSlurper().parse(cfg.file).applicationClassName.toString() - 'Application'
  202. String alias = GrailsNameUtils.getShortName(className.toString())
  203. applications[alias.toLowerCase()] = className
  204. }
  205. def destinationDir = new File(destination)
  206. destinationDir.mkdirs()
  207. applications.store(new FileOutputStream("${destination}/ulc-applications.properties".toString()), 'ULC Applications')
  208. }
  209. forEachUlcApplication = { callback ->
  210. Map<String,String> applications = [:]
  211. def pathResolver = new PathMatchingResourcePatternResolver(getClass().classLoader)
  212. pathResolver.getResources("file://${basedir}/src/**/*UlcConfiguration.xml".toString()).each { cfg ->
  213. String className = new XmlSlurper().parse(cfg.file).applicationClassName.toString() - 'Application'
  214. String alias = GrailsNameUtils.getShortName(className.toString())
  215. applications[alias.toLowerCase()] = className
  216. }
  217. applications.each { alias, className -> callback(alias, className) }
  218. }
  219. /*
  220. * The following code was adapted from
  221. * http://www.centerkey.com/java/browser/
  222. */
  223. private openURL(String url) {
  224. String[] browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"] as String[]
  225. String errMsg = "Error attempting to launch web browser"
  226. try { //attempt to use Desktop library from JDK 1.6+
  227. Class<?> d = Class.forName("java.awt.Desktop")
  228. d.getDesktop().browse()
  229. } catch (Exception ignore) { //library not available or failed
  230. String osName = System.getProperty("os.name")
  231. try {
  232. if (osName.startsWith("Mac OS")) {
  233. Class.forName("com.apple.eio.FileManager").openURL(url)
  234. } else if (osName.startsWith("Windows")) {
  235. Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url)
  236. } else { //assume Unix or Linux
  237. String browser = null
  238. for (String b : browsers) {
  239. if (browser == null && Runtime.getRuntime().exec(["which", b] as String[]).getInputStream().read() != -1) {
  240. Runtime.getRuntime().exec([browser = b, url] as String[])
  241. }
  242. }
  243. if (browser == null) {
  244. throw new Exception(Arrays.toString(browsers))
  245. }
  246. }
  247. } catch (Exception e) {
  248. javax.swing.JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString())
  249. }
  250. }
  251. }