import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.ruta.engine.RutaEngine;

import java.io.IOException;

import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngine;

public class RutaAnnotationVariableError {

    public static void main(String[] args) throws IOException, UIMAException {

        AnalysisEngineDescription ruta = AnalysisEngineFactory.createEngineDescription(
                        "org.apache.uima.ruta.engine.BasicEngine",
                        RutaEngine.PARAM_MAIN_SCRIPT, "annotation-variable"
                    );
        AnalysisEngine ae = createEngine(ruta);

        // Initial run where reference annotation variable is set
        JCas jCas = JCasFactory.createJCas();
        jCas.setDocumentText("Hello world");
        ae.process(jCas);
        Link link = JCasUtil.select(jCas, Link.class).stream().findFirst().get();
        System.out.println("Linked text: "+link.getReference().getCoveredText());

        // Second run where reference annotation variable is not set
        jCas = JCasFactory.createJCas();
        jCas.setDocumentText("Bye Bye world");
        ae.process(jCas);
        link = JCasUtil.select(jCas, Link.class).stream().findFirst().get();
        if(link.getReference() != null) {
            System.out.println("Linked text: " + link.getReference().getCoveredText());
        } else {
            // We hoped this would happen since reference was never set in the second run, but a CASRuntimeException
            // happens, because the previous value of the reference from the first run is used. There is no simple way
            // to initialize the reference to null in the script on every script invocation, but a rather awkward work
            // around has to be applied.
            System.out.println("No linked text!");
        }
    }

}
