Java Code Examples for org.apache.uima.cas.FSIterator#get()

The following examples show how to use org.apache.uima.cas.FSIterator#get() . 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: FilteredIteratorTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private void iterAndCount1a() {
  // create filtered iterator over Tokens only
  FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();
  FSTypeConstraint constraint = cas.getConstraintFactory().createTypeConstraint();
  constraint.add(tokenType.getName());
  it = cas.createFilteredIterator(it, constraint);

  // do iteration
  while (it.isValid()) {
    AnnotationFS a = it.get();
    assertTrue(a.getType().equals(tokenType));
    // System.out.println("Annotation type: " + a.getType().getName());
    // System.out.println("Covered text: " + a.getCoveredText());
    it.moveToNext();
  }

}
 
Example 2
Source File: RunAE.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Entity process complete.
 *
 * @param aCas the a cas
 * @param aStatus the a status
 * @see org.apache.uima.collection.StatusCallbackListener#entityProcessComplete(org.apache.uima.cas.CAS,
 *      org.apache.uima.collection.EntityProcessStatus)
 */
public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) {
  if (aStatus.isException()) {
    Iterator iter = aStatus.getExceptions().iterator();
    while (iter.hasNext()) {
      ((Throwable) iter.next()).printStackTrace();
    }
  } else if (genProgressMessages) {
    // retrieve the filename of the input file from the CAS
    // (it was put there by the FileSystemCollectionReader)
    if (!(xcasInput || xmiInput)) {
      Type fileLocType = aCas.getTypeSystem().getType(
              "org.apache.uima.examples.SourceDocumentInformation");
      Feature fileNameFeat = fileLocType.getFeatureByBaseName("uri");
      FSIterator it = aCas.getAnnotationIndex(fileLocType).iterator();
      FeatureStructure fileLoc = it.get();
      File inFile = new File(fileLoc.getStringValue(fileNameFeat));
      System.out.println("Processed Document " + inFile.getName());
    } else {
      System.out.println("doc" + docsProcessed++ + " processed successfully");
    }
  }
}
 
Example 3
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * This method exists simply as a convenience method for unit testing. It is not very efficient
 * and should not, in general be used outside the context of unit testing.
 * 
 * @param cas
 *          a CAS containing the annotation.
 * @param type
 *          a UIMA type.
 * @param index
 *          this can be either positive (0 corresponds to the first annotation of a type) or
 *          negative (-1 corresponds to the last annotation of a type.)
 * @return an annotation of the given type
 * @see <a href="package-summary.html#SortOrder">Order of selected feature structures</a>
 */
public static AnnotationFS selectByIndex(CAS cas, Type type, int index) {
  if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
    throw new IllegalArgumentException("Type [" + type.getName() + "] is not an annotation type");
  }
  // withSnapshotIterators() not needed here since we return only one result   
  FSIterator<AnnotationFS> i = cas.getAnnotationIndex(type).iterator();
  int n = index;
  i.moveToFirst();
  if (n > 0) {
    while (n > 0 && i.isValid()) {
      i.moveToNext();
      n--;
    }
  }
  if (n < 0) {
    i.moveToLast();
    while (n < -1 && i.isValid()) {
      i.moveToPrevious();
      n++;
    }
  }

  return i.isValid() ? i.get() : null;
}
 
Example 4
Source File: CasTreeViewer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Recursive method called by {@link buildTree(DefaultMutableTreeNode,FSIterator)}.
 * 
 * @param aParentNode
 *          root node of tree to be built
 * @param aIterator
 *          iterator over all annotation in CAS
 * @param aStartPos
 *          text position at which to begin processing
 * @param aEndPos
 *          text position at which to end processing
 */
private void _buildTree(DefaultMutableTreeNode aParentNode, FSIterator aIterator, int aStartPos,
        int aEndPos) {
  while (aIterator.isValid()) {
    AnnotationFS curAnnot = (AnnotationFS) aIterator.get();
    int curAnnotStart = curAnnot.getBegin();
    int curAnnotEnd = curAnnot.getEnd();
    if (curAnnotEnd <= aEndPos) {
      // move iterator to next annotation
      aIterator.moveToNext();

      if (curAnnotStart < curAnnotEnd) // account for bug in JTalent
      {
        // add this annotation as a child of aParentNode
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new AnnotationTreeNodeObject(
                curAnnot));
        aParentNode.add(newNode);
        // recursively add children to this node
        _buildTree(newNode, aIterator, curAnnotStart, curAnnotEnd);
      }
    } else
      break;
  }
}
 
Example 5
Source File: RunAE.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Entity process complete.
 *
 * @param aCas the a cas
 * @param aStatus the a status
 * @see org.apache.uima.collection.StatusCallbackListener#entityProcessComplete(org.apache.uima.cas.CAS,
 *      org.apache.uima.collection.EntityProcessStatus)
 */
@Override
public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) {
  if (aStatus.isException()) {
    Iterator iter = aStatus.getExceptions().iterator();
    while (iter.hasNext()) {
      ((Throwable) iter.next()).printStackTrace();
    }
  } else if (genProgressMessages) {
    // retrieve the filename of the input file from the CAS
    // (it was put there by the FileSystemCollectionReader)
    if (!(xcasInput || xmiInput)) {
      Type fileLocType = aCas.getTypeSystem().getType(
              "org.apache.uima.examples.SourceDocumentInformation");
      Feature fileNameFeat = fileLocType.getFeatureByBaseName("uri");
      FSIterator it = aCas.getAnnotationIndex(fileLocType).iterator();
      FeatureStructure fileLoc = it.get();
      File inFile = new File(fileLoc.getStringValue(fileNameFeat));
      System.out.println("Processed Document " + inFile.getName());
    } else {
      System.out.println("doc" + docsProcessed++ + " processed successfully");
    }
  }
}
 
Example 6
Source File: FSTreeModel.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Update.
 *
 * @param indexName the index name
 * @param index the index
 * @param cas1 the cas 1
 */
public void update(String indexName, FSIndex index, CAS cas1) {
  // this.indexName = indexName;
  this.cas = (CASImpl) cas1;
  final int size = index.size();
  this.rootString = "<html><font color=green>" + indexName + "</font> - <font color=blue>"
          + index.getType().getName() + "</font> [" + size + "]</html>";
  this.root = new FSNode(this, FSNode.DISPLAY_NODE, null, 0, null);
  this.fss = new ArrayList<>();
  FSIterator<TOP> it = index.iterator();
  int count = 0;
  for (it.moveToFirst(); it.isValid(); it.moveToNext()) {
    TOP fs = it.get();
    this.fss.add(new FSNode(this, getNodeType(fs.getType()), fs, fs._id(), count));
    ++count;
  }
  List<FSTreeNode> kids = createArrayChildren(0, size, this.fss, this);
  this.root.setChildren(kids);
  Object[] path = new Object[1];
  path[0] = this.root;
  TreeModelEvent event = new TreeModelEvent(this.root, path);
  for (int i = 0; i < this.treeModelListeners.size(); i++) {
    this.treeModelListeners.get(i).treeStructureChanged(event);
  }
}
 
Example 7
Source File: AnnotationIndexImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void addChildren(AnnotationTreeNodeImpl<T> node, FSIterator<T> it) {
  AnnotationTreeNodeImpl<T> dtr;
  T annot;
  while (it.isValid()) {
    annot = it.get();
    it.moveToNext();
    dtr = new AnnotationTreeNodeImpl<T>();
    dtr.set(annot);
    node.addChild(dtr);
    addChildren(dtr, subiterator(annot, false, true));
  }
}
 
Example 8
Source File: ConsumerCasUtils.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public static String getStringFeatValue(CAS aCasView, String aTypeS, String aFeatS) {
  String result = null;
  Type type = aCasView.getTypeSystem().getType(aTypeS);
  if (type != null) {
    FSIterator<AnnotationFS> idIter = aCasView.getAnnotationIndex(type).iterator();
    while (idIter.isValid()) {
      org.apache.uima.cas.FeatureStructure idFS = idIter.get();
      result = idFS.getStringValue(aCasView.getTypeSystem().getFeatureByFullName(
              aTypeS + ":" + aFeatS));
      idIter.moveToNext();
    }
  }
  return result;
}
 
Example 9
Source File: CASImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public <T extends AnnotationFS> T getDocumentAnnotationNoCreate() {
  if (this == this.svd.baseCAS) {
    // base CAS has no document
    return null;
  }
  FSIterator<Annotation> it = getDocAnnotIter();
  it.moveToFirst();  // revalidate in case index updated
  if (it.isValid()) {
    Annotation r = it.get();
    return (T) (inPearContext() 
                ? pearConvert(r)
                : r);
  }
  return null;
}
 
Example 10
Source File: VinciAnalysisEngineService_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes a given document by a AnalysisEngine. When completed this method returns a VinciFrame
 * containing XCAS translated into a set of Vinci subFrames. Each subframe containing one
 * annotation with all its attributes.
 *
 * @param ct the ct
 * @return VinciFrame containing XCAS translated into a set of Vinci subframes.
 * @exception Exception              if there is an error during processing
 */
private Transportable analyze(CASTransportable ct) throws Exception {
  CAS cas = ct.getCas();
  try {
    long annotStartTime = System.currentTimeMillis();
    mAE.process(cas);
    int annotationTime = (int) (System.currentTimeMillis() - annotStartTime);
    if (debug) {
      System.out.println("Annotation took: " + annotationTime + "ms");
    }
    ct.getExtraDataFrame().fset(Constants.ANNOTATION_TIME, annotationTime);
    // Extract CAS
    // UIMAFramework.getLogger().log("CAS ACount::" +
    // cas.getAnnotationIndex().size());
    int totalAnnots = 0;
    SofaFS sofa;
    FSIterator sItr = cas.getSofaIterator();
    while (sItr.isValid()) {
      sofa = (SofaFS) sItr.get();
      totalAnnots += cas.getView(sofa).getAnnotationIndex().size();
      sItr.moveToNext();
    }
    UIMAFramework.getLogger().log(Level.FINEST, "CAS ACount::" + totalAnnots);
    ct.setCommand(null);
    return ct;
  } catch (Exception ex) {
    ct.cleanup();
    throw ex;
  }
}
 
Example 11
Source File: UimaCopying.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
public static void copyFeatureStructuresOfType(String typeName, CAS sourceView,
    CAS destinationView) {
  FeatureStructureCopyingQueue featureStructureCopyingQueue = new FeatureStructureCopyingQueue(
      sourceView,
      destinationView);
  FSIterator<FeatureStructure> iterator = sourceView.getIndexRepository()
      .getAllIndexedFS(sourceView.getTypeSystem().getType(typeName));
  while (iterator.hasNext()) {
    FeatureStructure featureStructure = iterator.get();
    featureStructureCopyingQueue.enqueue(featureStructure);
  }
  featureStructureCopyingQueue.run();
}
 
Example 12
Source File: ConsumerCasUtils.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a Feature Structure of a given type.
 *
 * @param aCasView -
 *          CAS instance to retrieve data from
 * @param aTypeS -
 *          Feature Type
 * @return the first Feature Structure of a given type
 */
public static FeatureStructure getTcasFS(CAS aCasView, String aTypeS) {
  org.apache.uima.cas.FeatureStructure idFS = null;
  FSIterator idIter = aCasView.getAnnotationIndex(aCasView.getTypeSystem().getType(aTypeS)).iterator();
  while (idIter != null && idIter.isValid()) {
    idFS = idIter.get();
    idIter.moveToNext();
  }
  return idFS;
}
 
Example 13
Source File: PrintAnnotations.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Prints all Annotations of a specified Type to a PrintStream.
 * 
 * @param aCAS
 *          the CAS containing the FeatureStructures to print
 * @param aAnnotType
 *          the Type of Annotation to be printed
 * @param aOut
 *          the PrintStream to which output will be written
 */
public static void printAnnotations(CAS aCAS, Type aAnnotType, PrintStream aOut) {
  // get iterator over annotations
  FSIterator iter = aCAS.getAnnotationIndex(aAnnotType).iterator();

  // iterate
  while (iter.isValid()) {
    FeatureStructure fs = iter.get();
    printFS(fs, aCAS, 0, aOut);
    iter.moveToNext();
  }
}
 
Example 14
Source File: ConsumerCasUtils.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public static FeatureStructure getTcasFS(CAS aCasView, String aTypeS) {
  org.apache.uima.cas.FeatureStructure idFS = null;
  Type type = aCasView.getTypeSystem().getType(aTypeS);
  if (type != null) {
    FSIterator<AnnotationFS> idIter = aCasView.getAnnotationIndex(type).iterator();
    while (idIter.isValid()) {
      idFS = idIter.get();
      idIter.moveToNext();
    }
  }
  return idFS;
}
 
Example 15
Source File: SerializationReinitTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void createSentences() throws CASException {
  // TypeSystem ts = cas.getTypeSystem();
  // Type eosType = ts.getType(EOS_TYPE);
  // Type tokenType = ts.getType(TOKEN_TYPE);
  // //assert(tokenType != null);
  // Type sentenceType = ts.getType(SENT_TYPE);
  // Feature tokenTypeFeature = ts.getFeature(TOKEN_TYPE_FEAT);
  // Feature startFeature = ts.getFeature(CAS.START_FEAT);
  // Feature endFeature = ts.getFeature(CAS.END_FEAT);

  // System.out.println("\nCreating sentence annotations.");

  // Get a handle to the index repository.
  FSIndexRepository indexRepository = cas.getIndexRepository();
  // assert(indexRepository != null);
  Iterator<String> labelIt = indexRepository.getLabels();
  assertTrue(labelIt != null);
  // Get the standard index for tokens.
  FSIndex<AnnotationFS> tokenIndex = cas.getAnnotationIndex(tokenType);
  // assert(tokenIndex != null);
  // Get an iterator over tokens.
  FSIterator<AnnotationFS> it = tokenIndex.iterator();
  // assert(it != null);
  // Now create sentences. We do this as follows: a sentence starts where
  // the first token after an EOS starts, and ends with an EOS.
  long time = System.currentTimeMillis();
  int endOfSentenceCounter = 0;
  it.moveToFirst();
  boolean lookForStart = true;
  int start = 0, end; // Initialize start to pacify compiler.
  FeatureStructure tokenFS, sentFS;
  while (it.isValid()) {
    if (lookForStart) {
      // If we're looking for the start of a sentence, just grab the start
      // of the current FS.
      start = it.get().getIntValue(startFeature);
      lookForStart = false;
    } else {
      // Check if we've reached the end of a sentence.
      tokenFS = it.get();
      if (tokenFS.getFeatureValue(tokenTypeFeature).getType() == eosType) {
        end = tokenFS.getIntValue(endFeature);
        sentFS = cas.createFS(sentenceType);
        sentFS.setIntValue(startFeature, start);
        sentFS.setIntValue(endFeature, end);
        cas.getIndexRepository().addFS(sentFS);
        ++endOfSentenceCounter;
        lookForStart = true;
      }
    }
    it.moveToNext();
  }
  time = System.currentTimeMillis() - time;
  // System.out.println("Created " + endOfSentenceCounter + " sentences: " + new TimeSpan(time));
}
 
Example 16
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 17
Source File: SerializationNoMDTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void createSentences() {
  // TypeSystem ts = cas.getTypeSystem();
  // Type eosType = ts.getType(EOS_TYPE);
  // Type tokenType = ts.getType(TOKEN_TYPE);
  // //assert(tokenType != null);
  // Type sentenceType = ts.getType(SENT_TYPE);
  // Feature tokenTypeFeature = ts.getFeature(TOKEN_TYPE_FEAT);
  // Feature startFeature = ts.getFeature(CAS.START_FEAT);
  // Feature endFeature = ts.getFeature(CAS.END_FEAT);

  // System.out.println("\nCreating sentence annotations.");

  // Get a handle to the index repository.
  FSIndexRepository indexRepository = cas.getIndexRepository();
  // assert(indexRepository != null);
  Iterator<String> labelIt = indexRepository.getLabels();
  assertTrue(labelIt != null);
  // Get the standard index for tokens.
  FSIndex<AnnotationFS> tokenIndex = cas.getAnnotationIndex(tokenType);
  // assert(tokenIndex != null);
  // Get an iterator over tokens.
  FSIterator<AnnotationFS> it = tokenIndex.iterator();
  // assert(it != null);
  // Now create sentences. We do this as follows: a sentence starts where
  // the first token after an EOS starts, and ends with an EOS.
  long time = System.currentTimeMillis();
  int endOfSentenceCounter = 0;
  it.moveToFirst();
  boolean lookForStart = true;
  int start = 0, end; // Initialize start to pacify compiler.
  FeatureStructure tokenFS, sentFS;
  while (it.isValid()) {
    if (lookForStart) {
      // If we're looking for the start of a sentence, just grab the start
      // of the current FS.
      start = it.get().getIntValue(startFeature);
      lookForStart = false;
    } else {
      // Check if we've reached the end of a sentence.
      tokenFS = it.get();
      if (tokenFS.getFeatureValue(tokenTypeFeature).getType() == eosType) {
        end = tokenFS.getIntValue(endFeature);
        sentFS = cas.createFS(sentenceType);
        sentFS.setIntValue(startFeature, start);
        sentFS.setIntValue(endFeature, end);
        cas.getIndexRepository().addFS(sentFS);
        ++endOfSentenceCounter;
        lookForStart = true;
      }
    }
    it.moveToNext();
  }
  time = System.currentTimeMillis() - time;
  // System.out.println("Created " + endOfSentenceCounter + " sentences: " + new TimeSpan(time));
}
 
Example 18
Source File: CasAnnotationViewerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testAddAnnotationToTree() throws Exception {
  try {
    // create an annotation
    createExampleFS(this.cas);
    FSIterator iter = this.cas.getAnnotationIndex(exampleType).iterator();
    AnnotationFS annot = (AnnotationFS) iter.get();

    // init viewer
    viewer.setCAS(this.cas);

    // add to tree
    viewer.addAnnotationToTree(annot);

    // inspect results
    TreeModel model = viewer.getSelectedAnnotationTree().getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    assertEquals("Annotations", root.getUserObject().toString());
    DefaultMutableTreeNode typeNode = (DefaultMutableTreeNode) root.getChildAt(0);
    assertEquals("Example", typeNode.getUserObject().toString());
    DefaultMutableTreeNode fsNode = (DefaultMutableTreeNode) typeNode.getChildAt(0);
    Enumeration children = fsNode.children();
    assertEquals("begin = 1", ((DefaultMutableTreeNode) children.nextElement()).getUserObject()
            .toString());
    assertEquals("end = 5", ((DefaultMutableTreeNode) children.nextElement()).getUserObject()
            .toString());
    assertEquals("floatFeature = " + (float) 99.99, ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());
    assertEquals("stringFeature = aaaaaaa", ((DefaultMutableTreeNode) children.nextElement())
            .getUserObject().toString());
    assertEquals("boolFeature = true", ((DefaultMutableTreeNode) children.nextElement())
            .getUserObject().toString());
    assertEquals("byteFeature = 122", ((DefaultMutableTreeNode) children.nextElement())
            .getUserObject().toString());
    assertEquals("shortFeature = " + Short.MIN_VALUE, ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());
    assertEquals("longFeature = " + Long.MIN_VALUE, ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());
    assertEquals("doubleFeature = " + Double.MAX_VALUE, ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());

    assertEquals("intArrayFeature = [" + Integer.MAX_VALUE + "," + (Integer.MAX_VALUE - 1)
            + ",42," + (Integer.MIN_VALUE + 1) + "," + Integer.MIN_VALUE + "]",
            ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("floatArrayFeature = [" + Float.MAX_VALUE + ","
            + (float) (Float.MAX_VALUE / 1000.0) + "," + 42.0 + ","
            + (float) (Float.MIN_VALUE * 1000) + "," + Float.MIN_VALUE + "]",
            ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("stringArrayFeature = [zzzzzz,yyyyyy,xxxxxx,wwwwww,vvvvvv]",
            ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("boolArrayFeature = [true,false,true,false,true,false,true,false]",
            ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("byteArrayFeature = [8,16,64,-128,-1]", ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());
    assertEquals("shortArrayFeature = [" + Short.MAX_VALUE + "," + (Short.MAX_VALUE - 1) + ","
            + (Short.MAX_VALUE - 2) + "," + (Short.MAX_VALUE - 3) + "," + (Short.MAX_VALUE - 4)
            + "]", ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("longArrayFeature = [" + Long.MAX_VALUE + "," + (Long.MAX_VALUE - 1) + ","
            + (Long.MAX_VALUE - 2) + "," + (Long.MAX_VALUE - 3) + "," + (Long.MAX_VALUE - 4)
            + "]", ((DefaultMutableTreeNode) children.nextElement()).getUserObject().toString());
    assertEquals("doubleArrayFeature = [" + Double.MAX_VALUE + "," + Double.MIN_VALUE + ","
            + Double.parseDouble("1.5555") + "," + Double.parseDouble("99.000000005") + ","
            + Double.parseDouble("4.44444444444444444") + "]", ((DefaultMutableTreeNode) children
            .nextElement()).getUserObject().toString());

  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example 19
Source File: AbbreviationsExpanderAnnotator.java    From bluima with Apache License 2.0 4 votes vote down vote up
/**
 * REM: modified from CasUtils..
 * 
 * Get a list of annotations of the given annotation type constraint by a
 * start and end. It's good to provide an annotation that is close to the
 * region, to quickly move the iterator
 * 
 * @param cas
 *            a CAS.
 * @param type
 *            a UIMA type.
 * @param annotationCloseToTheRegion
 *            the covering annotation.
 * @return a return value.
 * @see Subiterator
 */
private static List<Annotation> selectMatching(CAS cas, final int begin,
        final int end, AnnotationFS annotationCloseToTheRegion) {

    final List<Annotation> list = new ArrayList<Annotation>();
    final FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();

    // Try to seek the insertion point.
    it.moveTo(annotationCloseToTheRegion);

    // If the insertion point is beyond the index, move back to the last.
    if (!it.isValid()) {
        it.moveToLast();
        if (!it.isValid()) {
            return list;
        }
    }

    // Ignore type priorities by seeking to the first that has the same
    // begin
    boolean moved = false;
    while (it.isValid() && (it.get()).getBegin() >= begin) {
        it.moveToPrevious();
        moved = true;
    }

    // If we moved, then we are now on one starting before the requested
    // begin, so we have to
    // move one ahead.
    if (moved) {
        it.moveToNext();
    }

    // If we managed to move outside the index, start at first.
    if (!it.isValid()) {
        it.moveToFirst();
    }

    // Skip annotations whose start is before the start parameter.
    while (it.isValid() && (it.get()).getBegin() < begin) {
        it.moveToNext();
    }

    while (it.isValid()) {
        AnnotationFS a = it.get();
        if (!(a instanceof Annotation))
            continue;

        // If the start of the current annotation is past the end parameter,
        // we're done.
        if (a.getBegin() > end) {
            break;
        }
        it.moveToNext();

        if (a.getBegin() == begin && a.getEnd() == end) {
            list.add((Annotation) a);
        }
    }
    return unmodifiableList(list);
}
 
Example 20
Source File: ConsumerCasUtils.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Returns an int value of a given Feature Structure.
 *
 * @param aCasView -
 *          CAS instance to retrieve data from
 * @param aTypeS -
 *          Feature Type
 * @param aFeatS -
 *          Feature Structure
 * @return - feature value as int
 */
public static int getIntFeatValue(CAS aCasView, String aTypeS, String aFeatS) {
  int result = 0;
  FSIterator idIter = aCasView.getAnnotationIndex(aCasView.getTypeSystem().getType(aTypeS)).iterator();
  while (idIter != null && idIter.isValid()) {
    org.apache.uima.cas.FeatureStructure idFS = idIter.get();
    result = idFS.getIntValue(aCasView.getTypeSystem().getFeatureByFullName(aTypeS + ":" + aFeatS));
    idIter.moveToNext();
  }
  return result;
}