My drool is working fine when I don't have agenda group but if I set focus i'm getting the following error:
package drools;
import droolsexec.Message;
import droolsexec.Customer;
rule "Good Bye"
agenda-group "group1"
dialect "java"
when
message: Message( status =="GOODBYE" )
customer: Customer(name == "NEHA")
then
System.out.println( message.getStatus());
end
This is my rule and i'm executing it by:
public class ExecuteDrools {
private static PackageBuilder pbuilder = new PackageBuilder();
private static StatefulSession sessionObject;
private static RuleBase rbase = RuleBaseFactory.newRuleBase();
public void runDrools(ArrayList list){
initialiseDrools();
initiliseMessageObject(list);
runRules();
}
private void initialiseDrools() {
//1. Read the DRL File and add to package builder
try {
Reader reader = new InputStreamReader(ExecuteDrools.class.getResourceAsStream("/HelloWorld.drl"));
pbuilder.addPackageFromDrl(reader);
} catch (DroolsParserException ex) {
Logger.getLogger(ExecuteDrools.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExecuteDrools.class.getName()).log(Level.SEVERE, null, ex);
}
//2. Check for any errors
PackageBuilderErrors errors = pbuilder.getErrors();
if (errors.getErrors().length > 0) {
System.out.println("Some errors exists in packageBuilder");
for (int i = 0; i < errors.getErrors().length; i++) {
System.out.println(errors.getErrors()[i]);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
//3. Add package to rule base
try {
rbase.addPackage(pbuilder.getPackage());
} catch (Exception e) {
System.out.println("Error: "+ e);
}
}
private void initiliseMessageObject(ArrayList list) {
sessionObject = rbase.newStatefulSession();
Iterator itr = list.iterator();
while(itr.hasNext()){
sessionObject.insert(itr.next());
}
}
private void runRules() {
sessionObject.getAgenda().getAgendaGroup("group2").setFocus();
sessionObject.fireAllRules();
}
}
I'm getting the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
at org.drools.common.BinaryHeapQueueAgendaGroup.setFocus(BinaryHeapQueueAgendaGroup.java:156)
at droolsexec.ExecuteDrools.runRules(ExecuteDrools.java:83)
at droolsexec.ExecuteDrools.runDrools(ExecuteDrools.java:36)
at droolsexec.MainClass.executeRules(MainClass.java:23)
at droolsexec.MainClass.main(MainClass.java:9)
you do not have an agenda group group2 in your drl file... you have it named group 1
Related
I have code snippet below.
What I want is if getNames() method catch an exception
( ex. InterruptedException ),
want to check if Got InterruptedException !!! prints out or not.
There are some examples of testing exception for a method
which throws an exception in its method ( ex. String method1() throws InterruptedException {...} ) in the Internet.
But not this case. Does anyone have some thought or idea?
public class A {
public List<String> getNames()
{
String addess = "address1";
int age = 17;
List<String> names = null;
try {
names = getSomeNames(address, sex);
}
catch (InterruptedException | ExecutionException e) {
throw new MyCustomException(e);
}
catch(Exception e) {
throw new MyCustomException(e);
}
return names;
}
List<String> getSomeNames(String address, int sex) throws InterruptedException, ExecutionException
{
// ...
// throw exceptions... at some point
//
return names;
}
}
public class MyCustomException extends Exception {
public MyCustomException(Throwable e) {
if (e.getCause() instanceof InterruptedException) {
// write log
System.out.println("Got InterruptedException !!!");
}
else if (e.getCause() instanceof ExecutionException) {
// write log
System.out.println("Got ExecutionException!!!");
}
else {
// write log
}
}
}
I tried this but the test failed and got NullPointerException in catch block.
#Test
public void testException() {
A objA = spy(new A());
try {
doThrow(MyCustomException.class).when(objA).getNames();
objA.getNnames();
}
catch (Exception e) {
System.out.println(e.getCause().toString()); // ==> throws java.lang.NullPointerException here.
}
}
There are several ways to test it.
First solution is to replace System.out with different stream and read from it later. ( I don't like this approach )
#Test
void whenSayHi_thenPrintlnCalled() throws IOException {
PrintStream normalOutput = System.out;
String result;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream temporalOutput = new PrintStream(baos)) {
System.setOut(temporalOutput);
ThatGuy thatGuy = new ThatGuy();
thatGuy.sayHi();
result = new String(baos.toByteArray(), StandardCharsets.UTF_8);
} finally {
System.setOut(normalOutput);
}
assertEquals("Hi", result.trim());
}
Second one is to use logger instead of just System.out. I consider this approach better not only from testing, but from code design perspective as well. Using this one you can just replace logger with Mockito.mock and user Mockito.verify to check what was called on your logger.
#Test
void whenSayHi_thenCallLogger() {
Logger logger = Mockito.mock(Logger.class);
ThatGuy thatGuy = new ThatGuy();
ReflectionTestUtils.setField(thatGuy, "logger", logger);
thatGuy.sayHiToLog();
verify(logger).error("Hi");
}
Class under testing looks like this:
class ThatGuy {
private static Logger logger = LoggerFactory.getLogger(ThatGuy.class);
void sayHi() {
System.out.println("Hi");
}
void sayHiToLog() {
logger.error("Hi");
}
}
I was trying to log the number of current active connections. I am using com.zaxxer.hikari.HikariJNDIFactory as my data source factory.
final Context context = new InitialContext();
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDataSource((DataSource) ((Context)context.lookup("java:comp/env")).lookup("jdbc/mydb"));
HikariPool hikariPool = new HikariPool(hikariConfig);
LOGGER.log(Level.INFO, "The count is ::" + hikariPool.getActiveConnections());
But it is throwing the following exception:
java.lang.RuntimeException: java.lang.NullPointerException
at com.zaxxer.hikari.util.PoolUtilities.createInstance(PoolUtilities.java:105)
at com.zaxxer.hikari.metrics.MetricsFactory.createMetricsTracker(MetricsFactory.java:34)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:131)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:99)
at com.something.servlet.HikariConnectionCount.doGet(HikariConnectionCount.java:35)
Where HikariConnectionCount.java is the file I have written
Programatic access is documented here https://github.com/brettwooldridge/HikariCP/wiki/MBean-(JMX)-Monitoring-and-Management
Here's a dirty recipe:
import org.springframework.beans.DirectFieldAccessor;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
public class HikariDataSourcePoolDetail {
private final HikariDataSource dataSource;
public HikariDataSourcePoolDetail(HikariDataSource dataSource) {
this.dataSource = dataSource;
}
public HikariPool getHikariPool() {
return (HikariPool) new DirectFieldAccessor(dataSource).getPropertyValue("pool");
}
public int getActive() {
try {
return getHikariPool().getActiveConnections();
} catch (Exception ex) {
return -1;
}
}
public int getMax() {
return dataSource.getMaximumPoolSize();
}
}
Use it thus:
try {
HikariDataSourcePoolDetail dsd = new HikariDataSourcePoolDetail((HikariDataSource)dataSource);
log.info("HikariDataSource details: max={} active={}", dsd.getMax(), dsd.getActive());
} catch (Exception e) {
log.error("HikariDataSourcePoolDetail failed: ", e);
}
I am currently facing following big problem:
I have a Framework-Project (maven), where a PropertyReader is included (reads "config.properties" in the same package and returns its values):
This is the Framework-Project:
public class PropertyReaderFramework {
private static Properties props;
private static void init(){
String filename = "com/ks/framework/properties/config.properties";
InputStream input = PropertyReaderFramework.class.getClassLoader()
.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
props = null;
} else {
props = new Properties();
}
try {
props.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key){
if(props == null) init();
return props.getProperty(key);
}
public static Properties getProperties(){
if(props == null) init();
return props;
}
}
And my main-project, where I need the information of the properties-file just has one class (for demonstation):
package testmsg;
import com.ks.framework.properties.PropertyReaderFramework;
public class main {
public static void main(String[] args) throws InterruptedException {
try {
String basepath = PropertyReaderFramework.getProperty("remoteFileAccess.script.location");
System.out.println(basepath);
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.sleep(5000);
}
}
}
The funny thing is, that if I execute the main() class in eclipse, it reads the value from the properties correctly.
But when I export it as a runnable JAR, it throws me following error:
Can anyone help me to solve this problem? I cannot figure out why it behaves like that...
I have created MDB to pick the message from MQ and inserting in to DB2.
I have created data sourse to get the DB connection in WAS. Its inserting message. But due to the speed of the MessageListener some messages not inserted because the connection got closed..
Please help me to handle the conction here..
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.NamingException;
#MessageDriven(
activationConfig = { #ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"), #ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/MDBQueue")
},
mappedName = "jms/MDBQueue")
public class AsyncMessageConsumerBean implements MessageListener {
// TODO Auto-generated constructor stub
private javax.naming.InitialContext ctx = null;
private javax.sql.DataSource serviceDataSource = null;
private String environment = null;
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
System.out.println("On Message Started.....");
try{
if (message instanceof javax.jms.BytesMessage)
{
javax.jms.BytesMessage bytesMessage = (javax.jms.BytesMessage) message;
byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(bytes);
System.out.println("Reply Message");
String replyMessage = new String(bytes, "UTF-8");
System.out.println(" The message received from MQ :-----" + replyMessage);
insertMQMessage(replyMessage);
}else {
javax.jms.TextMessage TextMessage = (javax.jms.TextMessage) message;
System.out.println("----------- The text message received from UM Queue"+TextMessage.getText());
insertMQMessage(TextMessage.getText());
}
}catch (JMSException ex) {
throw new RuntimeException(ex);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void insertMQMessage(String mqMessage) throws Exception
{
Statement stmtsql = null;
Connection connection = null;
try
{
connection = getDBConnection();
System.out.println("Connection Object :"+connection);
String mqMsgTrackerInsertQry = "";
System.out.println("MQ Tracker insert Query:" + mqMsgTrackerInsertQry);
stmtsql = connection.createStatement();
boolean status = stmtsql.execute(mqMsgTrackerInsertQry);
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (stmtsql != null)
try {
stmtsql.close();
} catch (SQLException ignore) {
}
if (connection != null)
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
private Connection getDBConnection() throws SQLException {
try {
ctx = new javax.naming.InitialContext();
serviceDataSource = (javax.sql.DataSource) ctx.lookup("jdbc/DB_DS_XA");
System.out.println("Datasource initiallised"+serviceDataSource);
} catch (NamingException e) {
System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!");
e.printStackTrace();
}
Connection connection = null;
try {
connection = serviceDataSource.getConnection();
//connection.setAutoCommit(false);
} catch (SQLException e) {
throw e;
}
return connection;
}
}
We use the ScheduledThreadPoolExecutor and after submitting the job we call shutdown immediately.
Because as per doc Shutdown does not kill the submitted task, running task and allows it to complete.
The question is after shutdown can we continue to use the future object that the ScheduledThreadPoolExecutor submit returns.
private static Future submitACall(Callable callableDelegate) {
ScheduledThreadPoolExecutor threadPoolExe = null;
try {
threadPoolExe = new ScheduledThreadPoolExecutor(1);
return threadPoolExe.submit(callableDelegate);
} finally {
threadPoolExe.shutdown();
}
}
//in another method...
if(future.isDone())
future.get();
Yes, you can, in a try-catch:
package testsomething;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class TestSomething {
private static Future future = null;
private static ScheduledThreadPoolExecutor threadPoolExe = null;
public static void main(String[] args) {
Callable callableDelegate = new MyCallable();
future = submitACall(callableDelegate);
try {
System.out.println("First get: " + ((Integer)future.get()));
} catch (InterruptedException | ExecutionException ex) {
System.out.println("Exception: " + ex);
}
try {
Thread.sleep(100L);
} catch (InterruptedException ex) {
System.out.println("Exception: " + ex);
}
try {
System.out.println("Thread pool shut down? " + threadPoolExe.isShutdown());
System.out.println("Second get through 'anotherMethod': " + anotherMethod());
} catch (InterruptedException | ExecutionException ex) {
System.out.println("Exception: " + ex);
}
}
private static Future submitACall(Callable callableDelegate) {
try {
threadPoolExe = new ScheduledThreadPoolExecutor(1);
return
threadPoolExe.submit(callableDelegate);
} finally {
threadPoolExe.shutdown();
}
}
private static Integer anotherMethod() throws ExecutionException, InterruptedException {
if(future.isDone())
return ((Integer)future.get());
else
return null;
}
private static class MyCallable implements Callable {
#Override
public Object call() throws Exception {
return new Integer(0);
}
}
}