Java Code Examples for org.apache.uima.fit.factory.JCasFactory#createJCas()

The following examples show how to use org.apache.uima.fit.factory.JCasFactory#createJCas() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LineOrientedTextReaderTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void test()
    throws Exception
{
    JCas doc = JCasFactory.createJCas();

    CollectionReader reader = createReader(LineOrientedTextReader.class,
            LineOrientedTextReader.PARAM_SOURCE_LOCATION, "LICENSE.txt");

    reader.getNext(doc.getCas());
    
    // select(doc, Sentence.class).forEach(s -> System.out.println(s.getCoveredText()));
    
    assertEquals(169, select(doc, Sentence.class).size());
    assertEquals(0, select(doc, Token.class).size());
}
 
Example 2
Source File: WebAnnoTsv3WriterTestBase.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void testZeroWidthAnnotationBeforeFirstTokenIsMovedToBeginOfFirstToken() throws Exception
{
    JCas jcas = JCasFactory.createJCas();
    
    DocumentMetaData.create(jcas).setDocumentId("doc");
    jcas.setDocumentText("  one two");
    new Token(jcas, 2, 5).addToIndexes();
    new Token(jcas, 6, 9).addToIndexes();
    new Sentence(jcas, 2, 9).addToIndexes();
    
    // NE is after the end of the last token and should be moved to the end of the last token
    // otherwise it could not be represented in the TSV3 format.
    new NamedEntity(jcas, 1, 1).addToIndexes();
    
    writeAndAssertEquals(jcas);
}
 
Example 3
Source File: WebAnnoTsv3WriterTestBase.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void testZeroWidthAnnotationBeyondLastTokenIsMovedToEndOfLastToken() throws Exception
{
    JCas jcas = JCasFactory.createJCas();
    
    DocumentMetaData.create(jcas).setDocumentId("doc");
    jcas.setDocumentText("one two  ");
    new Token(jcas, 0, 3).addToIndexes();
    new Token(jcas, 4, 7).addToIndexes();
    new Sentence(jcas, 0, 7).addToIndexes();
    
    // NE is after the end of the last token and should be moved to the end of the last token
    // otherwise it could not be represented in the TSV3 format.
    new NamedEntity(jcas, 8, 8).addToIndexes();
    
    writeAndAssertEquals(jcas);
}
 
Example 4
Source File: StandaloneArgument.java    From argument-reasoning-comprehension-task with Apache License 2.0 6 votes vote down vote up
public JCas getJCas()
        throws RuntimeException
{
    if (base64JCas == null) {
        return null;
    }

    try {
        byte[] bytes = new BASE64Decoder()
                .decodeBuffer(new ByteArrayInputStream(base64JCas.getBytes("utf-8")));
        JCas jCas = JCasFactory.createJCas();
        XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

        return jCas;
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: DocumentFactoryTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void ensureDuplicateKeyNotAllowed() throws UIMAException {
  JCas jCas = JCasFactory.createJCas();
  jCas.setDocumentText("This is sentence one. This is sentence two. This is sentence three.");

  List<Sentence> sentences = Annotations.createSentences(jCas);

  OdinSentence sentence1 = mock(OdinSentence.class, "s1");
  OdinSentence sentence2 = mock(OdinSentence.class, "s2");
  OdinSentence sentence3 = mock(OdinSentence.class, "s3");

  when(sentenceFactory.create()).thenReturn(ImmutableList.of(sentence1, sentence2, sentence3));
  when(sentence1.getBaleenSentence()).thenReturn(sentences.get(0));
  // Duplicate keys
  when(sentence2.getBaleenSentence()).thenReturn(sentences.get(1));
  when(sentence3.getBaleenSentence()).thenReturn(sentences.get(1));

  DocumentFactory documentFactory = new DocumentFactory(jCas, sentenceFactory);

  documentFactory.create();
}
 
Example 6
Source File: ConceptProvider.java    From bioasq with Apache License 2.0 6 votes vote down vote up
default List<Concept> getConcepts(List<String> texts, String viewNamePrefix)
        throws AnalysisEngineProcessException {
  JCas jcas;
  try {
    jcas = JCasFactory.createJCas();
  } catch (UIMAException e) {
    throw new AnalysisEngineProcessException(e);
  }
  List<JCas> views = texts.stream().map(text -> {
    String uuid = UUID.randomUUID().toString();
    JCas view = ViewType.createView(jcas, viewNamePrefix, uuid, text);
    InputElement ie = new InputElement(view, 0, text.length());
    ie.setDataset("N/A");
    ie.setQuuid(UUID.randomUUID().toString());
    ie.addToIndexes();
    return view;
  } ).collect(Collectors.toList());
  return getConcepts(views);
}
 
Example 7
Source File: DocumentGraphFactoryTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocumentGraphWithoutReferents() throws UIMAException {

  DocumentGraphOptions options =
      DocumentGraphOptions.builder().withReferenceTargets(false).build();
  DocumentGraphFactory factory = createfactory(options);

  JCas jCas = JCasFactory.createJCas();
  JCasTestGraphUtil.populateJcas(jCas);

  Graph graph = factory.create(jCas);

  assertEquals(0, graph.traversal().V().hasLabel(REFERENCE_TARGET).count().next().intValue());
  assertEquals(1, graph.traversal().V().hasLabel(EVENT).count().next().intValue());
  assertEquals(4, graph.traversal().V().hasLabel(MENTION).count().next().intValue());
  assertEquals(2, graph.traversal().V().hasLabel(RELATION).count().next().intValue());
  assertEquals(0, graph.traversal().E().hasLabel(MENTION_OF).count().next().intValue());
  assertEquals(2, graph.traversal().E().hasLabel(PARTICIPANT_IN).count().next().intValue());

  assertNoDocumentNode(graph);

  assertEquals(7, IteratorUtils.count(graph.vertices()));
  assertEquals(6, IteratorUtils.count(graph.edges()));
}
 
Example 8
Source File: CasMergeTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void copySpanWithSlotWithStackingTest()
    throws Exception
{
    AnnotatorState state = new AnnotatorStateImpl(CURATION);
    state.setUser(new User());
    
    slotLayer.setAnchoringMode(TOKENS);
    slotLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    
    JCas jcasA = createJCas(CurationTestUtils.createMultiLinkWithRoleTestTypeSystem("f1"));
    Type type = jcasA.getTypeSystem().getType(CurationTestUtils.HOST_TYPE);
    Feature feature = type.getFeatureByBaseName("f1");

    AnnotationFS clickedFs = CurationTestUtils.makeLinkHostMultiSPanFeatureFS(jcasA, 0, 0, feature, "A",
            CurationTestUtils.makeLinkFS(jcasA, "slot1", 0, 0));

    JCas mergeCAs = JCasFactory
            .createJCas(CurationTestUtils.createMultiLinkWithRoleTestTypeSystem("f1"));

    CurationTestUtils.makeLinkHostMultiSPanFeatureFS(mergeCAs, 0, 0, feature, "C",
            CurationTestUtils.makeLinkFS(mergeCAs, "slot1", 0, 0));

    sut.mergeSpanAnnotation(null, null, slotLayer, mergeCAs.getCas(), clickedFs, true);

    assertEquals(2, selectCovered(mergeCAs.getCas(), type, 0, 0).size());
}
 
Example 9
Source File: RemoveDanglingRelationsRepairTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
    throws Exception
{
    JCas jcas = JCasFactory.createJCas();

    jcas.setDocumentText("This is a test.");
    
    Token span1 = new Token(jcas, 0, 4);
    span1.addToIndexes();
    
    Token span2 = new Token(jcas, 6, 8);
    
    Dependency dep = new Dependency(jcas, 0, 8);
    dep.setGovernor(span1);
    dep.setDependent(span2);
    dep.addToIndexes();
    
    List<LogMessage> messages = new ArrayList<>();
    CasDoctor cd = new CasDoctor(RemoveDanglingRelationsRepair.class,
            AllFeatureStructuresIndexedCheck.class);
    // A project is not required for this check
    boolean result = cd.analyze(null, jcas.getCas(), messages);
    // A project is not required for this repair
    cd.repair(null, jcas.getCas(), messages);
    
    assertFalse(result);
    
    messages.forEach(System.out::println);
}
 
Example 10
Source File: CurationTestUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static JCas loadWebAnnoTsv3(String aPath) throws UIMAException, IOException
{
    CollectionReader reader = createReader(WebannoTsv3XReader.class,
            WebannoTsv3XReader.PARAM_SOURCE_LOCATION, "src/test/resources/" + aPath);
    JCas jcas = JCasFactory.createJCas();
    reader.getNext(jcas.getCas());
    return jcas;
}
 
Example 11
Source File: ChainAdapterTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception
{
    if (jcas == null) {
        jcas = JCasFactory.createJCas();
    }
    else {
        jcas.reset();
    }
    
    username = "user";
    
    project = new Project();
    project.setId(1l);
    project.setMode(PROJECT_TYPE_ANNOTATION);
    
    document = new SourceDocument();
    document.setId(1l);
    document.setProject(project);
    
    corefLayer = new AnnotationLayer(
            substring(CoreferenceChain.class.getName(), 0,
                    CoreferenceChain.class.getName().length() - ChainAdapter.CHAIN.length()),
            "Coreference", CHAIN_TYPE, project, true, TOKENS, ANY_OVERLAP);
    corefLayer.setId(1l);

    layerSupportRegistry = new LayerSupportRegistryImpl(asList());
    featureSupportRegistry = new FeatureSupportRegistryImpl(asList());
    
    behaviors = asList(new SpanOverlapBehavior(), new SpanCrossSentenceBehavior(),
            new SpanAnchoringModeBehavior());
}
 
Example 12
Source File: OpenNlpPosRecommenderTest.java    From inception with Apache License 2.0 5 votes vote down vote up
private List<CAS> loadData(Dataset ds, File ... files) throws UIMAException, IOException
{
    CollectionReader reader = createReader(Conll2006Reader.class,
        Conll2006Reader.PARAM_PATTERNS, files,
        Conll2006Reader.PARAM_LANGUAGE, ds.getLanguage());

    List<CAS> casList = new ArrayList<>();
    while (reader.hasNext()) {
        JCas cas = JCasFactory.createJCas();
        reader.getNext(cas.getCas());
        casList.add(cas.getCas());
    }
    return casList;
}
 
Example 13
Source File: GetStartedQuickPipeline.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws UIMAException {
  // uimaFIT automatically uses all type systems listed in META-INF/org.apache.uima.fit/types.txt

  // uimaFIT doesn't provide any collection readers - so we will just instantiate a JCas and
  // run it through our AE
  JCas jCas = JCasFactory.createJCas();

  // Instantiate the analysis engine using the value "uimaFIT" for the parameter
  // PARAM_STRING ("stringParam").
  AnalysisEngine analysisEngine = AnalysisEngineFactory.createEngine(GetStartedQuickAE.class,
          GetStartedQuickAE.PARAM_STRING, "uimaFIT");

  // run the analysis engine and look for a special greeting in your console.
  analysisEngine.process(jCas);
}
 
Example 14
Source File: WebAnnoTsv3WriterTestBase.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static JCas makeJCas() throws UIMAException
{
    TypeSystemDescription global = TypeSystemDescriptionFactory.createTypeSystemDescription();
    TypeSystemDescription local = TypeSystemDescriptionFactory
            .createTypeSystemDescriptionFromPath(
                    "src/test/resources/desc/type/webannoTestTypes.xml");
   
    TypeSystemDescription merged = CasCreationUtils.mergeTypeSystems(asList(global, local));
    
    JCas jcas = JCasFactory.createJCas(merged);

    DocumentMetaData.create(jcas).setDocumentId("doc");
    
    return jcas;
}
 
Example 15
Source File: ConstraintsVerifierTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
    throws Exception
{
    ConstraintsGrammar parser = new ConstraintsGrammar(new FileInputStream(
            "src/test/resources/rules/6.rules"));
    Parse p = parser.Parse();
    ParsedConstraints constraints = p.accept(new ParserVisitor());

    // Get imports
    Map<String, String> imports = new LinkedHashMap<>();
    imports = constraints.getImports();

    // Get rules
    // List<Rule> rules = new ArrayList<>();

    JCas jcas = JCasFactory.createJCas();
    jcas.setDocumentText("Just some text.");

    Lemma lemma1 = new Lemma(jcas, 0, 1);
    lemma1.setValue("good");
    lemma1.addToIndexes();

    Lemma lemma2 = new Lemma(jcas, 1, 2);
    lemma2.setValue("bad");
    lemma2.addToIndexes();

    Verifiable cVerifier = new ConstraintsVerifier();

    for (Lemma lemma : select(jcas, Lemma.class)) {
        if (lemma == lemma1) {
            assertEquals(true, cVerifier.verify(lemma, constraints));
        }
        if (lemma == lemma2) {
            assertEquals(false, cVerifier.verify(lemma, constraints));
        }
    }
}
 
Example 16
Source File: MtasDocumentIndexTest.java    From inception with Apache License 2.0 5 votes vote down vote up
private void annotateDocument(Project aProject, User aUser, SourceDocument aSourceDocument)
    throws Exception
{
    log.info("Preparing annotated document....");
    
    // Manually build annotated CAS
    JCas jCas = JCasFactory.createJCas();
    
    JCasBuilder builder = new JCasBuilder(jCas);

    builder.add("The", Token.class);
    builder.add(" ");
    builder.add("capital", Token.class);
    builder.add(" ");
    builder.add("of", Token.class);
    builder.add(" ");
    
    int begin = builder.getPosition();
    builder.add("Galicia", Token.class);
    
    NamedEntity ne = new NamedEntity(jCas, begin, builder.getPosition());
    ne.setValue("LOC");
    ne.addToIndexes();
    
    builder.add(" ");
    builder.add("is", Token.class);
    builder.add(" ");
    builder.add("Santiago", Token.class);
    builder.add(" ");
    builder.add("de", Token.class);
    builder.add(" ");
    builder.add("Compostela", Token.class);
    builder.add(" ");
    builder.add(".", Token.class);
    
    // Create annotation document
    AnnotationDocument annotationDocument = documentService
            .createOrGetAnnotationDocument(aSourceDocument, aUser);

    // Write annotated CAS to annotated document
    try (CasStorageSession casStorageSession = CasStorageSession.open()) {
        log.info("Writing annotated document using documentService.writeAnnotationCas");
        documentService.writeAnnotationCas(jCas.getCas(), annotationDocument, false);
    }

    log.info("Writing for annotated document to be indexed");
    await("Waiting for indexing process to complete")
            .atMost(60, SECONDS)
            .pollInterval(5, SECONDS)
            .until(() -> searchService.isIndexValid(aProject)
                    && !searchService.isIndexInProgress(aProject));
    log.info("Indexing complete!");
}
 
Example 17
Source File: RelationRendererTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception
{
    if (jcas == null) {
        jcas = JCasFactory.createJCas();
    }
    else {
        jcas.reset();
    }
    
    username = "user";
    
    project = new Project();
    project.setId(1l);
    project.setMode(PROJECT_TYPE_ANNOTATION);
    
    document = new SourceDocument();
    document.setId(1l);
    document.setProject(project);
    
    // Set up annotation schema with POS and Dependency
    AnnotationLayer tokenLayer = new AnnotationLayer(Token.class.getName(), "Token", SPAN_TYPE,
            project, true, SINGLE_TOKEN, NO_OVERLAP);
    tokenLayer.setId(1l);
    AnnotationFeature tokenLayerPos = new AnnotationFeature(1l, tokenLayer, "pos",
            POS.class.getName());

    AnnotationLayer posLayer = new AnnotationLayer(POS.class.getName(), "POS", SPAN_TYPE,
            project, true, SINGLE_TOKEN, NO_OVERLAP);
    posLayer.setId(2l);

    depLayer = new AnnotationLayer(Dependency.class.getName(), "Dependency", RELATION_TYPE,
            project, true, SINGLE_TOKEN, OVERLAP_ONLY);
    depLayer.setId(3l);
    depLayer.setAttachType(tokenLayer);
    depLayer.setAttachFeature(tokenLayerPos);
    dependencyLayerGovernor = new AnnotationFeature(2l, depLayer, "Governor",
            Token.class.getName());
    dependencyLayerDependent = new AnnotationFeature(3l, depLayer, "Dependent",
            Token.class.getName());

    featureSupportRegistry = new FeatureSupportRegistryImpl(asList());
    layerSupportRegistry = new LayerSupportRegistryImpl(asList());
    
    behaviors = asList(new RelationAttachmentBehavior(), new RelationOverlapBehavior(),
            new RelationCrossSentenceBehavior());
}
 
Example 18
Source File: NoMultipleIncomingRelationsCheckTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testOkBecauseCoref() throws Exception
{

    AnnotationLayer relationLayer = new AnnotationLayer();
    relationLayer.setName(CoreferenceChain.class.getName());

    relationLayer.setType(WebAnnoConst.CHAIN_TYPE);
    Mockito.when(annotationService.listAnnotationLayer(Mockito.isNull()))
            .thenReturn(Arrays.asList(relationLayer));

    JCas jcas = JCasFactory.createJCas();

    jcas.setDocumentText("This is a test.");

    Token spanThis = new Token(jcas, 0, 4);
    spanThis.addToIndexes();

    Token spanIs = new Token(jcas, 6, 8);
    spanIs.addToIndexes();

    Token spanA = new Token(jcas, 9, 10);
    spanA.addToIndexes();

    Dependency dep1 = new Dependency(jcas, 0, 8);
    dep1.setGovernor(spanThis);
    dep1.setDependent(spanIs);
    dep1.addToIndexes();

    Dependency dep2 = new Dependency(jcas, 0, 10);
    dep2.setGovernor(spanA);
    dep2.setDependent(spanIs);
    dep2.addToIndexes();

    List<LogMessage> messages = new ArrayList<>();

    boolean result = check.check(null, jcas.getCas(), messages);

    messages.forEach(System.out::println);

    assertTrue(result);
}
 
Example 19
Source File: NoMultipleIncomingRelationsCheckTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testOK() throws Exception
{
    AnnotationLayer relationLayer = new AnnotationLayer();
    relationLayer.setName(Dependency.class.getName());

    relationLayer.setType(WebAnnoConst.RELATION_TYPE);
    Mockito.when(annotationService.listAnnotationLayer(Mockito.isNull()))
            .thenReturn(Arrays.asList(relationLayer));

    JCas jcas = JCasFactory.createJCas();

    jcas.setDocumentText("This is a test.");

    Token spanThis = new Token(jcas, 0, 4);
    spanThis.addToIndexes();

    Token spanIs = new Token(jcas, 6, 8);
    spanIs.addToIndexes();

    Token spanA = new Token(jcas, 9, 10);
    spanA.addToIndexes();

    Dependency dep1 = new Dependency(jcas, 0, 8);
    dep1.setGovernor(spanThis);
    dep1.setDependent(spanIs);
    dep1.addToIndexes();

    Dependency dep2 = new Dependency(jcas, 6, 10);
    dep2.setGovernor(spanIs);
    dep2.setDependent(spanA);
    dep2.addToIndexes();

    List<LogMessage> messages = new ArrayList<>();

    boolean result = check.check(null, jcas.getCas(), messages);

    messages.forEach(System.out::println);

    assertTrue(result);
}
 
Example 20
Source File: EntityGraphFactoryTest.java    From baleen with Apache License 2.0 3 votes vote down vote up
@Test
public void testStopFetures() throws UIMAException {

  EntityGraphOptions options = EntityGraphOptions.builder().withStopFeatures("gender").build();
  EntityGraphFactory factory = createfactory(options);

  JCas jCas = JCasFactory.createJCas();
  JCasTestGraphUtil.populateJcas(jCas);

  Graph graph = factory.create(jCas);

  final GraphTraversalSource traversal = graph.traversal();

  assertTrue(traversal.V().not(has("gender")).hasNext());
}