Versions Compared
Key
- This line was added.
- This line was removed.
- Formatting was changed.
Writing the Apex Class
This webservice can be called from within Apex Class. This example will guide you on how to call "create" API.
Before you write Apex code that calls remote URL, you have to allow salesforce to make a call to external server.
- Log in to Salesforce.com.
- Go to Your Name > Setup > Administration Setup > Security Controls > Remote Site Settings.
- Add new remote site.
- Enter the name of remote site.
- Enter your JIRA URL in Remote Site URL, e.g., http://yourjiraurl.com/
- Click Save.
Once you are done, you can start writing the code. Here are the steps to write Salesforce Apex Class.
- Log in to Salesforce.com.
- Go to Setup > App Setup > Develop > Apex Classes > New
Paste this code into the field:
Code Block language java global class JIRAConnectorWebserviceCalloutCreate { @future (callout=true) WebService static void createIssue( String jiraURLbaseUrl, String systemId, String objectType, String objectId, String projectKey, String issueType) { try { HttpRequest req //Set your username and password here= buildRequest(baseUrl, JIRA.username, JIRA.password, systemId, objectType, objectId, projectKey, issueType); String username = 'yourJIRAusername'; JIRA.sendRequest(req); } catch(System.CalloutException e) { String password = 'yourJIRApassword'; System.debug(e); } } //Construct HTTPConstructs request needed to andcreate responsea JIRA issue from provided parameters. HttpRequest req@testVisible =private newstatic HttpRequest(); buildRequest(String baseUrl, String username, String password, HttpResponse res = new HttpResponse(); Http http = new Http(); String systemId, String objectType, String objectId, //Construct Authorization and Content header Blob headerValue = Blob.valueOf(username+':'+password); String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue); req.setHeader('Authorization', authorizationHeader);String projectKey, String issueType) { HttpRequest req.setHeader('Content-Type','application/json'); = new HttpRequest(); String basicAuthHeader //Construct Endpoint= JIRA.authHeader(username, password); String endpoint = jiraURL+'/rest/customware/connector/1.0/'+systemId+'/'+objectType+'/'+objectId+'/issue/create.json'getEndpoint(baseUrl, systemId, objectType, objectId); //Set Method and Endpoint and Bodyreq.setHeader('Authorization', basicAuthHeader); req.setHeader('Content-Type','application/json'); req.setMethod('POST'); req.setEndpoint(endpoint); req.setBody('{"project":"' + projectKey + '", "issueType":"' + issueType + '"}'); return tryreq; { } // Creates //Sendthe endpoint to JIRAcreate the issue from provided parameters. private static res = http.send(req); } catch(System.CalloutException e) {String getEndpoint(String baseUrl, String systemId, String objectType, String objectId) { return baseUrl + '/rest/customware/connector/1.0/' + systemId + System.debug(res.toString()); } '/' + objectType + '/' + objectId + '/issue/create.json'; } }
Warning Copying the above code and pasting it directly into the field may result in additional, unwanted characters being included. To avoid this from happening, we recommend pasting the code into a text editor that accepts plain text (e.g. Notepad.exe) and then recopying it again before pasting it into the field.
Change the variables accordingly:
Variables
Details
username
Your JIRA username
Your JIRA passwordpassword
- Click Save.
Warning | ||
---|---|---|
| ||
Please use this class with care. It can cause an infinite loop of Issue and Case creation if it conflicts with the JIRA Push to Remote System workflow. |
The Usage of Written Class
Now that the class is ready to be used and it can be called in various ways including:
- From within a Trigger.
- From Create JIRA Issue button, as a replacement of Configuring a JIRA Issue Creation Button.
Trigger
Salesforce Trigger can be used to automate the creation of JIRA issue. It is event-based process similar to JIRA workflow, yet more flexible.
In this example, we want to automate JIRA issue creation when Case is created:
Warning | ||
---|---|---|
| ||
You will NEED to create a custom profile called "JIRA Agent" in Salesforce.com to avoid causing an infinite loop. Then assign a user to that profile and block it to execute the trigger. This way, any cases created from JIRA will not trigger creation of more issues back to JIRA. |
First, create custom profile called 'JIRA Agent':
- Log in to Salesforce.com.
- Go to Setup > Administration Setup > Manage Users > Profiles > New Profile.
- Choose 'Existing Profile' to be: Custom: Support Profile.
- Fill in 'Profile Name' with : JIRA Agent.
Click Save.
Note title "CUSTOM: SUPPORT PROFILE" NOT AVAILABLE? Your version of Salesforce may not have the Custom: Support Profile option.
If so, you can create a new profile or clone from any existing profile. But please make sure that the profile has Read, Edit and Create permissions for the relevant object.
Second, assign the created profile to specific user that will be used in JIRA Connector:
- Go to Setup > Administration Setup > Manage Users > Users.
- Create/Edit the user that is used as JIRA agent.
- Use the created profile as profile of the user.
Click Save.
Warning title WARNING Make sure that this user is used in Application Links authentication in JIRA.
Third, add Trigger code to Case Trigger.
- Write Apex Class as described above
- Go to Setup > Application Setup > Customize > Cases > Triggers.
Create New Trigger and replace the code with:
Code Block trigger CreateIssue on Case (after insert) { //Identify profileCheck namewhether tocurrent beuser blockedis fromnot executingJIRA thisagent triggerso that String JIRAAgentProfileName = 'JIRA Agent'; List<Profile> p = [SELECT Id FROM Profile WHERE Name=:JIRAAgentProfileName]; //Check if specified Profile Name exist or not if(!p.isEmpty()) { //Check if current user's profile is catergorized in the blocked profile if(UserInfo.getProfileId()!= String.valueOf(p[0].id)) we don't create an infinite loop. if (JIRA.currentUserIsNotJiraAgent()) { for (Case c : Trigger.new) { // Define parameters to be used in calling Apex Class String jiraURLobjectType = 'http://jira.example.com'; String systemId = '4'; //Please change this accordingly to the configuration in JIRA String objectType ='Case'; //'CASE'; // Please change this accordinglyaccording to the configuration in JIRA object type String objectId = c.id; String projectKey = 'SFDC'; //Please change this accordingly to the configuration in JIRA String issueType = '1'; //Please change this accordingly to the configuration in JIRA //Execute Calls the triggeractual callout to create the JIRA issue. JIRAConnectorWebserviceCalloutCreate.createIssue(jiraURLJIRA.baseUrl, JIRA.systemId, ,objectType, objectId, projectKey, issueType); } } } }
Warning Copying the above code and pasting it directly into the field may result in additional, unwanted characters being included. To avoid this from happening, we recommend pasting the code into a text editor that accepts plain text (e.g. Notepad.exe) and then recopying it again before pasting it into the field.
Change the variables accordingly:
Variables
Details
jiraURL Your JIRA URL systemId
Your system Id in Connection. You should check this in JIRA under Connection objectType
Salesforce object that is used in Connection. In our example, it is Case
objectId
The id of the object. It varies in every operation. Therefore, it should be object.id
projectKey
Under which JIRA Project you want to create the issue.
issueType
standard JIRA issue type values range from '1' to '4' . '1' is for Bug and so on
- Click Save
Now you are ready to use the trigger.
Try out:
Create Case in Salesforce as normal user and check if JIRA Issue is created.
Button
Other than trigger, you can use the written Apex class for button. Using this method, you can eliminate some processes, including:
- The required Login page
- The prompt page of choosing Project and Issue type.
Steps:
- Write Apex Class as in above
Then, you can follow the steps in Configuring JIRA Issue Creation Button to create a button, there are slight changes in Step 8:
Label
Create JIRA Issue
Name
Create_JIRA_Issue (this is auto-populated when you add a new label)
Display Type
Detail Page Button
Behaviour
Execute Javascript
Content Source
On Click Javascript
Content
Code Block {!REQUIRESCRIPT("/soap/ajax/1029.0/connection.js")} {!REQUIRESCRIPT("/soap/ajax/1029.0/apex.js")} sforce.apex.execute("JIRAConnectorWebserviceCalloutCreate","createIssue", {jiraURLbaseUrl:"http://jira.example.com" , systemId: "41" , objectType: "Case", objectId:"{!Case.Id}", projectKey:"SFDC", issueType:"1"}); window.alert("JIRA Issue should be created.");
Change the variables accordingly:
Variables
Details
jiraURL baseUrl
Your JIRA URL
systemId
Your system Id in Connection. You should check this in JIRA under Connection
objectType
Salesforce object that is used in Connection. In our example, it is Case
objectId
The id of the object. It varies in every operation. Therefore, it should be object.id
projectKey
Under which JIRA Project you want to create the issue.
issueType
standard JIRA issue type values range from '1' to '4' . '1' is for Bug and so on
Now you are ready to test:
- Create new Case in JIRA.
- Click on Create JIRA Issue button.
- Till you see the pop up says: JIRA Issue should be created.
- Check your JIRA if the issue is created.
Panel | ||||
---|---|---|---|---|
| ||||
|
Warning |
---|
This setup can only be used if your JIRA instance is NOT behind a firewall. |
Unit
Test for Create EndpointEnter your code here:
language | java |
---|
Testing
Code Block |
---|
@isTest private class JIRAConnectorWebserviceCalloutCreateTest {
// Tests createIssue method in JIRAConnectorWebserviceCalloutCreate.
static testMethod void createIssueTest() {
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseJIRAConnector());
JIRAConnectorWebserviceCalloutCreate.createIssue(TestFixture.baseUrl, TestFixture.systemId,
TestFixture.objectType, TestFixture.objectId, TestFixture.projectKey, TestFixture.issueType);
Test.stopTest();
}
// Tests buildRequest method in JIRAConnectorWebserviceCalloutCreate.
static testMethod void buildRequestTest() {
HttpRequest req = JIRAConnectorWebserviceCalloutCreate.buildRequest(TestFixture.baseUrl, TestFixture.username,
TestFixture.password, TestFixture.systemId, TestFixture.objectType, TestFixture.objectId,
TestFixture.projectKey, TestFixture.issueType);
System.assertEquals(req.getMethod(), 'POST');
System.assertEquals(req.getEndpoint(), 'http://jira.com/rest/customware/connector/1.0/1/Case/1/issue/create.json');
}
} |