Groovy Script for JIRA-actions - groovy

I want to achieve the following using Adaptavist Scriptrunner in JIRA: A user comments on an issue and triggers a Scriptrunner custom script. If the issue is in the state "waiting for customer reply" and the user is a customer, trigger the workflow-transition "respond to question" and transfer the issue into the state "customer responded".
The Adaptavist Scriptrunner-Plugin uses Groovy as its language of choice for custom scripts. Unfortunately I have never worked with Groovy before and thus have no idea what I have to do to make this work. Out of the examples in the Scriptrunner docs I made the following:
import com.atlassian.jira.component.ComponentAccessor
def issue = event.issue
def workflow = ComponentAccessor.getWorkflowManager().getWorkflow(issue)
def wfd = workflow.getDescriptor()
def actionName = wfd.getAction(transientVars["actionId"] as int).getName()
This is supposed to get me the current workflow step but doesn't work. Would anyone be so kind, to help me write this script?
Cheers!

There's already available Script Listener called Fast-track transition an issue. You need just to create a new instance of it, bind it to your project and Issue Commented event, and add extra condition like issue.status.name == 'Waiting For Customer Reply' && currentUser == issue.reporter, and specify the transition. If you change workflow, you might need to update a listener too.
Also, these listeners, post-functions etc. are implemented as 'canned' scripts (classes implementing certain interface) which are available as plain groovy files in the plugin itself in the JAR file, they can teach a lot.

Related

How can I invoke a task module on handleTeamsMessagingExtensionSelectItem(...)?

I am building a messaging extension app for MS Teams using the Teams-Toolkit in Visual Studio Code. I have been able to launch task modules from the message context without a problem but is there a way to launch a task module from handleTeamsMessagingExtensionSelectItem(context, obj)? The goal is for the user to select an item from the query list which triggers a new task module where they can fill out and submit a form (adaptive card).
For more visibility, adding the answer from the comment section:
Task module can be opened using TaskModuleResponse return type.
Only TeamsTaskModuleFetchAsync() method supports TaskModuleResponse return type.
TeamsMessagingExtensionSelectItemAsync() method return type can be MessagingExtensionResponse only. As this response type can't be changed.
So, overall not feasible.

How to publish a PromotionSourceRule through Impex?

I have used the below impEx to create a coupon based promotion rule. The rule gets created successfully but the promotion modules doesn't get deployed to it.
INSERT_UPDATE PromotionSourceRule;code[unique=true];priority;maxAllowedRuns;stackable[default=false];ruleGroup(code);conditions;actions;website(Identifier)[default=$defaultPromoGrp];status(code)[default=$defaultRuleStatus];excludeFromStorefrontDisplay[default=false]
"#% beforeEach:
if(de.hybris.platform.personalizationsampledataaddon.util.CxAddOnSampleDataUtils.isPromotionSourceRuleUnmodifiable(line.get(new Integer(1)))){
line.clear();
}";
"#% afterEach: de.hybris.platform.core.Registry.getApplicationContext().getBean(""ruleEngineSystemSetup"").registerSourceRuleForDeployment(impex.getLastImportedItem(), new String[]{$promotionModule, $promotionPreviewModule});"
;coupon_code_20_percentage_cart_discount;25;1;true;couponPromotionRuleGroup;"[{""definitionId"":""y_qualifying_coupons"",""parameters"":{""coupons"":{""uuid"":""COUPON20"",""type"":""List(ItemType(AbstractCoupon))"",""value"":[""COUPON20""]}},""children"":[]}]";"[{""definitionId"":""y_order_percentage_discount"",""parameters"":{""value"":{""uuid"":""20"",""type"":""java.math.BigDecimal"",""value"":20}}}]";;;
did you do the import through the hac or as part of a system init/update?
The logic in the RuleEngineSystemSetup only works in the context of a system initialization or system update.
If you look at the default implementation you will see:
public class DefaultRuleEngineSystemSetup extends AbstractEventListener<AfterInitializationEndEvent>
so during the impex and the call to registerSourceRuleForDeployment the rules are only registered for publication and once the AfterInitializationEndEvent is fired (by the platform after an init/update) the collected rules are published.
If you run this script in the context of the hac you could use beanshell code to either invoke one of the regular RuleEngineService methods to initialize your module(s) or you could try to invoke the DefaultRuleEngineSystemSetup.onEvent(final AfterInitializationEndEvent event) method passing in a "fake" non-null event to trigger the logic inside the system setup class (it requires a non-null event for logging which event came in I believe, but other than that the event is not used)
The last thing I haven't tried, both requires some more scripting in your impex script.
Hope this helps,
Sebastian
The below impex will be used to compile and publish the promotion rules
$defaultPromoGrp = <promo-group>
$promotionSourceRulesQuery="select {psr.pk} from {PromotionSourceRule as psr},{PromotionGroup as pg} where {psr.code} in ('<Promotion Code with comma separated>') and {pg.Identifier}='$defaultPromoGrp' and {psr.website}={pg.pk}"
"#%groovy% ruleCompilerService = spring.getBean('ruleCompilerService');
platformRuleEngineService = spring.getBean('platformRuleEngineService');
flexibleSearchService = spring.getBean('flexibleSearchService');
List sourceRules = flexibleSearchService.search($promotionSourceRulesQuery).getResult();
spring.getBean('ruleMaintenanceService').compileAndPublishRules(sourceRules, ""promotions-module"", false);
";

Jenkins Script to Restrict all builds to a given node

We've recently added a second slave node to our Jenkins build environment running a different OS (Linux instead of Windows) for specific builds. Unsurprisingly, this means we need to restrict builds via the "Restrict where this project can be run" setting. However we have a lot of builds (100+) so the prospect of clicking through them all to change this setting manually isn't thrilling me.
Can someone provide a groovy script to achieve this via the Jenkins script console? I've used similar scripts in the past for changing other settings but I can't find any reference for this particular setting.
Managed to figure out the script for myself based on previous scripts and the Jenkins source. Script is as follows:
import hudson.model.*
import hudson.model.labels.*
import hudson.maven.*
import hudson.tasks.*
import hudson.plugins.git.*
hudsonInstance = hudson.model.Hudson.instance
allItems = hudsonInstance.allItems
buildableItems = allItems.findAll{ job -> job instanceof BuildableItemWithBuildWrappers }
buildableItems.each { item ->
boolean shouldSave = false
item.allJobs.each { job ->
job.assignedLabel = new LabelAtom('windows-x86')
}
}
Replace 'windows-x86' with whatever your node label needs to be. You could also do conditional changes based on item.name to filter out some jobs, if necessary.
You could try the Jenkins Job-DSL plugin
which would allow you to create a job to alter your other jobs. This works by providing a build step in a groovy based DSL to modify other jobs.
This one here would add a label to the job 'xxxx'. I've cheated a bit by using the job itself as a template.
job{
using 'xxxx'
name 'xxxx'
label 'Linux'
}
You might need to adjust it if some of you jobs are different types

Pre send script in groovy for jenkins

i have two dependent jobs. i need help for groovy script in jenkins, for writing pre send script for email-ext plugin.
i want to check whether buid reason is upstream cause, then set cancel variable=true
But i don't know how to write if condition in groovy for jenkins..For seperate jobs, will there be any seperate classes in jenkins(so i can create instance and call upstream cause)
is there any way to check build cause of downstream job is due to upstream..
Please help me on this code snippet..
Use Build.getCauses() method. It will return a list of causes for the build. Loop over it and check if there is an object of hudson.model.Cause.UpstreamCause among them.
To get the build object, use the following code snippet:
def thr = Thread.currentThread()
def build = thr?.executable
FYI, here is a link to the complete Jenkins Module API.

How do you forbid users from doing evil things in Groovy Scripts?

I'm planning to integrate Groovy Script Engine to my game so it will give the game nice moddability but how do you prevent players from writing evil scripts like deleting all files on C: drive?
Groovy includes library like java.io.File by default so it will be pretty easy to do once they decided to write such scripts.
I guess I can't prevent users from writing something like while(1==1){} but is there anyway to at least not let them allow to delete/modify files or something dangerous for PCs?
There's a blog post by Cedric Champeau on customising the Groovy Compilation process, the second part of it shows how to use SecureASTCustomizer and CompilerConfiguration to limit what Scripts can do (and then has examples of defining your own AST checks for System.exit, etc...
Look into the SecurityContext class.
The Groovy Web Console appears to have already solved this problem, because it won't execute something like System.exit(1). The source code is available on GitHub, so you can see how they did it.
If you're not sure where to start, I suggest getting in touch with the author, who should be able to point you in the right direction.
I know this is a old question. I'm posting this as it might help some people out there.
We needed to allow end-users to upload Groovy scripts and execute them as part of a web application (that does a lot of other things). Our concern was that within these Groovy scripts, some users might attempt to read files from the file system, read System properties, call System.exit(), etc.
I looked into http://mrhaki.blogspot.com/2014/04/groovy-goodness-restricting-script.html but that will not prevent an expert Groovy developer from bypassing the checks as pointed out by others in other posts.
I then tried to get http://www.sdidit.nl/2012/12/groovy-dsl-executing-scripts-in-sandbox.html working but setting the Security Manager and Policy implementation at runtime did not work for me. I kept running into issues during app server startup and web page access. It seemed like by the time the Policy implementation took hold, it was too late and "CodeSources" (in Java-Security-speak) already took its access settings from the default Java policy file.
I then stumbled across the excellent white paper by Ted Neward (http://www.tedneward.com/files/Papers/JavaPolicy/JavaPolicy.pdf) that explained quite convincingly that the best approach (for my use case) was to set the Policy implementation on JVM startup (instead of dynamically later on).
Below is the approach that worked for me (that combines Rene's and Ted's approaches). BTW: We're using Groovy 2.3.10.
In the [JDK_HOME]/jre/lib/security/java.security file, set the "policy.provider" value to "com.yourcompany.security.MySecurityPolicy".
Create the MySecurityPolicy class:
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.util.HashSet;
import java.util.Set;
public class MySecurityPolicy extends Policy {
private final Set<URL> locations;
public MySecurityPolicy() {
try {
locations = new HashSet<URL>();
locations.add(new URL("file", "", "/groovy/shell"));
locations.add(new URL("file", "", "/groovy/script"));
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
#Override
public PermissionCollection getPermissions(CodeSource codeSource) {
// Do not store these in static or instance variables. It won't work. Also... they're cached by security infrastructure ... so this is okay.
PermissionCollection perms = new Permissions();
if (!locations.contains(codeSource.getLocation())) {
perms.add(new AllPermission());
}
return perms;
}
}
Jar up MySecurityPolicy and drop the jar in [JDK_HOME]/jre/lib/ext directory.
Add "-Djava.security.manager" to the JVM startup options. You do not need to provide a custom security manager. The default one works fine.
The "-Djava.security.manager" option enables Java Security Manager for the whole application. The application and all its dependencies will have "AllPermission" and will thereby be allowed to do anything.
Groovy scripts run under the "/groovy/shell" and "/groovy/script" "CodeSources". They're not necessarily physical directories on the file system. The code above does not give Groovy scripts any permissions.
Users could still do the following:
Thread.currentThread().interrupt();
while (true) {} (infinite loop)
You could prepend the following (dynamically at runtime) to the beginning of every script before passing it onto the Groovy shell for execution:
#ThreadInterrupt
import groovy.transform.ThreadInterrupt
#TimedInterrupt(5)
import groovy.transform.TimedInterrupt
These are expalined at http://www.jroller.com/melix/entry/upcoming_groovy_goodness_automatic_thread
The first one handles "Thread.currentThread().interrupt()" a little more gracefully (but it doesn't prevent the user from interupting the thread). Perhaps, you could use AST to prevent interupts to some extent. In our case, it's not a big issue as each Groovy script execution runs in its own thread and if bad actors wish to kill their own thread, they could knock themselves out.
The second one prevents the infinite loop in that all scripts time out after 5 seconds. You can adjust the time.
Note that I noticed a performance degradation in the Groovy script execution time but did not notice a significant degradation in the rest of the web application.
Hope that helps.

Resources