Comment not inserted in the linked issue - jira

I am developing a plugin for jira in scriptrunner, it is a postfunction so something needs to happen when a button is clicked.
I am trying to click on the "MounaFixReleased" menu item and then generate a comment for the issue links that are marked within the "Resolves" subcategory as shown above. So a new comment should be inserted for all the issues within the "Resolves" subsection in the screen above. The transition "MounaFixReleased" leads to itself, it is available from any status to itself. Here is the button shown below that I am clicking on.  
Basically, what I want to do is to insert a comment saying the following:
Here is my code, the problem is that the comment is not getting printed within the resolved issues. There is no comment, it is just empty.
I am using this line for testing purposes and the comment gets printed in the log file but nothing gets inserted in the issue:
log.warn("CAM 4 " + linkedissue.getKey()+ " "+ inputParameters+" "+defectComment+" "+inputParameters.getCommentValue())
Here is the log in which I am printing all my log statements as you can tell everything seems to be printed the right way.
Here is my code:
import com.opensymphony.workflow.WorkflowContext
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.event.Event
import java.util.HashMap;
import java.util.List;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericEntity;
import com.atlassian.jira.event.issue.AbstractIssueEventListener;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import org.apache.log4j.Logger
import com.atlassian.jira.component.ComponentAccessor
import org.ofbiz.core.entity.GenericDelegator;
import com.atlassian.jira.issue.changehistory.ChangeHistoryManager;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.issue.changehistory.ChangeHistoryItem
import com.onresolve.scriptrunner.runner.util.UserMessageUtil
import com.atlassian.jira.config.SubTaskManager
import com.atlassian.jira.issue.Issue
import groovy.xml.MarkupBuilder
import com.atlassian.jira.config.properties.APKeys
import com.atlassian.jira.issue.link.LinkCollectionImpl;
import com.atlassian.jira.issue.link.IssueLink;
import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.issue.comments.CommentManager;
import com.atlassian.jira.issue.link.IssueLinkManager;
import com.atlassian.jira.util.ErrorCollection;
import com.atlassian.jira.util.JiraUtils;
import com.atlassian.jira.workflow.JiraWorkflow;
import com.atlassian.jira.workflow.WorkflowManager;
import com.atlassian.jira.workflow.WorkflowTransitionUtil;
import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;
import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider;
import com.opensymphony.module.propertyset.PropertySet;
import com.opensymphony.workflow.WorkflowException;
import com.opensymphony.workflow.loader.StepDescriptor;
import com.opensymphony.workflow.spi.SimpleStep;
import com.atlassian.jira.config.ConstantsManager
import com.atlassian.jira.workflow.ImmutableWorkflowDescriptor
import com.atlassian.jira.web.action.admin.workflow.ViewWorkflowStep
import com.opensymphony.workflow.loader.ActionDescriptor
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.issue.IssueInputParametersImpl
import com.atlassian.jira.bc.issue.IssueService.IssueValidationResult
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.workflow.WorkflowTransitionUtilFactory
import com.atlassian.jira.workflow.TransitionOptions
def log = Logger.getLogger("atlassian-jira.log")
SubTaskManager subTaskManager = ComponentAccessor.getSubTaskManager();
List < IssueLink > linksOut = ComponentAccessor.getIssueLinkManager().getOutwardLinks(issue.getId())
List < IssueLink > linksIn = ComponentAccessor.getIssueLinkManager().getInwardLinks(issue.getId())
ApplicationUser applicationUser = getCurrentUser();
ArrayList < Issue > issuesWithValidateError = new ArrayList < Issue > ();
List < IssueLink > links = new ArrayList < IssueLink > ()
log.warn("resolved " + linksOut.size() + " links in size " + linksIn.size() + " " + applicationUser)
log.warn("THIS IS MY LINK LINKSOUT " + linksOut.size())
for (IssueLink link in linksOut) {
if (link.getDestinationObject().getIssueTypeId().equals("5")) {
log.warn("THIS IS MY LINK everything " + link.getLinkTypeId() + " " + link.getDestinationObject().getKey())
links.add(link)
}
}
log.warn("THIS IS MY LINK linksIn " + linksIn.size())
for (IssueLink link in linksIn) {
if (link.getDestinationObject().getIssueTypeId().equals("5")) {
log.warn("THIS IS MY LINK everything " + link.getLinkTypeId() + " " + link.getDestinationObject().getKey())
links.add(link)
}
}
for (IssueLink link in links) {
log.warn("THIS IS MY LINK MOUNA " + link + link.getDestinationObject().getKey())
}
if (links.isEmpty()) {
log.warn("No linked Defect-Issues found.");
return;
}
User loggedInUser = getCurrentUser().getDirectoryUser();
log.warn("resolved transition 1" + loggedInUser)
WorkflowManager workflowManager = ComponentAccessor.getWorkflowManager();
log.warn("resolved transition 2")
JiraWorkflow workflow = workflowManager.getWorkflow(issue);
log.warn("resolved transition 3")
List < Object > actions = workflow.getLinkedStep(issue.getStatus()).getActions();
log.warn("resolved transition 4")
def wfd = workflow.getDescriptor();
log.warn("resolved transition 5")
def actionName = wfd.getAction(transientVars["actionId"] as int).getName();
log.warn("resolved transition 6 " + actionName)
def actionId = transientVars["actionId"] as int;
log.warn("resolved transition 7 " + actionId)
log.warn("This is the last action " + actionName);
List < String > sourceObjectLinkList = new ArrayList < String > ();
def targetStatus = getTargetStatus(issue);
log.warn("resolved transition targetStatus " + targetStatus + "end");
//transition(actionId, links)
for (IssueLink link: links) {
String foundID = foundActionID(link);
if (foundID == null) {
log.error("Action for Issue " + link.getKey() + " not found!");
issuesWithValidateError.add(link);
continue;
}
log.warn("CAM 0 " + foundID);
PerformTransition(link.getDestinationObject(), foundID, link.getSourceObject());
log.warn("links tostring " + links.toString());
sourceObjectLinkList.add(link.getDestinationObject().getKey());
log.warn("MOUNA COMMENT 11" + link.getDestinationObject().getKey())
}
log.warn("MOUNA COMMENT 22" + sourceObjectLinkList)
String fixComment = "The following Defects resolved by this Fix were notified: ISSUEKEYS.";
fixComment = fixComment.replaceAll("ISSUEKEYS", sourceObjectLinkList.toString());
log.warn("MOUNA CAMELIA COMMENT " + fixComment)
CommentManager commentManager = ComponentAccessor.getCommentManager();
// add comment but do NOT fire event
commentManager.create(issue, getCurrentUser(), fixComment, false);
/*
PERFORM TRANSITION
*/
void PerformTransition(Issue linkedissue, String transitionToBeDone, Issue sourceObject) {
def defectComment = "Fix FIXSUMMARY[ISSUEKEY] has been released by USERNAME[USER].";
log.warn("CAM 1 " + transitionToBeDone)
IssueService issueService = ComponentAccessor.getIssueService()
log.warn("CAM 1 " + transitionToBeDone)
ApplicationUser currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
log.warn("CAM 2")
TransitionOptions transitionOptions = new TransitionOptions.Builder()
.skipConditions()
.skipPermissions()
.skipValidators()
.build()
log.warn("CAM 3")
int transitionToBeDoneInt = transitionToBeDone as Integer
String status = getTargetStatus(sourceObject) as String;
def constantsManager = ComponentAccessor.getConstantsManager()
def statusName = constantsManager.getStatus(status).getName();
log.warn("STatus" + status)
def inputParameters = issueService.newIssueInputParameters()
log.warn("CAM comment " + defectComment + " summary: " + sourceObject.getSummary())
defectComment = defectComment.replaceAll("FIXSUMMARY", sourceObject.getSummary());
log.warn("CAM comment 2" + defectComment)
defectComment = defectComment.replaceAll("ISSUEKEY", sourceObject.getKey()).replaceAll("USERNAME", currentUser.getDisplayName());
log.warn("CAM comment 3" + defectComment)
defectComment = defectComment.replaceAll("USER", currentUser.getName());
log.warn("CAM comment 4 " + defectComment)
defectComment = defectComment.replaceAll("released", "set to \"" + statusName + "\" ");
log.warn("CAM comment 5 " + defectComment)
inputParameters.setComment(defectComment)
IssueService.TransitionValidationResult result = issueService.validateTransition(currentUser,
linkedissue.getId(),
transitionToBeDoneInt,
inputParameters,
transitionOptions);
log.warn("CAM 4 " + linkedissue.getKey()+ " "+ inputParameters+" "+defectComment+" "+inputParameters.getCommentValue())
log.warn("USER NAME MOUNA ")
//ApplicationUser myuser=ComponentAccessor.getUserManager().getUserByKey("itracfix");
//log.warn("USER NAME MOUNA " + myuser.getDisplayName())
try {
if (result.isValid()) {
log.warn("CAM 5 " + defectComment)
issueService.transition(currentUser, result)
log.warn("CAM 6 " + defectComment)
}
} catch (Exception e) {
log.warn("CAM 6 " + e)
log.warn(result.getErrorCollection().getErrors());
}
}
/*
GET CURRENT USER
*/
ApplicationUser getCurrentUser() {
ApplicationUser user = ComponentAccessor.getJiraAuthenticationContext().getUser();
if (user == null) {
String defaultUser = gc.getValue("user");
user = ComponentAccessor.getUserManager().getUserByName(defaultUser);
}
return user;
}
/*
GET TARGET STATUS
*/
def getTargetStatus(Issue issue) {
log.warn("resolved inside target")
def targetStatus = "";
try {
List currentSteps = (ArrayList) transientVars.get("currentSteps");
SimpleStep simpleStep = currentSteps.get(0);
int actionId = simpleStep.getActionId();
int beforeStepId = simpleStep.getStepId();
def workflow = ComponentAccessor.workflowManager.getWorkflow(issue)
ActionDescriptor ad = workflow.getDescriptor().getAction(actionId);
int afterStep = ad.getUnconditionalResult().getStep();
log.warn("resolved transition target " + afterStep)
log.warn("resolved transition target last " + ComponentAccessor.workflowManager.getNextStatusIdForAction(issue, transientVars['actionId'] as int))
targetStatus = ComponentAccessor.workflowManager.getNextStatusIdForAction(issue, transientVars['actionId'] as int)
def constantsManager = ComponentAccessor.getConstantsManager()
def statusName = constantsManager.getStatus(targetStatus).getName();
log.warn("resolved transition target " + targetStatus + "status name " + statusName)
} catch (Exception exception) {
log.error("getTargetStatus threw exception: " + exception.getMessage());
}
return targetStatus;
}
/*
FOUND ACTION ID
*/
String foundActionID(IssueLink issueLink) {
String id = null;
log.warn("foundActionID 1 here")
Issue issue = issueLink.getDestinationObject()
List < StepDescriptor > actionDescriptorList = ComponentAccessor.workflowManager.getWorkflow(issue).getDescriptor().getSteps();
log.warn("foundActionID 2 here")
List < ActionDescriptor > myStepDescriptor = null;
log.warn("foundActionID 3 here" + actionDescriptorList)
Boolean foundAction = false;
log.warn("foundActionID 1" + foundAction)
for (StepDescriptor stepDescriptor: actionDescriptorList) {
if (stepDescriptor.getName().equals(issue.getStatusObject().getName())) {
myStepDescriptor = stepDescriptor.getActions();
log.warn("foundActionID2 " + myStepDescriptor)
break;
}
}
for (ActionDescriptor actionDescriptor: myStepDescriptor) {
log.warn("foundActionID3 ")
WorkflowManager workflowManager = ComponentAccessor.getWorkflowManager();
JiraWorkflow workflow = workflowManager.getWorkflow(issue);
List < String > actionIDs = ["1021", "1031", "1041", "1051", "1061", "1071", "1081", "1091"]
if (actionIDs.contains(String.valueOf(actionDescriptor.getId()))) {
id = String.valueOf(actionDescriptor.getId());
foundAction = true;
log.warn("foundActionID5 " + id)
break;
}
}
if (!foundAction)
return null;
return id;
}

Related

changeLog.internalDelegator [GenericEntity.get] "internalDelegator" is not a field of ChangeGroup

I am writing some scriptrunner listener code in Jira to be triggered when an issue of type impediment is updated and here is my code:
import com.atlassian.event.Event
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericEntity;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.event.issue.AbstractIssueEventListener;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import org.apache.log4j.Logger
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.component.ComponentAccessor
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
def log = Logger.getLogger("atlassian-jira.log")
log.warn("Start Auto Defaults Listener");
log.warn("IssueMounaEvent = " + event);
Issue issue = event.getIssue();
log.warn("IssueMouna = " + issue);
if (issue.getIssueType().getName().equalsIgnoreCase("Impediment"))
{
log.warn("Analyzing IMPEDIMENT changelog Mouna ...");
event2= (IssueEvent) event;
def warning = analyzeImpedimentChangeLog(event2);
}
def analyzeImpedimentChangeLog(IssueEvent event) {
def warning = "";
log.warn("IMPEDIMENT STATUS ")
List<GenericValue> changeItems = null;
def impedimentStatus = event.getIssue().getStatus().getName();
log.warn("IMPEDIMENT STATUS "+impedimentStatus)
if (!"New".equalsIgnoreCase(impedimentStatus) && !"Inspecting".equalsIgnoreCase(impedimentStatus)) {
GenericValue changeLog = event.getChangeLog();
log.warn("HERE 1")
HashMap<String, Object> fields = new HashMap<String,Object>();
log.warn("HERE 2")
fields.put("group", changeLog.get("id"));
log.warn("HERE 3")
String author = changeLog.getString("author");
log.warn("HERE 4")
try{
log.warn("CHANGE LOG: "+changeLog.internalDelegator)
changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
log.warn("HERE 5")
}catch(Exception e){
log.warn("EXCEPTIONMOUNA "+e)
}
}
return warning;
}
I receive the following error, which is kind of weird because this was previously implemented in Java and it worked fine:
2022-08-11 EXCEPTIONMOUNA java.lang.IllegalArgumentException: [GenericEntity.get] "internalDelegator" is not a field of ChangeGroup
I would like to execute the following line of code:
changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
and I receive the exception above when writing the following line of code into the log:
log.warn("CHANGE LOG: "+changeLog.internalDelegator)
This code was previously implemented as a Java plugin and it worked fine in this way. What needs to be done in this case in order to adapt this statement to groovy in ScriptRunner?
I found a way to access the log, this one:
import com.atlassian.event.Event
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericEntity;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.event.issue.AbstractIssueEventListener;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import org.apache.log4j.Logger
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.component.ComponentAccessor
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericDelegator;
import com.atlassian.jira.issue.changehistory.ChangeHistoryManager;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.workflow.JiraWorkflow
import com.atlassian.jira.workflow.WorkflowManager
import org.apache.log4j.Logger
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.changehistory.ChangeHistoryItem
def log = Logger.getLogger("atlassian-jira.log")
log.warn("Start Auto Defaults Listener");
log.warn("IssueMounaEvent = " + event);
Issue issue = event.getIssue();
log.warn("IssueMouna = " + issue);
if (issue.getIssueType().getName().equalsIgnoreCase("Impediment"))
{
log.warn("Analyzing IMPEDIMENT changelog Mouna ...");
event2= (IssueEvent) event;
def warning = analyzeImpedimentChangeLog(event2);
if (!warning.isEmpty()) {
log.warn("Set IMPEDIMENT warning tooo Mouna " + warning);
setWarning(issue, warning);
}
else {
log.warn("No IMPEDIMENT warning");
}
}
def analyzeImpedimentChangeLog(IssueEvent event) {
String warning = "";
log.warn("IMPEDIMENT STATUS ")
//List<GenericValue> changeItems = null;
def impedimentStatus = event.getIssue().getStatus().getName();
// status New and Inspecting are out of scope
log.warn("IMPEDIMENT STATUS "+impedimentStatus)
if (!"New".equalsIgnoreCase(impedimentStatus) && !"Inspecting".equalsIgnoreCase(impedimentStatus)) {
GenericValue changeLog = event.getChangeLog();
log.warn("HERE 1")
HashMap<String, Object> fields = new HashMap<String,Object>();
log.warn("HERE 2")
fields.put("group", changeLog.get("id"));
log.warn("HERE 3")
String author = changeLog.getString("author");
log.warn("HERE 4")
//changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
log.warn("CHANGE LOG: "+changeLog.get("issue"))
List<GenericValue> changeItems = ComponentAccessor.getChangeHistoryManager().getAllChangeItems(issue)
// changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
//changeItems = changeLog
log.warn("HERE 5::: "+ changeItems)
log.warn("MOUNA IS HERE AFTER HERE 5 " +changeItems.size());
log.warn("VALUES 1");
int lastIndex= changeItems.size()-1;
log.warn("MOUNA IS HERE AFTER HERE 5 " +changeItems.size()+ " "+changeItems.get(lastIndex));
ChangeHistoryItem value= changeItems.get(lastIndex) as ChangeHistoryItem;
log.warn("GENERIC VALUE "+ value.getField());
String modifiedField=value.getField();
if(modifiedField.equals("Source Type") ||modifiedField.equals("Class")||
modifiedField.equals("Planning Required")){
log.warn("MOUNA SIZE");
def ChangeHistoryManager= ComponentAccessor.getChangeHistoryManager();
List<ChangeItemBean> fieldchangeItems = ChangeHistoryManager.getChangeItemsForField(issue, modifiedField)
if (fieldchangeItems.size()>0) {
log.warn("MOUNA FIRST "+ modifiedField);
//String content = transientVars['Source Type'] as String
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def newStringCf = customFieldManager.getCustomFieldObjectByName(modifiedField)
String newString = issue.getCustomFieldValue(newStringCf) as String
log.warn("MOUNA FIRST "+ newString);
//def val=cfValues['Source Type']?.value
//log.warn(sourceType+" MOUNA FIRST "+sourceTypechangeItems.get(sourceTypechangeItems.size()-1).getFromString());
String oldString = fieldchangeItems.get(fieldchangeItems.size()-1).getFromString();
warning = "Field \"" + modifiedField + "\" has been changed from \"" + oldString + "\" to \"" + newString + "\" by \"" + author + "\"";
log.warn("MOUNA FIRST "+warning);
}
}
changeItems.eachWithIndex { item, index ->
log.warn("ITEM MOUNA "+item);
}
}
log.warn("changeitemlog== "+warning);
return warning;
}
void setWarning(Issue mutableIssue, String warning)
{
log.warn("WARNING FUNC "+warning)
Warning = 13593
CustomField customField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(new Long(13593));
IssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();
customField.updateValue(null, mutableIssue, new ModifiedValue(mutableIssue.getCustomFieldValue(customField), warning), issueChangeHolder);
}

Jenkins use import in Jenkinsfile

How can I use import statements in Jenkinsfile?
This is the import statement:
import hudson.model.*
import jenkins.model.*
import hudson.tasks.test.AbstractTestResultAction
I want to use AbstractTestResultAction in a script section.
I solved it that way - this what the Jenkinsfile looks like:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import hudson.tasks.test.AbstractTestResultAction;
#NonCPS
def getTestSummary = { ->
def testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
def summary = ""
if (testResultAction != null) {
def total = testResultAction.getTotalCount()
def failed = testResultAction.getFailCount()
def skipped = testResultAction.getSkipCount()
summary = "Test results:\n\t"
summary = summary + ("Passed: " + (total - failed - skipped))
summary = summary + (", Failed: " + failed + " ${testResultAction.failureDiffString}")
summary = summary + (", Skipped: " + skipped)
} else {
summary = "No tests found"
}
return summary
}
pipeline {
...
post {
always {
script {
def testSummaryRaw = getTestSummary()
def testSummary = "`${testSummaryRaw}`"
...
}
}
}
...
}

GPS.ane for my app and i keep getting an error Line 55, Column 50 1120: Access of undefined property onClickStop

**trying to use the GPS.ane for my app and I keep getting an error
"Line 55, Column 50 1120: Access of undefined property onClickStop."
this is the line that is giving me the headache I think I am missing something small but i cant find it. The app is as you will think gives out the latitude and longitude of where you are at. thank you for you help **
**package {
import com.myflashlab.air.extensions.gps.Gps;
import com.myflashlab.air.extensions.gps.LocationAccuracy;
import com.myflashlab.air.extensions.gps.Location;
import com.myflashlab.air.extensions.gps.GpsEvent;
import com.myflashlab.air.extensions.nativePermissions.PermissionCheck;
import flash.utils.setTimeout;
import com.myflashlab.air.extensions.dependency.OverrideAir;
import flash.desktop.NativeApplication;
import flash.desktop.SystemIdleMode;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.StatusEvent;
import flash.events.InvokeEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.filesystem.File;
import flash.text.AntiAliasType;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.ui.Keyboard;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Main extends MovieClip{
private var _exPermissions:PermissionCheck = new PermissionCheck();
public function Main() {
// constructor code
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate);
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate);
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys);
stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.align = StageAlign.TOP_LEFT;
startBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStart);
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
checkPermissions();
}
private function onInvoke(e:InvokeEvent):void
{
NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvoke);
}
private function handleActivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}
private function handleDeactivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
}
private function handleKeys(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.BACK)
{
e.preventDefault();
NativeApplication.nativeApplication.exit();
}
}
private function checkPermissions():void
{
// first you need to make sure you have access to the Location API
var permissionState:int;
if(_exPermissions.os == PermissionCheck.ANDROID)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE);
}
if (permissionState == PermissionCheck.PERMISSION_UNKNOWN || permissionState == PermissionCheck.PERMISSION_DENIED)
{
if(_exPermissions.os == PermissionCheck.ANDROID)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION, onRequestResult);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE, onRequestResult);
}
}
else
{
textDisplay.appendText("permissions are already ok, you can use gps features."+ "\n");
init();
}
function onRequestResult($state:int):void
{
if ($state != PermissionCheck.PERMISSION_GRANTED)
{
textDisplay.appendText("You did not allow the app the required permissions!"+ "\n");
}
else
{
textDisplay.appendText("necessary permissions are now granted."+ "\n");
init();
}
}
}
public function onClickStart (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Started.\n");
// use the start method to get gps information periodically (the gps icon will be shown at your device status bar)
Gps.location.addEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.start(LocationAccuracy.HIGH, 0, 5000);
startBtn.alpha = 0.5;
stopBtn.alpha = 1;
}
public function onClickstop (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Stopped.\n");
// simply stop the gps service when you don't need to get location information periodically anymore.
Gps.location.removeEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.stop();
startBtn.alpha = 1;
stopBtn.alpha = 0.5;
}
function onLocationUpdate(e:GpsEvent):void
{
textDisplay.appendText(" ------------------------------- onLocationUpdate"+ "\n");
var loc:Location = e.param;
textDisplay.appendText("accuracy = " + loc.accuracy+ "\n");
textDisplay.appendText("altitude = " + loc.altitude+ "\n");
textDisplay.appendText("bearing = " + loc.bearing+ "\n");
textDisplay.appendText("latitude = " + loc.latitude+ "\n");
textDisplay.appendText("longitude = " + loc.longitude+ "\n");
textDisplay.appendText("provider = " + loc.provider+ "\n");
textDisplay.appendText("speed = " + loc.speed+ "\n");
textDisplay.appendText("time = " + loc.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
private function myDebuggerDelegate($ane:String, $class:String, $msg:String):void
{
textDisplay.appendText($ane+"("+$class+") "+$msg+ "\n");
}
private function init():void
{
// remove this line in production build or pass null as the delegate
OverrideAir.enableDebugger(myDebuggerDelegate);
Gps.init(); // call init only once in your project
// will return null if no known last location has been found
Gps.location.getLastLocation(onLocationResult);
// may take a while depending on when gps info is found
Gps.location.getCurrentLocation(onLocationResult);
function onLocationResult($result:Location):void
{
if (!$result)
{
textDisplay.appendText("location is null"+ "\n");
return;
}
textDisplay.appendText("accuracy = " + $result.accuracy+ "\n");
textDisplay.appendText("altitude = " + $result.altitude+ "\n");
textDisplay.appendText("bearing = " + $result.bearing+ "\n");
textDisplay.appendText("latitude = " + $result.latitude+ "\n");
textDisplay.appendText("longitude = " + $result.longitude+ "\n");
textDisplay.appendText("provider = " + $result.provider+ "\n");
textDisplay.appendText("speed = " + $result.speed+ "\n");
textDisplay.appendText("time = " + $result.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
}
}
}
**
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
public function onClickstop (evt:TouchEvent):void{
Your function has a low case s in stop, but when you refer to it you use a capital S.
Think that's all that's wrong

jenkins cli with checkout Subversion using groovy script

Is there a way to check out any Subversion project using Jenkins-Cli by executing a groovy script on the master? I can get to the point of creating SVN client manager[org.tmatesoft.svn.core.wc.SVNClientManager], but can't really understand how to employ that in checking out an SVN project from the URL.
After a lot of hit and trials I have come up with this, might be useful for someone else:
import jenkins.*;
import jenkins.model.*;
import hudson.*;
import hudson.model.*;
import hudson.slaves.SlaveComputer;
import hudson.scm.SubversionSCM;
import hudson.remoting.Channel;
import hudson.FilePath;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
private boolean checkNodeExist(String node_Name){
if (Jenkins.getInstance().slaves.find({it.name == node_Name}) == null)
return false;
else
return true;
}
private ISVNAuthenticationProvider createAuthenticationProvider(AbstractProject context) {
return Jenkins.getInstance().getDescriptorByType(SubversionSCM.DescriptorImpl.class)
.createAuthenticationProvider(context);
}
public class SimpleSVNDirEntryHandler implements ISVNDirEntryHandler {
private final List<SVNDirEntry> dirs = new ArrayList<SVNDirEntry>();
public List<String> getDirs() {
List<String> sortedDirs = new ArrayList<String>();
for (SVNDirEntry dirEntry : dirs) {
sortedDirs.add(dirEntry.getName());
}
return sortedDirs;
}
public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException {
dirs.add(dirEntry);
}
}
public void PerfromSVNListOperationOnMaster(SVNURL svnUrl){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider())
SVNLogClient logClient = clientManager.getLogClient();
SimpleSVNDirEntryHandler dirEntryHandler = new SimpleSVNDirEntryHandler();
List<String> dirs = new ArrayList<String>();
logClient.doList(repo.getLocation(),SVNRevision.HEAD, SVNRevision.HEAD,false,SVNDepth.INFINITY,SVNDirEntry.DIRENT_KIND,dirEntryHandler)
dirs = dirEntryHandler.getDirs();
println (dirs)
}
catch(SVNException svnEx){
println "#Error: " + svnEx;
throw svnEx
}
}
public void PerfromSVNCheckOutOperation(SVNURL svnUrl,boolean isMaster,String appender,SlaveComputer computer = null){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider());
SVNUpdateClient updateClient = clientManager.getUpdateClient();
updateClient.setIgnoreExternals(false);
String destDir = svnUrl.getPath().substring(svnUrl.getPath().lastIndexOf('/')+1);
if (isMaster == true){
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
}else{
if (computer == null){
throw new IllegalArgumentException("#Error: Argument:computer can't be null when we need to checkout in slave");
}else{
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
Channel slaveChannel = computer.getChannel();
FilePath fpSrc = new hudson.FilePath(new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender));
//println new java.io.File((slave.getWorkspaceRoot().toString()),destDir).toString().replace('\\','/')
FilePath fpDestination = new hudson.FilePath(slaveChannel,new java.io.File((slave.getWorkspaceRoot().toString()),destDir + '_' + appender).toString().replace('\\','/'));
println "Copying files recursively from Temp directory in master to slave";
int files_copied = fpSrc.copyRecursiveTo(fpDestination);
println files_copied
fpSrc.deleteRecursive();
}
}
}
catch (Exception ex){
throw new Exception("#Error:",ex);
}
}
if (args.length == 4){
String url = new String(args[0]);
SVNURL svn_url = null;
try{
svn_url = SVNURL.parseURIDecoded(url);
}
catch(SVNException svnEX){
println "#Error: Check SVN repository Location.";
throw svnEX;
}
String nodeName = new String(args[1]);
String operation = new String(args[2]);
String checkoutAppendString = new String(args[3]);
println args
if (nodeName.equalsIgnoreCase("master")){
println "Executing script on master"
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url);
}else{
PerfromSVNCheckOutOperation(svn_url,true,checkoutAppendString);
}
}else{
if (checkNodeExist(nodeName)){
slave = Jenkins.getInstance().slaves.find({it.name == nodeName});
SlaveComputer computer = slave.getComputer();
if (computer.isOffline()){
println "#Error: $slave is offline."
return
}else{
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url)
}else{
PerfromSVNCheckOutOperation(svn_url,false,checkoutAppendString,computer);
}
}
}else{
println "#Error: $nodeName not found."
return
}
}
}else{
println "Invalid Usage, expecting 3 arguments : 1.RepositoryURL 2.NodeName 3.OperationType"
return
}

Actionscript compiler MTASC and Events

Please help, how to make netEvent work in a compiled flash, for instance I can't even make macromedia example to work:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.onMetaData = function(infoObject:Object) {
for (var propName:String in infoObject) {
trace(propName + " = " + infoObject[propName]);
}
};
ns.play("http://www.helpexamples.com/flash/video/water.flv");
It must return metainfo, but seems like no event is called at all.
What am I doing wrong?
Thanks!
This is right from Adobe docs:
package {
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.Event;
public class NetConnectionExample extends Sprite {
private var videoURL:String = "Video.flv";
private var connection:NetConnection;
private var stream:NetStream;
public function NetConnectionExample() {
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
connection.connect(null);
}
private function netStatusHandler(event:NetStatusEvent):void {
switch (event.info.code) {
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Stream not found: " + videoURL);
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function connectStream():void {
stream = new NetStream(connection);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client = new CustomClient();
var video:Video = new Video();
video.attachNetStream(stream);
stream.play(videoURL);
addChild(video);
}
}
}
class CustomClient {
public function onMetaData(info:Object):void {
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
public function onCuePoint(info:Object):void {
trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
}
}
Looks to me like you're missing quite a bit in the code that you posted and you won't get what you're looking for by missing required setup code.

Resources