Java Code Examples for org.apache.uima.cas.FeatureStructure#getFeatureValue()

The following examples show how to use org.apache.uima.cas.FeatureStructure#getFeatureValue() . 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: AbstractJsonConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Write annotation with features (including non-primitives)
 *
 * @param generator the generator
 * @param annotation the annotation
 * @param features the features
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeFS(JsonGenerator generator, FeatureStructure annotation, List<Feature> features)
    throws IOException {
  generator.writeObjectFieldStart("fields");
  for (Feature feature : features) {
    if (feature.getRange().isPrimitive()) {
      writePrimitive(generator, annotation, feature);
    } else if (feature.getRange().isArray()) {
      writeArray(generator, annotation, feature);
    } else {
      if ("uima.cas.AnnotationBase:sofa".equals(feature.getName())) {
        continue;
      }
      FeatureStructure featureValue = annotation.getFeatureValue(feature);
      if (featureValue != null) {
        generator.writeFieldName(feature.getShortName());
        writeFS(generator, featureValue);
      }
    }
  }
  generator.writeEndObject();
}
 
Example 2
Source File: EmbeddedConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public boolean match(FeatureStructure fs) {
  // compile(((FeatureStructureImpl) fs).getCAS().getTypeSystem());
  final int max = this.featNames.size();
  for (int i = 0; i < max; i++) {
    if (fs == null) {
      // for now it will throw null pointer exception on next line.
      // This is the same behavior as V2
    }
    Feature feat = fs.getType().getFeatureByBaseName(this.featNames.get(i));
    if (feat == null) {
      return false;
    }
    fs = fs.getFeatureValue(feat); // could be null
  }
  return this.cons.match(fs);
}
 
Example 3
Source File: BooleanConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public boolean match(FeatureStructure fs) {
  final int max = this.featNames.size() - 1; // The last position in the
  // path!
  if (max < 0) {
    // If the path is empty, we can't get a boolean, and therefore the
    // constraint is not satisfied.
    return false;
  }
  Feature feat;
  for (int i = 0; i < max; i++) {
    feat = fs.getType().getFeatureByBaseName(this.featNames.get(i));
    if (feat == null) {
      return false;
    }
    fs = fs.getFeatureValue(feat);
  }
  feat = fs.getType().getFeatureByBaseName(this.featNames.get(max));
  if (feat == null) {
    return false;
  }
  return this.cons.match(fs.getBooleanValue(feat));
}
 
Example 4
Source File: IntConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public boolean match(FeatureStructure fs) {
  // compile(((FeatureStructureImpl) fs).getCAS().getTypeSystem());
  final int max = this.featNames.size() - 1; // The last position in the
  // path!
  if (max < 0) {
    // If the path is empty, we can't get an int, and therefore the
    // constraint is not satisfied.
    return false;
  }
  Feature feat;
  for (int i = 0; i < max; i++) {
    feat = fs.getType().getFeatureByBaseName(this.featNames.get(i));
    if (feat == null) {
      return false;
    }
    fs = fs.getFeatureValue(feat);
  }
  feat = fs.getType().getFeatureByBaseName(this.featNames.get(max));
  if (feat == null) {
    return false;
  }
  return this.intConstraint.match(fs.getIntValue(feat));
}
 
Example 5
Source File: FloatConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
@Override
public boolean match(FeatureStructure fs) {
  // compile(((FeatureStructureImpl) fs).getCAS().getTypeSystem());
  final int max = this.featNames.size() - 1; // The last position in the
  // path!
  if (max < 0) {
    // If the path is empty, we can't get a float, and therefore the
    // constraint is not satisfied.
    return false;
  }
  Feature feat;
  for (int i = 0; i < max; i++) {
    feat = fs.getType().getFeatureByBaseName(this.featNames.get(i));
    if (feat == null) {
      return false;
    }
    fs = fs.getFeatureValue(feat);
  }
  feat = fs.getType().getFeatureByBaseName(this.featNames.get(max));
  if (feat == null) {
    return false;
  }
  return this.floatConstraint.match(fs.getFloatValue(feat));
}
 
Example 6
Source File: StringConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public boolean match(FeatureStructure fs) {
  // compile(((FeatureStructureImpl) fs).getCAS().getTypeSystem());
  final int max = this.featNames.size() - 1; // The last position in the
  // path!
  if (max < 0) {
    // If the path is empty, we can't get a string, and therefore the
    // constraint is not satisfied.
    return false;
  }
  Feature feat;
  for (int i = 0; i < max; i++) {
    feat = fs.getType().getFeatureByBaseName(this.featNames.get(i));
    if (feat == null) {
      return false;
    }
    fs = fs.getFeatureValue(feat);
  }
  feat = fs.getType().getFeatureByBaseName(this.featNames.get(max));
  if (feat == null) {
    return false;
  }
  return this.stringConstraint.match(fs.getStringValue(feat));
}
 
Example 7
Source File: DiffAdapter_ImplBase.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Override
public List<? extends Position> generateSubPositions(int aCasId, AnnotationFS aFs,
        LinkCompareBehavior aLinkCompareBehavior)
{
    List<Position> subPositions = new ArrayList<>();
    
    for (LinkFeatureDecl decl : linkFeatures) {
        Feature linkFeature = aFs.getType().getFeatureByBaseName(decl.getName());
        ArrayFS array = (ArrayFS) aFs.getFeatureValue(linkFeature);
        if (array == null) {
            continue;
        }
        for (FeatureStructure linkFS : array.toArray()) {
            String role = linkFS.getStringValue(linkFS.getType().getFeatureByBaseName(
                    decl.getRoleFeature()));
            AnnotationFS target = (AnnotationFS) linkFS.getFeatureValue(linkFS.getType()
                    .getFeatureByBaseName(decl.getTargetFeature()));
            Position pos = getPosition(aCasId, aFs, decl.getName(), role, target.getBegin(),
                    target.getEnd(), aLinkCompareBehavior);
            subPositions.add(pos);
        }
    }
    
    return subPositions;
}
 
Example 8
Source File: RelationDiffAdapter.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public Position getPosition(int aCasId, FeatureStructure aFS, String aFeature, String aRole,
        int aLinkTargetBegin, int aLinkTargetEnd, LinkCompareBehavior aLinkCompareBehavior)
{
    Type type = aFS.getType();
    AnnotationFS sourceFS = (AnnotationFS) aFS.getFeatureValue(type
            .getFeatureByBaseName(sourceFeature));
    AnnotationFS targetFS = (AnnotationFS) aFS.getFeatureValue(type
            .getFeatureByBaseName(targetFeature));
    
    String collectionId = null;
    String documentId = null;
    try {
        FeatureStructure dmd = WebAnnoCasUtil.getDocumentMetadata(aFS.getCAS());
        collectionId = FSUtil.getFeature(dmd, "collectionId", String.class);
        documentId = FSUtil.getFeature(dmd, "documentId", String.class);
    }
    catch (IllegalArgumentException e) {
        // We use this information only for debugging - so we can ignore if the information
        // is missing.
    }
    
    String linkTargetText = null;
    if (aLinkTargetBegin != -1 && aFS.getCAS().getDocumentText() != null) {
        linkTargetText = aFS.getCAS().getDocumentText()
                .substring(aLinkTargetBegin, aLinkTargetEnd);
    }
    
    return new RelationPosition(collectionId, documentId, aCasId, getType(), 
            sourceFS != null ? sourceFS.getBegin() : -1,
            sourceFS != null ? sourceFS.getEnd() : -1,
            sourceFS != null ? sourceFS.getCoveredText() : null,
            targetFS != null ? targetFS.getBegin() : -1,
            targetFS != null ? targetFS.getEnd() : -1,
            targetFS != null ? targetFS.getCoveredText() : null,
            aFeature, aRole, aLinkTargetBegin, aLinkTargetEnd, linkTargetText,
            aLinkCompareBehavior);
}
 
Example 9
Source File: AgreementUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static Object extractLinkFeatureValueForAgreement(FeatureStructure aFs, String aFeature,
        int aLinkIndex, LinkCompareBehavior aLCB)
{
    ArrayFS links = (ArrayFS) aFs.getFeatureValue(aFs.getType().getFeatureByBaseName(
            aFeature));
    FeatureStructure link = links.get(aLinkIndex);
    
    switch (aLCB) {
    case LINK_TARGET_AS_LABEL:
        // FIXME The target feature name should be obtained from the feature
        // definition!
        AnnotationFS target = (AnnotationFS) link.getFeatureValue(link.getType()
                .getFeatureByBaseName("target"));
        
        return target.getBegin() + "-" + target.getEnd() + " ["
                + target.getCoveredText() + "]";
    case LINK_ROLE_AS_LABEL:
        // FIXME The role feature name should be obtained from the feature
        // definition!
        String role = link.getStringValue(link.getType().getFeatureByBaseName(
                "role"));
        
        return role;
    default:
        throw new IllegalStateException("Unknown link target comparison mode ["
                + aLCB + "]");
    }        
}
 
Example 10
Source File: CasAnnotationViewer.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
   * Get feature value in string, if value is not another annotation and not
   * an array of annotations.
   *
   * @param aFS the a FS
   * @param feature the feature
   * @return the feature value in string
   */
  private String getFeatureValueInString(FeatureStructure aFS, Feature feature) {
    if (this.cas == null || this.typeSystem == null || this.stringType == null || this.fsArrayType == null) {
      return "null";
    }

    Type rangeType = feature.getRange();
    if (this.typeSystem.subsumes(this.fsArrayType, rangeType)) {
      // If the feature is an FSArray, cannot render it as simple as "name=value".
      return "*FSArray*";
    }
    if (this.typeSystem.subsumes(this.stringType, rangeType)) {
      return checkString(aFS.getStringValue(feature), "null", 64);
    }
    if (rangeType.isPrimitive()) {
      return checkString(aFS.getFeatureValueAsString(feature), "null", 64);
    }
    if (rangeType.isArray()) {
//      String rangeTypeName = rangeType.getName();
      CommonArrayFS arrayFS = (CommonArrayFS) aFS.getFeatureValue(feature);
      String[] values = (arrayFS == null) ? null : arrayFS.toStringArray();
      if (values == null || values.length == 0) {
        return "null";
      }

      StringBuffer displayValue = new StringBuffer();
      displayValue.append("[");
      for (int i = 0; i < values.length - 1; i++) {
        displayValue.append(values[i]);
        displayValue.append(",");
      }
      displayValue.append(values[values.length - 1]);
      displayValue.append("]");
      return displayValue.toString();
    }

    // If none of the above, then it is an annotation object. Cannot render it as simple as "name=value".
    return "*FS*";
  }
 
Example 11
Source File: ChainAdapter.java    From webanno with Apache License 2.0 5 votes vote down vote up
private List<AnnotationFS> collectLinks(FeatureStructure aChain)
{
    List<AnnotationFS> links = new ArrayList<>();

    // Now we seek the link within the current chain
    AnnotationFS linkFs = (AnnotationFS) aChain.getFeatureValue(aChain.getType()
            .getFeatureByBaseName(getChainFirstFeatureName()));
    while (linkFs != null) {
        links.add(linkFs);

        linkFs = getNextLink(linkFs);
    }

    return links;
}
 
Example 12
Source File: ChainAdapter.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
 * Get the first link of a chain from the chain head feature structure.
 */
private AnnotationFS getFirstLink(FeatureStructure aChain)
{
    return (AnnotationFS) aChain.getFeatureValue(aChain.getType().getFeatureByBaseName(
            getChainFirstFeatureName()));
}
 
Example 13
Source File: WebannoTsv3Writer.java    From webanno with Apache License 2.0 4 votes vote down vote up
private void setChainAnnotation(JCas aJCas)
{
    for (String l : chainLayers) {
        if (l.equals(Token.class.getName())) {
            continue;
        }

        Map<AnnotationUnit, List<List<String>>> annotationsPertype = null;
        Type type = getType(aJCas.getCas(), l + CHAIN);
        Feature chainFirst = type.getFeatureByBaseName(FIRST);
        int chainNo = 1;
        for (FeatureStructure chainFs : selectFS(aJCas.getCas(), type)) {
            AnnotationFS linkFs = (AnnotationFS) chainFs.getFeatureValue(chainFirst);
            AnnotationUnit unit = getUnit(linkFs.getBegin(), linkFs.getEnd(),
                    linkFs.getCoveredText());
            Type lType = linkFs.getType();

            // this is the layer with annotations
            l = lType.getName();
            if (annotationsPerPostion.get(l) == null) {
                annotationsPertype = new HashMap<>();

            }
            else {
                annotationsPertype = annotationsPerPostion.get(l);
            }
            Feature linkNext = linkFs.getType().getFeatureByBaseName(NEXT);
            int linkNo = 1;
            while (linkFs != null) {
                AnnotationFS nextLinkFs = (AnnotationFS) linkFs.getFeatureValue(linkNext);
                if (nextLinkFs != null) {
                    addChinFeatureAnno(annotationsPertype, lType, linkFs, unit, linkNo,
                            chainNo);
                }
                else {
                    addChinFeatureAnno(annotationsPertype, lType, linkFs, unit, linkNo,
                            chainNo);
                }
                linkFs = nextLinkFs;
                linkNo++;
                if (nextLinkFs != null) {
                    unit = getUnit(linkFs.getBegin(), linkFs.getEnd(), linkFs.getCoveredText());
                }
            }
            if (annotationsPertype.keySet().size() > 0) {
                annotationsPerPostion.put(l, annotationsPertype);
            }
            chainNo++;
        }
    }
}
 
Example 14
Source File: SerializationReinitTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/** Test basic blob serialization
 */
public void testBlob() throws Exception {

  /*
   * Test that FS, indexes and strings work after repeated blob serialization
   * For each iteration, add two new FS, serialize and test all created so
   * The first FS sets the string feature using standard API => goes into stringlist
   * The second FS sets the string feature using lowlevel API => goes into stringheap 
   * 
   * Throw in tests of the byte, short and long heaps as well
   * 
   */
String testString = "testString";
cas.reset();
LowLevelCAS ll_cas = cas.getLowLevelCAS();
FSIndexRepository ir = cas.getIndexRepository();
int ll_strfeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theStringFeature);
int ll_bytefeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theByteFeature);
int ll_shortfeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theShortFeature);
int ll_bytearrayfeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theByteArrayFeature);
int ll_shortarrayfeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theShortArrayFeature);
int ll_longfeatcode = ll_cas.ll_getTypeSystem().ll_getCodeForFeature(theLongFeature);

for (int cycle = 0; cycle < 10; cycle +=2 ) {
  FeatureStructure newFS1 = cas.createFS(theTypeType); 
  newFS1.setIntValue(startFeature, cycle);
  newFS1.setIntValue(endFeature, cycle+1);
  // set string using normal string feature create
  newFS1.setStringValue(theStringFeature, testString);
  newFS1.setByteValue(theByteFeature, (byte)cycle);
  newFS1.setShortValue(theShortFeature, (short)cycle);
  newFS1.setLongValue(theLongFeature, (long)cycle);
  ByteArrayFS newBA1 = cas.createByteArrayFS(1); 
  ShortArrayFS newSA1 = cas.createShortArrayFS(1); 
  newBA1.set(0, (byte)cycle);
  newSA1.set(0, (short)cycle);
  newFS1.setFeatureValue(theByteArrayFeature, newBA1);
  newFS1.setFeatureValue(theShortArrayFeature, newSA1);
  ir.addFS(newFS1);

  FeatureStructure newFS2 = cas.createFS(theTypeType);
  ByteArrayFS newBA2 = cas.createByteArrayFS(1);
  ShortArrayFS newSA2 = cas.createShortArrayFS(1); 
  newFS2.setIntValue(startFeature, cycle+1);
  newFS2.setIntValue(endFeature, cycle+2);
  ir.addFS(newFS2);
  CASImpl ci = (CASImpl) cas;
  ci.setId2FSsMaybeUnconditionally(newFS2, newBA2, newSA2);
  // set string using lowlevel string create API
  final int llfs2 = ll_cas.ll_getFSRef(newFS2);
  final int llba2 = ll_cas.ll_getFSRef(newBA2);
  final int llsa2 = ll_cas.ll_getFSRef(newSA2);
  
  ll_cas.ll_setCharBufferValue(llfs2, ll_strfeatcode,
          testString.toCharArray(), 0, testString.length());
  ll_cas.ll_setByteValue(llfs2, ll_bytefeatcode, (byte)(cycle+1));
  ll_cas.ll_setShortValue(llfs2, ll_shortfeatcode, (short)(cycle+1));
  ll_cas.ll_setLongValue(llfs2, ll_longfeatcode, (long)(cycle+1));
  ll_cas.ll_setByteArrayValue(llba2, 0, (byte)(cycle+1));
  ll_cas.ll_setShortArrayValue(llsa2, 0, (short)(cycle+1));
  newFS2.setFeatureValue(theByteArrayFeature, newBA2);
  newFS2.setFeatureValue(theShortArrayFeature, newSA2);
  ir.addFS(newFS2);

  ByteArrayOutputStream fos = new ByteArrayOutputStream();
  Serialization.serializeCAS(cas, fos);
    cas.reset();
  ByteArrayInputStream fis = new ByteArrayInputStream(fos.toByteArray());
  Serialization.deserializeCAS(cas, fis);

  FSIndex<AnnotationFS> idx = cas.getAnnotationIndex(theTypeType);
  FSIterator<AnnotationFS> iter = idx.iterator();
  for (int tc = 0; tc < cycle + 1; tc++) {
    FeatureStructure testFS = iter.get();
    iter.moveToNext();
    assertTrue(tc == testFS.getIntValue(startFeature));
    assertTrue(testString.equals(testFS.getStringValue(theStringFeature)));
    assertTrue(tc == testFS.getByteValue(theByteFeature));
    assertTrue(tc == testFS.getShortValue(theShortFeature));
    assertTrue(tc == testFS.getLongValue(theLongFeature));
    ByteArrayFS ba = (ByteArrayFS)testFS.getFeatureValue(theByteArrayFeature);
    assertTrue(tc == ba.get(0));
    ShortArrayFS sa = (ShortArrayFS)testFS.getFeatureValue(theShortArrayFeature);
    assertTrue(tc == sa.get(0));
  }
  }  
}
 
Example 15
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 16
Source File: SerDesTest4.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testArrayAux() {
  ArrayList<FeatureStructure> fsl = new ArrayList<>();
  /**
   * Strings, non-array Long/Double:
   * Make equal items,
   * ser/deser, update one of the equal items, insure other not updated
   */
  FeatureStructure fsAt1 = newAkof(fsl);
  FeatureStructure fsAt2 = newAkof(fsl);
  cas.addFsToIndexes(fsAt1);
  cas.addFsToIndexes(fsAt2);

  createStringA(fsAt1, "at");
  createStringA(fsAt2, "at");
  verify("ArrayAuxStrings");

  FSIterator<FeatureStructure> it = deserCas.indexRepository.getAllIndexedFS(akof);
  FeatureStructure fsAt1d = it.next();
  FeatureStructure fsAt2d = it.next();
  StringArrayFS sa1 = (StringArrayFS) fsAt1d.getFeatureValue(akofAstring);
  StringArrayFS sa2 = (StringArrayFS) fsAt2d.getFeatureValue(akofAstring);
  sa1.set(1, "def");
  assertEquals(sa2.get(1), "abcat");
  assertEquals(sa1.get(1), "def");
  cas.reset();

  fsAt1 = newAkof(fsl);
  fsAt2 = newAkof(fsl);
  cas.addFsToIndexes(fsAt1);
  cas.addFsToIndexes(fsAt2);

  createLongA(fsAt1, 9);
  createLongA(fsAt2, 9);
  verify("ArrayAuxLongs");

  it = deserCas.indexRepository.getAllIndexedFS(akof);
  fsAt1d = it.next();
  fsAt2d = it.next();
  LongArrayFS la1 = (LongArrayFS) fsAt1d.getFeatureValue(akofAlong);
  LongArrayFS la2 = (LongArrayFS) fsAt2d.getFeatureValue(akofAlong);
  la1.set(2, 123L);
  assertEquals(la2.get(2), -45 + 9);
  assertEquals(la1.get(2), 123);
}
 
Example 17
Source File: XmiCasDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testOutOfTypeSystemArrayElement() throws Exception {
  //add to type system an annotation type that has an FSArray feature
  TypeDescription testAnnotTypeDesc = typeSystem.addType("org.apache.uima.testTypeSystem.TestAnnotation", "", "uima.tcas.Annotation");
  testAnnotTypeDesc.addFeature("arrayFeat", "", "uima.cas.FSArray");
  //populate a CAS with such an array
  CAS cas = CasCreationUtils.createCas(typeSystem, null, null);
  Type testAnnotType = cas.getTypeSystem().getType("org.apache.uima.testTypeSystem.TestAnnotation");
  Type orgType = cas.getTypeSystem().getType(
    "org.apache.uima.testTypeSystem.Organization");
  AnnotationFS orgAnnot1 = cas.createAnnotation(orgType, 0, 10);
  cas.addFsToIndexes(orgAnnot1);
  AnnotationFS orgAnnot2 = cas.createAnnotation(orgType, 10, 20);
  cas.addFsToIndexes(orgAnnot2);
  AnnotationFS testAnnot = cas.createAnnotation(testAnnotType, 0, 20);
  cas.addFsToIndexes(testAnnot);
  ArrayFS arrayFs = cas.createArrayFS(2);
  arrayFs.set(0, orgAnnot1);
  arrayFs.set(1, orgAnnot2);
  Feature arrayFeat = testAnnotType.getFeatureByBaseName("arrayFeat");
  testAnnot.setFeatureValue(arrayFeat, arrayFs);
  
  //serialize to XMI
  String xmiStr = serialize(cas, null);
  
  //deserialize into a CAS that's missing the Organization type
  File partialTypeSystemFile = JUnitExtension.getFile("ExampleCas/partialTestTypeSystem.xml");
  TypeSystemDescription partialTypeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(
          new XMLInputSource(partialTypeSystemFile));
  testAnnotTypeDesc = partialTypeSystem.addType("org.apache.uima.testTypeSystem.TestAnnotation", "", "uima.tcas.Annotation");
  testAnnotTypeDesc.addFeature("arrayFeat", "", "uima.cas.FSArray");
  CAS partialTsCas = CasCreationUtils.createCas(partialTypeSystem, null, null);
  XmiSerializationSharedData sharedData = new XmiSerializationSharedData();
  deserialize(xmiStr, partialTsCas, sharedData, true, -1);
  
  //check out of type system data
  Type testAnnotType2 = partialTsCas.getTypeSystem().getType("org.apache.uima.testTypeSystem.TestAnnotation");
  FeatureStructure testAnnot2 = partialTsCas.getAnnotationIndex(testAnnotType2).iterator().get(); 
  Feature arrayFeat2 = testAnnotType2.getFeatureByBaseName("arrayFeat");
  FeatureStructure arrayFs2 = testAnnot2.getFeatureValue(arrayFeat2);
  List ootsElems = sharedData.getOutOfTypeSystemElements();
  assertEquals(2, ootsElems.size());
  List ootsArrayElems = sharedData.getOutOfTypeSystemArrayElements((FSArray) arrayFs2);
  assertEquals(2, ootsArrayElems.size());
  for (int i = 0; i < 2; i++) {
    OotsElementData oed = (OotsElementData)ootsElems.get(i);
    XmiArrayElement arel = (XmiArrayElement)ootsArrayElems.get(i);
    assertEquals(oed.xmiId, arel.xmiId);      
  }
  
  //reserialize along with out of type system data
  String xmiStr2 = serialize(partialTsCas, sharedData);
  
  //deserialize into a new CAS and compare
  CAS cas2 = CasCreationUtils.createCas(typeSystem, null, null);
  deserialize(xmiStr2, cas2, null, false, -1);
  
  CasComparer.assertEquals(cas, cas2);    
}
 
Example 18
Source File: XmiCasDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testOutOfTypeSystemListElement() throws Exception {
    //add to type system an annotation type that has an FSList feature
    TypeDescription testAnnotTypeDesc = typeSystem.addType("org.apache.uima.testTypeSystem.TestAnnotation", "", "uima.tcas.Annotation");
    testAnnotTypeDesc.addFeature("listFeat", "", "uima.cas.FSList");
    
    //populate a CAS with such an list
    CAS cas = CasCreationUtils.createCas(typeSystem, null, null);
    Type testAnnotType = cas.getTypeSystem().getType("org.apache.uima.testTypeSystem.TestAnnotation");
    Type orgType       = cas.getTypeSystem().getType("org.apache.uima.testTypeSystem.Organization");
    
    AnnotationFS orgAnnot1 = cas.createAnnotation(orgType, 0, 10);
                             cas.addFsToIndexes(orgAnnot1);
    AnnotationFS orgAnnot2 = cas.createAnnotation(orgType, 10, 20);
                             cas.addFsToIndexes(orgAnnot2);
    AnnotationFS testAnnot = cas.createAnnotation(testAnnotType, 0, 20);
                             cas.addFsToIndexes(testAnnot);
                             
    Type nonEmptyFsListType = cas.getTypeSystem().getType(CAS.TYPE_NAME_NON_EMPTY_FS_LIST);
    Type emptyFsListType    = cas.getTypeSystem().getType(CAS.TYPE_NAME_EMPTY_FS_LIST);
    Feature headFeat = nonEmptyFsListType.getFeatureByBaseName("head");
    Feature tailFeat = nonEmptyFsListType.getFeatureByBaseName("tail");
    
    FeatureStructure emptyNode  = cas.createFS(emptyFsListType);
    
    FeatureStructure secondNode = cas.createFS(nonEmptyFsListType);
    secondNode.setFeatureValue(headFeat, orgAnnot2);
    secondNode.setFeatureValue(tailFeat, emptyNode);
    
    FeatureStructure firstNode = cas.createFS(nonEmptyFsListType);
    firstNode.setFeatureValue(headFeat, orgAnnot1);
    firstNode.setFeatureValue(tailFeat, secondNode);
    
    Feature listFeat = testAnnotType.getFeatureByBaseName("listFeat");
    testAnnot.setFeatureValue(listFeat, firstNode);
    
    //serialize to XMI
    String xmiStr = serialize(cas, null);
//    System.out.println(xmiStr);
    
    //deserialize into a CAS that's missing the Organization type
    File partialTypeSystemFile = JUnitExtension.getFile("ExampleCas/partialTestTypeSystem.xml");
    TypeSystemDescription partialTypeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(
            new XMLInputSource(partialTypeSystemFile));
    testAnnotTypeDesc = partialTypeSystem.addType("org.apache.uima.testTypeSystem.TestAnnotation", "", "uima.tcas.Annotation");
    testAnnotTypeDesc.addFeature("listFeat", "", "uima.cas.FSList");
    CAS partialTsCas = CasCreationUtils.createCas(partialTypeSystem, null, null);
    XmiSerializationSharedData sharedData = new XmiSerializationSharedData();
    deserialize(xmiStr, partialTsCas, sharedData, true, -1);
    
    //check out of type system data
    Type testAnnotType2 = partialTsCas.getTypeSystem().getType("org.apache.uima.testTypeSystem.TestAnnotation");
    FeatureStructure testAnnot2 = partialTsCas.getAnnotationIndex(testAnnotType2).iterator().get(); 
    Feature listFeat2 = testAnnotType2.getFeatureByBaseName("listFeat");
    FeatureStructure listFs = testAnnot2.getFeatureValue(listFeat2);
    List ootsElems = sharedData.getOutOfTypeSystemElements();
    assertEquals(2, ootsElems.size());
    
    OotsElementData oed = sharedData.getOutOfTypeSystemFeatures((TOP) listFs);
    XmlAttribute attr = oed.attributes.get(0);
    assertNotNull(attr);
    assertEquals(CAS.FEATURE_BASE_NAME_HEAD, attr.name);
    assertEquals(attr.value, ((OotsElementData)ootsElems.get(0)).xmiId);
    
    //reserialize along with out of type system data
    String xmiStr2 = serialize(partialTsCas, sharedData);
//    System.out.println(xmiStr2);
    
    //deserialize into a new CAS and compare
    CAS cas2 = CasCreationUtils.createCas(typeSystem, null, null);
    deserialize(xmiStr2, cas2, null, false, -1);
    
    CasComparer.assertEquals(cas, cas2);    
  }
 
Example 19
Source File: SerDesTest6.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private FeatureStructure maybeGetFeatureKind(FeatureStructure fs, TTypeSystem m, String kind) {
  Feature f = m.getFeature(fs, kind);
  return (f == null) ? null : fs.getFeatureValue(f);
}
 
Example 20
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 2 votes vote down vote up
/**
 * Get a feature value.
 *
 * @param aFS
 *            the feature structure.
 * @param aFeatureName
 *            the feature within the annotation whose value to set.
 * @return the feature value.
 */
public static FeatureStructure getFeatureFS(FeatureStructure aFS, String aFeatureName)
{
    return aFS.getFeatureValue(aFS.getType().getFeatureByBaseName(aFeatureName));
}