NullPointerException in PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() - eclipse-plugin

//obtain the active page
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
returns Exception in thread "Thread-3" java.lang.NullPointerExceptionµ.
What shall i do?

If the thread does not run in the active window, PlatformUI.getWorkbench().getActiveWorkbenchWindow() will return "null".
You must wrap your code in a Display, e.g.:
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
}
});

Add some null checks, it is possible for the workbench to not have an active window, not it is also possible for PlatformUI.getWorkbench to throw an IllegalStateException if the workbench is not yet started (e.g createAndRunWorkbench() has not yet been called).
IWorkbenchWindow window = PlatformUI.getWorkbench().getInstance()
.getActiveWorkbenchWindow();
if(workbenchWindow != null) {
IWorkbenchPage page = window .getActivePage();
}

I have a work-around for this. even though its an old post.
IWorkbench wb = PlatformUI.getWorkbench();
if (wb.getWorkbenchWindowCount() == 1) {
try{
wb.getWorkbenchWindows()[0].getActivePage().getPerspective();
}
catch(NullPointerException e)
{
Logger.log(e);
}
}

Related

(React Native) Huawei Location Kit - is there any way to know if network location services setting switch off?

to make our apps working indoor to fetch location we need Network Location Services switch to be on
And we're using this function to detect any setting that still off
We noticed the response which is LocationSettingsStates, when the switch on or off is always true
Am I using wrong function to detect it??
The class and methods mentioned in the original post are the right ones to be used for checking network location service availability.
Please refer to a partial code extracted from Huawei sample code obtained from Github
public void checkSettings(View view) {
new Thread() {
#Override
public void run() {
try {
CheckSettingsRequest checkSettingsRequest = new CheckSettingsRequest();
LocationRequest locationRequest = new LocationRequest();
checkSettingsRequest.setLocationRequest(locationRequest);
checkSettingsRequest.setAlwaysShow(false);
checkSettingsRequest.setNeedBle(false);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(checkSettingsRequest.getLocationRequest())
.setAlwaysShow(checkSettingsRequest.isAlwaysShow())
.setNeedBle(checkSettingsRequest.isNeedBle());
settingsClient.checkLocationSettings(builder.build())
.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
if (task != null && task.isSuccessful()) {
LocationSettingsResponse response = task.getResult();
if (response == null) {
return;
}
LocationSettingsStates locationSettingsStates =
response.getLocationSettingsStates();
stringBuilder.append(",\nisLocationPresent=")
.append(locationSettingsStates.isLocationPresent());
stringBuilder.append(",\nisLocationUsable=")
.append(locationSettingsStates.isLocationUsable());
stringBuilder.append(",\nisNetworkLocationUsable=")
.append(locationSettingsStates.isNetworkLocationUsable());
stringBuilder.append(",\nisNetworkLocationPresent=")
.append(locationSettingsStates.isNetworkLocationPresent());
stringBuilder.append(",\nisHMSLocationUsable=")
.append(locationSettingsStates.isHMSLocationUsable());
stringBuilder.append(",\nisHMSLocationPresent=")
.append(locationSettingsStates.isHMSLocationPresent());
LocationLog.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LocationLog.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
int statusCode = 0;
if (e instanceof ApiException) {
statusCode = ((ApiException) e).getStatusCode();
}
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
android.util.Log.i(TAG,
"Location settings are not satisfied. Attempting to upgrade "
+ "location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
if (e instanceof ResolvableApiException) {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(CheckSettingActivity.this, 0);
}
} catch (IntentSender.SendIntentException sie) {
android.util.Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
default:
break;
}
}
});
} catch (Exception e) {
LocationLog.i(TAG, "checkLocationSetting exception:" + e.getMessage());
}
}
}.start();
}
The execution results when “network location service” is turned on and off are shown below. It shows the state with true and false respectively.
In some phone, LocationSettings interface may not be able to get the exact state.
You can set the Priority to be PRIORITY_BALANCED_POWER_ACCURACY and use requestLocationUpdatesWithCallback interface to get location update.
If the network location is not enabled, you will get the error code NETWORK_LOCATION_SERVICES_DISABLED 10105.
Then it means the switch is not enabled.

How Selenium getPageSource() work when we use switchTowindow is used?

What driver.getPageSource() method return if I switch the driver to some other window i have checked it is returning me the page source of the first page i.e. the first webpage I have launched how to get page source of current switched window..without relaunching the page....??
I have written the code like this I am successfully switching to the new window..but unable to get page source of current window...
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}
driver.getPageSource() should return the current active window source. From your code you can call driver.getPageSource() after switching to window.
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
System.out.println(driver.getPageSource());
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}

I am not able to switch to IFrame using Internet Explorer

I have developed a s keyword driven framework. It has a action keyword to switch the frame.
It works fine with Mozilla. But when it comes to IE it is not switching. It logs error.
IE driver -IEDriverServer_x64_2.44.0
IE version -9
Selenium version -selenium-java-2.44.0
Thanks in advance.
public static void switchFrame(String object,String data)throws Exception{
try{
driver.switchTo().frame("Ifrm");
Log.info("Switched the frame");
}
catch(Exception e){
Log.error("Not able to switch the frame--- " + e.getMessage());
DriverScript.bResult = false;
}
}
Here exception occurs.
I assume, the value you specified in frame is id/name/etc. You have to access the frame by calling the driver with specified value. Code would be
driver.switchTo().frame(driver.findElement(By.id("Ifrm")));
Selenium won't let me switch to the iframe by ID on Internet Explorer, but it does allow me to switch by index. If you have some sort of property that you can check that it is only available on the iframe you can do the following
new WebDriverWait(driver, 5).until(
new Predicate<WebDriver>() {
#Override
public boolean apply(WebDriver input) {
try {
int i = 1;
while (true) {
driver.switchTo().defaultContent();
driver.switchTo().frame(i);
String aClass =
driver.findElement(By.xpath("/html/body"))
.getAttribute("class");
if (aClass.contains("modal")) {
return true;
}
++i;
}
} catch (NoSuchFrameException e) {
return false;
}
}
}
);
In my case I was looking for a body class of modal

terminate button in console of my eclipse plugin

I have developed an eclipse plugin in xtext and I need to write some messages in console.
To do that, I have seen this site http://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F and then I have implemented this code:
private static MessageConsole findConsole(String name) {
if (ConsolePlugin.getDefault() == null)
return null;
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName())) {
conMan.showConsoleView(existing[i]);
return (MessageConsole) existing[i];
}
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
public MessageConsoleStream getMessageStream() {
MessageConsole myConsole = findConsole("console");
if (myConsole != null) {
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = win.getActivePage();
String id = IConsoleConstants.ID_CONSOLE_VIEW;
IConsoleView view;
try {
view = (IConsoleView) page.showView(id);
view.display(myConsole);
return myConsole.newMessageStream();
} catch (PartInitException e) {
e.printStackTrace();
}
}
return null;
}
I have added org.eclipse.ui.console to plugin.xml > dependencies > required plugins.
When I want to print some message:
MessageConsoleStream out = getMessageStream();
out.println(...);
And it is working. But I need a "terminate button" in my console and it seems that this code isn't enough.
How can I do that?
Thanks.
That has nothing to do with the console at all. You want to create a viewContribution, which simply adds a button to the tool bar area of an existing view. There is also an example on stackoverflow. Or you might want to consult the Eclipse help on that topic.

Selenium Webdriver sessionId or check if all browser windows are closed

Is there a way to see if all the browser windows are closed? I see that if you call driver.quit() or driver.close() on the WebDriver, the sessionId becomes null. Is there a way to check that?
I don't want to make a call to a closed or quit driver as it throws a WebDriverException. So I want to check to see the state of the browser before continuing on.
Just set
driver=null;
everytime you quit the browser and than check
if (browser!=null){
//Attention: this comand is not supported
//as far as i know ;)
driver.doSomething();
}
or
try{
}catch (NullPointerException e)
e.printStackTrace();
System.err.print"DAMN";
}
or receive a NullPointerException ;)
public bool InstanceExist
{
get
{
if (Instance != null)
{
try
{
return (Instance.WindowHandles != null); // allways returns true if browser instance exist or thrown error
}
catch (Exception e)
{
return false;
// means that browser was closed by user
}
}
return false; // means that it wasn't created yet or was closed by developer programmally
}
}
You need to check 3 situations:
driver wasnt created
driver was closed by developer
browser was closed by user, but driwer instance still exists
All of those situations is checked with this code.
I think the cleanest way to detect if all windows are closed is smth like:
boolean allWindowsClosed = webDriver.getWindowHandles().isEmpty();
getWindowHandles returns a set of window handles for all open windows - see http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html#getWindowHandles()
Actually calling getWindowHandles while the browser windows is gone will raise an "UnreachableBrowserException".
You have to put the call into a try-catch block and handle that error. Actually that is the only known WORKING workournd for catching unexpected browser windows closes. I have a static method in a config class doing my driver handling: I restart my browser like this:
protected static void loadPages() {
if (driver == null || driver.toString().contains("null")) { //null refers to an missing session id
driver = new FirefoxDriver();
//load all my page objects like
loginpage = new LoginPage(driver);
//....
//....
}
try {
if (driver.getWindowHandles() == null || driver.getWindowHandles().isEmpty()){ //will cause an UnreachableBrowserException if the browser really is not avalable.
try { //you actually dont need this try catch block
driver.quit();
} catch (Exception e) {
System.err.println("Quitting levtover driver did not work.");
}
driver = null; //you have to set the driver to null
loadPages();
}
} catch (UnreachableBrowserException ube) {
driver = null; //like above set to null to make sure no driver left
}
}
Now, ofc your current test will fail but you will be able to go on with the rest of them.
in C#
public void BrowserCheck()
{
try
{
var h = webDriver.WindowHandles;
return; // no problem
}
catch // browser window is closed so re-init it
{
webDriver.Quit();
WebDriverInit(); // your init code
}
}