uk.nhs.cfh.dsp.snomed.converters.compositionalgrammar.parser.SnomedExpressionParserTest.java Source code

Java tutorial

Introduction

Here is the source code for uk.nhs.cfh.dsp.snomed.converters.compositionalgrammar.parser.SnomedExpressionParserTest.java

Source

/**
 * Crown Copyright (C) 2008 - 2011
 *
 * 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 uk.nhs.cfh.dsp.snomed.converters.compositionalgrammar.parser;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeAdaptor;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.runtime.tree.DOTTreeGenerator;
import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import uk.nhs.cfh.dsp.snomed.dao.TerminologyConceptDAO;
import uk.nhs.cfh.dsp.snomed.expression.model.impl.AbstractExpressionWithFocusConcepts;
import uk.nhs.cfh.dsp.snomed.objectmodel.SnomedConcept;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Map;
import java.util.TreeMap;

// TODO: Auto-generated Javadoc
/**
 * A test case for the SnomedExpressionParser that will be generated by ANTLR.
 *
 * <br>Version : @#VersionNumber#@
 * <br>Written by @author Jay Kola
 * <br>Created on Feb 6, 2010 at 2:21:08 PM
 */
public class SnomedExpressionParserTest extends AbstractDependencyInjectionSpringContextTests {

    /** The lexer. */
    private SnomedExpressionLexer lexer;

    /** The concept map. */
    private Map<String, SnomedConcept> conceptMap = new TreeMap<String, SnomedConcept>();

    /** The test file. */
    private File testFile;

    /** The logger. */
    private static Log logger = LogFactory.getLog(SnomedExpressionParserTest.class);

    /** The test terminology dao. */
    private TerminologyConceptDAO testTerminologyDAO;

    /* (non-Javadoc)
     * @see org.springframework.test.AbstractSingleSpringContextTests#getConfigLocations()
     */
    @Override
    protected String[] getConfigLocations() {
        return new String[] { "META-INF/spring/bundle-context-test.xml" };
    }

    /* (non-Javadoc)
     * @see org.springframework.test.AbstractSingleSpringContextTests#onSetUp()
     */
    @Override
    protected void onSetUp() throws Exception {

        lexer = new SnomedExpressionLexer();
        testFile = new File(SnomedExpressionParserTest.class.getResource("test-expression.sxt").toURI());
        assertNotNull("Data Access Object must not be null", testTerminologyDAO);
        assertNotNull(lexer);
        assertTrue(testFile.exists());
    }

    /**
     * Test lex and parse.
     *
     * @throws Exception the exception
     */
    public void testLexAndParse() throws Exception {

        // Parse the test file
        String source = testFile.getAbsolutePath();
        try {
            lexer.setCharStream(new ANTLRFileStream(source, "UTF8"));

            // Using the lexer as the token source, we create a token
            // stream to be consumed by the parser
            //
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            assertNotNull("Token passed by lexer must not be null", tokens);

            // Now we need an instance of our parser
            //
            SnomedExpressionParser parser = new SnomedExpressionParser(tokens);
            assertNotNull("Parser must not be null", parser);

            // Provide some user feedback
            //
            logger.info("    Lexer Start");
            long start = System.currentTimeMillis();
            tokens.LT(1);
            long lexerStop = System.currentTimeMillis();
            logger.info("      Lexed in " + (lexerStop - start) + "ms.");

            // And now we merely invoke the start rule for the parser
            //
            logger.info("    Parser Start");
            long pStart = System.currentTimeMillis();
            SnomedExpressionParser.snomed_return parserReturn = parser.snomed();
            assertNotNull("Parser return must not be null null", parserReturn);
            long stop = System.currentTimeMillis();
            logger.info("      Parsed in " + (stop - pStart) + "ms.");

            // Pick up the generic tree
            //
            CommonTree t = (CommonTree) parserReturn.getTree();
            assertNotNull("AST must not be null", t);
            String treeOutput = t.toStringTree();
            assertNotNull("Tree output must not be null", t);
            logger.info("treeOutput = " + treeOutput);

            CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
            nodes.setTokenStream(tokens);
            assertNotNull("Node stream must not be null", nodes);

            // NOw walk it with the generic tree walker, which does nothing but
            // verify the tree really.
            //
            try {
                if (parser.getNumberOfSyntaxErrors() == 0) {
                    SnomedExpressionTree walker = new SnomedExpressionTree(nodes, testTerminologyDAO);
                    assertNotNull("Expression tree must not be null", walker);
                    logger.info("    AST Walk Start\n");
                    pStart = System.currentTimeMillis();
                    AbstractExpressionWithFocusConcepts returnedExpression = walker.expression();
                    assertNotNull("Returned expression must not be null", returnedExpression);
                    logger.info("returnedExpression = " + returnedExpression);
                    stop = System.currentTimeMillis();
                    logger.info("\n      AST Walked in " + (stop - pStart) + "ms.");
                }

                // output tree to a graphics file using DOT
                if (tokens.size() < 4096) {
                    // Use the ANLTR built in dot generator
                    //
                    DOTTreeGenerator gen = new DOTTreeGenerator();
                    assertNotNull("DOT generator must not be null", gen);
                    source = source.substring(0, source.length() - 3);
                    String outputName = source + "dot";
                    logger.info("    Producing AST dot (graphviz) file");

                    StringTemplate st = gen.toDOT(t, new CommonTreeAdaptor());
                    assertNotNull("String template must not be null", st);
                    // Create the output file and write the dot spec to it
                    //
                    FileWriter outputStream = new FileWriter(outputName);
                    outputStream.write(st.toString());
                    outputStream.close();

                    //                    // Invoke dot to generate a .png file
                    //                    //
                    //                    logger.info("    Producing png graphic for tree");
                    //                    pStart = System.currentTimeMillis();
                    //                    Process proc = Runtime.getRuntime().exec("dot -Tpng -o" + source + "png " + outputName);
                    //                    proc.waitFor();
                    //                    File dotFile = new File(SnomedExpressionParserTest.class.getResource("test-expression.png").toURI());
                    //                    assertTrue("File must exist", dotFile.exists());
                    //                    stop = System.currentTimeMillis();
                    //                    logger.info("      PNG graphic produced in " + (stop - pStart) + "ms.");
                }
            } catch (Exception e) {
                logger.warn("AST Walk caused an error. Nested exception is : " + e.fillInStackTrace());
            }
        } catch (FileNotFoundException ex) {
            // The file we tried to parse does not exist
            //
            logger.warn("\n  !!The file " + source + " does not exist!!\n");
        } catch (Exception ex) {
            // Something went wrong in the parser, report this
            logger.warn("Parser threw an exception. Nested exception is : " + ex.fillInStackTrace());
        }
    }

    /**
     * Sets the test terminology dao.
     *
     * @param testTerminologyDAO the new test terminology dao
     */
    public void setTestTerminologyDAO(TerminologyConceptDAO testTerminologyDAO) {
        this.testTerminologyDAO = testTerminologyDAO;
    }
}