null pointer exception while executing test with testng - maven

// i am trying to execute test cases by grouping them using testng
package com.xyz.ngp.selenium;
import org.testng.annotations.*;
import javax.swing.*;
import com.thoughtworks.selenium.SeleneseTestNgHelper;
public class Grouping extends SeleneseTestNgHelper {
#BeforeGroups (groups = {"smoke"})
public void oneTimeSetUp() {
try {
String st="we are in BeforeGroups";
JOptionPane.showMessageDialog(null,st);
// scroll down to the bottom to see justprintsomething.
justprintsomething();
} catch (Exception e) {
e.printStackTrace();
}
}
#Test(groups = {"smoke"})
public void test1() throws Exception {
String st="you wanted to execute smoke group";
JOptionPane.showMessageDialog(null,st);
}
#Test(groups = {"functional"})
public void test2() throws Exception {
String st="you wanted to execute : either (functional) or this test: (test2)";
JOptionPane.showMessageDialog(null,st);
}
#Test(groups = {"test3"})
public void test3() throws Exception {
String st="you wanted to execute : this test: (test3)";
JOptionPane.showMessageDialog(null,st);
}
//#BeforeMethod (groups = "smoke") //do i need this beforegroups here?
public void justprintsomething() throws Exception {
try {
// it gets printed
String st="inside justprintsomething going to selenium.open";
JOptionPane.showMessageDialog(null,st);
// if i comment out the below line code works fine
selenium.open("http://www.google.com/");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// i am getting null pointer exception error just before selenium.open.

You never initialized the selenium object.

Related

Problem throwing exceptions inside CompletableFuture run async

I'm working on a microservice app, in service layout I want to invoke with CompletableFuture.runAsync(). The problem is when I want to throw exception, I have my own Handler Exception, but I can't capture error when it is produced in my catch block inside CompletedFuture shown below:
Controller:
#PostMapping(path="/offers/offer")
public CompletableFuture<Oferta> infoPropiedad(#Valid #RequestBody OfertaRequest inDTO) throws
WebServiceBadResponseException, SOAPException, IOException, InterruptedException, ExecutionException {
System.out.println("THREAD: "+Thread.currentThread().getName());
CompletableFuture<Oferta> outTO = new CompletableFuture<Oferta>();
return CompletableFuture.supplyAsync(()->{
try {
return ofertasService.ofertasService(inDTO);
} catch (Exception e) {
System.out.println("Error inesperado en la capa del controlador");
}
return null;
});
}
Service:
CompletableFuture<OfertaCrm> completableFutureCRM =
CompletableFuture.supplyAsync(()-> {
try {
return clientOferta.llamadaWebServiceOfertas(inDTOCrm);
} catch (Exception e1) {
//throw Exception and capture it with my handler class
}
});
ClientWs:
public OfertaCrm llamadaWebServiceOfertas(OfertaRequestCRM inDtoCrm)
throws SOAPException, IOException {
CompletableFuture<OfertaCrm> completableFuture = new CompletableFuture<OfertaCrm>();
logger.info("Iniciamos la llamada al WS");
//Error produces here and I want to controle it and capture with my handler class
Error handler:
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
#ExceptionHandler({
WebServiceBadResponseException.class,
SOAPException.class,
IOException.class
})
#ResponseBody
public ErrorMessage internalError(Exception exception) {
return new ErrorMessage(exception,exception.getMessage());
}
I could not be applying the correct form. Any idea how to throw the exception inside the supplyAsync block?
CompletableFuture will wrap the exception thrown within the execution inside a CompletionException. You can handle it by intercepting the root cause exception directly. Below is a simplified example.
Controller:
#RestController
public class SimpleController {
#Autowired
SimpleService simpleService;
#GetMapping("/testing")
public CompletableFuture<Integer> testing(){
return simpleService.doStuff();
}
}
Service:
#Service
public class SimpleService {
public CompletableFuture<Integer> doStuff(){
// 1 / 0 will throw ArithmeticException
return CompletableFuture.supplyAsync(() -> 1 / 0);
}
}
Controller Advice:
#RestControllerAdvice
public class SimpleControllerAdvice {
#ExceptionHandler(ArithmeticException.class)
public String handleCompletionException(ArithmeticException ex){
return "hello world";
}
}
GET /testing
hello world

#Transactional not working when using try catch block

The transactional roll back is not working when the exception is caught on the catch block, and another method is called for throw the exception. The pseudo code for the above is:
#Transactional(rollBackFor = Exception.class)
public void method1() {
// Calling another method
method2();
}
private void method2() {
try {
dbOperation1();
} catch (Exception e) {
handleFault()
}
}
handleFault() {
// Calling another method and throwing an exception
throwException()
}
throwException() {
//....
throw new Exception();
}

Java CompletableFuture - main class not terminated

I am trying to implment CompletableFuture which invokes a dummy callback method when completed.
However, after adding CompletableFuture.get() method my main class doesn't terminate.
I tried replacing CompletableFuture.get() with Thread.sleep(5000) but it doesn't seem to be right approach.
Please suggest what is causing CompletableFuture.get() to keep blocking even if the thread is complete.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture=new CompletableFuture<String>();
compFuture.supplyAsync(()->{
//Compute total
long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return ""+count;
}).thenApply(retVal->{
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
);
System.out.println("Main Thread 1");
try {
compFuture.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
class CallBackAsynchClass
{
String returnVal="";
public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {
System.out.println("Callback invoked:"+ret);
returnVal=ret;
}
#Override
public String toString() {
return "CallBackAsynchClass [returnVal=" + returnVal + "]";
}
}
I am expecting "Lock cleared" to be outputted but .get() seems to be holding up the lock.
.thenApply function returns a new instance of CompletableFuture, and it's this instance that you need to use, try using this way instead :
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
//Compute total
long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return "" + count;
});
CompletableFuture<String> future = compFuture.thenApply(retVal -> {
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; });
System.out.println("Main Thread 1");
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
Hope this helps

Spring AOP Not working properly

I'm trying to handle exceptions with AOP approach in my Spring/Swing Application and I couldn't make it work.
Main Class:
public class MainFrame extends JFrame {
private JPanel mainPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
initializeMainPanel();
}
private void initializeMainPanel() {
exitLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
throw new Exception("test");
}
});
}
}
Aspect Class:
#Aspect
public class AspectTest{
#AfterThrowing(pointcut = "execution(* com.test.MainFrame.*(..))", throwing = "ex")
public void logError(Exception ex) throws Throwable {
// ex.printStackTrace();
}
}
So, I throw an exception within my Mouse Listener and expect to catch it in my AspectTest class' AfterThrowing method but it does not work.
Can someone please help me to understand what I'm missing here?
#AfterThrowing cannot catch exceptions, only notice them and log them or do something similar. If you want to handle exceptions in an aspect you need to use an #Around advice.

Spring Aspect: surround entire method with try catch

How can I create a Spring Aspect (annotation driven e.g. #ExceptionTranslation) surrounding an entire method and put this method in a try...catch method?
#ExceptionTranslation
public void method() {
// do some stuff here...
}
so logically it does:
public void method() {
try {
// do some stuff here ...
} catch( Exception ex ) {
}
}
Below you can find a sample implementation of AfterThrows advice solving your problem.
CustomException.java
package com.yourpackage;
public class CustomException extends Exception {
public CustomException(final Throwable cause) {
super(cause);
}
}
ErrorBean.java
package com.yourpackage;
public class ErrorBean {
#ExceptionTranslation
public void translatedException() throws Exception {
throw new Exception("Foo");
}
public void notTranslatedException() throws Exception {
throw new Exception("Bar");
}
}
ExceptionTranslation.java
package com.yourpackage;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ExceptionTranslation {
}
SimpleThrowsAdvice.java
package com.yourpackage;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
public class SimpleThrowsAdvice implements ThrowsAdvice {
public static void main(String[] args) throws Exception {
ErrorBean errorBean = new ErrorBean();
AnnotationMatchingPointcut pc = AnnotationMatchingPointcut.forMethodAnnotation(ExceptionTranslation.class);
SimpleThrowsAdvice advice = new SimpleThrowsAdvice();
Advisor advisor = new DefaultPointcutAdvisor(pc, advice);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(errorBean);
pf.addAdvisor(advisor);
ErrorBean proxy = (ErrorBean) pf.getProxy();
try {
proxy.translatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
try {
proxy.notTranslatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
}
public void afterThrowing(Exception ex) throws Throwable {
System.out.println("***");
System.out.println("Generic Exception Capture");
System.out.println("Caught: " + ex.getClass().getName());
System.out.println("***\n");
throw new CustomException(ex);
}
}

Resources