Base64 JAVA encode with dynamic values in SCALA - GATLING - java

I'm USING GATLING AND trying to use in java's library "Base64" in scala for sending encode uder:password in header ("authorization") request, with dynamic values:
I'm trying to do as follow :
val register = {
exec(request.asJSON
.check(status.is(200))
.check(jsonPath("$..user").saveAs("user"))
.check(jsonPath("$..password").saveAs("password"))
).pause(1)
}
val myvalue: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"myvalue",
login,
Map("value"-> ("Basic " + Base64.getEncoder.encodeToString((("${user}").getBytes() + ":" + ("${password}").getBytes()).getBytes("utf-8")))),
Map())
I'd tried also Base64.getEncoder.encodeToString(("${uesr}" + ":" + "${password}").getBytes("utf-8"))))
But it seems like the Base64 take the String "${user}" and not the actual value, so the encryption does not work properly.
I'd tried to :
val helper = {
exec { session =>
val user : String= (session("user").as[String])
val password : String= (session("password").as[String])
val temp = "Basic " + Base64.getEncoder.encodeToString((user + ":" + password).getBytes("utf-8"))
val temp2: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"bla",
login,
Map("value"-> temp),
Map())
val assert = {
exec(helper.asJSON
.check(status.is(200))
.check(header("answer").saveAs("answer"))
).pause(1)
}
session
}
And here the encryption works properly, but the "exec" do not.
There is a way to save the values in run time without part of the exec?

I don't know Gatling that well, but I think this should work. It's not the prettiest but without seeing the full code and how it's used it's a bit difficult to come up with something that looks good:
var token: String = null
val registerAssert = exec(...)
def finalToken = {
Utils.createPostFormParamsRequest(
"Final token",
Constants.LOGIN,
Map("Authorization"-> token),
Map())
}
def saveToken(s: Session) = {
token = "Basic " + Base64.getEncoder.encodeToString((s("uuid").as[String].getBytes() + ":" + s("secret").as[String].getBytes()).getBytes("utf-8")
s
}
// now you're actually executing the above
scenario(...)
.exec(registerAssert)
.exec(saveToken(_))
.exec(finalToken) // I'm assuming finalToken is executable
The intention of this is to first save the token value in a class variable, and then only construct the finalToken request (which uses that token) afterwards. Hence the def, and when it's called the token value will have been set.

Related

Send ICS file via SMTP not correctly displayed in Outlook?

I'm trying to send calendar invites from my backend server.
Here is the function involved :
fun sendEventInvite(to: String, subject: String, text: String) {
val message: MimeMessage = emailSender.createMimeMessage()
message.setRecipient(Message.RecipientType.TO, InternetAddress(to))
message.subject = subject
val messageBodyText = MimeBodyPart()
messageBodyText.setText(text)
val messageBodyEvent = MimeBodyPart()
messageBodyEvent.dataHandler = ByteArrayDataSource(createEvent(), "text/calendar")
val multiPart = MimeMultipart()
multiPart.addBodyPart(messageBodyEvent)
message.setContent(multiPart)
emailSender.send(message)
}
And here is how I format the ICS file:
fun createEvent(): String{
return "BEGIN:VCALENDAR\n" +
"VERSION:2.0\n" +
"PRODID:-//GRTgaz Corporation//NONSGML Togaz'er//FR\n" +
"METHOD:REQUEST\n" +
"BEGIN:VEVENT\n" +
"UID:d8f5a0777-bf6d-25d2-f14a-52e7fe3df810\n" +
"DTSTAMP:20181119T105044Z\n" +
"ORGANIZER;CN=Baptiste Arnaud:MAILTO:baptiste.arnaud95#gmail.com\n" +
"DTSTART:20181120T150000\n" +
"DTEND:20181120T153000\n" +
"SUMMARY:Description\n" +
"END:VEVENT\n" +
"END:VCALENDAR\n")
}
This file content is supposed to work because it is exactly the same of a working example. So the problem comes from mail headers ? But I'm not sure what's missing.
How it should works:
But it's displayed like this:
All of the calls to addHeaderLine are not valid MIME headers so I don't know what you're trying to accomplish with that.
The use of MimeHelper is just confusing things. Call the corresponding methods on the MimeMessage object directly, and add "text" as the first MimeBodyPart in the multipart, before the ics attachment.

How to Fetch the component id using the component Name through JIRA REST API in groovy

I am working on a script where I need to fetch the component id of all stories where Component label is R TEST 4.4 is attached using JIRA REST API in groovy for any project.
I am trying the below code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
final String USAGE =
"Usage: -Djira.username=xxx -Djira.password=xxx -Djira.Component=R TEST 4.4"
String jiraUsername = 'ABCDEF'
String jiraPassword = '**************'
String jiraComponent = 'R TEST 4.4'
println "Getting issues..."
if (!jiraUsername?.trim()) {
fail("Empty property: jira.username " + USAGE)
}
if (!jiraPassword?.trim()) {
fail("Empty property: jira.password " + USAGE)
}
if (!jiraComponent?.trim()) {
fail("Empty property: jira.component " + USAGE)
}
final String JIRA_SEARCH_URL = "https://jira.testing.com/rest/api/latest/"
// see JIRA docs about search:
// https://docs.atlassian.com/jira/REST/latest/#idp1389824
String JQL = "project = ABCD"
JQL += " AND issuetype in standardIssueTypes()"
JQL += " AND status in (Resolved, Closed)"
JQL += " AND component = \"${jiraComponent}\""
def jira = new RESTClient(JIRA_SEARCH_URL)
def query = [:]
query['os_username'] = jiraUsername
query['os_password'] = jiraPassword
query['jql'] = JQL
query['startAt'] = 0
query['maxResults'] = 1000
try {
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
resp.status == 200
(resp.data instanceof net.sf.json.JSON)
resp.data.ids.each { id ->
println id.key
}
println "Total id's: " + resp.data.total
} catch (groovyx.net.http.HttpResponseException e) {
if (e.response.status == 400) {
// HTTP 400: Bad Request, JIRA JQL error
fail("JIRA query failed: ${e.response.data}", e)
} else {
fail("Failure HTTP status ${e.response.status}", e)
}
}
But this code is giving me the below error.
groovy.lang.MissingMethodException: No signature of method: ConsoleScript5.fail() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, groovyx.net.http.HttpResponseException) values: [JIRA query failed: [errorMessages:[The value 'R TEST 4.4' does not exist for the field 'component'.], errors:[:]], ...]
Possible solutions: wait(), find(), any(), wait(long), wait(long, int), main([Ljava.lang.String;)
In JIRA UI I can see the below value of the Compoenet/s field:
M Doc, R ABC 4.3 (Early Access), R TEST 4.4
REST API URL
https://jira.testing.com/rest/api/2/component/595","id":"595","name":"R TEST 4.4"
So basically I want this id 595 wherever this R TEST 4.4 is attached.
There are a number of problems with your script, but you're almost there:
1) there is no fail method, but you call it at 2 places, you should either create one or report errors differently.
2) (at least with my Jira version) There is no property ids under resp.data. I think you want to loop on issues property.
3) Properties fixVersion and component are actually arrays (and the key names are plural)
So to fix points 2 & 3 you can do that:
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
resp.data.issues.each { issue ->
println "${issue.key} : components:${issue.fields.components*.name} + fixVersions:${issue.fields.fixVersions*.name}"
}
println "Total issues: " + resp.data.total
I'm using Groovy's spread-dot operator (*.) to get the names of components and fixVersions, because the lists are not lists of Strings, but lists of objects with a name property.
Alternatively, if you are certain there is always 0 or 1 (but not several) fixVersion, you can do that:
println "${issue.key} components: ${issue.fields.components*.name} fixVersion:${issue.fields.fixVersions[0]?.name}"
It will print null if there is no fixVersion set.

Create Release Notes using JIRA Rest API in HTML format in groovy

I am working on a script where I need to create the release notes using JIRA REST API in HTML format for any project.The below four field should come in that release notes.
Issue Key Module Summary Release Note
I am trying the below code but it is giving me only the issue Key field but need all other fields as well and in html file.Could you please suggest me on this?
Issue:1
Initially it was giving me the output in below format:
NTTB-2141
NTTB-2144
NTTB-2140
But now it is giving me the output json fromat way.
Code which I am trying from the groovy console:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
final String USAGE =
"Usage: -Djira.username=xxx -Djira.password=xxx -Djira.fixVersion=1.0"
String jiraUsername = 'ABCDEF'
String jiraPassword = '********'
String jiraFixVersion = '3.8.101'
println "Getting issues..."
if (!jiraUsername?.trim()) {
fail("Empty property: jira.username " + USAGE)
}
if (!jiraPassword?.trim()) {
fail("Empty property: jira.password " + USAGE)
}
if (!jiraFixVersion?.trim()) {
fail("Empty property: jira.fixVersion " + USAGE)
}
final String JIRA_SEARCH_URL = "https://jira.test.com/rest/api/latest/"
// see JIRA docs about search:
// https://docs.atlassian.com/jira/REST/latest/#idp1389824
String JQL = "project = NCCB"
JQL += " AND issuetype in standardIssueTypes()"
JQL += " AND status in (Resolved, Closed)"
JQL += " AND fixVersion = \"${jiraFixVersion}\""
def jira = new RESTClient(JIRA_SEARCH_URL)
def query = [:]
query['os_username'] = jiraUsername
query['os_password'] = jiraPassword
query['jql'] = JQL
query['startAt'] = 0
query['maxResults'] = 1000
try {
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
assert (resp.data instanceof net.sf.json.JSON)
resp.data.issues.each { issue ->
println issue.key
}
println "Total issues: " + resp.data.total
} catch (groovyx.net.http.HttpResponseException e) {
if (e.response.status == 400) {
// HTTP 400: Bad Request, JIRA JQL error
fail("JIRA query failed: ${e.response.data}", e)
} else {
fail("Failure HTTP status ${e.response.status}", e)
}
}
I suspect the code is right, except for that assertion:
assert (resp.data instanceof net.sf.json.JSON)
I get a groovy.json.internal.LazyMap (maybe you have changed versions of Groovy or Jira or something).
As a result, the assertion fails and Groovy tries to be helpful by giving you a comparison... but it shows you the toString() of the result, which is a huge mess of maps.
If you remove that assertion, it works for me, and I suspect it will work for you too.
Edit: huh... you cannot literally take "all" data and print to html. You will have to select the properties you need, and those depend on your Jira configuration. Here is an example with only 2 properties that should be universal:
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
def output = new File('issues.html')
output << "<html><body><ul>"
resp.data.issues.each { issue ->
def url = "https://yourjirainstance/browse/${issue.key}"
output << "<li>${issue.key}: ${issue.fields.summary}</li>"
}
output << "</ul></body></html>"
println "Exported ${resp.data.total} issues to ${output.name}"
See here details about what the service will give you.
If you just want an HTML dump, maybe the REST API is not what you want: you can also ask Jira to export results of JQL as a printable output (that will actually be html).

Scala - Send Multiple Headers with scalaj.http.Http

I am making a post request with the libraries listed below. It seems like my last header is being cut off. Ive tried the following two ways but neither seems to be working.
import scalaj.http._
import scalaj.http.Http
var result = Http("https://example.com" + Key + "/rowset")
.postData(jsonOutput)
.headers(Seq("Authorization" -> ("Bearer " + accessToken)))
.headers(Seq("content-Type" -> "application/json"))
var result = Http("https://example.com" + Key + "/rowset")
.postData(jsonOutput)
.headers(Seq("Authorization" -> ("Bearer " + accessToken), "content-Type" -> "application/json"))
Just to check; you are doing something with the result variable? It is still just a request and will remain so until you call i.e. result.asString which will execute the request and return the response (HttpResponse[String] in case of asString).

Jsoup transform my javascript string into a single line

I am having trouble with the .append function in Jsoup. I am appending my simple Javascript file response string to a Jsoup Element. But after appending my response transforms into a single line which is hurting me a lot.
My string is like this
(function () {
var count = 0;
var root = this;
var require = root.require;
//var require = cordova.require;
require.config({
config: {
text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications
useXhr: function (url, protocol, hostname, port) {
//console.log("text.useXhr request came from : " + url + ", " + protocol + " and " + hostname);
return true;
//return true if you want to allow this url, given that the
//text plugin thinks the request is coming from protocol, hostname, port.
}
},
'is': {
isBundled: true
}
},
waitSeconds: 45,
baseUrl: 'scripts/app',
deps: ["app"],
BUt after appending to a Element it will become
(function () { var count = 0; var root = this; var require = root.require; //var require = cordova.require; require.config({ config: { text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications useXhr: function (url, protocol, hostname, port) { //console.log("text.useXhr request came from : " +
My Code is for this
String temp=script.attr("src");
temp=temp.replace("/"+Heirarchy, DomainName+"/"+Heirarchy.toLowerCase());
script.attr("src", temp);
script.removeAttr("data-main");
script.removeAttr("async");
String innerHtml="</script>\n<script>\n"+old_configString;
script.append(innerHtml);
old_configString is my Javascript response String....
You should use a DataNode for adding scripts or styles.
script.after(new DataNode("<script>" + old_configString + "</script>", "http://domain.tld/path"));

Categories

Resources