I created the following script in the script folder using netbeans. I can't save the domain class. Also, if I deploy the entire project as a war file, can I run the script using Windows scheduler?
Script
def json = ""
def txt = new URL("http://free.worldweatheronline.com/feed/weather.ashx?q=Singapore,Singapore&format=xml&num_of_days=1&key=b674fb7e94131612112609").text
def records = new XmlSlurper().parseText(txt)
def weather = records.weather
def dates = weather.date
def min = weather.tempMinC
def max = weather.tempMaxC
def img = weather.weatherIconUrl
def desc = weather.weatherDesc
def descLink = desc.toString().replaceAll(" ","%20")
println max
Weathers w = new Weathers()
w.cityName="singapore"
w.day = dates
w.description =desc
w.max = max
w.img = img
w.min = min
w.url = "jk"
Domain class
package org.mPest
class Weathers {
int id
String day
String min
String max
String img
String description
String cityName
String url
static constraints = {
id(blank:false, unique:true)
cityName(blank:false)
url(blank:false)
}
}
You can't use domain classes directly.
See this FAQ to read how to use domain classes from src/groovy:
import org.codehaus.groovy.grails.commons.ApplicationHolder
//…
def book = ApplicationHolder.application.getClassForName("library.Book").findByTitle("Groovy in Action")
I don't know if it possible to run the war packed script from windows but you could use the grails Quartz plugin to schedule your task...
Take a look at the grails run-script command. You should be able to use that to execute a script using something like windows scheduler or cron, but you'd have to have the full source code (not the war file) available for the script to execute with.
In Grails 2.x you should use Holders instead of ApplicationHolder. For example:
import grails.util.Holders
def validKeys = Holders.grailsApplication.getClassForName("com.vcd.Metadata").findAll { it.metadataKey }*.metadataKey
Related
I have a string in groovy that I want to convert into a map. When I run the code on my local computer through a groovy script for testing, I have no issues and a lazy map is returned. I can then convert that to a regular map and life goes on. When I try the same code through my Jenkins DSL pipeline, I run into the exception
groovy.json.internal.Exceptions$JsonInternalException: Not that kind of map
Here is the code chunk in question:
import groovy.json.*
String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"
def stringToMapConverter(String stringToBeConverted){
formattedString = stringToBeConverted.replace("=", ":")
def jsonSlurper = new JsonSlurper().setType(JsonParserType.LAX)
def mapOfString = jsonSlurper.parseText(formattedString)
return mapOfString
}
def returnedValue = stringToMapConverter(string1)
println(returnedValue)
returned value:
[value2:[red gold:false], value1:[red pink:true, gold silver:true, blue green:true], value3:[silver brown:false]]
I know that Jenkins and Groovy differ in various ways, but from searches online others suggest that I should be able to use the LAX JsonSlurper library within my groovy pipeline. I am trying to avoid hand rolling my own string to map converter and would prefer to use a library if it's out there. What could be the difference here that would cause this behavior?
Try to use
import groovy.json.*
//#NonCPS
def parseJson(jsonString) {
// Would like to use readJSON step, but it requires a context, even for parsing just text.
def lazyMap = new JsonSlurper().setType(JsonParserType.LAX).parseText(jsonString.replace("=", ":").normalize())
// JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
def m = [:]
m.putAll(lazyMap)
return m
}
String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"
def returnedValue = parseJson(string1)
println(returnedValue)
println(JsonOutput.toJson(returnedValue))
You can find information about normalize here.
After reviewing the docs, a number of questions here on SO, and trying a dozen or so different script configurations, I cannot figure out how to reference a shared Groovy library. I've added the library like so:
This appears to be working. I'm referencing the script like so:
You can see the error message therein:
Script1: 1: unable to resolve class Library , unable to find class
for annotation # line 1, column 1. #Library('sonarQubeAPI')_
The script code, not I think it matters, looks like this:
import groovy.json.JsonSlurper
class SonarQubeAPI{
static string getVersion(){
return "1.0";
}
static void getSonarStatus(projectKey){
def sonarQubeUserToken = "USERTOKEN";
def projectStatusUrl = "pathtosonarqube/api/qualitygates/project_status?projectKey=" + projectKey;
println("Retrieving project status for " + projectKey);
def json = getJson(sonarQubeUserToken, projectStatusUrl);
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(json);
println(object.projectStatus.status);
}
static string getJson(userToken, url){
def authString = "${userToken}:".getBytes().encodeBase64().toString();
def conn = url.toURL().openConnection();
conn.setRequestProperty( "Authorization", "Basic ${authString}" );
return conn.content.text;
}
}
I'm probably just a magic character off, but I can't seem to lock it down.
Shared libraries are a feature of Jenkins Pipelines, not of Jenkins (core) itself. You can use them only in Pipeline jobs (and child types like Multibranch Pipeline).
Grails 2.5.0
I'm defining an alternate context root via _Events.groovy using the eventConfigureTomcat closure. To do this, I've got code like so..
eventConfigureTomcat = { tomcat ->
def newContextRoot = "/"
def newContextPath = new File("/full/path/to/context/root")
// more code below that doesn't matter for this question...
}
For the newContextPath I want to pull that value from my Config.groovy (which is actually pulling it from an external config file). I've tried using grails.util.Holders but it doesn't seem to be wired up at this specific event yet. Is this possible?
You can set the value from your Config.groovy as an environment variable and then use it in _Events.groovy. If you still need to pull from an external config file, run a bash script inside of .bashrc/.bashprofile (wherever you define the environment variable).
eventConfigureTomcat = { tomcat ->
String altctxroot = System.getenv("ALT_CTX_ROOT")
def newContextRoot = "/"
def newContextPath = new File("$altctxroot")
}
I have a requirement to read csv file from command line as arguments or to save it in a specific folder and read it through script and update database tables. I am using spring security on my application as well. What would be a better approach to do this? I was thinking something like this-
class CsvFileUploadController{
static main(){
new CsvFileUploadController().uploadFile()
}
def uploadFile() {
def fileName = 'filecsv_products'
def csvfile = new File(ServletContextHolder.servletContext.getRealPath('fileupload/'+fileName)).text
println "csv file text = "+csvfile
}
}
I have a singleton class
#Singleton
class CustomerBundleSingleton {
def grailsApplication = Holders.getGrailsApplication()
String projName
private CustomerBundleSingleton() {
line 10: projName = // how to get sub-project name here ???
}
}
application.properties // my project is running
-----------------------
app.name = MyNewProject
application.properties // located in sub project
-----------------------
app.name = MySubProject
I tried grailsApplication.metadata['app.name'] in "line 10:" it returns "MyNewProject".Whereas I want a way to get the project name of the UserBundleSingleton located (MySubProjectName). Something like grailsApplication.current.metadata['app.name'] ???? .
So that it can give me back MySubProjectName instead of MyNewProject??
I have 3 suggestions depending on your requirements and your 'bundling'.
1) You don't have a bundle marker/descriptor
Assuming that you know the sub-project(Grails plugin) name, your life gets easier, instead of having to loop through all plugins...
You can probably use something among these lines.
// Plugin name is 'hibernate' in this example
import org.codehaus.groovy.grails.plugins.PluginManagerHolder
def hibernateVersion = PluginManagerHolder.pluginManager.getGrailsPlugin('hibernate').version
// Loop through all plugins
// PluginManagerHolder.pluginManager.getAllPlugins()
2) Using custom plugin properties to lookup plugins of interest
Other strategy, if you must lookup the bundle dynamically.
Create a custom marker property in each of your plugin descriptors
def specialProperty = "whatever"
Then inside your CustomerBundleSingleton
PluginManagerHolder.pluginManager.getAllPlugins().each {
if (it.properties.specialProperty) {
def subProjectName = it.name
def subProjectVersion = it.version
}
}
3) Custom bundle info resolution
You may also want to consider some metadata via META-INF/MANIFEST.MF or similar mechanism.
Hope it helps...