I want to write a groovy script that will copy all projects from a given view to new view with new name (see code below) and also will change config - replace strings from old value to new value.
I can copy jobs to new view, but how to modify them?
Lets say I need to change every occurrence of 'MR222' to 'MR999' in job configuration.
/* Variables */
def oldViewName = 'orig Name'
def newViewName = 'new Name'
def search = 'MR222'
def replace = 'MR999'
/* If new view doesnt exist create new view */
if ( ! Hudson.instance.getView(newViewName) ) {
def newView = new ListView(newViewName)
Hudson.instance.addView(newView)
/* For each job in old view, copy it, replace workspace and add to new view */
Hudson.instance.getView(oldViewName).getItems().each { item ->
AbstractProject project = Hudson.instance.copy(item, item.getName().replace(search, replace))
if (project.getCustomWorkspace()) {
project.setCustomWorkspace(project.getCustomWorkspace().replace(search, replace))
}
newView.add(project)
}
}
else {
println "View \"${newViewName}\" already exist"
}
Related
I have a groovy script that will be common to many jobs - they will all contain an Active Choices Reactive Parameter. Rather than repeat the same script dozens of times I would like to place in a (library | ??) one time, and reference it in each job.
The script works beautifully for any job I paste it in. Just need to know if it is possible to plop it into one place and share across all jobs. Update it once, updates all jobs.
import jenkins.model.Jenkins;
ArrayList<String> res = new ArrayList<String>();
def requiredLabels = [new hudson.model.labels.LabelAtom ("Product")];
requiredLabels.add(new hudson.model.labels.LabelAtom(ClientName));
Jenkins.instance.computers.each {
if (it.assignedLabels.containsAll(requiredLabels)) {
res.add(it.displayName);
}
}
return res;
CAVEAT: This will work only if you have access to your Jenkins box. I haven't tried to do it by adding paths to the jenkins home
You can use this:
Make all your functions into a groovy file. For example will call it: activeChoiceParams.groovy
Convert that file into a jar by: jar cvf <jar filename> <groovy file>. For example: jar cvf activeChoiceParams.jar activeChoiceParams.groovy
Move your jar file to /packages/lib/ext
Restart Jenkins
In your active choices groovy script use (for example>:
import activeChoiceParams
return <function name>()
All functions must return a list or a map
The option we decide on was to have a common parameters function .groovy we store in git. There is a service hook that pushes the files out to a known network location on check-in.
In our Jenkins build step we then have the control dynamically load up the script and invoke the function passing in any parameters.
ArrayList<String> res = new ArrayList<String>();
try {
new GroovyShell().parse( new File( '\\\\server\\share\\folder\\parameterFunctions.groovy' ) ).with {
res = getEnvironments(ClientName);
}
} catch (Exception ex) {
res.add(ex.getMessage());
}
return res;
And our parameterFunctions.groovy will respond how we want:
public ArrayList<String> getEnvironments(String p_clientName) {
ArrayList<String> res = new ArrayList<String>();
if (!(p_clientName?.trim())){
res.add("Select a client");
return res;
}
def possibleEnvironments = yyz.getEnvironmentTypeEnum();
def requiredLabels = [new hudson.model.labels.LabelAtom ("PRODUCT")];
requiredLabels.add(new hudson.model.labels.LabelAtom(p_clientName.toUpperCase()));
Jenkins.instance.computers.each { node ->
if (node.assignedLabels.containsAll(requiredLabels)) {
// Yes. Let's get the environment name out of it.
node.assignedLabels.any { al ->
def e = yyz.getEnvironmentFromString(al.getName(), true);
if (e != null) {
res.add(al.getName());
return; // this is a continue
}
}
}
}
return res;
}
Nope, looks like it isn't possible (yet).
https://issues.jenkins-ci.org/browse/JENKINS-46394
I found interesting solution by using Job DSL plugin.
usually job definition for Active Choices is look like:
from https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.BuildParametersContext.activeChoiceParam
job('example') {
parameters {
activeChoiceParam('CHOICE-1') {
choiceType('SINGLE_SELECT')
groovyScript {
script(readFileFromWorkspace('className.groovy') + "\n" + readFileFromWorkspace('executionPart.groovy'))
}
}
}
}
in className.groovy you can define class as a common part
with executionPart.groovy you can create instance and make your particular part
How to Show Pictures of students which is located in folder and the path is in database But I'm unable to Do it I Searched a lot but found nothing useful.
Please help me guys
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = #"select StudentID,c.DocumentType as DocumentID,DocumentNumber,Name,NameDari,FatherName,FatherNameDari,MobileNumber,Photo,b.ClassName as ClassID,d.LocationName as LocationID,e.TeacherName as TeacherID,a.Term,a.Score from StudentsInfo a
join Class b
on a.ClassID=b.ClassID
join Document c
on c.DocumentID=a.DocumentID
join Location d
on d.LocationID=a.LocationID
join Teachers e
on e.TeacherID=a.TeacherID";
var data = db.Database.SqlQuery<StudentsInfo>(query);
ReportViewer1.SizeToReportContent = true;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("Certificates.rdlc");
ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource ds = new ReportDataSource("Certificates", data);
ReportViewer1.LocalReport.DataSources.Add(ds);
this.ReportViewer1.LocalReport.EnableExternalImages = true;
ReportViewer1.LocalReport.Refresh();
}
}
First, make sure that you're already done these steps in RDLC report designer:
1) Set "External" mode from image source property.
2) Create a report parameter to hold inserted path from code behind by using Add Parameter from context menu.
Then, you can try example below after enabling EnableExternalImages:
this.ReportViewer1.LocalReport.EnableExternalImages = true;
/* begin added part */
// get absolute path to Project folder
string path = new Uri(Server.MapPath("~/path/to/Project/folder")).AbsoluteUri; // adjust path to Project folder here
// set above path to report parameter
var parameter = new ReportParameter[1];
parameter[0] = new ReportParameter("ImagePath", path); // adjust parameter name here
ReportViewer1.LocalReport.SetParameters(parameter);
/* end of added part */
ReportViewer1.LocalReport.Refresh();
Then in report expression editor, define simple expression that concatenates inserted path from ReportParameter and stored path from database (here the parameter name should match with ReportParameter in example code above):
=Parameters!ImagePath.Value + Fields!Photo.Value
References:
How to add an external image in RDLC Report (C#)
Dynamically add and display external Image in RDLC Report from code behind in ASP.Net
How do I include external GSPs or template in the GSP file when the template to be included is not under views folder?
Yes, you can easily do that. Here you go:
import grails.gsp.PageRenderer
class MyLib {
static namespace = "foo"
static defaultEncodeAs = "raw"
PageRenderer groovyPageRenderer
def externalTemplate = { attrs, body ->
String externalFilePath = attrs.externalPath
/*
* Put content of that external template to a file inside grails-app/views folder
* with a temporary unique name appended by current timestamp
*/
String temporaryFileName = "_external-" + System.currentTimeMillis() + ".gsp"
File temporaryFile = new File("./grails-app/views/temp/$temporaryFileName")
/*
* Copy content of external file path to the temporary file in views folder.
* This is required since the groovyPageRenderer can compile any GSP located inside
* the views folder.
*/
temporaryFile.text << new File(externalFilePath).text
/*
* Now compile the content of the external GSP code and render it
*/
out << groovyPageRenderer.render([template: "/temp/$temporaryFileName", model: attrs.model])
// Delete the file finally
temporaryFile.delete()
}
}
Now in your actual GSP where you want to include the external GSP, you can write so:
<body>
<foo:externalTemplate externalPath="/home/user/anyExternalFile.gsp" model="${[status: 1}" />
</body>
I know I am late for this reply but I encountered this problem when we tried to put report views outside of the views folder.
We couldn't use the above method because we are running a jar package and we couldn't create files inside views folder.
Here is the solution on Grails 4
first inject
def groovyPagesTemplateEngine
def groovyPageLayoutFinder
then in your controller
File externalFile = new File("/path/to/file.gsp")
if(externalFile && externalFile.exists()){
GroovyPageView groovyPageView = new GroovyPageView()
LinkedHashMap model = [:]
Template template = groovyPagesTemplateEngine.createTemplate(externalFile.text, externalFileName)
groovyPageView.setServletContext(getServletContext())
groovyPageView.setTemplate(template)
groovyPageView.setApplicationContext(getApplicationContext())
groovyPageView.setTemplateEngine(groovyPagesTemplateEngine)
groovyPageView.afterPropertiesSet()
request.setAttribute GrailsLayoutDecoratorMapper.LAYOUT_ATTRIBUTE, null
GrailsLayoutView grailsLayoutView = new GrailsLayoutView(groovyPageLayoutFinder, groovyPageView)
grailsLayoutView.render model, webRequest.getCurrentRequest(), webRequest.getResponse()
webRequest.renderView = false
return
}
else {
// something that shows error
render "not found"
}
Grails 2.2.0
I'm exploring grails and ajax, and maybe I'm an overzealous ajax adaptor, but I really think its a gamechanger, so I'm going in headfirst.
Datamodel is a master detail (1:n). A table in the client shows a piece of the list of master's properties. And upon clicking, the line folds open showing all the details (An attribute domain) and an option to add a new detail to the unfolded master. All well, opening this line calls
def show (Long id) {
def product = Product.get(id)
log.info('show ' + (request.xhr ? 'xerhr' : 'normal') + "product is ${product.title}")
def c = Attribute.createCriteria();
def attributeTypes = LookupValue.findByType('m_attr') //list of values for dropdown menu.
def result = c {
eq("movie", product)
}
for (attr in result) {
log.info('value: ${attr.value}')
}
render ([template: "attributes", model:[focus:params.id
, attributeList: result, attributeTypes: attributeTypes]])
}
Where the attributes templates displays all the related attributes (details) and an add option at the end where you can enter a new value and select a value from a dropdown menu. The client does do an ajax post back to the controller's saveAttribute method to save this new Attribute:
def saveAttribute(Long id, Long luv_id, String value) {
def attribute = new Attribute(movie : Product.get(id)
, label : LookupValue.get(luv_id)
, value : value);
attribute.save();
show();
}
and again calls show() to render the newly created list of attributes back to the client. Now show() does render all the existing attributes but it fails to retrieve the just created attribute whereas it definitely did end up in the database. It also shows up when I reload the page. Where do I go wrong? With hibernate I think I would do a session.flush() to get over this.
And maybe my architecture is wrong and I need to define a service and introducing some transaction boundaries?
def saveAttribute(Long id, Long luv_id, String value) {
Attribute attribute = new Attribute(movie: Product.get(id)
, label: LookupValue.get(luv_id)
, value: value).save(flush: true)
forward(action: "show", id: id)
}
i use grails-1.3.2 and gorm-hbase-0.2.4 plugin.
Sometimes i need to change tables structure(add new tables or columns).
I have created Car table:
class Car{
static belongsTo = [user:User]
String color
String model
//.....
static constraints = {
}
}
but when i want to create car object:
def create = {
Car car = new Car()
car.properties = params
car.save(flush: true)
}
I got the following exception:
ERROR gorm.SavePersistentMethod - APP_CAR
org.apache.hadoop.hbase.TableNotFoundException: APP_CAR
After i run application with create-drop, everithing starts work good..
but i can not after every changes delete all data,
i thought plugin have to do all updates
so, i am looking some way after changind tables structure continue to run application without drop tables..
If anybody know solution please help.
Grails will NOT do automatic updates to your tables, what if it drops a column in production automatically? Maybe that is not what you wanted.
There is a database migration plugin to do this and here is an excellent link that explains it. Note that you need to use grails prod instead of using the ones directly in the link, otherwise it will run in development mode only. The link does not show prod in its commands.
The official links are here and the spring source blog about this is here.
database migration plugin will not be works, because it works only with hibernate.
You need to do some changes in plugin source. HBasePluginSupport.grovy
static doWithApplicationContext = {ApplicationContext applicationContext ->
LOG.debug("Closure HBasePluginSupport.doWithApplicationContext{} invoked with arg $applicationContext")
assert !PluginManagerHolder.getPluginManager().hasGrailsPlugin("hibernate"),"hibernate plug-in conflicts with gorm-hbase plug-in"
// Read data source configuration, setting defaults as required
def dataSource = application.config.dataSource
// TODO write tests for this <--- Even maybe figure out if this is ever invoked
if (!dataSource) dataSource = new HBaseDefaults()
def dbCreate = dataSource?.dbCreate
if (!dbCreate) dbCreate = "create-drop"
LOG.debug("Data Source configured with dbCreate set to $dbCreate")
// TODO Complete dbCreate related processing
if (dbCreate?.toUpperCase()?.equals("CREATE-DROP")) {
def createIndexedTables = dataSource?.indexed
LOG.debug ("Flag createIndexedTables set to $createIndexedTables")
def tableManager = HBaseLookupUtils.getBean("hbase.table.manager")
tableManager.createSequenceTable()
tableManager.createReferenceTable()
application.domainClasses.each {domainClass ->
LOG.debug("Adding table for Domain Class $domainClass")
tableManager.createDomainTable(domainClass, createIndexedTables)
}
LOG.debug("List of all store found :")
tableManager.getTableNames().each {tn ->
LOG.debug("- $tn")
}
} else if (dbCreate?.toUpperCase()?.equals("UPDATE")) {
def createIndexedTables = dataSource?.indexed
def tableManager = HBaseLookupUtils.getBean("hbase.table.manager")
def existingTables = tableManager.getTableNames();
application.domainClasses.each {domainClass ->
LOG.debug("Domain Class $domainClass")
def tableDesc = new HTableDescriptor(HBaseNameUtils.getDomainTableName(domainClass))
if (!existingTables.contains(tableDesc.getNameAsString())) {
tableManager.createDomainTable(domainClass, createIndexedTables)
LOG.debug("Adding table for Domain Class $domainClass")
}
}
}
application.domainClasses.each {domainClass ->
LOG.debug("Adding dbms related methods to Domain Class $domainClass")
def domainClassManager = new HBaseDomainClassManager()
domainClassManager.createQueryMethods(domainClass)
domainClassManager.createPersistenceMethods(domainClass)
domainClassManager.addLazyLoadingSupport(domainClass)
domainClassManager.addDynamicFinders(domainClass)
}
}