How can I start a UiPath Robot from Groovy scripting language? - rest

How can I start a UiPath Robot from Groovy scripting language?
I have my process on UiPath Orchestrator and I want to send a set of REST API commands to the UiPath Orchestrator from Groovy to start the process.
I have read the Orchestrator documentation, but I was not able to create a working script.
The main idea for this is that after more study different software like for example Jira or Jenkins uses this Groovy language for scripting.

Here you can find a Groovy script code that starts UiPath Process on the UiPath Orchestrator:
def builder = new groovy.json.JsonBuilder();
def root = builder{
grant_type 'refresh_token'
client_id 'YOUR CLIENT ID'
refresh_token 'YOUR REFRESH TOKEN'
}
assert root instanceof Map
def link = new URL("https://account.uipath.com/oauth/token");
def connection = link.openConnection() as HttpURLConnection;
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("X-UIPATH-TenantName","YOUR TENANTNAME");
connection.setDoOutput(true);
def httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()))
httpRequestBodyWriter.write(builder)
httpRequestBodyWriter.close()
def auth = "0"
if(connection.responseCode == 200)
{
def resp = connection.inputStream.text
auth = resp.substring(resp.indexOf("access_token")+15,resp.indexOf("id_token")-3)
println resp
}
def builder2 = new groovy.json.JsonBuilder();
//process without parameters
/*def root2 = builder2.startInfo {
ReleaseKey 'YOUR PROCESS ReleaseKey'
Strategy 'All'
}*/
//process with parameters
def root2 = builder2.startInfo {
ReleaseKey 'YOUR PROCESS ReleaseKey'
Strategy 'All'
InputArguments '{"param1":"Test Youtube","param2":"GroovyConsole"}'
}
assert root2 instanceof Map
def link2 = new URL("https://platform.uipath.com/[Account Logical Name]/[Tenant Logical Name]/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs");
def connection2 = link2.openConnection() as HttpURLConnection;
connection2.setRequestProperty("Authorization",'Bearer '+auth);
connection2.setRequestProperty("Content-Type","application/json");
connection2.setRequestProperty("X-UIPATH-TenantName","YOUR TENANTNAME");
connection2.setRequestProperty("User-Agent","telnet");
connection2.setDoOutput(true);
def httpRequestBodyWriter2 = new BufferedWriter(new OutputStreamWriter(connection2.getOutputStream()))
httpRequestBodyWriter2.write(builder2)
httpRequestBodyWriter2.close()
println connection2.responseCode
println connection2.responseMessage

Related

Jmeter Groovy JavaMail API multipart add content to sample result

Looking at answers posted in Reading Emails based on recipient email id in Jmeter using groovy I actually managed to use the recipient search term.
Using the below in a JSR223 Sampler
import javax.mail.Multipart
import javax.mail.internet.MimeMultipart
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties()
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX')
inbox.open(javax.mail.Folder.READ_ONLY)
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')) // i.e. test+1#gmail.com
onlyFromGivenUser.each { message ->
if (message.getContent() instanceof Multipart) {
StringBuilder content = new StringBuilder()
def multipart = (Multipart) message.getContent()
multipart.eachWithIndex { Multipart entry, int i ->
def part = entry.getBodyPart(i)
if (part.isMimeType('text/plain')) {
content.append(part.getContent().toString())
}
}
SampleResult.setResponseData(content.toString(), 'UTF-8')
} else {
SampleResult.setResponseData(message.getContent().toString(), 'UTF-8')
}
}
This works perfectly, but fails when email is ContentType: multipart/MIXED as it does not drill down to multipart/RELATED, multipart/ALTERNATIVE and then to TEXT/PLAIN or TEXT/HTML, on which I like to do a regex on to extract a link from the body.
Guessing some counter on i is needed and an "if else", or something like mentioned here, but unsure how to convert to fit in the above script...
Any help would be much appreciated.
I stepped away from javax.mail.Multipart and javax.mail.internet.MimeMultipart and have implemented the below code in a While Controller
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties();
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX');
inbox.open(javax.mail.Folder.READ_ONLY);
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')); // i.e. test+1#gmail.com
try {
onlyToGivenUser.each { message ->
ByteArrayOutputStream emailRaw = new ByteArrayOutputStream();
message.writeTo(emailRaw);
SampleResult.setResponseData(emailRaw.toString(), 'UTF-8');
}
} catch (Exception ex) {
log.warn("Something went wrong", ex);
throw ex;
}
Hope this helps someone one day.

Gatling Sequential scenarios

I'm trying to use gatling and I have a problem.
1- I have one scenario that exec POST request for getting a list of tokens and save all tokens in csv
2- I create another scenario that exec GET request but I need a token for auth each request
My problem is before executing my first scenario my file doesn't exist and I have this following error:
Could not locate feeder file: Resource user-files/resources/token.csv not found
My code :
Scenario 1 :
val auth_app = scenario("App authentication")
.exec(http("App Authentication")
.post("/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParamSeq(Seq(("grant_type", "password"), ("client_id", clientID), ("client_secret", clientSecret)))
.check(jsonPath("$.token").saveAs("token")))
.exec(session => {
val token_data = new File(token_file_path)
if(token_data.exists()){
val writer = new PrintWriter(new FileOutputStream(new File(token_file_path), true))
writer.write(session("access_token").as[String].trim)
writer.write("\n")
writer.close()
}
else {
val writer = new PrintWriter(new FileOutputStream(new File(token_file_path), true))
writer.println("AccessToken")
writer.write(session("access_token").as[String].trim)
writer.write("\n")
writer.close()
}
session
})
Scenario 2 :
val load_catalog = scenario("Load catalog")
.exec(http("Load catalog")
.get("/list")
.headers(Map("Content-Type" -> "application/json", "Authorization Bearer" -> "${AccessToken}")))
.feed(csv(token_file_path).random)
My setup :
setUp(
auth_app.inject(atOnceUsers(10)).protocols(httpProtocol),
load_catalog.inject(nothingFor(120 seconds), atOnceUsers(10)).protocols(httpProtocol)
)
Is it possible to have a dynamic feeder with gatling ?

Save attachments from response in SoapUI

I get 2 files in response of a SOAP request. I try to save these files with followig Groovy script. I use script as a script assertion for test step. First file is saved successfully in execution, but couldn't find second one.
def fileName = "C:\\<mydirectory>"+'/test.pdf'
def fileName1 = "C:\\<mydirectory>"+'/test1.pdf'
def response = messageExchange.response
assert null != response, "response is null"
def outFile = new FileOutputStream(new File(fileName))
def outFile1 = new FileOutputStream(new File(fileName1))
def ins = messageExchange.responseAttachments[0]?.inputStream
def ins1 = messageExchange.responseAttachments[0]?.inputStream
if (ins) {
com.eviware.soapui.support.Tools.writeAll(outFile, ins)
}
ins.close()
outFile.close()
if (ins1) {
com.eviware.soapui.support.Tools.writeAll(outFile1, ins)
}
ins1.close()
outFile1.close()

How to do Rest PUT/POST in groovy

How to do HTTP PUT/POSTs from inside Groovy code without having to import any libraries (if at all possible)? I know there is a simple getText() methods that Groovy adds to the java.net.URL class, that could be used without adding any dependencies. Is there a way to do Rest PUT in the same fashion?
You can do it with HttpURLConnection in a similar way as you would do it with java:
def url = new URL('http://your_rest_endpoint')
def http = url.openConnection()
http.setDoOutput(true)
http.setRequestMethod('PUT')
http.setRequestProperty('User-agent', 'groovy script')
def out = new OutputStreamWriter(http.outputStream)
out.write('data')
out.close()
http.inputStream // read server response from it
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
url = "http://restapi3.apiary.io"
#Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient(url)
def jsonObj = new JsonSlurper().parseText('{ "title": "Pick-up posters from Post-Office" }')
def response = client.put(path: "/notes/id",
contentType: JSON,
body: jsonObj,
headers: [Accept: 'application/json'])
println("Status: " + response.status)
if (response.data) {
println("Content Type: " + response.contentType)
println("Headers: " + response.getAllHeaders())
println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}

How to test remote (production) Scalatra web service with Specs2?

I'm using Specs2 to test my Scalatra web service.
class APISpec extends ScalatraSpec {
def is = "Simple test" ^
"invalid key should return status 401" ! root401^
addServlet(new APIServlet(),"/*")
def root401 = get("/payments") {
status must_== 401
}
}
This tests the web service locally (localhost). Now I would like to perform the same tests to the production Jetty server. Ideally, I would be able to do this by only changing some URL. Is this possible at all ? Or do I have to write my own (possible duplicate) testing code for the production server?
I don't know how Scalatra manages its URLs but one thing you can do in specs2 is control parameters from the command-line:
class APISpec extends ScalatraSpec with CommandLineArguments { def is = s2"""
Simple test
invalid key should return status 401 $root401
${addServlet(new APIServlet(),s"$baseUrl/*")}
"""
def baseUrl = {
// assuming that you passed 'url www.production.com' on the command line
val args = arguments.commandLine.split(" ")
args.zip(args.drop(1)).find { case (name, value) if name == "url" => value }.
getOrElse("localhost:8080")
}
def root401 = get(s"$baseUrl/payments") {
status must_== 401
}
}