How to give administrative permission to Scheduler

Hi Experts.

I am creating issues through scheduler using com.atlassian.scheduler.SchedulerService. My scheduler is working fine but while creating issue i am getting exception which is in imgae.

My Code implementation:

import com.atlassian.scheduler.JobRunner;
import com.atlassian.scheduler.JobRunnerRequest;
import com.atlassian.scheduler.JobRunnerResponse;
import com.atlassian.scheduler.SchedulerService;

public class MyScheduler implements JobRunner  {


       @Override
	public JobRunnerResponse runJob(JobRunnerRequest request) {
		
		// Sync Employee and create issue
				
		return JobRunnerResponse.success();
	}

     public void registerJob(long sysFreq, String sysMetrics)  {
      
    scheduler.unregisterJobRunner(JOB_RUNNER_KEY);
		
		logger.info("Scheduling Job. Job id: "+JOB_ID);
		scheduler.registerJobRunner(JOB_RUNNER_KEY, this);
		final JobConfig jobConfig = 
                   JobConfig.forJobRunnerKey(JOB_RUNNER_KEY).withRunMode(RunMode.RUN_LOCALLY)
				.withSchedule(Schedule.forInterval(scheduleTime, null));
		
		scheduler.scheduleJob(JOB_ID, jobConfig);

     }

}

Note: Above code is my implementation for scheduler but it is having permission issue while creating issues. Exception is “anonymous user do not have permission to create issue in this project” but i am registering schedule by administrative credential. So how to give administrative access to my scheduler. Kindly need help to solve this permission issue.

I assume that your runJob method creates an issue using the IssueManager, maybe using the createIssueObject method?

Issue createIssueObject(
    ApplicationUser remoteUser, 
    Map<String, Object> fields) throws CreateException;

You’ll need to pass something other than null as the remoteUser argument.

1 Like

Thank you so much David i got the idea to solve this by set ApplicationUser remoteUser.

Hi David,

I have one problem here scheduler is a independent background process as it is not interacting with user. Then how i can get logged in user here. Below code(applicationUser object) is returning null once scheduler execute the block of code.


**ApplicationUser applicationUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()**

IssueResult createResult = issueService.create(applicationUser, createValidationResult);

 

JIRA has two modes here -

  • Anonymous access enabled
  • Anonymous access disabled

Projects in JIRA can implement their own permission schemes. Permission schemes can allow or disallow “anonymous users” to create issues.

You must adhere to this model: Either guarantee that you have anonymous access enabled in JIRA AND that anonymous users can create issues in the specific project OR create a system user account to create issues on behalf of.

1 Like

You’ll need to fetch the user under whose identity you want to create the issue. See the UserManager interface:

/**
 * Returns an {@link ApplicationUser} based on user key.
 *
 * @param userKey the key of the user
 * @return the ApplicationUser object
 * @since v5.1.1
 */
@Nullable
ApplicationUser getUserByKey(final @Nullable String userKey);

You could either assume the existence of a particular user, or otherwise allow an administrator to choose the user identity on some kind of settings screen.

1 Like

Hi David,

I did login with admin and i did setup user “dipesh” by setting screen and getting user object in sysout of below code but still i am getting same exception. Can we setup something else like give administrator acess to scheduler.

	System.out.println("User : ------------------------------: "+ComponentAccessor.getUserManager().getUserByKey("dipesh"));

Note: The below code is working if i give create issue permission to “anyone”(according to @sfbehnke)but i don’t want as it is security issue. Do you have any other approach. My purpose is creating issue by scheduler.

Exception :
Error while creating issue: {issuetype=The issue type sele
cted is invalid., pid=Anonymous users do not have permission to create issues in this project. Please try logging in first.}

Creating Issue Code :

IssueService issueService = ComponentAccessor.getComponent(IssueService.class);
		IssueInputParameters issueInputParameters = issueService.newIssueInputParameters();
		
		
		String projectKey="IHD";
		issueInputParameters.setSummary("123"+ ":"+"Create Jira Id");
		issueInputParameters.setIssueTypeId("10000");
		issueInputParameters.setAssigneeId("admin");
		issueInputParameters.setReporterId("admin");
		issueInputParameters.setPriorityId("1");
		issueInputParameters.setDescription("Create Jira Id");
		
		ProjectService projectService = ComponentAccessor.getComponent(ProjectService.class);
		Project project = projectService.getProjectByKey(ComponentAccessor.getUserManager().getUserByKey("dipesh"), projectKey).getProject();
		issueInputParameters.setProjectId(project.getId());
		
		CreateValidationResult  createValidationResult = issueService.validateCreate(ComponentAccessor.getUserManager().getUserByKey("dipesh"), issueInputParameters);
		
		
		if (_**createValidationResult.getErrorCollection().hasAnyErrors())**_ {
			// If the validation fails, render the list of issues with the error in a flash message
			System.out.println("Error while creating issue: "+createValidationResult.getErrorCollection().getErrors());
		}

		if (createValidationResult.isValid()) {
			**IssueResult createResult = issueService.create(ComponentAccessor.getUserManager().getUserByKey("dipesh"), createValidationResult);**
			System.out.println("Issue Created. issueId: "+createResult.getIssue().getId());
		}	

Thanks Davind

Inspect the results of

ComponentAccessor.getUserManager().getUserByKey("dipesh")

If you’re seeing “Anonymous users do not have permission to create issues in this project. Please try logging in first.” then it implies that you’re passing null to the IssueService.

hi, could you let me know how you make your schedule job workd, I want read all your code about this~
does it need a xml file?

Hi @jinbasekaran,

Just use below code if you are using jira 7. You don’t need to configure anything in XML file.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.spring.scanner.annotation.export.ExportAsService;
import com.atlassian.scheduler.JobRunner;
import com.atlassian.scheduler.JobRunnerRequest;
import com.atlassian.scheduler.JobRunnerResponse;
import com.atlassian.scheduler.SchedulerService;
import com.atlassian.scheduler.SchedulerServiceException;
import com.atlassian.scheduler.config.JobConfig;
import com.atlassian.scheduler.config.JobId;
import com.atlassian.scheduler.config.JobRunnerKey;
import com.atlassian.scheduler.config.RunMode;
import com.atlassian.scheduler.config.Schedule;


@ExportAsService ({HCMScheduler.class})
@Named("MYScheduler")
public class MyScheduler implements JobRunner  {
	
	private static Logger logger = Logger.getLogger("MyScheduler");
	
	private static final JobRunnerKey JOB_RUNNER_KEY = JobRunnerKey.of(EVENT_NAME);
	
	private static final JobId JOB_ID = JobId.of(MYScheduler.class.getName());
	
	
	public MyScheduler() {
		super();
	}

	
	

	@Override
	public JobRunnerResponse runJob(JobRunnerRequest request) {
		System.out.println("MyScheduler-----------------------: ");
		
	
		
		return JobRunnerResponse.success();
	}


	
	public void registerJob(long sysFreq, String sysMetrics)  {
		
		System.out.println("MyScheduler 2-----------------------: ");
		long scheduleTime=TimeUnit.MINUTES.toMillis(1);
		
			
		
		SchedulerService scheduler = ComponentAccessor.getComponent(SchedulerService.class);
		scheduler.unregisterJobRunner(JOB_RUNNER_KEY);
		
		logger.info("Scheduling Job. Job id: "+JOB_ID);
		scheduler.registerJobRunner(JOB_RUNNER_KEY, this);
		final JobConfig jobConfig = JobConfig.forJobRunnerKey(JOB_RUNNER_KEY).withRunMode(RunMode.RUN_LOCALLY)
				.withSchedule(Schedule.forInterval(scheduleTime, null));
	
		try {
			scheduler.scheduleJob(JOB_ID, jobConfig);
		} catch (SchedulerServiceException se) {
			logger.log(Level.WARNING, se.getMessage(), se); 
		}
	}
	
	public void unrgisterJob() {
		SchedulerService scheduler = ComponentAccessor.getComponent(SchedulerService.class);
		scheduler.unregisterJobRunner(JOB_RUNNER_KEY);
		logger.info("Unrgisterd scheduler job");
	}
}

Note : Below is the another jtrick example for scheduling task . You can follow the below link for code reference.