Environment
Eclipse Juno Service Release 1
GWT 2.5
Google Chrome with the GWT developer plugin
Running GWT on the Jetty server using 'run application' as Google web application
I am trying to set 2 cookies using gwt using the following code:
if(result.getStatus() == ServerResponse.SUCCESS) {
System.out.println("I will now set cookies: " + result.getMessage() + " and " + Integer.toString(result.getValue().getId()));
Cookies.setCookie("opsession", result.getMessage(), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES));
Cookies.setCookie("opuser", Integer.toString(result.getValue().getId()), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES));
System.out.println("Cookie set: session: " + Cookies.getCookie("opsession"));
main.checkLoginAndRedirect();
System.out.println("Redirected.");
} else if(result.getStatus() == ServerResponse.FAILURE){
new MessageBox(result.getShortTitle(), result.getMessage()).show();
}
It doesn't seem to work. The println's are there for debugging, and here is the output:
I will now set cookies: 1er1qmaly9ker and 1
Cookie set: session: null
nullnull
Redirected.
ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES is (was an int) a long that returns 20.
Update
Using
if(Cookies.getCookie("opsession") == null) {
System.out.println("opsession: cookie not found at all.");
}
I've confirmed that the cookie is not placed at all, and does not have a 'null' String value.
I've also changed
ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES into a long.
Update
Fiddler confirms that cookie data has been sent:
Response sent 30 bytes of Cookie data: Set-Cookie: JSESSIONID=4kr11hs48gvq;Path=/
But only if I use the longer version of setCookie:
Cookies.setCookie("opuser", Integer.toString(result.getValue().getId()), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES), null, "/", false);
If I use the String, String, long variant, fiddler notices no cookie data.
Should be
new Date(System.currentTimeMillis()
+ (ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES * 60000)))
to convert the expiry time to milliseconds.
Related
I am currently testing a web application deployed on IBM Websphere Application Server. I understand that I can set the LTPAToken timeout via the console configuration. However, is there any way I can retrieve the timeout duration or a listener in JAVA to indicate that the ltpatoken has expired?
You can get the token expiration time in your Java code like this (this will give you credential expiration time)
Subject callerSubject = WSSubject.getCallerSubject();
Set<WSCredential> credentials = callerSubject.getPublicCredentials(WSCredential.class);
// should contain only one credential
int credSize = credentials.size();
if( credSize != 1)
throw new RuntimeException("Invalid credential number: "+credSize);
WSCredential cred = credentials.iterator().next();
System.out.println("getExpiration: " + cred.getExpiration()+" date: " + new Date(cred.getExpiration()) + "<BR>");
if you are interested in particular in ltpatoken, you need to extend it a bit (but probably credential will be enough for you):
Set tokens = callerSubject.getPrivateCredentials();
for (Object o : tokens) {
if(o instanceof SingleSignonToken) {
SingleSignonToken ssoToken = (SingleSignonToken)o;
System.out.println("getName: " + ssoToken.getName()+"<BR>");
if("LtpaToken".equals(ssoToken.getName())){
System.out.println("getExpiration: " + ssoToken.getExpiration()+"<BR>");
}
}
}
The SingleSignonToken's getExpiration() method returns the expiration time in milliseconds. You can do something like this,
ssoToken.getExpiration() - System.currentTimeMillis();
to find out how much time this token has left. Or, you can call the isValid() method that will do that for you.
Fairly new to Play trying to change the language dynamically.
route
GET /language/:lang controllers.Index.setLanguage(lang: String)
Tried so far (but none of them work)
Lang.apply(language);
Lang.change(language); // <-- doesn't even compile
Lang.apply(language);
ctx().changeLang(language);
view
#import play.i18n.Messages
...
#Messages.get("message")
#messages.at("message")
...
Both not working..
application.config
messages
Method with some logging
public Result setLanguage(String language) {
Http.Context context = Http.Context.current();
String langFromHttpContext = context.lang().language();
String langFromCtx = ctx().lang().language();
String playLangCookieVal = request().cookies().get("PLAY_LANG").value();
boolean changed = ctx().changeLang(language);
Logger.info("Request param: " + language);
Logger.info("Http context language: " + langFromHttpContext);
Logger.info("ctx language: " + langFromHttpContext);
Logger.info("PLAY_LANG cookie value: " + langFromCtx);
Logger.info("Changed: " + changed);
return ok(index.render("Index"));
}
Result
application - Request param: en
application - Http context language: nl
application - ctx language: nl
application - PLAY_LANG cookie value: nl
application - Changed: false
You need to delete the application.langs="nl" from the configuration. It's deprecated and replaced by the play.i18n.langs.
You must leave only play.i18n.langs=["en","nl"]
You code does not work because Play reads the application.langs="nl" and ignore play.i18n.langs=["en","nl"] (because langs already read from the application.langs), so it suggest your application use only "nl" language and, of course could not set it to "en", so ctx().changeLang(language) method return false
Try this:
ctx().changeLang(language);
first time i'm using aws api in java to get the cloud watch statistics for my ec2-instance. i googled about this and i found some code snippet. here it is
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(
new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("ec2-<my-static-ip>.compute-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("Instanceid");
instanceDimension.setValue(InstanceId);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(
new Date(new Date().getTime()
- offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withDimensions(
new Dimension().withName("InstanceId").withValue(
InstanceId))
.withMetricName("CPUUtilization")
.withStatistics("Average", "Maximum")
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch
.getMetricStatistics(request);
double avgCPUUtilization = 0;
List dataPoint = getMetricStatisticsResult.getDatapoints();
for (Object aDataPoint : dataPoint) {
Datapoint dp = (Datapoint) aDataPoint;
avgCPUUtilization = dp.getAverage();
System.out.println(InstanceId
+ " instance's average CPU utilization : "
+ dp.getAverage());
}
} catch (AmazonServiceException ase) {
System.out
.println("Caught an AmazonServiceException, which means the request was made "
+ "to Amazon EC2, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
so, using this code i tried to get statistics, but first time it throws error saying
com.amazonaws.AmazonClientException: Unable to execute HTTP request:Connection to https://ec2-<my-static-ip>.compute-1.amazonaws.com refused
then i thought it was sending https requests. so i enabled ssl on my instance and tried, then i'm getting below exception.
com.amazonaws.AmazonClientException: Unable to execute HTTP request: peer not authenticated
i was using OpenJDK in my instance, so i thought that may causing the problem. then i removed openjdk and installed Oracle JDK 1.7. but still same problem.
My questions are,
1) how can i send only HTTP (instead of HTTPS) requests to get statistics?
2)how to get rid of this problem, so that i can get my results?
But please don't ask me to read any docs, because i messed up by searching in net, blogs,forums, docs... etc. then i end up here. so, please just provide me solution or tell me where i'm going wrong.
Can anybody please help me out this issue.
thank you in Advance.
Got Solution.
1) removed setting end point for AmazonCloudWatchClient.
2) problem with the AWS credentials (Access key ID, Secret key).So, i created another set of credentials and gave CloudWatchFullAccess policy for the user.
Now it is working like Charm... :-)
Thanks.
I have a code on selenium to test a form. But first i go to another page and then redirect to the my page. When i set cookies to new domain , i got error :
Exception in thread "main" org.openqa.selenium.InvalidCookieDomainException: You may only set cookies for the current domain
My Code :
//it is going to example.com and example redirect me to the "example.com" all cookie domains is "example.com"
driver.get("http://www.example.com?id=1");
Set<Cookie> cookies = driver.manage().getCookies();
Iterator<Cookie> itr = cookies.iterator();
while (itr.hasNext()){
Cookie c = itr.next();
System.out.println("Cookie Name: " + c.getName() + " --- " + "Cookie Domain: " + c.getDomain() + " --- " + "Cookie Value: " + c.getValue());
driver.manage().addCookie(c);
}
How can i manage that ? I have to get/set cookies for example.com
Like mentioned in previous answer this is expected behavior.
The only work around to date is to driver.get("domain.com/404") page. But this doesn't always work due to SSO often protects domain.com/*
I have made a new feature request on the spec: https://github.com/w3c/webdriver/issues/1238
to make it so the 404 work-around can always work.
The webdriver spec
https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie forces
the current browser session to be on the domain where you are adding
the cookie to.
This makes tons of sense and I agree with it.
This unfortunately prevents 2 key use cases:
You want to re-use cookies from another webdriver session in a new
session to avoid repeating the work it took to get the cookies. Such
as having to repeat a login. Allow a webdriver pool to be shared
amongst unrelated threads where each thread might have their own
cookies. The only current work around is to attempt to force the
webdriver to go to a 404 error page with something like:
webdriver.get("http://the-cookie-domain.com/404adsfasdf"). This would
cause the page to go to domain and would allow you to add cookies with
addCookie. But this hardly ever works. Because the page is very often
protected by SSO, any attempt to go to http://the-cookie-domain.com/*
sends you to an SSO login page e.g. http://login.ssodomain.com and now
you have the same problem.
We should add a new method to the spec webdriver.goTo404Page(domain)
to allow this use-case. This method should simulate a 404 HTTP status
code response from domain in the browser.
Alternatively maybe be a new overload to addCookie could allow this,
for example: void addCookie(Cookie var1, String goTo404PageOfDomain);
By allowing users to go to a fake 404 page of any given domain, this
guarantees the 404-page workaround works for any page and these 2 use
cases are now possible.
For firefox, you can modify Marionette slightly to just remove this check.
diff --git a/testing/marionette/cookie.js b/testing/marionette/cookie.js
--- a/testing/marionette/cookie.js
+++ b/testing/marionette/cookie.js
## -144,14 +144,14 ## cookie.add = function(newCookie, {restri
newCookie.domain = "." + newCookie.domain;
}
- if (restrictToHost) {
- if (!restrictToHost.endsWith(newCookie.domain) &&
- ("." + restrictToHost) !== newCookie.domain &&
- restrictToHost !== newCookie.domain) {
- throw new InvalidCookieDomainError(`Cookies may only be set ` +
- `for the current domain (${restrictToHost})`);
- }
- }
+// if (restrictToHost) {
+// if (!restrictToHost.endsWith(newCookie.domain) &&
+// ("." + restrictToHost) !== newCookie.domain &&
+// restrictToHost !== newCookie.domain) {
+// throw new InvalidCookieDomainError(`Cookies may only be set ` +
+// `for the current domain (${restrictToHost})`);
+// }
+// }
// remove port from domain, if present.
// unfortunately this catches IPv6 addresses by mistake
diff --git a/testing/marionette/driver.js b/testing/marionette/driver.js
--- a/testing/marionette/driver.js
+++ b/testing/marionette/driver.js
## -2638,9 +2638,9 ## GeckoDriver.prototype.addCookie = functi
let {protocol, hostname} = this.currentURL;
const networkSchemes = ["ftp:", "http:", "https:"];
- if (!networkSchemes.includes(protocol)) {
- throw new InvalidCookieDomainError("Document is cookie-averse");
- }
+// if (!networkSchemes.includes(protocol)) {
+// throw new InvalidCookieDomainError("Document is cookie-averse");
+// }
let newCookie = cookie.fromJSON(cmd.parameters.cookie);
diff --git a/testing/marionette/test_cookie.js b/testing/marionette/test_cookie.js
--- a/testing/marionette/test_cookie.js
+++ b/testing/marionette/test_cookie.js
## -190,10 +190,10 ## add_test(function test_add() {
});
equal(2, cookie.manager.cookies.length);
- Assert.throws(() => {
- let biscuit = {name: "name3", value: "value3", domain: "domain3"};
- cookie.add(biscuit, {restrictToHost: "other domain"});
- }, /Cookies may only be set for the current domain/);
+// Assert.throws(() => {
+// let biscuit = {name: "name3", value: "value3", domain: "domain3"};
+// cookie.add(biscuit, {restrictToHost: "other domain"});
+// }, /Cookies may only be set for the current domain/);
cookie.add({
name: "name4",
Why not let the browser be redirected to "example.com" before adding the cookies. Once on that domain, add the cookie values you've taken from "example.com" and the refresh the page?
As per the answer by the team on this issue on the project tracker,
The cookies methods only act on cookies that would be visible as this
is the only thing that can be made to work consistently across all
browsers. The behaviour that you see is the expected behaviour.
I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.