Java Code Examples for org.apache.uima.cas.CAS#getTypeSystem()

The following examples show how to use org.apache.uima.cas.CAS#getTypeSystem() . 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: CASArtifact.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
CASArtifact(
    @Nullable LabelAdapters labelAdapters,
    CAS cas,
    String artifactID
) {
  this.labelAdapters = labelAdapters;
  this.cas = cas;

  TypeSystem typeSystem = cas.getTypeSystem();
  metadataType = typeSystem.getType("ArtifactMetadata");
  keyFeature = metadataType.getFeatureByBaseName("key");
  valueFeature = metadataType.getFeatureByBaseName("value");

  metadataCas = cas.createView("metadata");
  metadataCas.setDocumentText("");

  Type idType = typeSystem.getType("ArtifactID");
  Feature idFeat = idType.getFeatureByBaseName("artifactID");
  this.artifactID = artifactID;
  FeatureStructure documentIdFs = metadataCas.createFS(idType);
  documentIdFs.setStringValue(idFeat, artifactID);
  metadataCas.addFsToIndexes(documentIdFs);
  metadataIndex = metadataCas.getIndexRepository().getIndex("metadata", metadataType);

  casMetadata = new CASMetadata();
}
 
Example 2
Source File: AllTypes.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Update.
 */
// create a hash table of all types
private void update() {
  cachedResult.clear();

  CAS tcas = modelRoot.getCurrentView();
  if (null == tcas)
    return;
  TypeSystem typeSystem = tcas.getTypeSystem();

  if (typeSystem == null)
    return;

  Iterator typeIterator = typeSystem.getTypeIterator();

  while (typeIterator.hasNext()) {
    Type type = (Type) typeIterator.next();
    String typeName = type.getName();
    if (null != typeName && !typeName.endsWith("[]")) {
      cachedResult.put(type.getName(), type);
    }
  }
}
 
Example 3
Source File: CasOutputDestination.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor, initializes all fields.
 *
 * @param destinationView The view to write to.
 * @param casMappings The property cas mappings
 * @param annotationTypeForControlWord The annotation type to create for control words.
 * @param name the name of the view
 */
CasOutputDestination(CAS destinationView,
    List<PropertyCasMapping> casMappings,
    Map<String, Type> annotationTypeForControlWord,
    String name,
    boolean writeTables
) {
  this.destinationView = destinationView;
  this.sofaBuilder = new StringBuilder();
  this.completedAnnotations = new ArrayList<>();
  this.annotationPropertyWatchers = casMappings.stream()
      .map(AnnotationPropertyWatcher::new)
      .collect(Collectors.toList());
  this.annotationTypeForControlWord = annotationTypeForControlWord;
  this.name = name;
  this.writeTables = writeTables;
  TypeSystem typeSystem = destinationView.getTypeSystem();
  illegalCharType = typeSystem.getType("biomedicus.v2.rtf.IllegalXmlCharacter");
  valueFeat = illegalCharType.getFeatureByBaseName("value");
}
 
Example 4
Source File: AnnotationFeaturesViewer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the feature names for type.
 *
 * @param aTypeName the a type name
 * @param cas the cas
 * @return the feature names for type
 */
// untimely ripped from UIMA since it does not work with a taeDescription
private String[] getFeatureNamesForType(String aTypeName, CAS cas) {
  TypeSystem ts = cas.getTypeSystem();
  Type t = ts.getType(aTypeName);
  if (t != null) {
    List features = t.getFeatures();
    String[] featNames = new String[features.size()];
    for (int i = 0; i < features.size(); i++) {
      Feature f = (Feature) features.get(i);
      featNames[i] = f.getShortName();
    }
    return featNames;
  } else {
    return null;
  }
}
 
Example 5
Source File: ArrayIndexTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public void testArrayIndex() {
  try {
    CAS cas = this.ae.newCAS();
    FSIndexRepository ir = cas.getIndexRepository();
    TypeSystem ts = cas.getTypeSystem();
    Type annotationType = ts.getType(CAS.TYPE_NAME_ANNOTATION);
    Type annotArrayType = ts.getArrayType(annotationType);

    FSIndex<FeatureStructure> arrayIndexAll = ir.getIndex(idxId);
    assertEquals(countIndexMembers(arrayIndexAll), 0);
    FSIndex<FeatureStructure> arrayIndexFSArray = ir.getIndex(idxId, ts.getType(CAS.TYPE_NAME_FS_ARRAY));
    assertEquals(countIndexMembers(arrayIndexFSArray), 0);
    FSIndex<FeatureStructure> arrayIndexAnnotArray = ir.getIndex(idxId, annotArrayType);
    assertNull(arrayIndexAnnotArray);
  } catch (ResourceInitializationException e) {
    assertTrue(false);
  }
}
 
Example 6
Source File: CasFlowController_ImplBase.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void checkTypeSystemChange(CAS aCAS) throws AnalysisEngineProcessException {
  TypeSystem typeSystem = aCAS.getTypeSystem();
  if (typeSystem != mLastTypeSystem) {
    typeSystemInit(typeSystem);
    mLastTypeSystem = typeSystem;
  }
}
 
Example 7
Source File: CasAnnotator_ImplBase.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Checks it the type system of the given CAS is different from the last type system this
 * component was operating on. If it is different, calls the typeSystemInit method on the
 * component.
 */
private void checkTypeSystemChange(CAS aCAS) throws AnalysisEngineProcessException {
  TypeSystem typeSystem = aCAS.getTypeSystem();
  if (typeSystem != mLastTypeSystem) {
    typeSystemInit(typeSystem);
    mLastTypeSystem = typeSystem;
  }
}
 
Example 8
Source File: FSCollectionFactory.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static <T extends FeatureStructure> T createIntegerList(CAS aCas, int... aValues) {
  if (aValues == null) {
    return null;
  }
  
  TypeSystem ts = aCas.getTypeSystem();

  Type emptyType = ts.getType(CAS.TYPE_NAME_EMPTY_INTEGER_LIST);

  if (aValues.length == 0) {
    return aCas.createFS(emptyType);
  }
  
  Type nonEmptyType = ts.getType(CAS.TYPE_NAME_NON_EMPTY_INTEGER_LIST);
  Feature headFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_HEAD);
  Feature tailFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_TAIL);

  FeatureStructure head = aCas.createFS(nonEmptyType);
  FeatureStructure list = head;
  int i = 0;
  while (i < aValues.length) {
    head.setIntValue(headFeature, aValues[i]);
    i++;
    if (i < aValues.length) {
      FeatureStructure tail = aCas.createFS(nonEmptyType);
      head.setFeatureValue(tailFeature, tail);
      head = tail;
    } else {
      head.setFeatureValue(tailFeature, aCas.createFS(emptyType));
    }
  }

  return (T) list;
}
 
Example 9
Source File: FSCollectionFactory.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static <T extends FeatureStructure> T createFloatList(CAS aCas, Collection<Float> aValues) {
  if (aValues == null) {
    return null;
  }
  
  TypeSystem ts = aCas.getTypeSystem();

  Type emptyType = ts.getType(CAS.TYPE_NAME_EMPTY_FLOAT_LIST);

  if (aValues.size() == 0) {
    return aCas.createFS(emptyType);
  }
  
  Type nonEmptyType = ts.getType(CAS.TYPE_NAME_NON_EMPTY_FLOAT_LIST);
  Feature headFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_HEAD);
  Feature tailFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_TAIL);

  FeatureStructure head = aCas.createFS(nonEmptyType);
  FeatureStructure list = head;
  Iterator<Float> i = aValues.iterator();
  while (i.hasNext()) {
    head.setFloatValue(headFeature, i.next());
    if (i.hasNext()) {
      FeatureStructure tail = aCas.createFS(nonEmptyType);
      head.setFeatureValue(tailFeature, tail);
      head = tail;
    } else {
      head.setFeatureValue(tailFeature, aCas.createFS(emptyType));
    }
  }

  return (T) list;
}
 
Example 10
Source File: FSCollectionFactory.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static <T extends FeatureStructure> T createFloatList(CAS aCas, float... aValues) {
  if (aValues == null) {
    return null;
  }
  
  TypeSystem ts = aCas.getTypeSystem();

  Type emptyType = ts.getType(CAS.TYPE_NAME_EMPTY_FLOAT_LIST);

  if (aValues.length == 0) {
    return aCas.createFS(emptyType);
  }
  
  Type nonEmptyType = ts.getType(CAS.TYPE_NAME_NON_EMPTY_FLOAT_LIST);
  Feature headFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_HEAD);
  Feature tailFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_TAIL);

  FeatureStructure head = aCas.createFS(nonEmptyType);
  FeatureStructure list = head;
  int i = 0;
  while (i < aValues.length) {
    head.setFloatValue(headFeature, aValues[i]);
    i++;
    if (i < aValues.length) {
      FeatureStructure tail = aCas.createFS(nonEmptyType);
      head.setFeatureValue(tailFeature, tail);
      head = tail;
    } else {
      head.setFeatureValue(tailFeature, aCas.createFS(emptyType));
    }
  }

  return (T) list;
}
 
Example 11
Source File: AnalysisEnginePoolTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Auxilliary method used by testProcess()
 * 
 * @param aTaeDesc
 *          description of TextAnalysisEngine to test
 */
protected void _testProcess(AnalysisEnginePool aPool, int i)
        throws UIMAException {
  AnalysisEngine tae = aPool.getAnalysisEngine(0);
  try {
    // Test each form of the process method. When TestAnnotator executes, it
    // stores in static fields the document text and the ResultSpecification.
    // We use thse to make sure the information propogates correctly to the annotator.

    // process(CAS)
    CAS tcas = tae.newCAS();
    mLastTypeSystem = tcas.getTypeSystem();
    tcas.setDocumentText("new test");
    tae.process(tcas);
    tcas.reset();

    // process(CAS,ResultSpecification)
    ResultSpecification resultSpec = new ResultSpecification_impl(tcas.getTypeSystem());
    resultSpec.addResultType("NamedEntity", true);

    tcas.setDocumentText("testing...");
    tae.process(tcas, resultSpec);
    tcas.reset();
  } finally {
    aPool.releaseAnalysisEngine(tae);
  }
}
 
Example 12
Source File: XCasToCasDataSaxHandlerTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testConversions() throws Exception {
  try {
    // complex CAS obtained by deserialization
    File typeSystemFile = JUnitExtension.getFile("ExampleCas/testTypeSystem.xml");
    TypeSystemDescription typeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(
            new XMLInputSource(typeSystemFile));
    CAS cas = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(),
            new FsIndexDescription[0]);

    InputStream serCasStream = new FileInputStream(JUnitExtension.getFile("ExampleCas/cas.xml"));
    
    XCASDeserializer deser = new XCASDeserializer(cas.getTypeSystem());
    ContentHandler deserHandler = deser.getXCASHandler(cas);
    SAXParserFactory fact = SAXParserFactory.newInstance();
    SAXParser parser = fact.newSAXParser();
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setContentHandler(deserHandler);
    xmlReader.parse(new InputSource(serCasStream));
    serCasStream.close();
    _testConversions(cas);

    // a CAS with multiple Sofas
    InputStream translatorAeStream = new FileInputStream(JUnitExtension
            .getFile("CpeSofaTest/TransAnnotator.xml"));
    AnalysisEngineDescription translatorAeDesc = UIMAFramework.getXMLParser()
            .parseAnalysisEngineDescription(new XMLInputSource(translatorAeStream, null));
    AnalysisEngine transAnnotator = UIMAFramework.produceAnalysisEngine(translatorAeDesc);
    CAS cas2 = transAnnotator.newCAS();
    CAS englishView = cas2.createView("EnglishDocument");
    englishView.setSofaDataString("this beer is good", "text/plain");
    transAnnotator.process(cas2);
    _testConversions(cas2);

  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example 13
Source File: CASArtifact.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
CASArtifact(
    @Nullable LabelAdapters labelAdapters,
    Artifact artifact,
    CAS cas
) {
  this.labelAdapters = labelAdapters;
  this.cas = cas;

  TypeSystem typeSystem = cas.getTypeSystem();
  metadataType = typeSystem.getType("ArtifactMetadata");
  keyFeature = metadataType.getFeatureByBaseName("key");
  valueFeature = metadataType.getFeatureByBaseName("value");

  metadataCas = cas.createView("metadata");
  metadataCas.setDocumentText("");

  Type idType = typeSystem.getType("ArtifactID");
  Feature idFeat = idType.getFeatureByBaseName("artifactID");
  this.artifactID = artifact.getArtifactID();
  FeatureStructure documentIdFs = metadataCas.createFS(idType);
  documentIdFs.setStringValue(idFeat, artifactID);
  metadataCas.addFsToIndexes(documentIdFs);
  metadataIndex = metadataCas.getIndexRepository().getIndex("metadata", metadataType);

  casMetadata = new CASMetadata();
  casMetadata.putAll(artifact.getMetadata());

  copyDocuments(artifact);
}
 
Example 14
Source File: XCASDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testOutOfTypeSystem2() throws Exception {
    // deserialize a complex CAS into one with no TypeSystem
    CAS cas = CasCreationUtils.createCas(new TypeSystemDescription_impl(),
            new TypePriorities_impl(), new FsIndexDescription[0]);
    OutOfTypeSystemData ootsd = new OutOfTypeSystemData();
    InputStream serCasStream = new FileInputStream(JUnitExtension.getFile("ExampleCas/cas.xml"));
    XCASDeserializer deser = new XCASDeserializer(cas.getTypeSystem());
    ContentHandler deserHandler = deser.getXCASHandler(cas, ootsd);
    SAXParserFactory fact = SAXParserFactory.newInstance();
    SAXParser parser = fact.newSAXParser();
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setContentHandler(deserHandler);
    xmlReader.parse(new InputSource(serCasStream));
    serCasStream.close();

    // now reserialize including OutOfTypeSystem data
    XCASSerializer xcasSer = new XCASSerializer(cas.getTypeSystem());
    StringWriter sw = new StringWriter();
    XMLSerializer xmlSer = new XMLSerializer(sw, false);
    xcasSer.serialize(cas, xmlSer.getContentHandler(), true, ootsd);
    String xml = sw.getBuffer().toString();
//    System.out.println("debug writing temp/xmlv3.xml");
//    FileUtils.saveString2File(xml, new File("c:/temp/xmlv3.xml"));
//    System.out.println(xml);

    // deserialize into a CAS that accepts the full typesystem
    CAS cas2 = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(), indexes);
    XCASDeserializer deser2 = new XCASDeserializer(cas2.getTypeSystem());
    ContentHandler deserHandler2 = deser2.getXCASHandler(cas2);
    xmlReader = parser.getXMLReader();
    xmlReader.setContentHandler(deserHandler2);
    xmlReader.parse(new InputSource(new StringReader(xml)));

    // check that array refs are not null
    Type entityType = cas2.getTypeSystem().getType("org.apache.uima.testTypeSystem.Entity");
    Feature classesFeat = entityType.getFeatureByBaseName("classes");
    Iterator<FeatureStructure> iter = cas2.getIndexRepository().getIndex("testEntityIndex").iterator();
    assertTrue(iter.hasNext());
    while (iter.hasNext()) {
      FeatureStructure fs = iter.next();
      StringArrayFS arrayFS = (StringArrayFS) fs.getFeatureValue(classesFeat);
      assertNotNull(arrayFS);
      for (int i = 0; i < arrayFS.size(); i++) {
        assertNotNull(arrayFS.get(i));
      }
    }
  }
 
Example 15
Source File: AnnotationSchemaServiceImpl.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the current CAS already contains the required type system.
 */
private boolean isUpgradeRequired(CAS aCas, TypeSystemDescription aTargetTypeSystem)
{
    TypeSystem ts = aCas.getTypeSystem();
    boolean upgradeRequired = false;
    nextType: for (TypeDescription tdesc : aTargetTypeSystem.getTypes()) {
        Type t = ts.getType(tdesc.getName());
        
        // Type does not exist
        if (t == null) {
            log.debug("CAS update required: type {} does not exist", tdesc.getName());
            upgradeRequired = true;
            break nextType;
        }
        
        // Super-type does not match
        if (!Objects.equals(tdesc.getSupertypeName(), ts.getParent(t).getName())) {
            log.debug("CAS update required: supertypes of {} do not match: {} <-> {}",
                    tdesc.getName(), tdesc.getSupertypeName(), ts.getParent(t).getName());
            upgradeRequired = true;
            break nextType;
        }
        
        // Check features
        for (FeatureDescription fdesc : tdesc.getFeatures()) {
            Feature f = t.getFeatureByBaseName(fdesc.getName());
            
            // Feature does not exist
            if (f == null) {
                log.debug("CAS update required: feature {} on type {} does not exist",
                        fdesc.getName(), tdesc.getName());
                upgradeRequired = true;
                break nextType;
            }
            
            // Range does not match
            if (CAS.TYPE_NAME_FS_ARRAY.equals(fdesc.getRangeTypeName())) {
                if (!Objects.equals(fdesc.getElementType(),
                        f.getRange().getComponentType().getName())) {
                    log.debug(
                            "CAS update required: ranges of feature {} on type {} do not match: {} <-> {}",
                            fdesc.getName(), tdesc.getName(), fdesc.getRangeTypeName(),
                            f.getRange().getName());
                    upgradeRequired = true;
                    break nextType;
                }
            }
            else {
                if (!Objects.equals(fdesc.getRangeTypeName(), f.getRange().getName())) {
                    log.debug(
                            "CAS update required: ranges of feature {} on type {} do not match: {} <-> {}",
                            fdesc.getName(), tdesc.getName(), fdesc.getRangeTypeName(),
                            f.getRange().getName());
                    upgradeRequired = true;
                    break nextType;
                }
            }
        }
    }
    
    return upgradeRequired;
}
 
Example 16
Source File: MultiprocessingAnalysisEngine_implTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void run() {
  
  while (true) {
   
    if (!MultiThreadUtils.wait4go(this)) {
      break;
    }

    try {
      
      Random r = new Random();
  
      // Test each form of the process method. When TestAnnotator executes, it
      // stores in static fields the document text and the ResultSpecification.
      // We use thse to make sure the information propagates correctly to the 
      // annotator. (However, we can't check these until after the threads are
      // finished, as their state is nondeterministic during multithreaded
      // processing.)
  
      // process(CAS)
      for (int i = 0; i < 5; i++) {
        CAS tcas = mAE.newCAS();
        mLastTypeSystem = tcas.getTypeSystem();
        tcas.setDocumentText("new test");
        mAE.process(tcas);
        Thread.sleep(0, r.nextInt(1000));  // between 0 and 1 microseconds
        tcas.reset();

        // process(CAS,ResultSpecification)
        ResultSpecification resultSpec = new ResultSpecification_impl(tcas.getTypeSystem());
        resultSpec.addResultType("NamedEntity", true);

        tcas.setDocumentText("testing...");
        Thread.sleep(0, r.nextInt(1000));  // between 0 and 1 microseconds
        mAE.process(tcas, resultSpec);
        Thread.sleep(0, r.nextInt(1000));  // between 0 and 1 microseconds
        tcas.reset();
      }
    } catch (Throwable t) {
      t.printStackTrace();
      //can't cause unit test to fail by throwing exception from thread.
      //record the failure and the main thread will check for it later.
      mFailure = t;
    }
  }
}
 
Example 17
Source File: ComplexTypeTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testProfType()
    throws Exception
{
    TypeSystemDescription tsd = TypeSystemDescriptionFactory
            .createTypeSystemDescription("desc.types.TestTypeSystemDescriptor");

    CAS cas = CasCreationUtils.createCas(tsd, null, null);
    cas.setDocumentText("I listen to lectures by Prof. Gurevych sometimes.");

    TypeSystem ts = cas.getTypeSystem();
    Type profType = ts.getType("de.tud.Prof");
    Feature profNameFeature = profType.getFeatureByBaseName("fullName");
    Feature profBossFeature = profType.getFeatureByBaseName("boss");

    AnnotationFS proemel = cas.createAnnotation(profType, 0, 0);
    proemel.setStringValue(profNameFeature, "Hans Juergen Proeml");
    cas.addFsToIndexes(proemel);

    AnnotationFS gurevych = cas.createAnnotation(profType, 24, 38);
    gurevych.setStringValue(profNameFeature, "Iryna Gurevych");
    gurevych.setFeatureValue(profBossFeature, proemel);
    cas.addFsToIndexes(gurevych);

    /*
     * for (String feature : Arrays.asList("fullName", "boss")) { Feature someFeature =
     * gurevych.getType().getFeatureByBaseName(feature); if
     * (someFeature.getRange().isPrimitive()) { String value =
     * gurevych.getFeatureValueAsString(someFeature); System.out.println(value); } else {
     * FeatureStructure value = gurevych.getFeatureValue(someFeature);
     * System.out.printf("%s (%s)%n", value.getFeatureValueAsString(profNameFeature),
     * value.getType()); } }
     */

    ConstraintsGrammar parser = new ConstraintsGrammar(new FileInputStream(
            "src/test/resources/rules/prof.rules"));
    Parse p = parser.Parse();

    ParsedConstraints constraints = p.accept(new ParserVisitor());

    Evaluator constraintsEvaluator = new ValuesGenerator();

    List<PossibleValue> possibleValues = constraintsEvaluator.generatePossibleValues(gurevych,
            "professorName", constraints);

    List<PossibleValue> exValues = new LinkedList<>();
    exValues.add(new PossibleValue("Iryna Gurevych", false));

    assertEquals(possibleValues, exValues);

}
 
Example 18
Source File: XmiCasDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testTypeSystemFiltering() throws Exception {
  try {
    // deserialize a complex CAS from XCAS
    CAS cas = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(), indexes);

    InputStream serCasStream = new FileInputStream(JUnitExtension.getFile("ExampleCas/cas.xml"));
    XCASDeserializer deser = new XCASDeserializer(cas.getTypeSystem());
    ContentHandler deserHandler = deser.getXCASHandler(cas);
    SAXParserFactory fact = SAXParserFactory.newInstance();
    SAXParser parser = fact.newSAXParser();
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setContentHandler(deserHandler);
    xmlReader.parse(new InputSource(serCasStream));
    serCasStream.close();

    // now read in a TypeSystem that's a subset of those types
    TypeSystemDescription partialTypeSystemDesc = UIMAFramework.getXMLParser()
            .parseTypeSystemDescription(
                    new XMLInputSource(JUnitExtension
                            .getFile("ExampleCas/partialTestTypeSystem.xml")));
    TypeSystem partialTypeSystem = CasCreationUtils.createCas(partialTypeSystemDesc, null, null)
            .getTypeSystem();

    // reserialize as XMI, filtering out anything that doesn't fit in the
    // partialTypeSystem
    StringWriter sw = new StringWriter();
    XMLSerializer xmlSer = new XMLSerializer(sw, false);
    XmiCasSerializer xmiSer = new XmiCasSerializer(partialTypeSystem);
    xmiSer.serialize(cas, xmlSer.getContentHandler());
    String xml = sw.getBuffer().toString();
    // System.out.println(xml);

    // deserialize into another CAS (which has the whole type system)
    CAS cas2 = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(), indexes);
    XmiCasDeserializer deser2 = new XmiCasDeserializer(cas2.getTypeSystem());
    ContentHandler deserHandler2 = deser2.getXmiCasHandler(cas2);
    xmlReader.setContentHandler(deserHandler2);
    xmlReader.parse(new InputSource(new StringReader(xml)));

    // check that types have been filtered out
    Type orgType = cas2.getTypeSystem().getType("org.apache.uima.testTypeSystem.Organization");
    assertNotNull(orgType);
    assertTrue(cas2.getAnnotationIndex(orgType).size() == 0);
    assertTrue(cas.getAnnotationIndex(orgType).size() > 0);

    // but that some types are still there
    Type personType = cas2.getTypeSystem().getType("org.apache.uima.testTypeSystem.Person");
    FSIndex personIndex = cas2.getAnnotationIndex(personType);
    assertTrue(personIndex.size() > 0);

    // check that mentionType has been filtered out (set to null)
    FeatureStructure somePlace = personIndex.iterator().get();
    Feature mentionTypeFeat = personType.getFeatureByBaseName("mentionType");
    assertNotNull(mentionTypeFeat);
    assertNull(somePlace.getStringValue(mentionTypeFeat));
  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example 19
Source File: AnnotationTreeTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testTree() throws Exception {

    // The two XCASes used in this test contain the same data, but the
    // second one contains all annotations twice. So in that case, every
    // other annotation is filtered by the unambiguous iterator.

    File dataDir = JUnitExtension.getFile(casDataDirName);
    File xcasDir = new File(dataDir, xcasSampleDirName);

    try {
      File tsFile = new File(xcasDir, sampleTsFileName);
      Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(tsFile));
      // instantiate CAS to get type system. Also build style
      // map file if there is none.
      TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor;
      
      TypePriorities typePriorities = new TypePriorities_impl();
      TypePriorityList priorityList = typePriorities.addPriorityList();
      priorityList.addType("uima.cas.TOP");
      priorityList.addType("uima.tcas.Annotation");
      
      CAS cas = CasCreationUtils.createCas(tsDesc, typePriorities, new FsIndexDescription[0]);
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      XCASDeserializer xcasDeserializer = new XCASDeserializer(cas.getTypeSystem());
      File xcasFile = new File(xcasDir, sampleXcas1FileName);
      parser.parse(xcasFile, xcasDeserializer.getXCASHandler(cas));
      AnnotationTreeNode root = cas.getAnnotationIndex().tree(cas.getDocumentAnnotation())
                           	  .getRoot();
      // There are 7 paragraph annotations in the CAS.
      assertTrue("There should be 7 paragraphs, but are: " + root.getChildCount(), root
                          	  .getChildCount() == 7);
      // The first paragraph contains 19 sentences, each subsequent one
      // contains only one sentence.
      assertTrue(root.getChild(0).getChildCount() == 19);
      for (int i = 1; i < root.getChildCount(); i++) {
        assertTrue(root.getChild(i).getChildCount() == 1);
      }
      // First sentence contains 8 tokens.
      assertTrue(root.getChild(0).getChild(0).getChildCount() == 8);
      // Same for only sentence in second paragraph.
      assertTrue(root.getChild(1).getChild(0).getChildCount() == 8);
    } catch (IOException e) {
      e.printStackTrace();
      assertTrue(false);
    }
  }
 
Example 20
Source File: XCasWriterCasConsumer.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Serialize a CAS to a file in XCAS format
 * 
 * @param aCas
 *          CAS to serialize
 * @param name
 *          output file
 * 
 * @throws IOException
 *           if an I/O failure occurs
 * @throws SAXException
 *           if an error occurs generating the XML text
 */
private void writeXCas(CAS aCas, File name) throws IOException, SAXException {

  try (OutputStream out = new FileOutputStream(name)) {
    XCASSerializer ser = new XCASSerializer(aCas.getTypeSystem());
    XMLSerializer sax2xml = new XMLSerializer(out, false);
    ser.serialize(aCas, sax2xml.getContentHandler());
  }
}