Cucumber, biggest challenge, browser invoke - cucumber

In my framework each feature file when converted to step def I have to put browser invoke codes (SetProperties) and for each operations new windows comes. Please help me resolve the issue I tried inherentance where i put the codes and extended to step def classes did not work. I want to open one browser and that will do the operations for every feature files.
For example: I have a feature file for login content verification and another feature file for after login.
I put in the login the userName and Password again I had to put userName and password cor the other feature file after login along with browser invoke codes.

if you are still looking for answer. I would suggest initialize your browser in every step definition file or inside page object class(if you are using POM). create a class e.g: TestContext.java initialize your webdriver in that class.
public class TestContext {
private WebDriverLibrary webDriverLibrary;
private PageObjectLibrary pageObjectLibrary;
public TestContext() {
webDriverLibrary = new WebDriverLibrary();
pageObjectLibrary = new PageObjectLibrary(webDriverLibrary.getDriver());
}
// return WebDriverLibrary object
public WebDriverLibrary getWebDriverLibrary() {
return webDriverLibrary;
}
// return PageObjectLibrary object
public PageObjectLibrary getPageObjectLibrary() {
return pageObjectLibrary;
}
}
public class WebDriverLibrary {
private static WebDriver driver;
private static DriverType driverType;
private static EnvironmentType environmentType;
public WebDriverLibrary() {
driverType = FileReaderLibrary.getInstance().getConfigReader().getBrowser();
environmentType = FileReaderLibrary.getInstance().getConfigReader().getEnvironment();
}
// return webdriver instance
public WebDriver getDriver() {
if (driver == null)
driver = createDriver();
return driver;
}
private WebDriver createDriver() {
switch (environmentType) {
case LOCAL:
driver = createLocalDriver();
break;
case REMOTE:
driver = createRemoteDriver();
break;
}
return driver;
}
}
Hope this helps you.

Related

Is there a way to close and reopen browser when using cucumber scenario outlines and webdriver io

I'm using v5 of web driver io and a cucumber framework. I have scenario outlines with multiple examples. I would like to close the browser and reopen it in between the examples so I have a clean webpage. But I can't find a way to do this. I'm sure I've seen anything about this but I can't find it.
I've looked through the webdriverio docs and the last things I can find was from 2016 which said it wasn't possible but there was a discussion about implementing something but I can't find any more detail.
Are you looking for this:
browser.reloadSession()
https://webdriver.io/docs/api/browser/reloadSession.html
You can use hooks, I share an example below.
UiHooks.java :
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class UiHooks {
public static final String BASE_URL = "https://baseURL/";
private Scenario scenario;
#Before
public void beforeScenario(Scenario scenario) {
this.scenario = scenario;
}
#After(order = 1) //This will run first
public void afterScenario() {
if (scenario.isFailed()){
//do something like Secreen Shot or logger
}
}
#After(order = 0)//This will run second
public void afterTest() {
if (HookUtil.driver != null) {
HookUtil.driver.close();
}
if (HookUtil.seleniumBase != null) {
HookUtil.seleniumBase.stopService();
}
}
}
HookUtil.java :
public class HookUtil {
public static WebDriver driver = null;
public static SeleniumBase seleniumBase = null;
}
And then you can create a setup and call in the first step :
private void Setup() {
seleniumBase = new SeleniumBase(UiHooks.BASE_URL);
driver = seleniumBase.getDriver();
HookUtil.driver = driver;
HookUtil.seleniumBase = seleniumBase;
}

TestNG Close Browsers after Parallel Test Execution

I want to close browsers after completion of all test. Problem is I am not able to close the browser since the object created ThreadLocal driver does not recognize the driver after completion of test value returning is null.
Below is my working code
package demo;
import java.lang.reflect.Method;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ParallelMethodTest {
private static ThreadLocal<dummy> driver;
private int input;
private int length;
#BeforeMethod
public void beforeMethod() {
System.err.println("Before ID" + Thread.currentThread().getId());
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
if (driver == null) {
driver = new ThreadLocal<dummy>();
}
if (driver.get()== null) {
driver.set(new dummy());
}
}
#DataProvider(name = "sessionDataProvider", parallel = true)
public static Object[][] sessionDataProvider(Method method) {
int len = 12;
Object[][] parameters = new Object[len][2];
for (int i = 0; i < len; i++) {
parameters[i][0] = i;
parameters[i][1]=len;
}
return parameters;
}
#Test(dataProvider = "sessionDataProvider")
public void executSessionOne(int input,int length) {
System.err.println("Test ID---" + Thread.currentThread().getId());
this.input=input;
this.length=length;
// First session of WebDriver
// find user name text box and fill it
System.out.println("Parameter size is:"+length);
driver.get().getDriver().findElement(By.name("q")).sendKeys(input + "");
System.out.println("Input is:"+input);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#AfterMethod
public void afterMethod() {
System.err.println("After ID" + Thread.currentThread().getId());
driver.get().close();
}
}
package demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
public class dummy {
public WebDriver getDriver() {
return newDriver;
}
public void setNewDriver(WebDriver newDriver) {
this.newDriver = newDriver;
}
private WebDriver newDriver;
public dummy() {
newDriver = new ChromeDriver();
newDriver.get("https://www.google.co.in/");
}
#AfterClass
public void close(){
if(newDriver!=null){
System.out.println("In After Class");
newDriver.quit();
}
}
}
Thanks in Advance.
private static ThreadLocal<dummy> driver is added at the class level. What is happening is that you have already declared the variable at class level. i.e. memory is already allocated to it. Multiple threads are just setting and resetting the values of the same variable.
What you need to do is create a factory that will return an instance of Driver based on a parameter you pass to it.Logic can be anything but taking a general use case example the factory will create a new object and return only if an existing object doesn't exist. Declare and initialise the driver (from factory) in your #Test Methods
Sample code for the factory would be something like
static RemoteWebDriver firefoxDriver;
static RemoteWebDriver someOtherDriver;
static synchronized RemoteWebDriver getDriver(String browser, String browserVersion, String platform, String platformVersion)
{
if (browser == 'firefox')
{
if (firefoxDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
firefoxDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
}
else
{
if (someOtherDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
someOtherDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
return someOtherDriver;
}
You have a concurrency issue: multiple threads can create a ThreadLocal instance because dummy == null can evaluate to true on more than one thread when run in parallel. As such, some threads can execute driver.set(new dummy()); but then another thread replaces driver with a new ThreadLocal instance.
In my experience it is simpler and less error prone to always use ThreadLocal as a static final to ensure that multiple objects can access it (static) and that it is only defined once (final).
You can see my answers to the following Stack Overflow questions for related details and code samples:
How to avoid empty extra browser opens when running parallel tests with TestNG
Session not found exception with Selenium Web driver parallel execution of Data Provider test case
This is happening because you are creating the driver instance in beforeMethod function so it's scope ends after the function ends.
So when your afterMethod start it's getting null because webdriver instance already destroy as beforeMethod function is already completed.
Refer below links:-
http://www.java-made-easy.com/variable-scope.html
What is the default scope of a method in Java?

Philips Hue Bridge cannot connect to server desktop application

I am trying to connect my Desktop to the PHILIPS Hue light server using java.
When the code runs, it will flow into the Controller.java. When that happens, the FindBridges method in Controller.java runs. This is where the error occurs. In debugging, it displays a NullPointerException in thread "AWT-Event-Queue-0".
I presume that the server/lightbulb cannot be found at all, even though it is turned on and my android application can connect to it.
The error is stated below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.philips.lighting.gui.DesktopView$1.actionPerformed(DesktopView.java:72)
Controller.java
package com.philips.lighting;
import java.util.List;
import java.util.Random;
import javax.swing.JDialog;
import com.philips.lighting.hue.sdk.upnp.*;
import com.philips.lighting.data.HueProperties;
import com.philips.lighting.gui.AccessPointList;
import com.philips.lighting.gui.DesktopView;
import com.philips.lighting.gui.LightColoursFrame;
import com.philips.lighting.gui.PushLinkFrame;
import com.philips.lighting.hue.sdk.PHAccessPoint;
import com.philips.lighting.hue.sdk.PHBridgeSearchManager;
import com.philips.lighting.hue.sdk.PHHueSDK;
import com.philips.lighting.hue.sdk.PHMessageType;
import com.philips.lighting.hue.sdk.PHSDKListener;
import com.philips.lighting.model.PHBridge;
import com.philips.lighting.model.PHBridgeResourcesCache;
import com.philips.lighting.model.PHHueError;
import com.philips.lighting.model.PHHueParsingError;
import com.philips.lighting.model.PHLight;
import com.philips.lighting.model.PHLightState;
public class Controller {
private PHHueSDK phHueSDK;
private DesktopView desktopView;
private PushLinkFrame pushLinkDialog;
private LightColoursFrame lightColoursFrame;
private static final int MAX_HUE=65535;
private Controller instance;
public Controller(DesktopView view) {
this.desktopView = view;
this.phHueSDK = PHHueSDK.getInstance(); // or phHueSDK = PHHueSDK.getInstance();
this.instance = this;
}
public void findBridges() {
//To uniquely identify your app in the bridge whitelist we recommend you set your app name, and the device
phHueSDK.setAppName("SmartShowroomApp"); // e.g. phHueSDK.setAppName("QuickStartApp");
phHueSDK.setDeviceName("SmartDevice"); // e.g. If you are programming for Android: phHueSDK.setDeviceName(android.os.Build.MODEL);
phHueSDK = PHHueSDK.getInstance();
PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(true, true);
//This starts a UPNP/Portal Search and takes around 10 seconds.
//The PHSDKListener (onAccessPointsFound) will be notified with the bridges found.
}
private PHSDKListener listener = new PHSDKListener() {
#Override
public void onAccessPointsFound(List<PHAccessPoint> accessPointsList) {
// Handle your bridge search results here.
//Typically if multiple results are returned you will want to display them in a list
// and let the user select their bridge.
//If one is found you may opt to connect automatically to that bridge.
phHueSDK = PHHueSDK.getInstance();
desktopView.getFindingBridgeProgressBar().setVisible(false);
if (accessPointsList != null && accessPointsList.size() > 0)
{
AccessPointList accessPointList = new AccessPointList(accessPointsList, instance);
accessPointList.setVisible(true);
accessPointList.setLocationRelativeTo(null); // Centre the AccessPointList Frame
phHueSDK.getAccessPointsFound().clear(); // Clear all connected access points
phHueSDK.getAccessPointsFound().addAll(accessPointsList); // Adds multiple results to the list
}
else
{
PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(false, false, true);
}
}
#Override
public void onAuthenticationRequired(PHAccessPoint accessPoint) {
// Start the Pushlink Authentication.
phHueSDK = PHHueSDK.getInstance();
desktopView.getFindingBridgeProgressBar().setVisible(false);
phHueSDK.startPushlinkAuthentication(accessPoint);
// Arriving here indicates that Pushlinking is required (to prove the User has physical access to the bridge).
//Typically here you will display a pushlink image (with a timer) indicating to to the user they need to push the button on their bridge within 30 seconds.
pushLinkDialog = new PushLinkFrame(instance);
pushLinkDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pushLinkDialog.setModal(true);
pushLinkDialog.setLocationRelativeTo(null); // Center the dialog.
pushLinkDialog.setVisible(true);
}
#Override
public void onBridgeConnected(PHBridge bridge) {
phHueSDK = PHHueSDK.getInstance();
phHueSDK.setSelectedBridge(bridge);
phHueSDK.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL);
// Here it is recommended to set your connected bridge in your sdk object (as above) and start the heartbeat.
// At this point you are connected to a bridge so you should pass control to your main program/activity.
// Also it is recommended you store the connected IP Address/ Username in your app here.
//This will allow easy automatic connection on subsequent use.
// Remember to disable the heartbeat when exiting your app
//phHueSDK.disableAllHeartbeat();
//If you are only interested in a particular resource (e.g. Lights), you can enable the multi resource heartbeat as follows:
//PHHeartbeatManager heartbeatManager = PHHeartbeatManager.getInstance();
//heartbeatManager.enableLightsHeartbeat(bridge, PHHueSDK.HB_INTERVAL);
// To stop the heartbeat you can use either of the below
//heartbeatManager.disableLightsHeartbeat(bridge);
//heartbeatManager.disableAllHeartbeats(bridge);
desktopView.getFindingBridgeProgressBar().setVisible(false);
String username = HueProperties.getUsername();
String lastIpAddress = bridge.getResourceCache().getBridgeConfiguration().getIpAddress();
System.out.println("On connected: IP " + lastIpAddress);
HueProperties.storeUsername(username);
HueProperties.storeLastIPAddress(lastIpAddress);
HueProperties.saveProperties();
// Update the GUI.
desktopView.getLastConnectedIP().setText(lastIpAddress);
desktopView.getLastUserName().setText(username);
// Close the PushLink dialog (if it is showing).
if (pushLinkDialog!=null && pushLinkDialog.isShowing()) {
pushLinkDialog.setVisible(false);
}
// Enable the Buttons/Controls to change the hue bulbs.s
desktopView.getRandomLightsButton().setEnabled(true);
desktopView.getSetLightsButton().setEnabled(true);
}
#Override
public void onCacheUpdated(List cacheNotificationsList, PHBridge bridge) {
// Here you receive notifications that the BridgeResource Cache was updated. Use the PHMessageType to
// check which cache was updated, e.g.
if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) {
System.out.println("Lights Cache Updated ");
}
}
#Override
public void onConnectionLost(PHAccessPoint accessPoint) {
// Here you would handle the loss of connection to your bridge.
phHueSDK = PHHueSDK.getInstance();
if (accessPoint == null)
{
System.out.println("Please reconnect to your bridge.");
}
}
#Override
public void onConnectionResumed(PHBridge bridge) {
PHHueSDK phHueSDK = PHHueSDK.getInstance();
for (int i = 0; i < phHueSDK.getDisconnectedAccessPoint().size(); i++)
{
if (phHueSDK.getDisconnectedAccessPoint().get(i).getIpAddress()
.equals(bridge.getResourceCache().getBridgeConfiguration().getIpAddress())) {
phHueSDK.getDisconnectedAccessPoint().remove(i);
}
}
}
#Override
public void onError(int code, final String message) {
// Here you can handle events such as Bridge Not Responding, Authentication Failed and Bridge Not Found.
if (code == PHHueError.BRIDGE_NOT_RESPONDING) {
desktopView.getFindingBridgeProgressBar().setVisible(false);
desktopView.getFindBridgesButton().setEnabled(true);
desktopView.getConnectToLastBridgeButton().setEnabled(true);
desktopView.showDialog(message);
}
else if (code == PHMessageType.PUSHLINK_BUTTON_NOT_PRESSED) {
pushLinkDialog.incrementProgress();
}
else if (code == PHMessageType.PUSHLINK_AUTHENTICATION_FAILED) {
if (pushLinkDialog.isShowing()) {
pushLinkDialog.setVisible(false);
desktopView.showDialog(message);
}
else {
desktopView.showDialog(message);
}
desktopView.getFindBridgesButton().setEnabled(true);
}
else if (code == PHMessageType.BRIDGE_NOT_FOUND) {
desktopView.getFindingBridgeProgressBar().setVisible(false);
desktopView.getFindBridgesButton().setEnabled(true);
desktopView.showDialog(message);
}
}
#Override
public void onParsingErrors(List<PHHueParsingError> parsingErrorsList) {
// Any JSON parsing errors are returned here.
//Typically your program should never return these.
for (PHHueParsingError parsingError: parsingErrorsList) {
System.out.println("ParsingError : " + parsingError.getMessage());
}
}
};
public PHSDKListener getListener() {
return listener;
}
public void setListener(PHSDKListener listener) {
this.listener = listener;
}
public void randomLights() {
PHBridge bridge = phHueSDK.getSelectedBridge();
PHBridgeResourcesCache cache = bridge.getResourceCache();
// And now you can get any resource you want, for example:
List<PHLight> allLights = cache.getAllLights();
Random rand = new Random();
for (PHLight light : allLights) {
PHLightState lightState = new PHLightState();
lightState.setHue(rand.nextInt(MAX_HUE));
bridge.updateLightState(light, lightState); // If no bridge response is required then use this simpler form.
}
}
public void showControlLightsWindow() {
if (lightColoursFrame == null) {
lightColoursFrame = new LightColoursFrame();
}
lightColoursFrame.setLocationRelativeTo(null); // Centre window
lightColoursFrame.setVisible(true);
}
/**
* Connect to the last known access point.
* This method is triggered by the Connect to Bridge button but it can equally be used to automatically connect to a bridge.
*
*/
public boolean connectToLastKnownAccessPoint() {
String username = HueProperties.getUsername();
String lastIpAddress = HueProperties.getLastConnectedIP();
if (username==null || lastIpAddress == null) {
desktopView.showDialog("Missing Last Username or Last IP. Last known connection not found.");
return false;
}
//Obviously, every time a user opens up their Android hue app or application you don't want them to have to select their bridge, authenticate pushlink everytime.
//The recommended way to overcome this issue is to store the connected IP Address/Username (using your preferred method storage) and if set try to connect automatically.
PHAccessPoint accessPoint = new PHAccessPoint();
accessPoint.setIpAddress(lastIpAddress);
accessPoint.setUsername(username);
phHueSDK.connect(accessPoint);
return true;
//Note that the .connect method returns control to your PHSDKListener, so when connected the onBridgeConnected will be called again, and if your users Bridge IP has changed for example, onError will be called and can be handled programatically.
}
public void enableFindBridgesButton() {
desktopView.getFindBridgesButton().setEnabled(true);
}
public void showProgressBar() {
desktopView.getFindingBridgeProgressBar().setVisible(true);
}
}
DesktopView.java
package com.philips.lighting.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import layout.TableLayout;
import com.philips.lighting.Controller;
import com.philips.lighting.data.HueProperties;
/**
* DesktopView.java
*
* The main GUI showing last connected IP/Username and buttons for Finding Bridges and Changing the Hue Lights, once connected to a bridge.
*
*/
public class DesktopView extends JFrame {
private static final long serialVersionUID = -7469471678945429320L;
private Controller controller;
private JButton setLightsButton;
private JButton randomLightsButton;
private JButton findBridgesButton;
private JButton connectToLastBridgeButton;
private JProgressBar findingBridgeProgressBar;
private JTextField lastConnectedIP;
private JTextField lastUserName;
public DesktopView(){
setTitle("Hue Desktop");
JPanel mainPanel = new JPanel();
// TODO - Move to another class
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(2,3));
findingBridgeProgressBar = new JProgressBar();
findingBridgeProgressBar.setBorderPainted(false);
findingBridgeProgressBar.setIndeterminate(true);
findingBridgeProgressBar.setVisible(false);
//Set up components preferred size
String lastUsername = HueProperties.getUsername();
String lastConnectedIPStr = HueProperties.getLastConnectedIP();
JLabel labelLastConIP = new JLabel("Last Connected IP:");
lastConnectedIP = new JTextField(lastConnectedIPStr);
lastConnectedIP.setEditable(false);
JLabel labelLastUsername = new JLabel("Last UserName:");
lastUserName = new JTextField(lastUsername);
lastUserName.setEditable(false);
findBridgesButton = new JButton("Find New Bridges");
findBridgesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
findBridgesButton.setEnabled(false);
connectToLastBridgeButton.setEnabled(false);
controller.findBridges();
findingBridgeProgressBar.setBorderPainted(true);
findingBridgeProgressBar.setVisible(true);
}
});
connectToLastBridgeButton = new JButton("Auto Connect");
connectToLastBridgeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (controller.connectToLastKnownAccessPoint()) {
connectToLastBridgeButton.setEnabled(false);
findBridgesButton.setEnabled(false);
findingBridgeProgressBar.setBorderPainted(true);
findingBridgeProgressBar.setVisible(true);
}
}
});
setLightsButton = new JButton("Change Light Colours");
setLightsButton.setEnabled(false);
setLightsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
controller.showControlLightsWindow();
}
});
randomLightsButton = new JButton("Randomize Lights");
randomLightsButton.setEnabled(false);
randomLightsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
controller.randomLights();
}
});
double border = 10;
double size[][] =
{{border, 160, 20, 300, 20, 160}, // Columns
{border, 26, 10, 26, 26, 26,6,26}}; // Rows
mainPanel.setLayout (new TableLayout(size));
mainPanel.add(labelLastConIP, " 1, 1");
mainPanel.add(lastConnectedIP, " 3, 1");
mainPanel.add(labelLastUsername, " 1, 3");
mainPanel.add(lastUserName, " 3, 3");
mainPanel.add(findingBridgeProgressBar, " 3, 5");
mainPanel.add(connectToLastBridgeButton, " 5, 1");
mainPanel.add(findBridgesButton, " 5, 3");
mainPanel.add(randomLightsButton, " 5, 5");
mainPanel.add(setLightsButton, " 5, 7");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(700,270));
getContentPane().add(new JLabel(" An example Java/Swing Desktop Application to control your Hue Lights."), BorderLayout.NORTH);
getContentPane().add(mainPanel, BorderLayout.CENTER);
//4. Size the frame.
pack();
setLocationRelativeTo(null); // Centre the window.
setVisible(true);
}
public void setController(Controller controller) {
this.controller = controller;
}
public JButton getSetLightsButton() {
return setLightsButton;
}
public JButton getRandomLightsButton() {
return randomLightsButton;
}
public JButton getFindBridgesButton() {
return findBridgesButton;
}
public JButton getConnectToLastBridgeButton() {
return connectToLastBridgeButton;
}
public void showDialog(String message) {
JOptionPane.showMessageDialog(this, message);
}
public JProgressBar getFindingBridgeProgressBar() {
return findingBridgeProgressBar;
}
public JTextField getLastConnectedIP() {
return lastConnectedIP;
}
public JTextField getLastUserName() {
return lastUserName;
}
}
HueDesktop.java
package com.philips.lighting;
import com.philips.lighting.data.HueProperties;
import com.philips.lighting.gui.DesktopView;
import com.philips.lighting.hue.sdk.PHHueSDK;
/**
* HueDesktop.java
* An example Java/Swing Desktop application illustrating how to connect to a bridge and change your Hue lights
* using a Java Desktop Application.
*
* For more information on programming for Hue see:
* http://developers.meethue.com
*
*/
class HueDesktop {
public static void main(String args[]) {
new HueDesktop();
}
public HueDesktop() {
PHHueSDK phHueSDK = PHHueSDK.create();
// Load in HueProperties, if first time use a properties file is created.
HueProperties.loadProperties();
// Set Up the View (A JFrame, MenuBar and Console).
DesktopView desktopView = new DesktopView();
// Bind the Model and View
Controller controller = new Controller(desktopView);
desktopView.setController(controller);
// Register the PHSDKListener to receive callbacks from the bridge.
phHueSDK.getNotificationManager().registerSDKListener(controller.getListener());
}
}
Did you ever solve this? In future it is probably best to post hue Java SDK issues on the GitHub site. https://github.com/PhilipsHue/PhilipsHueSDK-Java-MultiPlatform-Android/issues
I would have seen this sooner on here (I wrote this code btw so am possibly the culprit).
I do remember seeing a similar issue before, am pretty sure it was related to Macs and the JDK Compiler level used (I possibly used an incompatible Swing component on Mac and JDK 1.6). Can you let me know your OS and JDK Compiler level and I will check this further?

Specific TableController name not working

I have an extremely odd error and wondered if anyone knew the reason for this.
When I create a new DataObject and TableController called Content and ContentController respectively, it doesn't register the tablecontroller and the help documentation it automatically generates has lost its styling.
I can't connect to the controller at all but all other controllers work as expected.
If I just rename it to DataController and that's just the name of the controller, not the dataobject everything works perfectly.
Is ContentController a reserved word of some kind or is this just specifically happening on my machine?
public class DataController : TableController<Content>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MobileContext context = new MobileContext();
DomainManager = new EntityDomainManager<Content>(context, Request, Services);
}
// GET tables/Content
public IQueryable<Content> GetAllContent()
{
return Query();
}
// GET tables/Content/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<Content> GetContent(string id)
{
return Lookup(id);
}
// PATCH tables/Content/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Content> PatchContent(string id, Delta<Content> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/Content/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<IHttpActionResult> PostContent(Content item)
{
Content current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/Content/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteContent(string id)
{
return DeleteAsync(id);
}
}
An MVC project will create an application directory called Content. This will override your route mapping to the ContentController.
You can get around this if desired through changing RouteMaps and other trickery although probably the simpliest answer is to change the name of the controller...

Native Interface for J2Me device Codename One

I created an Interface class:
package userclasses;
import com.codename1.system.NativeInterface;
public interface NativeJ2MEInterface extends NativeInterface {
public void pollBackground();
}
This is the native class - after I edited it:
package userclasses;
import userclasses.StateMachine;
public class NativeJ2MEInterfaceImpl {
public void pollBackground() {
try {
Date now = new Date();
long timeToRun = now.getTime() + (1000 * 60 );
System.out.println("RUNNNNNNN forest runnn!");
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
}
catch (Exception e) {
System.out.println("EXC-1:"+e.getMessage());
}
}
public boolean isSupported() {
return true;
}
}
I want to call the javax.microedition.io.PushRegistry registerAlarm method, but my Codename One J2ME build fails saying:
error: cannot find symbol
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
I added a midp_2.1.jar to the native j2me directory, but it did not work.
How can I get this to work? Or how can I directly access j2me alarm API?
Don't add the jar, it will get packaged into the final build.
Try setting the build argument j2me.ashaNative=true.

Resources