use of com.codename1.io.Cookie in project CodenameOne by codenameone.
the class TestComponent method testCookiesInBrowserComponent.
private void testCookiesInBrowserComponent() throws IOException {
Cookie.clearCookiesFromStorage();
Form f = new Form("CookiesInBrowser");
String formName = "CookiesInBrowser";
f.setName(formName);
f.setLayout(new BorderLayout());
BrowserComponent bc = new BrowserComponent();
f.add(BorderLayout.CENTER, bc);
f.show();
TestUtils.waitForFormName(formName, 2000);
String baseUrl = "http://solutions.weblite.ca/cn1tests/cookie";
String clearCookiesUrl = baseUrl + "/reset.php";
String setCookiesUrl = baseUrl + "/set.php";
String checkCookiesUrl = baseUrl + "/check.php";
String setCookiesUrlSession = baseUrl + "/set_session.php";
final BrowserStatus status = new BrowserStatus(bc);
bc.setURL(clearCookiesUrl);
status.waitReady();
status.reset();
bc.setURL(checkCookiesUrl);
status.waitReady();
Map<String, Object> res = status.getJSONContent();
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
status.reset();
bc.setURL(setCookiesUrl);
status.waitReady();
status.reset();
bc.setURL(checkCookiesUrl);
status.waitReady();
res = status.getJSONContent();
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
status.reset();
bc.setURL(clearCookiesUrl);
status.waitReady();
status.reset();
bc.setURL(checkCookiesUrl);
status.waitReady();
res = status.getJSONContent();
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
status.reset();
bc.setURL(setCookiesUrlSession);
status.waitReady();
status.reset();
bc.setURL(checkCookiesUrl);
status.waitReady();
res = status.getJSONContent();
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
// Now let's try to share cookies between the browser component and
// a connection request.
ConnectionRequest.setUseNativeCookieStore(true);
Cookie.clearCookiesFromStorage();
BrowserComponent bc2 = new BrowserComponent();
bc.getParent().replace(bc, bc2, null);
bc = bc2;
f.revalidate();
final BrowserStatus status2 = new BrowserStatus(bc);
bc.setURL(clearCookiesUrl);
status2.waitReady();
status2.reset();
// First verify that the cookie is not set in either browser or connection request
bc.setURL(checkCookiesUrl);
status2.waitReady();
res = status2.getJSONContent();
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
// Next let's set the cookie in the browser, and verify that it is set in both
// browser and connection request.
status2.reset();
bc.setURL(setCookiesUrl);
status2.waitReady();
status2.reset();
bc.setURL(checkCookiesUrl);
status2.waitReady();
res = status2.getJSONContent();
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
// Now let's delete the cookie in the browser and verify that it is deleted in
// both the browser and connection request.
status2.reset();
bc.setURL(clearCookiesUrl);
status2.waitReady();
status2.reset();
bc.setURL(checkCookiesUrl);
status2.waitReady();
res = status2.getJSONContent();
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
// Now let's set the cookie in the ConnectionRequest and verify that it is set in both
// connection request and browser.
ConnectionRequest.fetchJSON(setCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
status2.reset();
bc.setURL(checkCookiesUrl);
status2.waitReady();
res = status2.getJSONContent();
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
}
use of com.codename1.io.Cookie in project CodenameOne by codenameone.
the class CodenameOneImplementation method getCookiesForURL.
/**
* Returns the cookies for this URL
*
* @param url the url on which we are checking for cookies
* @return the cookies to submit to the given URL
*/
public Vector getCookiesForURL(String url) {
Vector response = null;
if (Cookie.isAutoStored()) {
cookies = (Hashtable) Storage.getInstance().readObject(Cookie.STORAGE_NAME);
}
String protocol = "";
int pos = -1;
if ((pos = url.indexOf(":")) >= 0) {
protocol = url.substring(0, pos);
}
boolean isHttp = ("http".equals(protocol) || "https".equals(protocol));
boolean isSecure = "https".equals(protocol);
String path = getURLPath(url);
if (cookies != null && cookies.size() > 0) {
String domain = getURLDomain(url);
Enumeration e = cookies.keys();
while (e.hasMoreElements()) {
String domainKey = (String) e.nextElement();
if (domain.indexOf(domainKey) > -1) {
Hashtable h = (Hashtable) cookies.get(domainKey);
if (h != null) {
Enumeration enumCookies = h.elements();
if (response == null) {
response = new Vector();
}
while (enumCookies.hasMoreElements()) {
Cookie nex = (Cookie) enumCookies.nextElement();
if (nex.isHttpOnly() && !isHttp) {
continue;
}
if (nex.isSecure() && !isSecure) {
continue;
}
if (path.indexOf(nex.getPath()) != 0) {
continue;
}
response.addElement(nex);
}
}
}
}
}
return response;
}
use of com.codename1.io.Cookie in project CodenameOne by codenameone.
the class CodenameOneImplementation method addCookie.
public void addCookie(Cookie[] cookiesArray) {
if (cookies == null) {
cookies = new Hashtable();
}
int calen = cookiesArray.length;
for (int i = 0; i < calen; i++) {
Cookie cookie = cookiesArray[i];
Hashtable h = (Hashtable) cookies.get(cookie.getDomain());
if (h == null) {
h = new Hashtable();
cookies.put(cookie.getDomain(), h);
}
purgeOldCookies(h);
if (cookie.getExpires() != 0 && cookie.getExpires() < System.currentTimeMillis()) {
h.remove(cookie.getName());
} else {
h.put(cookie.getName(), cookie);
}
}
if (Cookie.isAutoStored()) {
if (Storage.getInstance().exists(Cookie.STORAGE_NAME)) {
Storage.getInstance().deleteStorageFile(Cookie.STORAGE_NAME);
}
Storage.getInstance().writeObject(Cookie.STORAGE_NAME, cookies);
}
}
use of com.codename1.io.Cookie in project CodenameOne by codenameone.
the class ConnectionRequest method performOperation.
/**
* Performs the actual network request on behalf of the network manager
*/
void performOperation() throws IOException {
if (shouldStop()) {
return;
}
if (cacheMode == CachingMode.OFFLINE) {
InputStream is = getCachedData();
if (is != null) {
readResponse(is);
Util.cleanup(is);
} else {
responseCode = 404;
throw new IOException("File unavilable in cache");
}
return;
}
CodenameOneImplementation impl = Util.getImplementation();
Object connection = null;
input = null;
output = null;
redirecting = false;
try {
String actualUrl = createRequestURL();
if (timeout > 0) {
connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest(), timeout);
} else {
connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest());
}
if (shouldStop()) {
return;
}
initConnection(connection);
if (httpMethod != null) {
impl.setHttpMethod(connection, httpMethod);
}
if (isCookiesEnabled()) {
Vector v = impl.getCookiesForURL(actualUrl);
if (v != null) {
int c = v.size();
if (c > 0) {
StringBuilder cookieStr = new StringBuilder();
Cookie first = (Cookie) v.elementAt(0);
cookieSent(first);
cookieStr.append(first.getName());
cookieStr.append("=");
cookieStr.append(first.getValue());
for (int iter = 1; iter < c; iter++) {
Cookie current = (Cookie) v.elementAt(iter);
cookieStr.append(";");
cookieStr.append(current.getName());
cookieStr.append("=");
cookieStr.append(current.getValue());
cookieSent(current);
}
impl.setHeader(connection, cookieHeader, initCookieHeader(cookieStr.toString()));
} else {
String s = initCookieHeader(null);
if (s != null) {
impl.setHeader(connection, cookieHeader, s);
}
}
} else {
String s = initCookieHeader(null);
if (s != null) {
impl.setHeader(connection, cookieHeader, s);
}
}
}
if (checkSSLCertificates && canGetSSLCertificates()) {
sslCertificates = getSSLCertificatesImpl(connection, url);
checkSSLCertificates(sslCertificates);
if (shouldStop()) {
return;
}
}
if (isWriteRequest()) {
progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
output = impl.openOutputStream(connection);
if (shouldStop()) {
return;
}
if (NetworkManager.getInstance().hasProgressListeners() && output instanceof BufferedOutputStream) {
((BufferedOutputStream) output).setProgressListener(this);
}
if (requestBody != null) {
if (shouldWriteUTFAsGetBytes()) {
output.write(requestBody.getBytes("UTF-8"));
} else {
OutputStreamWriter w = new OutputStreamWriter(output, "UTF-8");
w.write(requestBody);
}
} else {
buildRequestBody(output);
}
if (shouldStop()) {
return;
}
if (output instanceof BufferedOutputStream) {
((BufferedOutputStream) output).flushBuffer();
if (shouldStop()) {
return;
}
}
}
timeSinceLastUpdate = System.currentTimeMillis();
responseCode = impl.getResponseCode(connection);
if (isCookiesEnabled()) {
String[] cookies = impl.getHeaderFields("Set-Cookie", connection);
if (cookies != null && cookies.length > 0) {
ArrayList cook = new ArrayList();
int clen = cookies.length;
for (int iter = 0; iter < clen; iter++) {
Cookie coo = parseCookieHeader(cookies[iter]);
if (coo != null) {
cook.add(coo);
cookieReceived(coo);
}
}
impl.addCookie((Cookie[]) cook.toArray(new Cookie[cook.size()]));
}
}
if (responseCode == 304 && cacheMode != CachingMode.OFF) {
cacheUnmodified();
return;
}
if (responseCode - 200 < 0 || responseCode - 200 > 100) {
readErrorCodeHeaders(connection);
// redirect to new location
if (followRedirects && (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307)) {
String uri = impl.getHeaderField("location", connection);
if (!(uri.startsWith("http://") || uri.startsWith("https://"))) {
// relative URI's in the location header are illegal but some sites mistakenly use them
url = Util.relativeToAbsolute(url, uri);
} else {
url = uri;
}
if (requestArguments != null && url.indexOf('?') > -1) {
requestArguments.clear();
}
if ((responseCode == 302 || responseCode == 303)) {
if (this.post && shouldConvertPostToGetOnRedirect()) {
this.post = false;
setWriteRequest(false);
}
}
impl.cleanup(output);
impl.cleanup(connection);
connection = null;
output = null;
if (!onRedirect(url)) {
redirecting = true;
retry();
}
return;
}
responseErrorMessge = impl.getResponseMessage(connection);
handleErrorResponseCode(responseCode, responseErrorMessge);
if (!isReadResponseForErrors()) {
return;
}
}
responseContentType = getHeader(connection, "Content-Type");
if (cacheMode == CachingMode.SMART || cacheMode == CachingMode.MANUAL) {
String last = getHeader(connection, "Last-Modified");
String etag = getHeader(connection, "ETag");
Preferences.set("cn1MSince" + createRequestURL(), last);
Preferences.set("cn1Etag" + createRequestURL(), etag);
}
readHeaders(connection);
contentLength = impl.getContentLength(connection);
timeSinceLastUpdate = System.currentTimeMillis();
progress = NetworkEvent.PROGRESS_TYPE_INPUT;
if (isReadRequest()) {
input = impl.openInputStream(connection);
if (shouldStop()) {
return;
}
if (input instanceof BufferedInputStream) {
if (NetworkManager.getInstance().hasProgressListeners()) {
((BufferedInputStream) input).setProgressListener(this);
}
((BufferedInputStream) input).setYield(getYield());
}
if (!post && cacheMode == CachingMode.SMART && destinationFile == null && destinationStorage == null) {
byte[] d = Util.readInputStream(input);
OutputStream os = FileSystemStorage.getInstance().openOutputStream(getCacheFileName());
os.write(d);
os.close();
readResponse(new ByteArrayInputStream(d));
} else {
readResponse(input);
}
if (shouldAutoCloseResponse()) {
input.close();
}
input = null;
}
} finally {
// always cleanup connections/streams even in case of an exception
impl.cleanup(output);
impl.cleanup(input);
impl.cleanup(connection);
timeSinceLastUpdate = -1;
input = null;
output = null;
connection = null;
}
if (!isKilled()) {
Display.getInstance().callSerially(new Runnable() {
public void run() {
postResponse();
}
});
}
}
use of com.codename1.io.Cookie in project CodenameOne by codenameone.
the class TestComponent method testCookies.
private void testCookies() throws IOException {
Cookie.clearCookiesFromStorage();
String baseUrl = "http://solutions.weblite.ca/cn1tests/cookie";
String clearCookiesUrl = baseUrl + "/reset.php";
String setCookiesUrl = baseUrl + "/set.php";
String checkCookiesUrl = baseUrl + "/check.php";
String setCookiesUrlSession = baseUrl + "/set_session.php";
// Try without native cookie store
ConnectionRequest.setUseNativeCookieStore(false);
ConnectionRequest.fetchJSON(clearCookiesUrl);
Map<String, Object> res = ConnectionRequest.fetchJSON(checkCookiesUrl);
System.out.println(res);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
ConnectionRequest.fetchJSON(setCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
// Now check that session cookies (no explicit expiry) are set correctly
ConnectionRequest.fetchJSON(clearCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
ConnectionRequest.fetchJSON(setCookiesUrlSession);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
// Try with native cookie store
ConnectionRequest.setUseNativeCookieStore(true);
ConnectionRequest.fetchJSON(clearCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
ConnectionRequest.fetchJSON(setCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
// Now check that session cookies (no explicit expiry) are set correctly
ConnectionRequest.fetchJSON(clearCookiesUrl);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
ConnectionRequest.fetchJSON(setCookiesUrlSession);
res = ConnectionRequest.fetchJSON(checkCookiesUrl);
TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
Throwable[] t = new Throwable[1];
// Now test a different cookie date format.
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void handleException(Exception err) {
Log.p("handling exception " + err);
t[0] = err;
}
@Override
protected void handleRuntimeException(RuntimeException err) {
Log.p("handling runtime exception " + err);
t[0] = err;
}
@Override
protected void handleErrorResponseCode(int code, String message) {
Log.p("Error response " + code + ", " + message);
}
};
String oldProp = (String) Display.getInstance().getProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", null);
Display.getInstance().setProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", "true");
req.setUrl(baseUrl + "/test_rfc822cookie.php");
req.setFollowRedirects(true);
req.setPost(false);
req.setDuplicateSupported(true);
// req.setFailSilently(true);
try {
NetworkManager.getInstance().addToQueueAndWait(req);
} finally {
// NetworkManager.getInstance().removeErrorListener(errorListener);
Display.getInstance().setProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", oldProp);
}
TestUtils.assertTrue(req.getResponseCode() == 200, "Unexpected response code. Expected 200 but found " + req.getResponseCode());
TestUtils.assertTrue(t[0] == null, t[0] != null ? ("Exception was thrown getting URL " + t[0].getMessage()) : "");
}
Aggregations