I've included fully testable code below, which generates the following error when supplied with a dataset xml containing empty fields. A sample dataset.xml is also below.
java.lang.IllegalArgumentException: table.column=places.CITY value is
empty but must contain a value (to disable this feature check, set
DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS to true)
The thread here is similar but is different since it uses multiple dbTester.getConnection() whereas my code only uses one, yet has the same error. The main problem relates to this line databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE); .
It seems to be ignored entirely. I've tried putting the init code inside the #Test method but the error remains.
dataset.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<places address="123 Up Street" city="Chicago" id="001"/>
<places address="456 Down Street" city="" id="002"/>
<places address="789 Right Street" city="Boston" id="003"/>
</dataset>
Code:
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBConnectionIT {
IDatabaseTester databaseTester = null;
IDatabaseConnection iConn = null;
Connection connection = null;
#Before
public void init() throws Exception {
databaseTester = new JdbcDatabaseTester(org.hsqldb.jdbcDriver.class.getName(), "jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true", "sa", "");
iConn = databaseTester.getConnection();
DatabaseConfig databaseConfig = iConn.getConfig();
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
connection = iConn.getConnection();
createTable(connection);
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File("dataset.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onSetup();
}
#Test
public void testDBUnit() {
try {
PreparedStatement pst = connection.prepareStatement("select * from places");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createTable(Connection conn) throws Exception {
PreparedStatement pp = conn.prepareStatement(
"CREATE TABLE PLACES" +
"(address VARCHAR(255), " +
"city TEXT, " +
"id VARCHAR(255) NOT NULL primary key)");
pp.executeUpdate();
pp.close();
}
}
EDIT (based on César Rodríguez's answer):
I've now refactored out this method in the parent class:
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
}
and created a sub-class which #Overrides this method, but it's saying this sub-class is not being used. How do I address this class (DBConnectionOverride) in the parent class, to solve my problem?
class DBConnectionOverride extends DBConnectionIT {
#Override
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
}
I've stumbled upon the correct answer, at least the one which solves my problem. It related to this line all along databaseTester.onSetup() which could simply be replaced with DatabaseOperation.CLEAN_INSERT.execute(iConn, dataSet);. Feel free comment on why this seemed to have fixed the error.
You must override method setUpDatabaseConfig(DatabaseConfig config) as follows:
#Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
Hope it helps
for me it's work:
IDatabaseConnection dbConn = new DatabaseDataSourceConnection(getDataSource());
dbConn.getConfig().setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
DatabaseOperation.CLEAN_INSERT.execute(dbConn, getiDataSet(loadDBData.source()));
Related
What I'm trying to achieve - Simple unit test for my EmailUtil which i have written for a Spring MVC application.
Where I'm stuck - Though i have mocked the MIMEmessage and JavaMailSender, test case failing in MimeMessageHelper.set**** methods.
Appreciate any help on this as I have tried few different ways even using PowerMock and no luck for last couple of days.
EmailUtil.Java
import java.util.List;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.Attachment;
import com.dashboard.domain.Email;
public class EmailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class
.getName());
/**
* Private constructor to make sure that no one creating instance
*/
private EmailUtil() {
}
/**
* Functionality to send the mail. This method used the mail sender
* configuration from spring-context file.
*
* #param email
* #param mailSender
* #throws MessagingException
*/
public static void sendEmail(JavaMailSender mailSender, Email email)
throws MessagingException {
LOGGER.info("Start of the method: sendEmail");
MimeMessage mimeMessage = mailSender.createMimeMessage();
// use the true flag to indicate you need a multi part message
boolean hasAttachments = email.getAttachments() != null
&& !email.getAttachments().isEmpty();
LOGGER.info(" mimeMessage - {} ",mimeMessage);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
hasAttachments);
LOGGER.info(" MimeMessageHelper - {} ",helper);
helper.setTo(email.getTo());
helper.setFrom(email.getFrom());
helper.setCc(email.getCc());
helper.setSubject(email.getSubject());
helper.setText(email.getText(), true);
List<Attachment> attachments = email.getAttachments();
if (!attachments.isEmpty()) {
for (Attachment attachment : attachments) {
String filename = attachment.getFilename();
DataSource dataSource = new ByteArrayDataSource(
attachment.getData(), attachment.getMimeType());
if (attachment.isInline()) {
helper.addInline(filename, dataSource);
} else {
helper.addAttachment(filename, dataSource);
}
}
}
mailSender.send(mimeMessage);
LOGGER.info("End of the method: sendEmail");
}
}
EmailUtilTest.Java
import static org.easymock.EasyMock.expect;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.easymock.EasyMock;
import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.ApplicationConstant;
import com.dashboard.domain.Email;
/**
* PowerMockDemo
* #author s.arumugam
*
*/
#RunWith(PowerMockRunner.class)
#PrepareForTest(EmailUtil.class)
public class EmailUtilTest {
Email email = new Email();
#Mock
JavaMailSender javaMailSender;
#Mock
MimeMessage mimeMessage;
#Mock
MimeMessageHelper mimeMessageHelper;
#Before
public void initList() {
email.setFrom(ApplicationConstant.DEFAULT_MAIL_ID.getValue());
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
}
#Test
public void sendEmailTest() throws Exception{
mimeMessageHelper.setSubject(email.getSubject());
mimeMessageHelper.setFrom(new InternetAddress(email.getFrom(), true));
mimeMessageHelper.setCc(new InternetAddress(email.getCc()[0], true));
mimeMessageHelper.setTo(new InternetAddress(email.getTo()[0], true));
mimeMessageHelper.setText(email.getText());
expect(javaMailSender.createMimeMessage()).andReturn(mimeMessage);
Address sendTo[]={new InternetAddress(email.getTo()[0])};
mimeMessage.setRecipients(RecipientType.TO,sendTo);
EasyMock.expectLastCall().times(1);
EasyMock.replay(mimeMessage);
EasyMock.replay(javaMailSender);
EmailUtil.sendEmail(javaMailSender, email);
EasyMock.verify(mimeMessage);
EasyMock.verify(javaMailSender);
}
}
Error Message:
java.lang.AssertionError: Unexpected method call MimeMessage.setRecipients(To, [to.email#userdomain.com]):
MimeMessage.setRecipients(To, [to.email#userdomain.com]): expected: 1, actual: 0 at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94) at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97) at $javax.mail.internet.MimeMessage$$EnhancerByCGLIB$$a6025b60.setRecipients(<generated>) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:581) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:595) at com.dashboard.util.EmailUtil.sendEmail(EmailUtil.java:50)
Ohh.. I managed to fix the issue.. purely by random trial and error..! That says I need to get into deep understanding of how these mock utils works.. Working test case below with a hope someone can find a complete working example with test case;
#RunWith(EasyMockRunner.class)
public class EmailUtilTest extends EasyMockSupport{
#Mock
JavaMailSender mailSender;
#Mock
MimeMessage mimeMessage;
#Test
public void testSendEmail() throws MessagingException{
Email email = new Email();
email.setFrom("from.email#dashboard.com");
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
EasyMock.expect(mailSender.createMimeMessage()).andReturn(mimeMessage);
mailSender.send(mimeMessage);
EasyMock.expectLastCall();
EasyMock.replay(mailSender);
EmailUtil.sendEmail(mailSender, email);
EasyMock.verify(mailSender);
}
}
The reason you are getting java.lang.AssertionError is because EasyMock uses the equals() method to compare parameters passed to methods, and you cannot use equals() to compare arrays.
Address toAddress = new InternetAddress("a#b.com");
Address[] a1 = { toAddress };
Address[] a2 = { toAddress };
if (a1.equals(a2)) { // this will be false
// so this won't happen
}
Thankfully, EasyMock provides us with several different argument matchers. In this case we should use EasyMock.aryEq(). So in order to mock out the call to setRecipients() method:
mimeMessage.setRecipients(EasyMock.eq(RecipientType.TO) , EasyMock.aryEq(sendTo));
I'm not sure how the accepted answer is working without changes to the EmailUtil class.
I have Eclipse Java EE IDE Helios Service Release 2 Build id: 20110218-0911; I am trying use them with SeleniumRC and when I compile the code appears the next error message:
Type mismatch: cannot convert from DataProviderSites to annotation
The attribute DataProviderSites is undefined for the annotation type Test
However, when I validate the code, is visualized "the validation completed with no errors or warnings"
The Code in DataProviderSites.java is:
package script;
import org.junit.Test;
import junit.framework.TestCase;
import com.thoughtworks.selenium.SeleneseTestBase;
import org.junit.AfterClass;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import java.io.File;
import jxl.*;
public class DataProviderSites extends SeleneseTestBase {
#BeforeClass
public void setUp() throws Exception {
SeleniumServer seleniumserver=new SeleniumServer();
seleniumserver.boot();
seleniumserver.start();
setUp("http://www.examinator.ws/", "*firefox");
selenium.open("/");
selenium.windowMaximize();
selenium.windowFocus();
}
#DataProviderSites
(name = "DPS1")
public Object[][] createData1() throws Exception{
Object[][] retObjArr=getTableArray("test\\Resources\\Data\\sitios.xls",
"DataPool", "TestData");
return(retObjArr);
}
#Test(DataProviderSites = "DPS1")
public void testDataProviderSites(String nombre) throws Exception {
selenium.type("sitio", nombre);
if (selenium.isTextPresent("examinator"))
selenium.click("xpath=/descendant::button[#type='submit']");
else
selenium.waitForPageToLoad("30000");
selenium.click("xpath=/descendant::a[text()='"+nombre+"']");
}
#AfterClass
public void tearDown(){
selenium.close();
selenium.stop();
}
public String[][] getTableArray(String xlFilePath, String sheetName, String tableName) throws Exception{
String[][] tabArray=null;
Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
Sheet sheet = workbook.getSheet(sheetName);
int startRow,startCol, endRow, endCol,ci,cj;
Cell tableStart=sheet.findCell(tableName);
startRow=tableStart.getRow();
startCol=tableStart.getColumn();
Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false);
endRow=tableEnd.getRow();
endCol=tableEnd.getColumn();
System.out.println("startRow="+startRow+", endRow="+endRow+", " +
"startCol="+startCol+", endCol="+endCol);
tabArray=new String[endRow-startRow-1][endCol-startCol-1];
ci=0;
for (int i=startRow+1;i<endRow;i++,ci++){
cj=0;
for (int j=startCol+1;j<endCol;j++,cj++){
tabArray[ci][cj]=sheet.getCell(j,i).getContents();
}
}
return(tabArray);
}
}
Anybody have a idea to resolve this?
Just click the error and click "Convert to TestNG(Annotations)".
Validation does not check the logic like it does not check for syntax of code.
But when we compile the program it will check for syntax so you got type cast exception.
Validation success does not mean program is correct.
I think annotations(#Test(DataProviderSites = "DPS1"), #DataProviderSites
(name = "DPS1")) causes the exception.
I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.
I'm using a daemon-script which is monitoring a remote server. When the remote server is up, i want that Netbeans automatically connects it's Debugger to the remote Server.
Is it possible to control this behavior from commandline?
To type Something like
netbeans --attach-debugger 192.168.178.34:9009
inside a terminal to do that? Or what other ways do i have to get access to Netbeans-internal stuff? (until now, i was just a "user" of Netbeans so i don't know the internals and how to access them very well)
Or will i have to write a Netbeans Plugin to do that? If yes, can you give me a good starting point to add that functionality?
Ok since there is no option to attach the Debugger from commandline, i wrote a Netbeans Plugin with the help of this blog entry and this thread from the NB-mailinglist. Now i'm able to call my plugin actions from the Commandline.
So build a simple NetBeans Module, which contains 2 important classes.
This is the class which gets the commandline parameters and forwards them to my Action:
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
#ServiceProvider(service = OptionProcessor.class)
public class TriggerActionCommandLine extends OptionProcessor {
//Here we specify "runAction" as the new key in the command,
//but it could be any other string you like, of course:
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "debug");
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
#Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
#Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = (String[]) values.get(action);
if (args.length > 0) {
//Set the value to be the first argument from the command line,
//i.e., this is "GreetAction", for example:
final String ip = args[0];
//Wait until the UI is constructed,
//otherwise you will fail to retrieve your action:
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
#Override
public void run() {
//Then find & perform the action:
Action a = findAction(AttachDebugger.ACTION_NAME);
// forward IP address to Action
ActionEvent e = new ActionEvent(this, 1, ip);
a.actionPerformed(e);
}
});
}
}
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/PSFActions");
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
logger.info(fileObject.getName());
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
return null;
}
}
This is my Plugin Action which attaches the Debugger to the given remote address:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.debugger.jpda.DebuggerStartException;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.python.util.PythonInterpreter;
#ActionID(category = "PSFActions", id = "de.mackaz.AttachDebugger")
#ActionRegistration(displayName = "#CTL_AttachDebuggerAction")
#ActionReferences({
#ActionReference(path = "Menu/Tools", position = 1800, separatorBefore = 1750, separatorAfter = 1850)
})
public final class AttachDebugger implements ActionListener {
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
public static final String ACTION_NAME="AttachDebugger";
#Override
public void actionPerformed(ActionEvent e) {
String ip;
if (!e.getActionCommand().contains("Attach Debugger")) {
ip = e.getActionCommand();
} else {
ip = lookupIP();
}
try {
logger.log(Level.INFO, "Attaching Debugger to IP {0}", ip);
JPDADebugger.attach(
ip,
9009,
new Object[]{null});
} catch (DebuggerStartException ex) {
int msgType = NotifyDescriptor.ERROR_MESSAGE;
String msg = "Failed to connect debugger to remote IP " + ip;
NotifyDescriptor errorDescriptor = new NotifyDescriptor.Message(msg, msgType);
DialogDisplayer.getDefault().notify(errorDescriptor);
}
}
}
Now i can attach the Netbeans debugger to a specific address by calling netbeans/bin/netbeans --debug 192.168.178.79
While am trying to execute the Helloword process example from the section 2.3 in
https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/drools-flow/html_single/index.html#d4e24 site am unable to find the below mentioned class.
org.drools.builder.KnowledgeType
Could anyone please tell from which package can i get this class?
Thanks!
That part of the documentation seems a little outdated. You should use ResourceType. I've updated the docs with the following code fragment instead (should also appear on the link you're using once the build succeeds):
package com.sample;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
/**
* This is a sample file to launch a process.
*/
public class ProcessTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
// start a new process instance
ksession.startProcess("com.sample.ruleflow");
logger.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
private static KnowledgeBase readKnowledgeBase() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("ruleflow.rf"), ResourceType.DRF);
return kbuilder.newKnowledgeBase();
}
}