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
}
}
Related
So I have a file called "text1.txt" that has only one line -
version.build=846
I want to do something like this-
def svntag = ccsmp_v_ {version.build}
println $svntag
ccsmp_v_846
Is there any way to do this ?
You can read a file from the workspace using the methods from pipeline utility steps plugin.
For your case it would be best to use readProperties method, for example:
def properties = readProperties file: '<your properties file in the workspace>'
Then you can access the value with:
def svntag = "ccsmp_v_${properties['version.build']}"
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).
In my jenkins pipeline I am working with properties stored in file.
I can read properties from file and add new items to the map using this code, but I do not understand how to persist my changes.
node('hozuki-best-girl') {
def propertiesPath = "${env.hozuki_properties}"
def props = readProperties file: propertiesPath
props['versionCode'] = 100500
}
What should I do in order to persist my changes? There is no writeProperties method here https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#code-readproperties-code-read-properties-from-files-in-the-workspace-or-text
you can use yaml format instead of properties.
it also simple and human readable and in jenkins-pipeline there are read and write operations for yaml
or you can use this kind of code:
#NonCPS
def propsToString(Map map){
return new StringWriter().with{w-> (map as Properties).store(w, null); w; }.toString()
}
writeFile file: propertiesPath, text: propsToString(props)
The Phoenix AutoTest Plugin has a writeProperties step.
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
Well, it seems a simple task but I didn't manage to make it run.
I have a groovy script that runs fine under Windows Vista when calling from prompt:
> cd MY_GAILS_PROJECT_DIR
> groovy cp src/groovy scripts/myscript.groovy
Now, I want to execute this script (and passing to it some input arguments) through my my Maintenance Service Class (called from a controller) as below,
class MaintenanceService {
def executeMyScript() {
"groovy cp src/groovy scripts/myscript.groovy".execute()
}
}
It does not work at all! I don't even manage to have the execute() method recognizing any command (like "cd .".execute()) throwing exception:
Error 500: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
1- How can I execute a groovy script from my grails application?
2- What are the best practices here? For instance, should I use the QuartzPlugin and then the triggerNow method for executing a script? should I use a Gant Task? If yes, how to do it?
Thank you.
If you don't mind your script running asynchronously (in a separate process to the service method), the following should work assuming groovy is on your PATH variable:
def cmd = ['groovy.bat', 'cp', 'src/groovy scripts/myscript.groovy']
cmd.execute()
If you want to view the output of the process in the application console, you should try something like this instead
// Helper class for redirecting output of process
class StreamPrinter extends Thread {
InputStream inputStream
StreamPrinter(InputStream is) {
this.inputStream = is
}
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).withReader {reader ->
String line
while ((line = reader.readLine()) != null) {
println(line)
}
}
}
}
// Execute the script
def cmd = ['groovy', 'cp', 'src/groovy scripts/myscript.groovy']
Process executingProcess = cmd.execute()
// Read process output and print on console
def errorStreamPrinter = new StreamPrinter(executingProcess.err)
def outputStreamPrinter = new StreamPrinter(executingProcess.in)
[errorStreamPrinter, outputStreamPrinter]*.start()
Update:
In response to your comment below, try the following (which assumes you're on Windows):
1: Create the file C:\tmp\foo.groovy. The content of this file should be simply:
println 'it works!'
2: In the groovy console, run the following:
cmd = ['groovy.bat', 'C:\\tmp\\foo.groovy']
cmd.execute().text
3: You should see the result of the script (the text 'it works!') shown in the Groovy console
If you can't get this simple example working, there's something wrong with your environment, e.g. 'groovy.bat' is not on your PATH. If you can get this example working, then you should be able to work forward from it to achieve your objective.
As of grails 1.3.6 the run-script command is built in to let you run
grails run-script myScript.groovy
For earlier versions of grails, check out my updated blog post from what Carlos posted above.
Easiest Way:
Generate an Groovy Class and place at in your /src/groovy Folder of your Grails Project.
Import that Class in your Domain Class and use the Functions you defined.
My 2 Cents...
This might help as well:
http://naleid.com/blog/2008/03/31/using-gant-to-execute-a-groovy-script-within-the-grails-context-updated/
Carlos
Another decision you can use GroovyScriptEngine for example:
file MyScript.groovy:
static String showMessage() {
println("Message from showMessage")
}
file BootStrap.groovy:
class BootStrap {
def init = { servletContext ->
new GroovyScriptEngine("scripts")
.loadScriptByName("MyScript.groovy")
.showMessage()
}
def destroy = {
}
}