I am trying to run a dbunit test case by loading data from an xml file (dataset.xml) and the program fails to find the table. I am new to dbunit and lack of good working examples is preventing me from running a simple program. Can anybody please guide on this?
Error Log
SEVERE: Table 'states' not found in tableMap=org.dbunit.dataset.OrderedTableNameMap[_tableNames=[], _tableMap={}, _caseSensitiveTableNames=false]
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.64 sec <<< FAILURE!
testMe(com.istore.dao.DatabaseXmlTest) Time elapsed: 0.579 sec <<< ERROR!
org.dbunit.dataset.NoSuchTableException: states
at org.dbunit.database.DatabaseDataSet.getTableMetaData(DatabaseDataSet.java:288)
at org.dbunit.operation.DeleteAllOperation.execute(DeleteAllOperation.java:109)
at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:79)
at org.dbunit.AbstractDatabaseTester.executeOperation(AbstractDatabaseTester.java:190)
at org.dbunit.AbstractDatabaseTester.onSetup(AbstractDatabaseTester.java:103)
at org.dbunit.DatabaseTestCase.setUp(DatabaseTestCase.java:156)
at junit.framework.TestCase.runBare(TestCase.java:139)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Tests in error:
testMe(com.istore.dao.DatabaseXmlTest): states
dataset.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<states state_id="1" state_cd="NJ" name="New Jersey" tax_pct="6" active="Y"/>
<states state_id="2" state_cd="PA" name="Pennsylvania" tax_pct="6" active="Y"/>
</dataset>
DatabaseXmlTest.java
public class DatabaseXmlTest extends DataSourceBasedDBTestCase {
public static final String url = "jdbc:hsqldb:mem:my-project-test;shutdown=true";
public static final String driver = "org.hsqldb.jdbcDriver";
public static final String user = "";
public static final String pwd = "";
#Override
protected DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUsername(user);
dataSource.setPassword(pwd);
dataSource.setUrl(url);
return dataSource;
}
#Override
protected IDataSet getDataSet() throws Exception {
InputStream inputStream = getClass().getResourceAsStream("/dataset.xml");
Reader reader = new InputStreamReader(inputStream);
FlatXmlDataSet dataset = new FlatXmlDataSet(reader);
return dataset;
}
public void testMe() throws Exception {
DataSource dataSource = getDataSource();
HsqldbConnection cn = new HsqldbConnection(dataSource.getConnection(), null);
DatabaseOperation.CLEAN_INSERT.execute(cn, getDataSet());
//get all states
List<State> states = new StateDao(dataSource).getAllStates();
assertNotNull(states);
}
}
StateDao.java
public class StateDao {
private static final Logger LOG = Logger.getLogger(StateDao.class);
protected DataSource dataSource;
public StateDao(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<State> getAllStates() throws SQLException {
String sql = "select * from states a where a.active='Y'";
StateQueryExecutor executor = new StateQueryExecutor(dataSource.getConnection(), sql);
List<State> states = executor.getAllStates();
LOG.debug("states = " + states);
return states;
}
}
Related
every time I run my code, it shows an error in these lines given below.
File src =ts.getScreenshotAs(OutputType.FILE);
driver = (WebDriver) clazz.getDeclaredField("driver").get(testobject);
extest.get().addScreenCaptureFromPath(getScreenshotAs(result.getMethod().getMethodName(), driver),result.getMethod().getMethodName());
full code is given below
This Is my base class
public class IntDriverr {
public WebDriver driver;
public Properties prop;
public WebDriver intDriver() throws IOException {
prop = new Properties();
FileInputStream fis = new FileInputStream(
"E:\\JavaPractice\\E2EProject\\src\\main\\java\\Myproject\\data.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browserName.equals("Firefox")) {
System.setProperty("webdriver.geckodriver.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
public String getScreenshotAs(String TestCaseName,WebDriver driver) throws IOException {
TakesScreenshot ts = ((TakesScreenshot)driver);
File src =ts.getScreenshotAs(OutputType.FILE);
String dp =System.getProperty("user.dir")+"\\reports\\"+TestCaseName+".png";
File file =new File(dp);
FileUtils.copyFile(src, file);
return dp;
}
I'm using this code on ITeatListeners for Failed Test Case
public class listeners extends IntDriverr implements ITestListener {
ExtentReports extend = ExtentReporterNG.generateReport();
ExtentTest test;
private static ThreadLocal<ExtentTest> extest = new ThreadLocal<ExtentTest>();
public void onTestStart(ITestResult result) {
test = extend.createTest(result.getMethod().getMethodName());
extest.set(test);
}
public void onTestSuccess(ITestResult result) {
extest.get().log(Status.PASS, "Suscess");
}
public void onTestFailure(ITestResult result) {
WebDriver driver = null;
extest.get().fail(result.getThrowable());
Object testobject = result.getInstance();
Class clazz = result.getTestClass().getRealClass();
try {
driver = (WebDriver) clazz.getDeclaredField("driver").get(testobject);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
extest.get().addScreenCaptureFromPath(getScreenshotAs(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (Exception e) {
e.printStackTrace();
}
}
public void onFinish(ITestContext context) {
extend.flush();
}
But When I trigger through testng xml file I'm getting this error
java.lang.NoSuchFieldException: driver
at java.base/java.lang.Class.getDeclaredField(Class.java:2411)
at Myproject.listeners.onTestFailure(listeners.java:33)
at org.testng.internal.TestListenerHelper.runTestListeners(TestListenerHelper.java:96)
at org.testng.internal.TestInvoker.runTestResultListener(TestInvoker.java:220)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:657)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
java.lang.NullPointerException
at Myproject.IntDriverr.getScreenshotAs(IntDriverr.java:42)
at Myproject.listeners.onTestFailure(listeners.java:39)
at org.testng.internal.TestListenerHelper.runTestListeners(TestListenerHelper.java:96)
at org.testng.internal.TestInvoker.runTestResultListener(TestInvoker.java:220)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:657)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
===============================================
Suite
Total tests run: 2, Passes: 1, Failures: 1, Skips: 0
===============================================
This error might observed in case when there WebDriver object is not created in one of the test case you are executing. i faced same error and i found after declaring public WebDriver driver; at class level solved the error.
Hope this might help you as well.
I have below 2 Junits.
public class TransactionManagerTest {
String fileName = "data/test/tnx-log/tnc.log";
#Test
public void beginTransactionTest_withEmptyTxnLogFile() throws IOException, ParseException {
new File(fileName).delete();
TransactionManager transactionManager = new TransactionManagerImpl(fileName);
transactionManager.beginTransaction();
ZonedDateTime transactionStartDate = transactionManager.getTransactionStartDate();
ZonedDateTime transactionEndDate = transactionManager.getTransactionEndDate();
ZonedDateTime now = ZonedDateTime.now();
Assert.assertEquals(now.getDayOfMonth(), transactionStartDate.getDayOfMonth());
Assert.assertEquals(now.getMonth(), transactionStartDate.getMonth());
Assert.assertEquals(now.getYear(), transactionStartDate.getYear());
Assert.assertEquals(0, transactionStartDate.getHour());
Assert.assertEquals(0, transactionStartDate.getMinute());
Assert.assertEquals(0, transactionStartDate.getSecond());
Assert.assertEquals(now.getDayOfMonth(), transactionEndDate.getDayOfMonth());
Assert.assertEquals(now.getMonth(), transactionEndDate.getMonth());
Assert.assertEquals(now.getYear(), transactionEndDate.getYear());
Assert.assertEquals(now.getHour(), transactionEndDate.getHour());
}
#Test
public void beginTransactionTest_success() throws IOException, ParseException {
File file = new File(fileName);
System.out.println(file.exists());
System.out.println(file.delete());
TransactionManager transactionManager = new TransactionManagerImpl(fileName);
File localFile = new File(fileName);
boolean txnLogFileExist = localFile.exists();
localFile = null;
Assert.assertTrue(txnLogFileExist);
ZonedDateTime startDate = ZonedDateTime.of(2019, 04, 25, 10, 35, 30, 000, ZoneId.of("UTC"));
ZonedDateTime endDate = ZonedDateTime.of(2019, 04, 25, 10, 40, 30, 000, ZoneId.of("UTC"));
transactionManager.beginTransaction(startDate, endDate);
transactionManager.markSuccess();
ZonedDateTime transactionStartDate = transactionManager.getTransactionStartDate();
ZonedDateTime transacitonEndDate = transactionManager.getTransactionEndDate();
Assert.assertTrue(endDate.isEqual(transactionStartDate));
Assert.assertNotNull(transacitonEndDate);
}
And below is the implementation of My TransacitonManager and CsvService.
public class TransactionManagerImpl implements TransactionManager {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private CsvService csvService;
public TransactionManagerImpl(String txnLogFile) throws IOException {
this.csvService = new CsvServiceImpl(txnLogFile);
}
public class CsvServiceImpl implements CsvService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private String txnLogFile;
public CsvServiceImpl(String txnLogFile) throws IOException {
this.txnLogFile = txnLogFile;
createTxnInfoFile();
}
#Override
public void createTxnInfoFile() throws IOException {
File file = new File(txnLogFile);
if (!file.exists()) {
boolean directoryStructureCreated = file.getParentFile().mkdirs();
logger.info("Directory structure created {} {} ", txnLogFile, directoryStructureCreated);
boolean fileCreated = file.createNewFile();
logger.info("txn log file created {} {} ", txnLogFile, fileCreated);
}
file = null;
}
The issue is that my first JUnit runs fine, but when i execute the 2nd junit the CsvService.createTxnInfoFile gets IOException
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at dummy.name.service.impl.CsvServiceImpl.createTxnInfoFile(CsvServiceImpl.java:88)
at dummy.name.service.impl.CsvServiceImpl.<init>(CsvServiceImpl.java:29)
at dummy.name.service.impl.TransactionManagerImpl.<init>(TransactionManagerImpl.java:25)
at dummy.name.service.TransactionManagerTest.beginTransactionTest_success(TransactionManagerTest.java:25)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:79)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:70)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
output
2019-04-22 08:40:28,895 [main] INFO g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false
2019-04-22 08:40:28,895 [main] INFO g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false
2019-04-22 08:40:28,895 [main] INFO g.t.service.impl.CsvServiceImpl - txn log file created data/test/tnx-log/tnc.log true
2019-04-22 08:40:28,957 [main] INFO g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false
2019-04-22 08:40:28,957 [main] INFO g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false
#Override
public void createTxnInfoFile() throws IOException {
File file = new File(txnLogFile);
if (!file.exists()) {
boolean directoryStructureCreated = file.getParentFile().mkdirs();
logger.info("Directory structure created {} {} ", txnLogFile, directoryStructureCreated);
logger.info("file.getAbsoluteFile() : " + file.getAbsoluteFile() + " canWrite() : " + file.canWrite());
boolean fileCreated = file.createNewFile();
logger.info("txn log file created {} {} ", txnLogFile, fileCreated);
}
file = null;
}
Issue resolved, instead of deleting and creating new file for every test. I am now deleting the content of file without deleting the actual file as below.
#After
public void tearDown() throws FileNotFoundException {
this.transactionManager = null;
PrintWriter writer = new PrintWriter(fileName);
writer.print("");
writer.close();
}
I´m developing an Eclipse 4 RCP Application and I want to test some functions of my Parts.
I have a Test Class like this:
#BeforeClass
public static void initUI() {
display = new Display();
shell = new Shell(display);
configPart = new ConfigPart();
configPart.postConstruct(shell);
}
#Test
public void testConfigPart() {
String testText = "TitleText";
configPart.title.setText(testText);
assertEquals(testText, ConfigHandler.getInstance().getInternalConfig()
.getTitle());
}
During the creation of the ConfigPart a DataBinding is created and that is where I run into an AssertionFailedException. The statement is:
DataBindingContext ctx = new DataBindingContext();
Is there a way to avoid this or is there another way to test E4 Applications?
Edit:
The statement(s) where the Exception is raised:
public DataBindingContext(Realm validationRealm) {
Assert.isNotNull(validationRealm, "Validation realm cannot be null");
public static void isNotNull(Object object, String message) {
if (object == null) throw new AssertionFailedException("null argument:" + message);
The Stack Trace:
org.eclipse.core.runtime.AssertionFailedException: null argument:Validation realm cannot be null
at org.eclipse.core.runtime.Assert.isNotNull(Assert.java:85)
at org.eclipse.core.databinding.DataBindingContext.<init>(DataBindingContext.java:95)
at org.eclipse.core.databinding.DataBindingContext.<init>(DataBindingContext.java:82)
at de.uni_due.s3.jack.editor.parts.config.ConfigPart.addDataBinding(ConfigPart.java:350)
at de.uni_due.s3.jack.editor.parts.config.ConfigPart.postConstruct(ConfigPart.java:81)
at de.uni_due.s3.jack.editor.parts.config.ConfigPartTest.initUI(ConfigPartTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
A call to the empty constructor new DataBindingContext() delegates to this(Realm.getDefault()) (see Eclipse source code). This means that you need to have some kind of a stub Realm set as default for your testing purposes.
You can use this solution from the Eclipse Wiki. Here is a copy-paste from the Wiki (adapted for your setup). I would think about whether you really need to have the setup in #BeforeClass or if #Before would be better.
public class DefaultRealm extends Realm {
private Realm previousRealm;
public DefaultRealm() {
previousRealm = super.setDefault(this);
}
/**
* #return always returns true
*/
public boolean isCurrent() {
return true;
}
protected void syncExec(Runnable runnable) {
runnable.run();
}
/**
* #throws UnsupportedOperationException
*/
public void asyncExec(Runnable runnable) {
throw new UnsupportedOperationException("asyncExec is unsupported");
}
/**
* Removes the realm from being the current and sets the previous realm to the default.
*/
public void dispose() {
if (getDefault() == this) {
setDefault(previousRealm);
}
}
}
Test code:
private static DefaultRealm realm;
#BeforeClass
public static void initUI() {
display = new Display();
shell = new Shell(display);
realm = new DefaultRealm();
configPart = new ConfigPart();
configPart.postConstruct(shell);
}
#AfterClass
public static void tearDownUI() {
realm.dispose();
}
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)
I keep getting the following exception,
java.lang.IllegalStateException: No tx on thread at org.apache.geronimo.transaction.manager.TransactionManagerImpl.getActiveTransactionImpl(TransactionManagerImpl.java:201)
at org.apache.geronimo.transaction.manager.TransactionManagerImpl.getResource(TransactionManagerImpl.java:194)
at org.apache.openejb.core.transaction.JtaTransactionPolicy.getResource(JtaTransactionPolicy.java:111)
at org.apache.openejb.core.transaction.EjbTransactionUtil.afterInvoke(EjbTransactionUtil.java:76)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:246)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:178)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:260)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:240)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:91)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:284)
at $Proxy70.call(Unknown Source)
at com.xyz.cms.epgmgmt.entitymanager.ProviderManagerTest.testWithTransaction(ProviderManagerTest.java:66)
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 junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I am using OpenEJB4 for JUnit testing.
The EJB itself is stateless with no transaction annotation (which makes the Transaction required). I found an older post on this forum and tried the same fix but didnt work. I dont have hibernate validation on my classpath. Am using Hibernate 3.
My test is as follows,
public class ProviderManagerTest extends TestCase {
Context context;
/**
* Bootstrap the Embedded EJB Container
*
* #throws Exception
*/
protected void setUp() throws Exception {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.put("log4j.category.OpenEJB.options ", " debug");
p.put("RcsDB", "new://Resource?type=DataSource");
p.put("RcsDB.JdbcDriver", "oracle.jdbc.driver.OracleDriver");
p.put("RcsDB.JdbcUrl", "jdbc:oracle:thin:#dbserver:1521:ttv");
p.put("RcsDB.JtaManaged", "true");
p.put("RcsDB.JtaManaged", "true");
p.put("RcsDB.username", "username");
p.put("RcsDB.password", "password");
context = EJBContainer.createEJBContainer(p).getContext();
context.bind("inject", this);
}
#Test
public void testWithTransaction() throws Exception {
Caller transactionalCaller = (Caller) context.lookup("java:global/cms_epgmgmt/TransactionBean");
transactionalCaller.call(new Callable() {
public Object call() throws Exception {
Provider testProvider = new Provider();
testProvider.setName("test");
IProviderManager providerManager = null;
providerManager = (IProviderManager) context.lookup("java:global/cms_epgmgmt/ProviderManager");
providerManager.create(testProvider);
return null;
}
});
}
/*private void testProviderCreation()
{
Provider testProvider = new Provider();
testProvider.setName("test");
providerManager.create(testProvider);
}
*/
public static interface Caller {
public <V> V call(Callable<V> callable) throws Exception;
}
/**
* This little bit of magic allows our test code to execute in
* the scope of a container controlled transaction.
*/
#Stateless
#TransactionAttribute(REQUIRES_NEW)
public static class TransactionBean implements Caller {
public <V> V call(Callable<V> callable) throws Exception {
return callable.call();
}
}
}
where provider manager is as below,
#Local(IProviderManager.class)
#Stateless
public class ProviderManager implements IProviderManager{
#PersistenceContext(unitName = "epgmanagerjpaunit")
private EntityManager entityManager;
public void create(Provider provider)
{
entityManager.persist(provider);
}
}
Thanks in advance,
-v-