/**

   Copyright 2009 OpenEngSB Division, Vienna University of Technology

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE\-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.openengsb.drools;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.io.File;
import java.io.IOException;

import org.drools.RuleBase;
import org.drools.StatefulSession;
import org.drools.WorkingMemory;
import org.drools.event.AfterActivationFiredEvent;
import org.drools.event.DefaultAgendaEventListener;
import org.drools.rule.Package;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openengsb.core.model.Event;
import org.openengsb.drools.RuleBaseSource.RuleBaseElement;
import org.openengsb.util.IO;

public class DirectorySourceTest {

    private static class RuleListener2 extends DefaultAgendaEventListener {
        protected int numFired = 0;

        @Override
        public void afterActivationFired(AfterActivationFiredEvent event, WorkingMemory workingMemory) {
            numFired++;
            super.afterActivationFired(event, workingMemory);
        }
    }

    private RuleBaseSource source;
    private RuleBase rb;
    private StatefulSession session;
    private RuleListener2 listener;

    @Before
    public void setUp() throws Exception {
        File rbDir = new File("data/rulebase");
        rbDir.mkdirs();
        copyAllFiles(new File("src/test/resources/rulebase"), "data/rulebase/");

        source = new DirectoryRuleSource("data/rulebase");
        rb = source.getRulebase();
    }

    private void copyAllFiles(File srcDir, String dest) throws IOException {
        for (File f : srcDir.listFiles()) {
            IO.copyFile(f, new File(dest + "/" + f.getName()));
        }
    }

    private void createSession() {
        session = rb.newStatefulSession();
        listener = new RuleListener2();
        session.addEventListener(listener);
    }

    @After
    public void tearDown() throws Exception {
        IO.deleteStructure(new File("data"));
        if (session != null) {
            session.dispose();
        }
    }

    @Test
    public void testGetRuleBase() throws Exception {
        Assert.assertNotNull(rb);
        Package p = rb.getPackage("org.openengsb");
        assertNotNull(p);
        System.err.println(p.getRules().length);
    }

    @Test
    public void testGetRules() throws Exception {
        createSession();
        Event testEvent = new Event("nomatter_domain", "hello");
        session.insert(testEvent);
        session.fireAllRules();
    }

    @Test
    public void testFireRules() throws Exception {
        testGetRules();
        Assert.assertEquals(listener.numFired, 1);
    }

    @Test
    public void testAddRule() throws Exception {
        source.add(RuleBaseElement.Rule, "test3", "when\n" + "  e : Event( name == \"hello\")\n" + "then\n"
                + "  System.out.println(\"this rule was added by the addrule-function\");\n");
        createSession();
        Event event = new Event("", "hello");
        session.insert(event);
        session.fireAllRules();
        assertEquals(2, listener.numFired);
    }

    @Test
    public void testAddImport() throws Exception {
        Package p = getPackage();
        assertNull(p.getImports().get("java.util.Currency"));
        source.add(RuleBaseElement.Import, "java.util.Currency", "ignored");
        p = getPackage();
        assertNotNull(p.getImports().get("java.util.Currency"));
    }

    private Package getPackage() throws RuleBaseException {
        Package p = source.getRulebase().getPackage("org.openengsb");
        return p;
    }

    @Test
    public void testRemoveImport() throws Exception {
        Package p = getPackage();
        source.add(RuleBaseElement.Import, "java.util.Currency", "ignored");
        source.delete(RuleBaseElement.Import, "java.util.Currency");
        p = getPackage();
        assertNull(p.getImports().get("java.util.Currency"));
    }

    @Test
    public void testAddFunction() throws Exception {
        source.add(RuleBaseElement.Function, "notify", "function void notify(String message) {\n"
                + "System.out.println(\"notify: \" + message);\n}");
        Package p = getPackage();
        assertFalse(p.getFunctions().isEmpty());
        assertNotNull(p.getFunctions().get("notify"));
    }

    @Test
    public void testRemoveFunction() throws Exception {
        source.add(RuleBaseElement.Function, "notify", "function void notify(String message) {\n"
                + "System.out.println(\"notify: \" + message);\n}");
        source.delete(RuleBaseElement.Function, "notify");
        Package p = getPackage();
        assertNull(p.getFunctions().get("notify"));
    }

    @Test
    public void testRuleCallingFunctionUsingImport() throws Exception {
        source.add(RuleBaseElement.Function, "test", "function void test(Object message) {\n"
                + "System.out.println(\"notify: \" + message);\n}");
        source.add(RuleBaseElement.Import, "java.util.Random", "ignored");
        source.add(RuleBaseElement.Rule, "test", "when\n" + "  e : Event( name == \"testevent\")\n" + "then\n"
                + "  test(new Random());\n");
        createSession();

        session.insert(new Event("", "testevent"));
        session.fireAllRules();
        assertEquals(1, listener.numFired);
    }

    @Test
    public void testGlobalLoaded() throws Exception{
        String global = getPackage().getGlobals().get("test");
        assertNotNull(global);
    }

}

@@ -833,16 +833,59 @@
 ertNull;
+%0Aimport static org.junit.Assert.assertTrue;
 %0A%0Aimport
@@ -926,16 +926,89 @@
 ception;
+%0Aimport java.util.HashSet;%0Aimport java.util.Random;%0Aimport java.util.Set;
 %0A%0Aimport
@@ -1606,16 +1606,82 @@
 red = 0;
+%0A        protected Set%3CString%3E rulesFired = new HashSet%3CString%3E();
 %0A%0A      
@@ -1793,24 +1793,95 @@
 ngMemory) %7B%0A
+            rulesFired.add(event.getActivation().getRule().getName());%0A
             
@@ -2609,32 +2609,32 @@
        %7D%0A    %7D%0A%0A
-
     private void
@@ -2648,24 +2648,124 @@
 Session() %7B%0A
+        if (session != null) %7B%0A            session.dispose();%0A            session = null;%0A        %7D%0A
         sess

improve test-setup