Explain how to Create Cron Job in Hybris - cron

I did my research but couldn't find the authentic answer.
Any inputs from hybris experts highly appreciated

Cronjob: The job to be performed. For this Create an item type extending from CronJob.
Job: Where the actual cronjob logic will be written. For this Create a class extending from AbstractJobPerformable<...abovegeneratedModel> and override the perform() method. Here perform method will contain actual job logic.
Define the above Job class as a bean in xxxcore-spring.xml.
Go to hmc-->System-->Right click on Cronjobs and Create your new cronjob.
Trigger: Holds cron expression when to fire cronjob. Add the trigger conditions through TimeSchedule tab.
Click StartCronJob Now to schedule the cronjob.
You can also use impex script to create trigger as thijsraets said.
INSERT_UPDATE Trigger;cronJob(code)[unique=true];cronExpression
;myCronJob;30 23 14 2 5 ? 2015

You probably want this cronJob to perform a custom action, for this you need to link up the cronJob with an actual action/task: the job itself. Create a bean that extends AbstractJobPerformable and implements the "perform" method. Now in the hMC you can create your Cron Job (System->CronJobs), under Job point to the bean you have created.
If you would like to do this from code you can use impex, for instance:
INSERT_UPDATE CronJob;code[unique=true];job(code);sessionLanguage(isocode);sessionCurrency(isocode)
;myCronJob;myJobBean;en;EUR
INSERT_UPDATE Trigger;cronJob(code)[unique=true];cronExpression
;myCronJob;30 23 14 2 5 ? 2015
Assign to a String and import this impex (or just execute in hac):
final CSVReader importReader = new CSVReader(impEx);
final Importer importer = new Importer(importReader);
importer.getReader().setDumpingAllowed(true);
try
{
importer.importAll();
}
catch (final ImpExException e)
{
e.printStackTrace();
}
importReader.closeQuietly();
importer.close();
(If you are using 5.5.1: the triggers do not work properly if you indicate multiple execution times. No problem if you only specify a single execution time , we hope SAP will solve this)

Related

How to define the execution order of cucumber Test Cases

I want to have two different scenarios in the same feature.
The thing is that Scenario 1 needs to be executed before Scenario 2. I have seen that this can be achieved through cucumber Hooks but when digging in the explanations, there's no concrete cucumber implementation in the examples I have found.
How can I get Scenario 1 executed before Scenario 2?
The feature file is like this:
#Events #InsertExhPlan #DelExhPln
Feature: Insert an Exh Plan and then delete it
#InsertExhPlan
Scenario: Add a new ExhPlan
Given I login as admin
And I go to automated test
When I go to ExhPlan section
And Insert a new exh plan
Then The exh plan is listed
#DeleteExhPlan
Scenario: Delete an Exh Plan
Given I login as admin
And Open the automatized tests edition
When I go to the exh plan section
And The new exh plan is deleted
Then The new exhibitor plan is deleted
The Hooks file is:
package com.barrabes.utilities;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import static com.aura.steps.rest.ParentRestStep.logger;
public class Hooks {
#Before(order=1)
public void beforeScenario(){
logger.info("================This will run before every Scenario================");
}
#Before(order=0)
public void beforeScenarioStart(){
logger.info("-----------------Start of Scenario-----------------");
}
#After(order=0)
public void afterScenarioFinish(){
logger.info("-----------------End of Scenario-----------------");
}
#After(order=1)
public void afterScenario(){
logger.info("================This will run after every Scenario================");
}
}
The order is now as it should be but I don't see how does the Hooks file control exection order.
You don't use Hooks for that purpose. Hooks are used for code that you need to run before and/or after tests, and/or before and/of after test suites; not to control the order of features and/or scenarios.
Cucumber scenarios are executed top to bottom. For the example you showed there, Scenario: Add a new ExhPlan will execute before Scenario: Delete an Exh Plan if you pass the tag #Events in the test runner. Also, you should not have the scenario tags at the feature level. So, you should remove #InsertExhPlan and #DelExhPln at the Feature level. Alternatively, you could pass a comma-separated list of scenario tags to the test runner in the order you want. For example, if you need to run scenario 2 before scenario 1, you would pass the tags for the corresponding scenarios in the order you wish them to be executed. Moreover, you can do this as well from your CI environment. For example, you can have Jenkins jobs that execute the tasks in a specific order by passing the scenario tags in that order. And, if you wish to be run in the default order, simply you can pass the feature tag.
About Hooks, this should be for code that needs to be run for all features and scenarios. For specific stuff you need to run for a particular feature, you need to use Background in the Cucumber file. Background block is run before each scenario in a given feature file.

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);
";

Groovy Script for JIRA-actions

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.

How to tell if this is the last poll in spring integration cron triggers?

We are using cron based triggers in our file and db polling. Sometimes we like to know if this is the last poll or not. Is this something available in spring integration?
I am not sure what you mean by "last" - last today?
It's not too hard to write a custom version of the CronTrigger to call this.sequenceGenerator.next(...) again with the new result to see if the next poll will be tomorrow.
The question is really what action do you want to take if that occurs? Only knowing it inside the trigger doesn't help very much; I guess you could set a boolean lastToday and test it elsewhere in your app.
Spring Integration 4.2 (currently at milestone 2) has conditional pollers which would allow you to take some action after the last poll (as determined above) completes.
You can do that only from the custom Trigger implementation. For example we often show OnlyOnceTrigger:
#Bean
public Trigger onlyOnceTrigger() {
return new Trigger() {
private final AtomicBoolean invoked = new AtomicBoolean();
#Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return this.invoked.getAndSet(true) ? null : new Date();
}
};
}
You can inject to your version the ApplicationEventPublisher and in case of the end for triggering (the next date as null) you emit some custom ApplicationEvent.
From other side you configure an <int-event:inbound-channel-adapter> for that event. And your Spring Integration application is ready to react for that!
Seems for me it's just enough to extend CronTrigger and invoke super.nextExecutionTime() for your case...

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

Resources