how to get the path of cookies using ssjs? - cookies

I am trying to get the path of a cookie
I have several cookies with the same name but with different paths.
The following example return null using the getpath() method
var request = facesContext.getExternalContext().getRequest();
var cookies = request.getCookies();
print(cookies[1].getName()))
print(cookies[1].getPath()))
I also tried the global object "cookie" in xpages but how do I get the path from that?
How can I get the path of all the cookies using ssjs?

You can't. Googled a bit. Seems to be a common problem beyond Domino and XPages. Both getDomain and getPath return null, because browser does not send it to the server. Explained here getDomain() of javax.servlet.http.Cookie is returning null
Also a short thought here https://coderanch.com/t/283519/java/Cookie-getDomain-returns-null that it may be security feature.

Both ways of getting a cookie return a java.servlet.http.Cookie, which does have the getPath() method, which you're using. Are you sure the path is getting set? Looking at an POST request from an XPage (both via the servlet it's calling and FireBug), the DomAuthSessId and SessionID cookies don't have a path set, so getPath() returns null.

Related

How to get CookieManager from JMeter SampleResult

I have a backend listener that posts JMeter results to an external server. It works for most parts. However, I'd like to get cookie info for failed requests. Backend listener only gets SampleResult and I don't see an API to access cookie info from SampleResult. Does anyone have an idea?
View Result Tree listener is able to print out request cookies, so there must be a way. However, it's not obvious what's the class name for that particular listener. If anyone can point me to that source code, it'll be a starting point.
With current JMeter implementation it is not possible unless your create your own AbstractBackendListenerClient implementation which will be cookies-aware.
Also depending on how do you parse result you can substitute a "not interesting" SampleResult field (for example Response Message) with cookie values for failed requests. It can be done using i.e. JSR223 PostProcessor and the following Groovy code
if (!prev.isSuccessful()) {
def manager = sampler.getCookieManager()
def cookies = new StringBuilder()
for (int i = 0; i < manager.getCookieCount(); i++) {
cookies.append(manager.get(i).getName()).append('=').append(manager.get(i).getValue())
}
prev.setResponseMessage(cookies.toString())
}
Hard to help without seeing some code, but one general direction could be this: you can check if your SampleResult is of type HTTPSampleResult, and if yes, get its cookies, using getCookies() method. Whole process could be wrapped as the following function:
public String getCookiesForHttpResult(SampleResult sampleResult) {
if (sampleResult instanceof HTTPSampleResult) {
HTTPSampleResult httpSampleResult = (HTTPSampleResult) sampleResult;
return httpSampleResult.getCookies();
}
// not HTTP result
return null;
}
Something like that is done in JMeter's RequestViewHTTP.java
Getting CookieManager in backend listener can be problematic, since it's mutable: by the time backend listener reads from CookieManager, list of cookies may be different from the time of request execution.

JMeter - Verify a Specific Cookie Value was Used?

So in my Test Plan I have a Cookie Manager setup inside my Thread Group which sets a specific Cookie value for 1 Cookie. Let's call it, MYID. I'm trying to figure out a way to verify that this specific Cookie's value was used to complete this one HTTP Request, because if I set my MYID to a specific value *(which actually tells which web server to go to), say to "Server1", but Server1 is down, unavailable, etc... HAProxy should change this and send you to Server2.
So basically I want to try and make sure that Cookie MYID was equal to "Server1" all the way through the HTTP Request.
I am trying to use a BeanShell PostProcessor to verify the Cookie's value after the request is ran, but when I tried using some code I have inside a PreProcessor that sets a cookie in a different Test Plan of mine I get an error saying:
Error Message:
Typed variable declaration : Attempt to resolve method: getCookieManager() on undefined variable or class name: sampler
And below here is the Code slightly modified from a BeanShell PreProcessor in another Test Plan I have...
CODE:
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
CookieManager manager = sampler.getCookieManager();
for (int i = 0; i < manager.getCookieCount(); i++) {
Cookie cookie = manager.get(i);
if (cookie.getName().equals("MYID")) {
if (cookie.getValue().equals("Server1")) {
log.info("OK: The Cookie contained the Correct Server Number...");
} else {
log.info("ERROR: The Cookie did NOT contain the Correct Server Number...");
}
break;
}
}
For the error, I was thinking the "sampler" object was no longer available since the Request was already run, or something along those lines, but I'm not sure...
Or, is there another JMeter object I should be using instead of the "BeanShell PostProcessor" in order to verify the Cookie's value was correct..?
Any thoughts or suggestion would be greatly appreciated!
Thanks in Advance,
Matt
If you trying to get cookie manager from the parent sampler in the Beanshell PostProcessor - you need to use ctx.getCurrentSampler(), not "sampler" as it is not exposed in script variables.
So just change this line:
CookieManager manager = sampler.getCookieManager();
to
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
And your script should start working as you expect.
ctx is a shorthand to JMeterContext instance and getCurrentSampler() method name is self-explanatory.
For more information on Beanshell scripting check out How to use BeanShell: JMeter's favorite built-in component guide.

Peoplecode - how to create cookies?

We are trying to create a cookie in the PeopleSoft Peoplecode by using the %Response object.
However, the code we tried is failing.
&YourCookie = %Response.AddCookie("YourCookieName", "LR");
Another snippet we tried to create the cookie
Local object &Response = %Response;
Local object &YourCookie;
&YourCookie = &Response.CreateCookie("YourCookieName");
&YourCookie.Domain = %Request.AuthTokenDomain;
&YourCookie.MaxAge = -1; /* Makes this a session cookie (default) */
&YourCookie.Path = "/";
&YourCookie.Secure = True; /* Set to true if using https (will still work with http) */
&YourCookie.Value = "Set the cookie value here. Encrypt sensitive information.";
The document reference points to IScript functions called CreateCookie methods etc.
http://docs.oracle.com/cd/E15645_01/pt850pbr0/eng/psbooks/tpcr/chapter.htm?File=tpcr/htm/tpcr21.htm
However, these don't work in Peoplecode. We don't have the knowledge to create IScript or use it. Any insight with the People code API for cookies or IScript is much appreciated.
I just tested on PeopleTools 8.54.11 and was able to create a cookie using the snippet you provided above.
I did find I had an issue if I set
&YourCookie.Secure = True;
in an environment where I was using HTTP.
If you set Secure to False the cookie will be available in both HTTP and HTTPS
if you set Secure to True the cookie is only available in HTTPS
PeopleTools 8.54 Documentation showing the CreateCookie method
I have been trying to do this (same code snippet) from within signon peoplecode, tools release is 8.54.09. I can execute the first two lines of code, but as soon as the line of code executing the CreateCookie() method executes, I get tossed out / end up on the signon error page.
This seems to support the previous answer saying that the API has removed the method, but the answer before that says it has been successful on tools 8.54.11 -- does that mean they removed it, then put it back, and I happen to be stuck with a release where it was removed? :-/

Redirecting root context path or binding it to a servlet or mapping it with a welcome-file

I am using Jetty-9 in embedded mode and need only one web application. Consequently I would like the root URL to go to the homepage of that application, i.e. something like
http://localhost:4444/
should end up in a servlet. I start out with:
ServletContextHandler scContext =
new ServletContextHandler(ServletContextHandler.SESSIONS);
scContext.setContextPath("/");
None of the following worked, neither
scContext.addServlet(ListsServlet.class, "/");
nor
scContext.setWelcomeFiles(new String[]{"/lists})
where /lists is mapped to the ListsServlet servlet. All I get is a 403 (Forbidden).
I do not use the DefaultServlet, which seems to handle welcome files. But since the ServletContextHandler has setWelcomeFiles I expected it to contain the logic to use them.
Any ideas?
For the 403 Forbidden error, you have some security setup that is not allowing you to access the handlers/servlets.
Eliminate that security (for now), verify that the rest is working, then add security a bit later to lock down specifics.
If you want to see some the suggestions below at work, consider looking at the code example in the answer from another stackoverflow: How to correctly support html5 <video> sources with jetty.
Welcome files are appended to the incoming request path if there is nothing present at that location. For example requesting a directory and then a welcome-file of 'index.html' is appended to the request path.
While this would work ...
scContext.setWelcomeFiles(new String[]{"lists"})
// Add Default Servlet (must be named "default")
ServletHolder holderDefault = new ServletHolder("default",DefaultServlet.class);
holderDefault.setInitParameter("resourceBase",baseDir.getAbsolutePath());
holderDefault.setInitParameter("dirAllowed","true");
holderDefault.setInitParameter("welcomeServlets","true");
holderDefault.setInitParameter("redirectWelcome","true");
scContext.addServlet(holderDefault,"/");
It's likely not what you are aiming for, as you said the root path only.
The above would also make changes to requests like /foo/ to /foo/lists
Instead, it might make more sense to use a Rewrite rule + handler instead of the welcome-files approach.
RewriteHandler rewrite = new RewriteHandler();
rewrite.setHandler(scContext);
RewritePatternRule rootRule = new RewritePatternRule();
rootRule.setPattern("/");
rootRule.setReplacement("/list");
rootRule.setTerminating(true);
rewrite.addRule(rootRule);
server.setHandler(rewrite);
This RewritePatternRule simply changes any request path / to /list and then forwards that request to the wrapped ssContext (if you want to see the /list on the browser, change it to a RedirectPatternRule instead.

Where are the cookies stored?

I am sending a HTTPWebRequest from C# code and in response I am getting a cookie containing session ID. I am not able to locate the cookie in the public/non public members of response. However fiddler is capturing the cookie and its path is "/". Can anyone please tell me where should I look for this cookie? I have checked the folder "C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Cookies" and its not there.
Cookies may be physically stored in different locations, depending on the browser.
I think you're better off getting the HttpWebRequest working with cookies.
See the answer to this question regarding adding a CookieContainer to the request object.
Every browser store cookies onto different locations
For example
Cookie information is stored in the profile folder, in two files.
Starting with Firefox 3.0 and SeaMonkey 2.0 the cookie information is
stored in the files cookies.sqlite and permissions.sqlite. In Firefox
2 or below and Mozilla Suite/SeaMonkey 1.x, cookies are stored in the
cookies.txt file and cookie site permissions are stored in the
hostperm.1 file. File Description cookies.sqlite cookies.txt Holds
all of your cookies, including login information, session data, and
preferences. permissions.sqlite hostperm.1 Holds preferences about
which sites you allow or prohibit to set cookies, to display images,
to open popup windows and to initiate extensions installation.
Cookie storage depends on both your browser and OS. In older browsers, they were just stored in a file path named something like "Cookies". Most modern browsers store cookies in some encrypted way, usually in a sqllite db flat file. If you could provide more info on what you are trying to track down via the actual local cookie storage (as opposed to using the browser's built in cookie browser), it would help get more info on where to look or alternatives for what you have in mind.
If you want to use persistent cookies with HttpWebRequest, you'll need to import wininet.dll to handle this (or you handle persistence yourself).
There's an example on MSDN in the Community Content section for WebRequest.Create Method.
snippet
[DllImport("wininet.dll", CharSet=CharSet.Auto , SetLastError=true)]
private static extern bool InternetGetCookie (string url, string name, StringBuilder data, ref int dataSize);
private static string RetrieveIECookiesForUrl(string url)
{
StringBuilder cookieHeader = new StringBuilder(new String(' ', 256), 256);
int datasize = cookieHeader.Length;
if (!InternetGetCookie(url, null, cookieHeader, ref datasize))
{
if (datasize < 0)
return String.Empty;
cookieHeader = new StringBuilder(datasize); // resize with new datasize
InternetGetCookie(url, null, cookieHeader, ref datasize);
}
// result is like this: "KEY=Value; KEY2=what ever"
return cookieHeader.ToString();
}