Applitools openBase() failed with com.applitools.eyes.EyesException - visual-testing

I'm unable to figure out why is this code failing, I browsed through Applitools tutorials and I can't figure out what is happening here.
This is the exception being thrown:
com.applitools.eyes.EyesException: eyes.openBase() failed
at com.applitools.eyes.EyesBase.openBase(EyesBase.java:1037)
at com.applitools.eyes.selenium.SeleniumEyes.open(SeleniumEyes.java:246)
at com.applitools.eyes.selenium.Eyes.open(Eyes.java:77)
at com.applitools.eyes.selenium.Eyes.open(Eyes.java:1374)
at BaseTests.validateWindow(BaseTests.java:49)
at SearchTests.testSearchByFullTitle(SearchTests.java:11)
This is SearchTests:
import org.junit.Test;
public class SearchTests extends BaseTests {
#Test
public void testSearchByFullTitle(){
String title = "Agile Testing";
page.search(title);
validateWindow();
}
}
Validate window method:
public void validateWindow(){
eyes.open(driver, "Automation Bookstore", "neka metoda npr: "+
Thread.currentThread().getStackTrace()[2].getMethodName());
eyes.checkWindow();
eyes.close();
}
and the class throwing the exception:
protected void openBase() throws EyesException {
openLogger();
int retry = 0;
do {
try {
if (isDisabled) {
logger.verbose("Ignored");
return;
}
sessionEventHandlers.testStarted(getAUTSessionId());
validateApiKey();
logOpenBase();
validateSessionOpen();
initProviders();
this.isViewportSizeSet = false;
sessionEventHandlers.initStarted();
beforeOpen();
RectangleSize viewportSize = getViewportSizeForOpen();
viewportSizeHandler.set(viewportSize);
try {
if (viewportSize != null) {
ensureRunningSession();
}
} catch (Exception e) {
GeneralUtils.logExceptionStackTrace(logger, e);
retry++;
continue;
}
this.validationId = -1;
isOpen = true;
afterOpen();
return;
} catch (EyesException e) {
logger.log(e.getMessage());
logger.getLogHandler().close();
throw e;
}
} while (MAX_ITERATION > retry);
throw new EyesException("eyes.openBase() failed");
}

After some debugging, I found that I had a typo in my API key. After fixing that, works as expected.

In my case, the same issue was caused by using null as a value for the testName parameter.
I didn't understand it from the beginning, cause I relied on the javadoc for the open function:
/**
* Starts a test.
*
* #param driver The web driver that controls the browser hosting the application under test.
* #param appName The name of the application under test.
* #param testName The test name. (i.e., the visible part of the document's body) or {#code null} to use the current window's viewport.
* #return A wrapped WebDriver which enables SeleniumEyes trigger recording and frame handling.
*/
public WebDriver open(WebDriver driver, String appName, String testName) {
RectangleSize viewportSize = SeleniumEyes.getViewportSize(driver);
this.configuration.setAppName(appName);
this.configuration.setTestName(testName);
this.configuration.setViewportSize(viewportSize);
return open(driver);
}

Related

Try-Catch not working for controller to class library [Debugger Mode]

I am running dotnet core 2.* and as the title mentions I have trouble getting my try catch to work when calling from API. And before anyone comments I am also running middle-ware to catch any exceptions. It too doesn't perform as expected
Addinional Information:
The Two Classes are in different namespaces/projects
Queries.Authentication is static.
They are both in the same solution
Controller:
[AllowAnonymous]
[HttpPost]
public string Login([FromBody] AuthRequest req)
{
// See if the user exists
if (Authenticate(req.username, req.password))
{
try {
// Should Fail Below
UserDetails ud = Queries.Authentication.GetUser(req.username);
} catch (RetrievalException e){ }
catch (Exception e){ } // Exception Still Comes Through
}
}
Queries.Authentication.GetUser Code:
public static class Authentication {
public static UserDetails GetUser (string username)
{
// Some Code
if (details.success)
{
// Some Code
}
else
{
throw new RetrievalException(details.errorMessage); // This is not caught propperly
}
}
}
Retrieval Exception:
public class RetrievalException : Exception
{
public RetrievalException()
{
}
public RetrievalException(String message)
: base(message)
{
}
public RetrievalException(String message, Exception inner)
: base(message, inner)
{
}
}
EDIT: Adding Middleware Code Here as per request:
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NullReferenceException))
{
message = "Null Reference Exception";
status = HttpStatusCode.InternalServerError;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(RSClientCore.RetrievalException))
{
message = " The User could not be found.";
status = HttpStatusCode.NotFound;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = "{\"message\":\"" + message + "\",\"code\" :\""+ (int)status + "\"}";
response.WriteAsync(err);
}
}
App Config:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} else
{
app.UseExceptionHandler();
}
...
}
Service Config:
public void ConfigureServices(IServiceCollection services)
{
// Add Model View Controller Support
services.AddMvc( config =>
config.Filters.Add(typeof (CustomExceptionFilter))
);
UPDATE: After playing around with it I noticed that even though my program throws the exception, if I press continue the API controller then handles it as if the exception was never thrown (as in it catches it and does what I want). So I turned off the break on Exception setting, this fixed it in debugger mode. However this the break doesn't seem to be an issue when I build/publish the program. This makes me think it is definitely a issue with visual studio itself rather than the code.
When you set ExceptionHandled to true that means you have handled the exception and there is kind of no error anymore. So try to set it to false.
context.ExceptionHandled = false;
I agree it looks a bit confusing, but should do the trick you need.
Relevant notes:
For those who deal with different MVC and API controller make sure you implemented appropriate IExceptionFilter as there are two of them - System.Web.Mvc.IExceptionFilter (for MVC) and System.Web.Http.Filters.IExceptionFilter (for API).
There is a nice article about Error Handling and ExceptionFilter Dependency Injection for ASP.NET Core APIs you could use as a guide for implementing exception filters.
Also have a look at documentation: Filters in ASP.NET Core (note selector above the left page menu to select ASP.NET Core 1.0, ASP.NET Core 1.1,ASP.NET Core 2.0, or ASP.NET Core 2.1 RC1). It has many important notes and explanations why it works as it does.

Jmeter: junit request is not giving results

I am using junit request in jmeter to get the performance result of the scripts. When I run the script it is not giving any error however it is not giving the results.
I am adding the jav source code of junit request and also will provide the output screen.
please check what is the issue as i have added the required plugins and jar into the same
package com.seleniummaster.jmeterjunit;
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
public class LoginTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
//use Firefox driver
// driver = new FirefoxDriver();
//use demo.mahara.org site for testing
System.setProperty("webdriver.gecko.driver",
"D:\\Seleniumdriver\\geckodriver.exe");
driver = new MarionetteDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
baseUrl = "http://demo.mahara.org";
//timeout if site page does not load in 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#After
public void tearDown() throws Exception {
//quit the test
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
#Test
public void test() throws InterruptedException {
//navigate to base url
driver.get(baseUrl + "/");
//clear username filed
driver.findElement(By.id("login_login_username")).clear();
//enter user name
driver.findElement(By.id("login_login_username")).sendKeys("student1");
//clear password
driver.findElement(By.id("login_login_password")).clear();
//enter password
driver.findElement(By.id("login_login_password")).sendKeys("Testing1");
//click on submit button
driver.findElement(By.id("login_submit")).click();
//assert the Dashboard link text
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("Dashboard"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
assertEquals("Dashboard", driver.findElement(By.linkText("Dashboard")).getText());
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I recently faced the same issue. I checked below two boxes in the Junit Request page on Jmeter UI.
Append assertion errors
Append runtime exception
After this when I executed the test again, I found the error in the "View Results Tree" listener under Response Message field.
Hope this helps.
Please try making all private variables as public. It may happen that JMeter is not able access those.
Also, refer console on JMeter, it should show you errors/exceptions.

NullPointerException error on Implementing Location API on J2me

I am trying to implement jsr-179 APi into Nokia Symbian phone for periodic location update using setLocationListener through J2me. In emulator it is working fine. While I installed Midlet on the device nokia 5230, it is given NullPointerException and the application is automatically terminating. What might be possible causes?
Below is my class, I am instantiating object for this class on a form in netbeans
class MovementTracker implements LocationListener {
LocationProvider provider;
Location lastValidLocation;
UpdateHandler handler;
boolean done;
public MovementTracker() throws LocationException
{
done = false;
handler = new UpdateHandler();
new Thread(handler).start();
//Defining Criteria for Location Provider
/*
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
*/
//you can place cr inside getInstance
provider = LocationProvider.getInstance(null);
//listener,interval,timeout,int maxAge
//Passing -1 selects default interval
// provider.setLocationListener(MovementTracker.this, -1, -1, -1);
provider.setLocationListener(MovementTracker.this, -1, 30000, 30000);
}
public void locationUpdated(LocationProvider provider, Location location)
{
handler.handleUpdate(location);
batteryLevel = System.getProperty("com.nokia.mid.batterylevel");
sn = System.getProperty("com.nokia.mid.networksignal");
localTime = System.currentTimeMillis();
Send_Location();
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
class UpdateHandler implements Runnable
{
private Location updatedLocation = null;
// The run method performs the actual processing of the location
public void run()
{
Location locationToBeHandled = null;
while (!done)
{
synchronized(this)
{
if (updatedLocation == null)
{
try
{
wait();
}
catch (Exception e)
{
// Handle interruption
}
}
locationToBeHandled = updatedLocation;
updatedLocation = null;
}
// The benefit of the MessageListener is here.
// This thread could via similar triggers be
// handling other kind of events as well in
// addition to just receiving the location updates.
if (locationToBeHandled != null)
processUpdate(locationToBeHandled);
}
try
{
Thread.sleep(10000); //Sleeps for 10 sec & then sends the data
}
catch (InterruptedException ex)
{
}
}
public synchronized void handleUpdate(Location update)
{
updatedLocation = update;
notify();
}
private void processUpdate(Location update)
{
latitude = update.getQualifiedCoordinates().getLatitude();
longitude = update.getQualifiedCoordinates().getLongitude();
altitude = update.getQualifiedCoordinates().getAltitude();
}
}
}
public MovementTracker() throws LocationException
...
I have not written any code for handling LocationException.
No code is very dangerous practice, just search the web for something like "java swallow exceptions".
It is quite possible that because of implementation specifics Nokia throws LocationException where emulator does not throw it. Since you don't handle exception this may indeed crash you midlet at Nokia - and you wouldn't know the reason for that because, again, you have written no code to handle it.
How can I catch that exception?
The simplest thing you can do is to display an Alert with exception message and exit the midlet after user reads and dismisses alert

json ihttpmodule compression

I wrote an IHttpModule that compress my respone using gzip (I return a lot of data) in order to reduce response size.
It is working great as long as the web service doesn't throws an exception.
In case exception is thrown, the exception gzipped but the Content-encoding header is disappear and the client doesn't know to read the exception.
How can I solve this? Why the header is missing? I need to get the exception in the client.
Here is the module:
public class JsonCompressionModule : IHttpModule
{
public JsonCompressionModule()
{
}
public void Dispose()
{
}
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(Compress);
}
private void Compress(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Request;
HttpResponse response = app.Response;
try
{
//Ajax Web Service request is always starts with application/json
if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json"))
{
//User may be using an older version of IE which does not support compression, so skip those
if (!((request.Browser.IsBrowser("IE")) && (request.Browser.MajorVersion <= 6)))
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);
if (acceptEncoding.Contains("gzip"))
{
response.AddHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("deflate"))
{
response.AddHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
}
}
catch (Exception ex)
{
int i = 4;
}
}
}
Here is the web service:
[WebMethod]
public void DoSomething()
{
throw new Exception("This message get currupted on the client because the client doesn't know it gzipped.");
}
I appriciate any help.
Thanks!
Even though it's been a while since you posted this question, I just had the same issue and here's how I fixed it:
In the Init() method, add a handler for the Error event
app.Error += new EventHandler(app_Error);
In the handler, remove Content-Type from the Response headers and set the Response.Filter property to null.
void app_Error(object sender, EventArgs e)
{
HttpApplication httpApp = (HttpApplication)sender;
HttpContext ctx = HttpContext.Current;
string encodingValue = httpApp.Response.Headers["Content-Encoding"];
if (encodingValue == "gzip" || encodingValue == "deflate")
{
httpApp.Response.Headers.Remove("Content-Encoding");
httpApp.Response.Filter = null;
}
}
Maybe there's a more elegant way to do this but did the trick for me.

Embedded HTML control for Blackberry?

Is there any api for viewing html content from w/in your blackberry application? To be clear, I don't mean launching the browser on top of my app to view a page. But rather rendering the page w/in my app.
Yes. Check out the net.rim.device.api.browser.field package or the Blackberry Browser section of application integration.
Everything sort of finishes here:
Field field = browserContent.getDisplayableContent();
See:
JDE 4.0.0 API for the package
RIM app integration guide
Signed only api, as usual.
//BrowserField is available for 4.5 OS. RIM provide sample app for BrowserField Demo. you can find the sample example and run it.
/*
* BrowserFieldDemo.java
*
* Copyright © 1998-2010 Research In Motion Ltd.
*
* Note: For the sake of simplicity, this sample application may not leverage
* resource bundles and resource strings. However, it is STRONGLY recommended
* that application developers make use of the localization features available
* within the BlackBerry development platform to ensure a seamless application
* experience across a variety of languages and geographies. For more information
* on localizing your application, please refer to the BlackBerry Java Development
* Environment Development Guide associated with this release.
*/
package com.rim.samples.device.blackberry.browser;
import java.io.IOException;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.browser.field.*;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.system.*;
/**
* This sample application demonstrates how to create a web browser using the
* net.rim.device.api.browser.field package.
*/
public final class BrowserFieldDemo extends UiApplication implements RenderingApplication
{
private static String REFERER = "referer";
private RenderingSession _renderingSession;
private HttpConnection _currentConnection;
private MainScreen _mainScreen;
/**
* Entry point for application
* #param args Command line arguments (not used)
*/
public static void main(String[] args)
{
BrowserFieldDemo app = new BrowserFieldDemo();
// Make the currently running thread the application's event
// dispatch thread and begin processing events.
app.enterEventDispatcher();
}
// Constructor
public BrowserFieldDemo()
{
_mainScreen = new MainScreen();
pushScreen(_mainScreen);
_renderingSession = RenderingSession.getNewInstance();
// Enable javascript
//_renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, RenderingOptions.JAVASCRIPT_ENABLED, true);
PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread("http://www.google.com", null, null, null, this);
thread.start();
}
/**
* Processes an http connection
*
* #param connection The connection to the web content
* #param e The event triggering the connection
*/
void processConnection(HttpConnection connection, Event e)
{
// Cancel previous request
if (_currentConnection != null)
{
try
{
_currentConnection.close();
}
catch (IOException e1)
{
}
}
_currentConnection = connection;
BrowserContent browserContent = null;
try
{
browserContent = _renderingSession.getBrowserContent(connection, this, e);
if (browserContent != null)
{
Field field = browserContent.getDisplayableContent();
if (field != null)
{
synchronized (Application.getEventLock())
{
_mainScreen.deleteAll();
_mainScreen.add(field);
}
}
browserContent.finishLoading();
}
}
catch (RenderingException re)
{
Utilities.errorDialog("RenderingSession#getBrowserContent() threw " + re.toString());
}
finally
{
SecondaryResourceFetchThread.doneAddingImages();
}
}
/**
* #see net.rim.device.api.browser.RenderingApplication#eventOccurred(net.rim.device.api.browser.Event)
*/
public Object eventOccurred(Event event)
{
int eventId = event.getUID();
switch (eventId)
{
case Event.EVENT_URL_REQUESTED :
{
UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;
PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(urlRequestedEvent.getURL(),
urlRequestedEvent.getHeaders(),
urlRequestedEvent.getPostData(),
event, this);
thread.start();
break;
}
case Event.EVENT_BROWSER_CONTENT_CHANGED:
{
// Browser field title might have changed update title.
BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event;
if (browserContentChangedEvent.getSource() instanceof BrowserContent)
{
BrowserContent browserField = (BrowserContent) browserContentChangedEvent.getSource();
String newTitle = browserField.getTitle();
if (newTitle != null)
{
synchronized (getAppEventLock())
{
_mainScreen.setTitle(newTitle);
}
}
}
break;
}
case Event.EVENT_REDIRECT :
{
RedirectEvent e = (RedirectEvent) event;
String referrer = e.getSourceURL();
switch (e.getType())
{
case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT :
// Show redirect message.
Application.getApplication().invokeAndWait(new Runnable()
{
public void run()
{
Status.show("You are being redirected to a different page...");
}
});
break;
case RedirectEvent.TYPE_JAVASCRIPT :
break;
case RedirectEvent.TYPE_META :
// MSIE and Mozilla don't send a Referer for META Refresh.
referrer = null;
break;
case RedirectEvent.TYPE_300_REDIRECT :
// MSIE, Mozilla, and Opera all send the original
// request's Referer as the Referer for the new
// request.
Object eventSource = e.getSource();
if (eventSource instanceof HttpConnection)
{
referrer = ((HttpConnection)eventSource).getRequestProperty(REFERER);
}
break;
}
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setProperty(REFERER, referrer);
PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(e.getLocation(), requestHeaders,null, event, this);
thread.start();
break;
}
case Event.EVENT_CLOSE :
// TODO: close the appication
break;
case Event.EVENT_SET_HEADER : // No cache support.
case Event.EVENT_SET_HTTP_COOKIE : // No cookie support.
case Event.EVENT_HISTORY : // No history support.
case Event.EVENT_EXECUTING_SCRIPT : // No progress bar is supported.
case Event.EVENT_FULL_WINDOW : // No full window support.
case Event.EVENT_STOP : // No stop loading support.
default :
}
return null;
}
/**
* #see net.rim.device.api.browser.RenderingApplication#getAvailableHeight(net.rim.device.api.browser.BrowserContent)
*/
public int getAvailableHeight(BrowserContent browserField)
{
// Field has full screen.
return Display.getHeight();
}
/**
* #see net.rim.device.api.browser.RenderingApplication#getAvailableWidth(net.rim.device.api.browser.BrowserContent)
*/
public int getAvailableWidth(BrowserContent browserField)
{
// Field has full screen.
return Display.getWidth();
}
/**
* #see net.rim.device.api.browser.RenderingApplication#getHistoryPosition(net.rim.device.api.browser.BrowserContent)
*/
public int getHistoryPosition(BrowserContent browserField)
{
// No history support.
return 0;
}
/**
* #see net.rim.device.api.browser.RenderingApplication#getHTTPCookie(java.lang.String)
*/
public String getHTTPCookie(String url)
{
// No cookie support.
return null;
}
/**
* #see net.rim.device.api.browser.RenderingApplication#getResource(net.rim.device.api.browser.RequestedResource,
* net.rim.device.api.browser.BrowserContent)
*/
public HttpConnection getResource( RequestedResource resource, BrowserContent referrer)
{
if (resource == null)
{
return null;
}
// Check if this is cache-only request.
if (resource.isCacheOnly())
{
// No cache support.
return null;
}
String url = resource.getUrl();
if (url == null)
{
return null;
}
// If referrer is null we must return the connection.
if (referrer == null)
{
HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null);
return connection;
}
else
{
// If referrer is provided we can set up the connection on a separate thread.
SecondaryResourceFetchThread.enqueue(resource, referrer);
}
return null;
}
/**
* #see net.rim.device.api.browser.RenderingApplication#invokeRunnable(java.lang.Runnable)
*/
public void invokeRunnable(Runnable runnable)
{
(new Thread(runnable)).start();
}
}
/**
* A Thread class to fetch content using an http connection
*/
final class PrimaryResourceFetchThread extends Thread
{
private BrowserFieldDemo _application;
private Event _event;
private byte[] _postData;
private HttpHeaders _requestHeaders;
private String _url;
/**
* Constructor to create a PrimaryResourceFetchThread which fetches the web
* resource from the specified url.
*
* #param url The url to fetch the content from
* #param requestHeaders The http request headers used to fetch the content
* #param postData Data which is to be posted to the url
* #param event The event triggering the connection
* #param application The application requesting the connection
*/
PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData, Event event, BrowserFieldDemo application)
{
_url = url;
_requestHeaders = requestHeaders;
_postData = postData;
_application = application;
_event = event;
}
/**
* Connects to the url associated with this object
*
* #see java.lang.Thread#run()
*/
public void run()
{
HttpConnection connection = Utilities.makeConnection(_url, _requestHeaders, _postData);
_application.processConnection(connection, _event);
}
}
/////////////////////////////////////////////////////////////////
/*
* SecondaryResourceFetchThread.java
*
* Copyright © 1998-2010 Research In Motion Ltd.
*
* Note: For the sake of simplicity, this sample application may not leverage
* resource bundles and resource strings. However, it is STRONGLY recommended
* that application developers make use of the localization features available
* within the BlackBerry development platform to ensure a seamless application
* experience across a variety of languages and geographies. For more information
* on localizing your application, please refer to the BlackBerry Java Development
* Environment Development Guide associated with this release.
*/
package com.rim.samples.device.blackberry.browser;
import java.util.Vector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.browser.field.BrowserContent;
import net.rim.device.api.browser.field.RequestedResource;
/**
* This class provides the ability to set up an http connection if a referrer
* exists (a browser making the request).
*/
class SecondaryResourceFetchThread extends Thread
{
/**
* Callback browser field.
*/
private BrowserContent _browserField;
/**
* Images to retrieve.
*/
private Vector _imageQueue;
/**
* True is all images have been enqueued.
*/
private boolean _done;
/**
* Sync object.
*/
private static Object _syncObject = new Object();
/**
* Secondary thread.
*/
private static SecondaryResourceFetchThread _currentThread;
/**
* Enqueues secondary resource for a browser field.
*
* #param resource - resource to retrieve.
* #param referrer - call back browsr field.
*/
static void enqueue(RequestedResource resource, BrowserContent referrer)
{
if (resource == null)
{
return;
}
synchronized( _syncObject )
{
// Create new thread.
if (_currentThread == null)
{
_currentThread = new SecondaryResourceFetchThread();
_currentThread.start();
}
else
{
// If thread alread is running, check that we are adding images for the same browser field.
if (referrer != _currentThread._browserField)
{
synchronized( _currentThread._imageQueue)
{
// If the request is for a different browser field,
// clear old elements.
_currentThread._imageQueue.removeAllElements();
}
}
}
synchronized( _currentThread._imageQueue)
{
_currentThread._imageQueue.addElement(resource);
}
_currentThread._browserField = referrer;
}
}
/**
* Constructor
*
*/
private SecondaryResourceFetchThread()
{
_imageQueue = new Vector();
}
/**
* Indicate that all images have been enqueued for this browser field.
*/
static void doneAddingImages()
{
synchronized( _syncObject )
{
if (_currentThread != null)
{
_currentThread._done = true;
}
}
}
/**
* Connects to the requested resource
*
* #see java.lang.Runnable#run()
*/
public void run()
{
while (true)
{
if (_done)
{
// Check if we are done requesting images.
synchronized( _syncObject )
{
synchronized( _imageQueue )
{
if (_imageQueue.size() == 0)
{
_currentThread = null;
break;
}
}
}
}
RequestedResource resource = null;
// Request next image.
synchronized( _imageQueue )
{
if (_imageQueue.size() > 0)
{
resource = (RequestedResource)_imageQueue.elementAt(0);
_imageQueue.removeElementAt(0);
}
}
if (resource != null)
{
HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null);
resource.setHttpConnection(connection);
// Signal to the browser field that resource is ready.
if (_browserField != null)
{
_browserField.resourceReady(resource);
}
}
}
}
}
///////////////////////////////////////////////////////////////////
/*
* Utilities.java
*
* Copyright © 1998-2010 Research In Motion Ltd.
*
* Note: For the sake of simplicity, this sample application may not leverage
* resource bundles and resource strings. However, it is STRONGLY recommended
* that application developers make use of the localization features available
* within the BlackBerry development platform to ensure a seamless application
* experience across a variety of languages and geographies. For more information
* on localizing your application, please refer to the BlackBerry Java Development
* Environment Development Guide associated with this release.
*/
package com.rim.samples.device.blackberry.browser;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.util.StringUtilities;
/**
* This class provides common functions required by the
* BrowserContentManagerDemo and BrowserFieldDemo. This class allows the
* aforementioned classes to make a connection to a specified url.
*/
class Utilities
{
/**
* Connect to a web resource
* #param url The url of the resource
* #param requestHeaders The request headers describing the connection to be made
* #param postData The data to post to the web resource
* #return The HttpConnection object representing the connection to the resource, null if no connection could be made
*/
static HttpConnection makeConnection(String url, HttpHeaders requestHeaders, byte[] postData)
{
HttpConnection conn = null;
OutputStream out = null;
try
{
conn = (HttpConnection) Connector.open(url);
if (requestHeaders != null)
{
// From
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3
//
// Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP
// request if the referring page was transferred with a secure protocol.
String referer = requestHeaders.getPropertyValue("referer");
boolean sendReferrer = true;
if (referer != null && StringUtilities.startsWithIgnoreCase(referer, "https:") && !StringUtilities.startsWithIgnoreCase(url, "https:"))
{
sendReferrer = false;
}
int size = requestHeaders.size();
for (int i = 0; i < size;)
{
String header = requestHeaders.getPropertyKey(i);
// Remove referer header if needed.
if ( !sendReferrer && header.equals("referer"))
{
requestHeaders.removeProperty(i);
--size;
continue;
}
String value = requestHeaders.getPropertyValue( i++ );
if (value != null)
{
conn.setRequestProperty( header, value);
}
}
}
if (postData == null)
{
conn.setRequestMethod(HttpConnection.GET);
}
else
{
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
out = conn.openOutputStream();
out.write(postData);
}
}
catch (IOException e1)
{
errorDialog(e1.toString());
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (IOException e2)
{
errorDialog("OutputStream#close() threw " + e2.toString());
}
}
}
return conn;
}
/**
* Presents a dialog to the user with a given message
* #param message The text to display
*/
public static void errorDialog(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(message);
}
});
}
}