This questions has been asked a few times but they all are using the #Configuration annotation. For what I am doing this is not necessary. I am using the singleton pattern to create a connection to my database. However I am getting the following error:
[ERROR] com.htd.aop.logging.LoggingAspect - Exception in com.htd.web.rest.PoResource.generateJobTicket() with cause = null
java.lang.NullPointerException: null
at com.htd.config.DataSourceDAO.<init>(DataSourceDAO.java:24) ~[classes/:na]
at com.htd.config.DataSourceDAO.getInstance(DataSourceDAO.java:35) ~[classes/:na]
at com.htd.repository.PoDataSource.<init>(PoDataSource.java:12) ~[classes/:na]
at com.htd.web.rest.util.createJobTicket.<init>(createJobTicket.java:16) ~[classes/:na]
at com.htd.web.rest.PoResource.generateJobTicket(PoResource.java:339) ~[classes/:na]
at com.htd.web.rest.PoResource$$FastClassBySpringCGLIB$$cfcd338a.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.htd.aop.logging.LoggingAspect.logAround(LoggingAspect.java:49) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
The error is telling to me look at line 24 on my DataSourceDAO class because it is null. It is referring to the following:
// Step 1: JDBC props
String DB_URL = env.getProperty("spring.datasource.url");
String USER = env.getProperty("spring.datasource.username");
String PASS = env.getProperty("spring.datasource.password");
Full code:
public class DataSourceDAO {
#Inject
private Environment env;
private static DataSourceDAO instance;
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
// Step 1: JDBC props
String DB_URL = env.getProperty("spring.datasource.url");
String USER = env.getProperty("spring.datasource.username");
String PASS = env.getProperty("spring.datasource.password");
private DataSourceDAO() { }
public static DataSourceDAO getInstance() {
if (instance == null) {
synchronized (DataSourceDAO.class) {
if (instance == null) {
instance = new DataSourceDAO();
}
}
}
return instance;
}
public java.sql.Connection getConnection() throws ClassNotFoundException,
SQLException {
Class.forName("com.mysql.jdbc.Driver");
if (conn == null) {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
}
return conn;
}
}
I am not sure why it would be null. #Inject should work fine, or so I thought.
First of all you won't get anything injected in a class that you are instancing manually.
After you fixed the manual initialization of the class you should note that inside the constructor you won't have your injected properties available, they're all set after instantiation.
If you want to do some behaviour after instancing the object you should use #PostConstruct callback (http://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/)
Related
I am trying to add Ignite to an existing apache-tomcat application and I am running into an issue trying to retrieve data that I have previously inserted into an IgniteCache.
Below is a mockup of the code in question.
public static MyClass getInstance(){
Ignite ig = WSUtil.getIgnite();
IgniteCache<Integer,MyClass> myCache = ig.getOrCreateCache("MyClass");
MyClass instance = myCache.get( 0 );
if(instance == null) {
try{
instance = //IO opperations to create instance
myCache.put(0, instance);
}catch(Exception e) {
log.error("\tMessage: "+e.getMessage());
throw e;
}finally {
//close IO
}
}
return instance;
}
The first time this method is called an instance variable is successful created and stored but the second time it is called, the following errors occur when myCache.get( 0 ) is called :
javax.cache.CacheException: class org.apache.ignite.IgniteCheckedException: com.xxxx.services.MyClass
at com.xxxx.services.misc.impl.yyyy.getInstance(yyyy.java:84)
at com.xxxx.services.misc.impl.zzzz.getProductName(zzzz.java:324)
at com.xxxx.services.misc.impl.cccc.getProductName(cccc.java:92)
at com.xxxx.services.misc.impl.cccc.getProductInfo(cccc.java:752)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at com.xxxx.prime.aop.MethodCachingInterceptor.invoke(MethodCachingInterceptor.java:56)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy52.getProductInfo(Unknown Source)
at com.xxxx.ws.ProductInfoWS.invoke(ProductInfoWS.java:60)
at com.xxxx.ws.ProductInfoWS.invoke(ProductInfoWS.java:25)
at com.sun.xml.ws.api.server.InstanceResolver$1.invokeProvider(InstanceResolver.java:256)
at com.sun.xml.ws.server.InvokerTube$2.invokeProvider(InvokerTube.java:156)
at com.sun.xml.ws.server.provider.SyncProviderInvokerTube.processRequest(SyncProviderInvokerTube.java:78)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:595)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:554)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:539)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:436)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:243)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:444)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:135)
at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:129)
at com.sun.xml.ws.transport.http.servlet.WSServlet.doGet(WSServlet.java:82)
at java.lang.Thread.run(Thread.java:748)
Caused by: class org.apache.ignite.IgniteCheckedException: com.xxxx.services.MyClass
... 60 more
Caused by: class org.apache.ignite.binary.BinaryInvalidTypeException: com.xxxx.services.MyClass
... 1 more
Caused by: java.lang.ClassNotFoundException: com.xxxx.services.MyClass
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
... 29 more
I have tried to so something similar with a simple Person object running an Ignite server on my workstation without any problem.
public static void main (String[] args) throws IgniteException{
//preparing igniteconfig
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setClientMode(true);
cfg.setPeerClassLoadingEnabled(true);
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Collections.singletonList("127.0.0.1:47500..47509"));
cfg.setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(ipFinder));
Ignite ignite = Ignition.start(cfg);
IgniteCache <Integer, Person> personCache = ignite.getOrCreateCache("personCache");
Person p = new Person("Billy","Jean");
personCache.put(0, p);
Person p2 = personCache.get(0);
System.out.println("p: " + p.toString());
System.out.println("p2: " + p2.toString());
System.out.println(">> task exectued, check output");
ignite.close();
}
It's quite possible that Ignite and your code are loaded from two different classloaders (as you have pointed out), such as, Apache Ignite may be loaded from the common libraries directory while the user code may be loaded from a specific web app directory. In this case, Apache Ignite may not see your libraries.
You can try setting IgniteConfiguration.classLoader property to e.g. getClass().getClassLoader() before starting Ignite node.
I work on a small educational project - easy java app with database and gui. I work in NetBeans IDE.
For graphical interface I use JavaFX, and as I've testet this part work perfectly fine, but I have some problem with JDBC part (I use JDBC driver for sqlite database, created with DB browser for sqlite). My main application class looks like this:
public class BazaLyoko extends Application {
#Override
public void start(Stage stage) throws Exception {
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
stage.setTitle(tytul);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And when I change those lines:
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
To this (to replace value retrieved from database to a placeholder - I did this to ensure if the error is rather connected with JavaFX or JDBC part)
String tytul = "";
Program start without problem, but when I try to use my database application don't start. There isn't any compilation error or anything like that (or maybe I just don't see them, as I'm quite new to this IDE, though I think such things are usually blatantly visible) just no application window appear.
Here's the code for my database class(they both share the same package):
public class Database {
public static Connection conn;
public Database()
{
connect();
}
public static void connect()
{
String connectionString = "jdbc:sqlite:BazaLyoko.db";
try
{
conn = DriverManager.getConnection(connectionString);
if (conn != null)
{
DatabaseMetaData meta = conn.getMetaData();
//System.out.println("Nazwa sterownika to " + meta.getDriverName());
//System.out.println("Stworzono baze danych.");
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private ResultSet doQuery(String query) throws SQLException
{
Statement stmt = null;
try
{
stmt = this.conn.createStatement();
ResultSet result = stmt.executeQuery(query);
return result;
}
catch (SQLException e )
{
throw new Error("Problem", e);
}
finally
{
if (stmt != null) { stmt.close(); }
}
}
public String getEpisodeName(int nr) throws SQLException
{
ResultSet result = doQuery("SELECT tytul FROM Odcinki WHERE numer="+String.valueOf(nr));
result.next();
return result.getString("tytul");
}
}
Database of that name is located inside my project directory (i also tried to copy it to package directory but nothing changed), the names of the table and column are correct to and exist a row with value 1 in column numer.
What I'm missing or doing wrong?
Edit:
I manage to get the following Stack Trace:
No suitable driver found for jdbc:sqlite:BazaLyoko.db
at com.sun.corba.se.impl.util.Utility.printStackTrace(Utility.java:933)
at bazalyoko.Database.connect(Database.java:46)
at bazalyoko.Database.<init>(Database.java:26)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at bazalyoko.Database.doQuery(Database.java:57)
at bazalyoko.Database.getEpisodeName(Database.java:75)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
... 1 more
Exception running application bazalyoko.BazaLyoko
Java Result: 1
am working with spring boot and mongoDB. have written the repository for my model and have written my own logic to increment id by using mongo inc. while doing
gradle test
the tests are failing with the following exception.
org.springframework.data.mapping.model.MappingException: Cannot use a complex object as a key value.
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeMapInternal(MappingMongoConverter.java:669)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createMap(MappingMongoConverter.java:585)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:471)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:430)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:418)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:322)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:418)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:392)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:356)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:79)
at org.springframework.data.mongodb.core.MongoTemplate.toDbObject(MongoTemplate.java:853)
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1014)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:963)
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy94.save(Unknown Source)
at org.springframework.data.repository.CrudRepository$save.call(Unknown Source)
at com.auth.mongo.impl.ApplicationRepositoryImpl.save(ApplicationRepositoryImpl.groovy:26)
at com.auth.repository.ApplicationRepository$save$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
can any one suggest me what am doing wrong
EDIT:
FOR Example: Application Class is the domain
class Application implements Serializable {
String id
APIKey apiKey
Map actions = [:]
Application() {
}
Application(APIKey apiKey) {
this.apiKey = apiKey
List customerActionsList = [] // added some actions
actions.put(Role.User, customerActionsList)
}
APIKey:
String apiKey
String application
DateTime whenCreated
boolean active
APIKey() {
}
APIKey(String application, DateTime whenCreated, boolean active) {
this.apiKey = generateAPIKey(application)
this.application = application
this.whenCreated = whenCreated
this.active = active
}
repository class is as follows:
#Component
class ApplicationRepositoryImpl implements ApplicationRepository {
private final Logger logger = LoggerFactory.getLogger(ApplicationRepositoryImpl.class)
#Autowired
ApplicationRepositoryMongo applicationRepositoryMongo
#Autowired
SequenceRepository sequenceRepository
#Override
Serializable save(Application application) {
application.id = application.id?:sequenceRepository.getNextSequenceId(Application.simpleName).sequence
return applicationRepositoryMongo.save(application).id
}
#Override
Application find(String id) {
return applicationRepositoryMongo.findOne(id)
}
I am incrementing the id of Application class as follows
public SequenceId getNextSequenceId(String type) {
//get sequence type
Query query = new Query(Criteria.where("id").is(type))
//increase sequence id by
Update update = new Update()
update.inc('sequence', 1)
//return new increased i
FindAndModifyOptions options = new FindAndModifyOptions()
options.returnNew(true)
//this is the magic happened
SequenceId seqId = mongoOperation.findAndModify(query, update, options, SequenceId.class)
return seqId
}
While saving the domain object getting the above exception. I have done all mongo configuration. the configuration is working for other domains.
There's an open Improvement in Spring Don't require Converters for Complex classes that are used as Ids. Currently Spring decided to not support it.
decided not to support it at all
I am trying to mock enum using powerMock but got Field 'fTestClass' was not found in class error when i ran test. I found that the issue is with Junit 4.12 and powermock-module-junit4 1.5.6. so I changed to 1.6.1 now I am getting below error ...
java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor9.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:142)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:61)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:109)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:57)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
at OrderEventProcessorTest.setUp(OrderEventProcessorTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:133)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
Basically I am trying to mock enum to check the functionality of insert, update, delete operations to cassandra db. the enum gives setups the cassadra db connection. I want to mock it so I don't need to connect to the DB to test my crud functionality. Please let me know if still is there any versioning issues with Junit 4.12 and powermock 1.6.1 . I am using mockito-core 1.10.19 and maven-surefire-plugin 2.19.1
EDITED
ENUM for DB connection
public enum CassProvider {
INSTANCE;
private Map<String,ThreadLocal<PreparedStatement>> psMap;
private String[] hostnames;
private String username;
private String password;
private String keyspace;
private Cluster cluster;
private Session session;
private CassProvider() {
init();
psMap = createPreparedStatements();
}
private void init() {
//get host, port, user , pasword from properties file
cluster = Cluster.builder().addContactPoints(hostnames).withPort(port).withCredentials(username, password).build();
session = cluster.connect(keyspace);
}
private static Map<String,ThreadLocal<PreparedStatement>> createPreparedStatements() {
//code goes for mapping preparedStatements
return psMap;
}
public PreparedStatement getPreparedStatement(String id) {
//logic for preparedStatement
return preparedStatement;
}
public Session getSession() {
return session;
}
}
Code I would like to test for different conditions it executes different prepared statements
if (eventMappingType != null && processEvent) {
.......
BatchStatement batchStatement = new BatchStatement();
PreparedStatement psFieldInsert = CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_FV");
if (eventMappingType.getSimpleFields() != null) {
for (FieldType fieldType : eventMappingType.getSimpleFields().getField()) {
Object value = MVEL.executeExpression(fieldType.getSerializedExpr(), context);
batchStatement.add(psFieldInsert.bind(keyFields.get("orderNumber"),dateStringToDate(eventDateTime), fieldType.getValue(), value != null ? value.toString() : value));
}
}
if (eventType.compareToIgnoreCase("OrderPlaced") == 0) {
//Update the lookup table for given name 2 orders.
if (name != null && name.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_NAME").bind(name, dateStringToDate(eventDateTime), orderNumber));
}
//Update the lookup table for accIds 2 orders; not sure if we need this for now
if (accIds != null && accIds.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_ACCIDS").bind(accIds, dateStringToDate(eventDateTime), orderNumber));
}
if (SAPOrderNumber != null) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_SAP_ORDER").bind(SAPOrderNumber, orderNumber));
}
}
CassProvider.INSTANCE.getSession().execute(batchStatement);
}
Not sure how your Cluster.builder() method works but I suggest you make that you configurable, i.e. to open it up for your test class to inject a mocked builder that in the end returns a mocked Cluster that in turn returns a mocked Session...
My java code to run the report
DBConnector class
public class DBConnector {
private static final String url = "jdbc:postgresql://localhost:5432/DB";
private static final String user = "postgres";
private static final String password = "123";
private Connection connection;
private static DBConnector dBConnector = null;
public DBConnector() throws SQLException, ClassNotFoundException {
connection = null;
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, password);
if (connection == null) {
System.out.println("Failed to make connection!");
}
}
private static DBConnector getDBConnector() throws SQLException, ClassNotFoundException {
if (dBConnector == null) {
dBConnector = new DBConnector();
}
return dBConnector;
}
public static Connection getConnectionToDB() throws SQLException, ClassNotFoundException {
return getDBConnector().connection;
}
Master report
parameters in Master report, this hotelid and custid are the parameters i want to sent to subreport
Both parameters are integers
parameter properties
subreport properties in Master report
2 properties defined
Sub report
parameters in sub report
hotelid properties
Query in my subreport
select firstname,lastname
from customers
where custid=$P{custid} and hotelid=$P{hotelid}
i get a NullPointerException when running the master report.
i can't find why its coming.
when i preview the report report is generating perfectly.
can some one please help me???
Here's the error i get
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at net.sf.jasperreports.engine.JRPropertiesMap.readObject(JRPropertiesMap.java:185)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1846)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1945)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1869)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1667)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1323)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1945)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1869)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1945)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1869)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:88)
at net.sf.jasperreports.engine.util.JRLoader.loadObjectFromLocation(JRLoader.java:257)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:308)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:257)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:275)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:426)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillBandNoOverflow(JRVerticalFiller.java:424)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnHeader(JRVerticalFiller.java:467)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:251)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:113)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:891)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:795)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:63)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:402)