I'm very new to JMeter and need your help on how to modify a cookie.
Here is the scenario:
I'm testing an assessment/test taking website that offers multiple answers to questions. When a user makes his selections and hits the submit button, the JavaScript in the page appends his answers (e.g., "Answers = BBAACDA...") to the cookie and makes the next GET request (instead of a POST request!).
Since, JMeter does not execute JavaScript (as popularly mentioned in its manual - it's not a browser), it cannot append the answers to the cookie. As a result, my test plan fails to recognize user interaction.
How can I add/append/modify a dynamic cookie? Thanks in advance!
--Ishti
Use a Beanshell pre-processor or better a Jsr223 Pre-Processor with groovy and use code mentionned here:
http://javaworks.wordpress.com/2011/08/05/setting-cookie-in-jmeter/
Code:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = sampler.getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<HOST>","/",false,0);
manager.add(cookie);
I had to implement some changes in the code that worked for me:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<DOMAIN>","<PATH>",false,0, true, true, 0);
manager.add(cookie);
Following the definition in http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie.html
It is possible to modify or add a cookie manually in a groovy pre-processor script in the same way as https://stackoverflow.com/a/38505077/5747304.
Here's how to find and edit a cookie by browsing all cookies in the cookie manager:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
log.info("#########################################################################");
// cookie manager
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
def NbOfCookies = manager.getCookieCount();
for (def i = 0; i < NbOfCookies; i++) {
log.info("Cookie n° " + (i+1) + ": " + manager.get(i).getName() + ": " + manager.get(i).getValue());
if (manager.get(i).getName() == "Cookie_name_to_find") {
log.info("MAJ of Cookie_name_to_find");
manager.get(i).setValue("New_cookie_value");
log.info("-> " + manager.get(i).getName() + ": " + manager.get(i).getValue());
}
}
log.info("#########################################################################");
Here is the list of cookie manager methods like add or delete ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/CookieManager.html.
Here is the list of cookie methods to modify more properties like the domain, its expiration date ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie .html
It should be known that according to the standart chosen in the cookie manager, the manually modified values can still be modified by the manager before the request so you have to be careful.
Related
Could you help me do the task using JavaScript?
I have a task and if i do it manually it looks like this:
i create Saved Search in NetSuite.
Download the result of created saved search in csv.
The i put this file on ftp server, using FileZilla. (i had a connection with server previously: write a domain, username and password - that's all)
Now, a need it solve through sutlet script.
1. Create Saved Search - done
2. Create csv with result of saved search in content and put it in file cabinet in the NetSuite - done
3. Ok, now i have a needs me file but i do not understand how to pass it on ftp.
*i tried to study several articles, but frankly speaking could not to solve my problem. Moreover, their article seems about manually method not automative
this aritcle - https://ursuscode.com/netsuite-tips/suitescript-2-0-sftp-tool/*
var searchResult = Contacts.run().getRange(0,999);
log.debug('Contacts', searchResult);
var Header = 'INTERNAL ID' + ';' + 'FIRST NAME' + ';' + 'LAST NAME';
var Content = "";
for (var i = 0; i < searchResult.length; i++) {
var internalid = searchResult[i].getValue('internalid');
var FirstName = searchResult[i].getValue('firstname');
var LastName = searchResult[i].getValue('lastname');
Content = Content + internalid + ';'
+ FirstName + ';'
+ LastName;
Content = Content + '\n';
}
var fileObj = file.create({
name: 'test.csv',
fileType: file.Type.CSV,
contents: Header + '\n' + Content
});
fileObj.folder = 45434;
var fileId = fileObj.save();
var savedFileObj = file.load({
id: fileId
});
var myPwGuid = '';
var myHostKey = ''
var objConnection = sftp.createConnection({
username: '',
passwordGuid: myPwGuid,
url: 'ftp.expertsender.com',
hostKey: myHostKey
});
NetSuite does not support ftp, it only supports sftp.
NetSuite has the support for SFTP, FTP and SFTP runs in different port numbers, However FTP transfers data in plain text format which will compromise your security, using SFTP is the better option as it will transfer your data in encrypted format and security is assured.
In your example, I believe you're calling FTP request which will not work in this case.
Oki,
Now, the article you did mention is the right one : why ? Because the first required step to be able to use SFTP is to generate a GUID. You are talking about manual methods, well yes, including the one in that Article, but it is not a problem, because once you have generated the GUID, you don't need to change it, so it is a one time action, unless your ftp credential change.
So, first step : use "ursuscode" to create a Suitelet. Deploy that suitelet and use it to generate the GUID (it is a form where you need to set the ftp password, host...). Using the same form, you can then generate the HOST key (check the video).
Second step, use the Generated GUID and HOST Key in your code.
Third step, add the code to upload the file : from netsuite help page, here is an example:
connection.upload({
directory: 'relative/path/to/remote/dir',
filename: 'newFileNameOnServer.js',
file: myFileToUpload,
replaceExisting: true
});
By the way, you can upload the file without the need to Save and Reload it again (https://system.na2.netsuite.com/app/help/helpcenter.nl?fid=section_4617004932.html).
Note: remember that this is an SFTP, so probably support only SFTP not FTP.
Suggestion: About the GUID (and the other data needed for the connection), I suggest that you use a Script Parameter to provide the GUID to your script code, so if your password change, you can regenerate the GUID and update the script parameter value without the need to touch your code.
Hope this helps!
I've created a cookie in Scala, which I would like Javascript to be able to delete and/or modify.
Here is how I created the cookie in Scala ensuring the httpOnly param is set to false: (
Sticky Cookies in Scala
)
I used the following method to delete the cookie in JavaScript, but the cookie does not delete.
( javascript - delete cookie )
Aside from attempting to delete the cookie, it doesn't seem like I can modify the contents of the cookie either.
How can I ensure the JavaScript can modify and delete the cookie created in Scala?
I fixed the issue.
I had to ensure that both the cookie created in Scala and the one deleted/modified in JavaScript both had the same path.
For example, in Scala:
new Cookie(sCookieID, sValue, Option(nSecondsExpire), "/", scala.None, false, false)
In JavaScript:
document.cookie = sCookieID + "=" + sValue+ "; " + sExpire + "; path=/";
Notice the path in both examples used "/". Once I used the same path, I was able to delete/modify the cookies in JavaScript. Before this I hadn't explicitly set the path in the JavaScript code.
Ok, so I'm learning web design as a co-op at a company. However, the department I'm in is lacking in knowledgeable people in web design. So here we go...
Building a site that will allow the department to manage PTO. I want to implement ajax b/c the main page will have a calendar system so the manager can view the PTO week by week. As a precursor to that, I'm attempting to implement ajax with the "add Employee" page for practice.
However, I can't seem to figure out what I'm missing (aka, why it's not doing anything)
This page just needs to add the new employee to the database. No display needed.
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
Simple enough so far.
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
This is the part where I'm assuming it's correct as I'm still learning ajax and how it works. I don't think I need to handle a response as I simply want the called jsp file to automatically do whats needed. (if that's possible).
The jsp file looks like this
<%
ResultSet rsEmpl;
Connection connection1 = getDBConnection();
Statement statment1=connection1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String fName = request.getParameter("firstNameField");
String lName = request.getParameter("lastNameField");
String manager = request.getParameter("managerField");
String networkID = request.getParameter("networkIDField");
Int empId = 0;
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
%>
I have a button on the page that executes the javascript function that contains the ajax info. I'm avoiding jquery atm b/c I'm trying to understand this stuff and how it works before I attempt to use "shortcuts" like jquery. I'm working towards a degree in Software Engineering so understanding this stuff is my priority, not getting it done.(that's just a bonus) If you need anymore information I can provide it. Sorry for my lack of knowledge and if this is completely off base then :(
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
That gives you whole HTML DOM elements back, not the values of those elements. HTML DOM elements are like Java classes, having properties, methods and so on. Assuming that it are HTML input elements like <input>, then use their value property instead to get the value. So:
var firstName = document.getElementById("firstNameField").value;
var lastName = document.getElementById("lastNameField").value;
var manager = document.getElementById("managerField").value;
var networkID = document.getElementById("networkIDField").value;
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
The escape() is the wrong function. It escapes JS syntax, it does not encode URI components. You should be using encodeURIComponent() function instead.
The jsp file looks like this
...
Int empId = 0;
...
This doesn't compile. It should be int instead.
...
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
...
Unnecessarily overcomplicated. Learn how to use DB builtin sequences/autoincrement IDs. Refer the DB specific manual or ask DB admin for help.
...
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
...
You should put quotes around string values in the SQL query. Assuming that lName, fName and networkID are strings, not numbers, then it should look like this:
statement1.execute("INSERT INTO PTO_employee VALUES (" + empID + ",'" + lName + "','" + fName + "'," + 0 + "," + 2 + ",'" + networkID + "'");
But you have there a huge SQL injection attack hole and you also don't seem to close DB resources at all after use, so they may leak away and cause your webapp to crash sooner or later because the DB runs out of resources. Use PreparedStatement to create a parameterized SQL query and use its setters to set the values. Close the resources in finally block.
After all, reading the server logs should provide you information about compile errors and any server exceptions. Reading the ajax response should provide you information about the response status and body. Your core problem was that you ignored it and thus didn't have any chance to understand what is happening.
There is a cool Firefox extension which lets you export all cookies to a Netscape HTTP Cookies File, cookies.txt, which you can then use with wget (et.al.)
Here is an example cookies.txt file for the happycog.com site:
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_visit 998800044
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_activity 1314160044
How can I build the same style "cookies export" with Javascript? Granted it would only be able to read cookies for the current domain. That would be just fine.
Additional Details:
I realize that cookies can't be exported to the file system with pure javascript. I'd be happy with them being exported to a textarea, or with document.write. I just want to know how I can get them in the same format where I can basically copy and paste them to a cookies.txt file. The challenge here is to do it with javascript, though, and not to use an addon.
var cookieData = document.cookie.split(';').map(function(c) {
var i = c.indexOf('=');
return [c.substring(0, i), c.substring(i + 1)];
});
copy(JSON.stringify(JSON.stringify(cookieData)));
This will export your cookies into an array of key/value pairs (eg. [ [key1, val1], [key2, val2], ...]), and then copy it to your clipboard. It will not retain any expiration date info because that's impossible to extract via Javascript.
To import the cookies back, you'd run the following code:
var cookieData = JSON.parse(/*Paste cookie data string from clipboard*/);
cookieData.forEach(function (arr) {
document.cookie = arr[0] + '=' + arr[1];
});
Sorry about the delayed response - had to sleep. I have just been playing with this and concluded that the answer is NO.
The reason for this is that Javascript does not have access to any more information than the cookie's name and value, you can't retrieve the path, expiry time, etc etc. What do you actually want to do? Is this for one specific site you are developing or just for general use when browsing?
All cookies for the page is stored in document.cookie
Is it possible to query AD from javascript?
I'm working from within SharePoint, and I can get the current SharePoint user's information using some js I found on a blog.
But I'm wondering if I can then query AD to see if the current user is in a specific AD group.
I think you'd be better off writing a quick asp.net page that you could call via AJAX and get some JSON back. .NET directory services class are going to be much better at talking to Active Directory than javascript, unless you can find a js library specifically for this (which I haven't been able to find).
This is a little late, but for future visitors from Google, I had to write something in JavaScript to fix a scheduled task that is run with cscript:
var conn = WScript.CreateObject("ADODB.Connection")
var rootDSE = GetObject("LDAP://RootDSE");
var context = rootDSE.Get("defaultNamingContext");
conn.Provider = "ADsDSOObject";
conn.Open("ADs Provider");
var query = "<LDAP://" + context + ">;(&(objectCategory=person)(objectClass=user));samAccountName;subtree";
var cmd = WScript.CreateObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = query;
cmd.Properties.Item("SearchScope") = 2;
cmd.Properties.Item("Page Size") = 500;
var r = cmd.Execute();
while(!r.EOF)
{
for (var e=new Enumerator(r.Fields);!e.atEnd();e.moveNext())
{
WScript.Stdout.Write(e.Item().name + "=" + e.Item().value + " ");
}
WScript.Stdout.WriteLine("");
r.MoveNext();
}
There is no way known to me how one could access AD from a client script. I could only think of some kind of an ActiveX control which does the job, however that 1) would work only in IE 2) would also be limited to zone settings in IE.
So, the reason is why you need this. Most probably, to be able to show the user something or hide something from the user. If this is the case, you could think of applying the "target audiences" solution to your page (see here - http://office.microsoft.com/en-us/sharepointserver/HA101690531033.aspx). For instance, add two versions of your webpart to the page, one for users who are in the group and another for users who aren't.
If you really need to have this information on the client side in JS, you can create some "AD helper" web service on your server and call into that service using AJAX, as per #squillman's post.