NullPointer on MenuItem when loading controller - nullpointerexception

Ok, I'm having trouble making a Menu with Menu Items.
I was following this tutorial ( http://docs.oracle.com/javafx/2/ui_controls/menu_controls.htm ), but when I run it I get a nullpointer error. My code looks like this:
#Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
ventas.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
FXMLLoader ventasloader;
ventasloader = new FXMLLoader(getClass().getResource("VentasGUI.fxml"));
Stage ventasstage = new Stage();
AnchorPane ventas = null;
try {
ventas = (AnchorPane) ventasloader.load();
} catch (IOException ex) {
Logger.getLogger(PuntoDeVentaController.class.getName()).log(Level.SEVERE, null, ex);
}
Scene ventasscene = new Scene(ventas);
ventasstage.setScene(ventasscene);
ventasstage.setTitle("Venta");
VentasGUIController controller = ventasloader.<VentasGUIController>getController();
controller.setUser(userID);
ventasstage.show();
}
...but even when I leave just the skeleton code that NetBeans automatically adds:
#Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
ventas.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
throw new UnsupportedOperationException("Not supported yet.");
}
...rather than get the "Not supported yet" I get the nullpointerexception. I looked at the docs on http://docs.oracle.com/javafx/2/api/javafx/scene/control/MenuItem.html but I don't see that my event handler is empty, and it seems to be exactly the same as in the tutorial.
Anyone know what I'm doing wrong?
Thanks!

You haven't told where the NPE occurs so I guess here:
ventas.setOnAction(new EventHandler<ActionEvent>() {
Further I guess that ventas is a JavaFX control which you have defined in your .fxml file.
There are two things which have to be done that a connection between the .fxml file and the Java code works.
Annotate ventas with #FXML in your Java file
Define the fx:id of the ventas control in the SceneBuilder (set it to ventas)

Related

Integrate Extent Reports with AWS Device Farm and Jenkins

I am new to automation and I have been integrating AWS device farm to run my test cases on cloud. I have integrated Jenkins with AWS device farm to run the tests on the go. I want to integrate Extent Reports to see the results of the run inside Jenkins. I can't find any tutorial to do so. Can you please help me with this.
I have installed the HTML publisher in Jenkins and I have implemented Extent Reports for my local run and its working. But, I have no idea how to integrate for the cloud.
Thanks in advance. Stay Safe
Here is my code for local integration of Extent Reports
ExtentTest test;
ExtentReports extent = ExtentReportsBlackstone.getReportObject();
ThreadLocal<ExtentTest> extentTest = new ThreadLocal<ExtentTest>();
AppiumDriver<?> driver ;
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName()).assignCategory(result.getMethod().getGroups());
extentTest.set(test);
}
#Override
public void onTestSuccess(ITestResult result){
// TODO Auto-generated method stub
extentTest.get().log(Status.PASS, "Test Passed");
Properties prop = UtilityBase.globalProperties();
if(prop.getProperty("captureScreenshotOnTestPass").equals("true")) {
String testMethodName = result.getMethod().getMethodName();
try {
Class clazz = result.getTestClass().getRealClass();
Field field = clazz.getDeclaredField("driver");
field.setAccessible(true);
driver = (AppiumDriver<?>) field.get(result.getInstance());
} catch(Exception e) {
e.printStackTrace();
}
try {
extentTest.get().addScreenCaptureFromPath(getScreenshot(this.driver,testMethodName), result.getMethod().getMethodName());
} catch(IOException e){
e.printStackTrace();
}
}
}
#Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
extentTest.get().fail(result.getThrowable());
String testMethodName = result.getMethod().getMethodName();
try {
Class clazz = result.getTestClass().getRealClass();
Field field = clazz.getDeclaredField("driver");
field.setAccessible(true);
driver = (AppiumDriver<?>) field.get(result.getInstance());
} catch(Exception e) {
e.printStackTrace();
}
try {
extentTest.get().addScreenCaptureFromPath(getScreenshot(this.driver,testMethodName), result.getMethod().getMethodName());
} catch(IOException e){
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
try {
UtilityBase.deleteFolder(System.getProperty("user.dir")+"/reports");
}catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
extent.flush();
}
}
estimate cannot be integrated, aws is a bit limited and for that option we opted for lambatest, where we send it to run in the cloud but the evidence remains in extend report in our aws node
aws asks to compile the project and upload the project which runs on its own server, I don't like that way of execution

Show custom message without breaking page using exception filter

I am using one MVC application where i have to handle all exception occurs in the code. I have found about exception filter and implemented there. Below is the created exception filter code:
public class HandleException : HandleErrorAttribute
{
#region Log Initialization
FileLogService logService = new
FileLogService(typeof(HandleException));
#endregion
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
Log(filterContext.Exception);
base.OnException(filterContext);
}
private void Log(Exception exception)
{
logService.Error(exception.ToString());
}
}
Now i used this filter as attribute in my controller like below:
[AuthSession]
[HandleException]
public class OrganizationalController : BaseController
{
public ActionResult OrgSummary()
{
try
{
int a = 1, b = 0;
int result = a / b;
}
catch (Exception ex)
{
throw ex;
}
ViewData["ShowGrid"] = false;
return View();
}
}
As you can see in above code i am trying to generate exception in the code. In catch exception block when i used throw keyword then exception filter getting executed else not.
Now i need here when any exception occurs in the application i need to show a custom popup message for user. In popup message once user click on ok button then user should be available on the same page. The page should not break or get blank.
How could i implement this functionality?
Try this code. May be it helps
public class MyExceptionFilter: FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// below code will redirect to the error view
filterContext.Result = new RedirectResult("ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
and then you need to apply the above as an attribute to your action methods like:
[MyExceptionFilter]
public ActionResult XYZ()
{
}

How to check if save button is clicked in Eclipse Plugin development?

Probably a duplicate of this question, but I am specifically looking for a way to check that the save button in Eclipse was clicked, not that the editor is being saved.
You can use an IExecutionListener to listen to the File Save command. Something like:
ICommandService commandSvc = PlatformUI.getWorkbench().getAdapter(ICommandService.class);
Command saveCommand = commandSvc.getCommand(IWorkbenchCommandConstants.FILE_SAVE);
saveCommand.addExecutionListener(new IExecutionListener()
{
#Override
public void preExecute(final String commandId, final ExecutionEvent event)
{
}
#Override
public void postExecuteSuccess(final String commandId, final Object returnValue)
{
}
#Override
public void postExecuteFailure(final String commandId, final ExecutionException exception)
{
}
#Override
public void notHandled(final String commandId, final NotHandledException exception)
{
}
});
IWorkbenchCommandConstants.FILE_SAVE is the standard constant containing the file save command id.
The ExecutionEvent parameter has a getTrigger method which returns to object that caused the command to run. It looks like this will be a MenuItem if the 'File > Save' menu caused the command to run.

Mocking the static method with Mockito

I am trying to mock static method using powermock.
Below is my code:
public class Helper{
public static User getLoggedInUser(HttpServletRequest request) throws NotFoundException {
String access = request.getHeader("Authorization");
if(access == null || access.isEmpty()) {
throw new Exception("Access is null");
}
User user = new User();
return user;
}
}
And this is the controller function from where i am calling the static method getUser:
#RequestMapping(value = "user/userInfo/{Id}", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
ResultDTO getUser(#PathVariable("Id") Integer Id, HttpServletRequest request) throws NotFoundException, UnauthorizedException {
Integer userID = -1;
User user = Helper.getLoggedInUser(request);
if(user != null){
userID = user.getUserId();
}
//do something
}
And this is my test class:
//#RunWith(PowerMockRunner.class)
//#PrepareForTest(Helper.class)
public class CustomerControllerNGTest {
#InjectMocks
private userController instance = new PaymentCustomerController();
public PaymentCustomerControllerNGTest() {
}
#BeforeClass
public void setUpClass() throws Exception {
}
#AfterClass
public static void tearDownClass() throws Exception {
}
#BeforeMethod
public void setUpMethod() throws Exception {
try{
MockitoAnnotations.initMocks(this);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
try{
mockMvc = MockMvcBuilders.standaloneSetup(instance).build();
// mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
#AfterMethod
public void tearDownMethod() throws Exception {
}
#Test
public void testGetUserInfo() throws Exception {
User user = new User();
user.setUserId(1234);
HttpServletRequest request = mock(HttpServletRequest.class);
//this is for the static method
PowerMockito.mockStatic(Helper.class);
**PowerMockito.when(Helper.getLoggedInUser(request)).thenReturn(user);**
//do something
}
}
Now whenever i am executing the test case, and whenever it is executing the lone marked with bold, it is going inside the static method and throwing the exception "Access is null" rather than mocking the method , it is executing the method. Any idea?
I also tried by uncommenting these lines:
//#RunWith(PowerMockRunner.class)
//#PrepareForTest(Helper.class)
but still same exception.
Thanks
Try to uncomment:
//#RunWith(PowerMockRunner.class)
//#PrepareForTest(Helper.class)
and use
Mockito.when(Helper.getLoggedInUser(request)).thenReturn(user);
I wrote blog post on topic, that contain links to working examples on GitHub. These use TestNg instead of JUnit, but this shouldn't matter.
EDIT
I would suggest to always use latest combination of Mockito and PowerMock available. Older combinations were often pretty buggy with confusing errors. Current latest combination is Mockito 1.9.5-rc1+, PowerMock 1.5+. Pre-1.5 versions of PowerMock wasn't Java7 compliant.

Android App: Replace default button background with custom background in a Dialog Fragment

What I'm trying to do is change the default backgrounds of a custom DialogFragment that I have written. Normally, I would do this by changing the XML layout file, however, for a DialogFragment these buttons don't exist in the layout file.
In essence, I'm trying to get access to the setPositiveButton, setNegativeButton and setNeutral buttons in order to modify them. Alternatively, I would next try to do this by getting them by id, however, since they aren't defined in a layout file, I do not have a corresponding id for them. I've found plenty examples of how to modify the rest of the layout, but I can't find anywhere that positive/neutral/negative buttons are modifiable.
Ideally, I could do this in the following block of code:
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
...
}
})
Thanks in advance.
Here is the code ... The button instance is valid only after the dialog created. Hope this helps you.
public static class CustomDialog extends DialogFragment
{
public static CustomDialog newInstance()
{
return new CustomDialog();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
super.onCreateDialog(savedInstanceState);
Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog dialog = builder.create();
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return dialog;
}
#Override
public void onStart()
{
super.onStart();
Button pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
Button nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(R.color.Blue));
nButton.setBackgroundColor(getResources().getColor(R.color.Green));
}
}