org.apache.uima.cas.impl.CASCompleteSerializer Java Examples

The following examples show how to use org.apache.uima.cas.impl.CASCompleteSerializer. 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: CasPersistenceUtils.java    From webanno with Apache License 2.0 6 votes vote down vote up
public static void readSerializedCas(CAS aCas, File aFile)
    throws IOException
{
    CAS realCas = getRealCas(aCas);
    // UIMA-6162 Workaround: synchronize CAS during de/serialization
    synchronized (((CASImpl) realCas).getBaseCAS()) {
        try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(aFile))) {
            CASCompleteSerializer serializer = (CASCompleteSerializer) is.readObject();
            deserializeCASComplete(serializer, (CASImpl) realCas);
            
            // Workaround for UIMA adding back deleted DocumentAnnotations
            // https://issues.apache.org/jira/browse/UIMA-6199
            // If there is a DocumentMetaData annotation, then we can drop any of the default
            // UIMA DocumentAnnotation instances (excluding the DocumentMetaData of course)
            if (!aCas.select(DocumentMetaData.class.getName()).isEmpty()) {
                aCas.select(CAS.TYPE_NAME_DOCUMENT_ANNOTATION)
                    .filter(fs -> !DocumentMetaData.class.getName().equals(
                            fs.getType().getName()))
                    .forEach(aCas::removeFsFromIndexes);
            }
        }
        catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
    }
}
 
Example #2
Source File: SCAS.java    From ambiverse-nlu with Apache License 2.0 5 votes vote down vote up
public SCAS copy() throws UIMAException, IOException, ClassNotFoundException {
    JCas jcas = JCasFactory.createJCas();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ObjectOutputStream docOS = new ObjectOutputStream(buffer);
    CASCompleteSerializer serializerOut = Serialization.serializeCASComplete(this.getJCas().getCasImpl());
    docOS.writeObject(serializerOut);
    docOS.close();
    ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
    CASCompleteSerializer serializerIn = (CASCompleteSerializer)is.readObject();
    Serialization.deserializeCASComplete(serializerIn, jcas.getCasImpl());
    return new SCAS(jcas.getCas());
}
 
Example #3
Source File: BratAnnotatorUtility.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static CAS clearAnnotations(CAS aCas)
    throws IOException
{
    CAS target;
    try {
        target = CasFactory.createCas((TypeSystemDescription) null);
    }
    catch (UIMAException e) {
        throw new IOException(e);
    }
    
    // Copy the CAS - basically we do this just to keep the full type system information
    CASCompleteSerializer serializer = serializeCASComplete((CASImpl) getRealCas(aCas));
    deserializeCASComplete(serializer, (CASImpl) getRealCas(target));

    // Remove all annotations from the target CAS but we keep the type system!
    target.reset();
    
    // Copy over essential information
    if (exists(aCas, getType(aCas, DocumentMetaData.class))) {
        copyDocumentMetadata(aCas, target);
    }
    else {
        WebAnnoCasUtil.createDocumentMetadata(aCas);
    }
    target.setDocumentLanguage(aCas.getDocumentLanguage()); // DKPro Core Issue 435
    target.setDocumentText(aCas.getDocumentText());
    
    // Transfer token boundaries
    for (AnnotationFS t : selectTokens(aCas)) {
        target.addFsToIndexes(createToken(target, t.getBegin(), t.getEnd()));
    }

    // Transfer sentence boundaries
    for (AnnotationFS s : selectSentences(aCas)) {
        target.addFsToIndexes(createSentence(target, s.getBegin(), s.getEnd()));
    }

    return target;
}
 
Example #4
Source File: AnnotationSchemaServiceImpl.java    From webanno with Apache License 2.0 5 votes vote down vote up
/**
 * Load the contents from the source CAS, upgrade it to the target type system and write the
 * results to the target CAS. An in-place upgrade can be achieved by using the same CAS as
 * source and target.
 */
@Override
public void upgradeCas(CAS aSourceCas, CAS aTargetCas, TypeSystemDescription aTargetTypeSystem)
    throws UIMAException, IOException
{
    CasStorageSession.get().assertWritingPermitted(aTargetCas);
    
    // Save source CAS type system (do this early since we might do an in-place upgrade)
    TypeSystem sourceTypeSystem = aSourceCas.getTypeSystem();

    // Save source CAS contents
    ByteArrayOutputStream serializedCasContents = new ByteArrayOutputStream();
    CAS realSourceCas = getRealCas(aSourceCas);
    // UIMA-6162 Workaround: synchronize CAS during de/serialization
    synchronized (((CASImpl) realSourceCas).getBaseCAS()) {
        serializeWithCompression(realSourceCas, serializedCasContents, sourceTypeSystem);
    }

    // Re-initialize the target CAS with new type system
    CAS realTargetCas = getRealCas(aTargetCas);
    // UIMA-6162 Workaround: synchronize CAS during de/serialization
    synchronized (((CASImpl) realTargetCas).getBaseCAS()) {
        CAS tempCas = CasFactory.createCas(aTargetTypeSystem);
        CASCompleteSerializer serializer = serializeCASComplete((CASImpl) tempCas);
        deserializeCASComplete(serializer, (CASImpl) realTargetCas);

        // Leniently load the source CAS contents into the target CAS
        CasIOUtils.load(new ByteArrayInputStream(serializedCasContents.toByteArray()),
                getRealCas(aTargetCas), sourceTypeSystem);
    }
}
 
Example #5
Source File: CasPersistenceUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static void writeSerializedCas(CAS aCas, File aFile)
    throws IOException
{
    FileUtils.forceMkdir(aFile.getParentFile());
    
    CASCompleteSerializer serializer = null;
    
    CAS realCas = getRealCas(aCas);
    // UIMA-6162 Workaround: synchronize CAS during de/serialization
    synchronized (((CASImpl) realCas).getBaseCAS()) {
        try {
            serializer = serializeCASComplete((CASImpl) getRealCas(aCas));

            // BEGIN SAFEGUARD --------------
            // Safeguard that we do NOT write a CAS which can afterwards not be read and thus
            // would render the document broken within the project
            // Reason we do this: https://issues.apache.org/jira/browse/UIMA-6162
            CAS dummy = WebAnnoCasUtil.createCas();
            deserializeCASComplete(serializer, (CASImpl) getRealCas(dummy));
            // END SAFEGUARD --------------
        }
        catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                preserveForDebugging(aFile, aCas, serializer);
            }
            throw new IOException(e);
        }

        try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(aFile))) {
            os.writeObject(serializer);
        }
    }
}
 
Example #6
Source File: CasMerge.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static void clearAnnotations(CAS aCas)
    throws UIMAException
{
    CAS backup = CasFactory.createCas((TypeSystemDescription) null);
    
    // Copy the CAS - basically we do this just to keep the full type system information
    CASCompleteSerializer serializer = serializeCASComplete((CASImpl) getRealCas(aCas));
    deserializeCASComplete(serializer, (CASImpl) getRealCas(backup));

    // Remove all annotations from the target CAS but we keep the type system!
    aCas.reset();
    
    // Copy over essential information
    if (exists(backup, getType(backup, DocumentMetaData.class))) {
        copyDocumentMetadata(backup, aCas);
    }
    else {
        WebAnnoCasUtil.createDocumentMetadata(aCas);
    }
    aCas.setDocumentLanguage(backup.getDocumentLanguage()); // DKPro Core Issue 435
    aCas.setDocumentText(backup.getDocumentText());
    
    // Transfer token boundaries
    for (AnnotationFS t : selectTokens(backup)) {
        aCas.addFsToIndexes(createToken(aCas, t.getBegin(), t.getEnd()));
    }

    // Transfer sentence boundaries
    for (AnnotationFS s : selectSentences(backup)) {
        aCas.addFsToIndexes(createSentence(aCas, s.getBegin(), s.getEnd()));
    }
}
 
Example #7
Source File: CasPersistenceUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static void writeSerializedCas(CAS aCas, File aFile)
    throws IOException
{
    FileUtils.forceMkdir(aFile.getParentFile());

    try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(aFile))) {
        CASCompleteSerializer serializer = serializeCASComplete((CASImpl) aCas);
        os.writeObject(serializer);
    }
}
 
Example #8
Source File: CasPersistenceUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static void readSerializedCas(CAS aCas, File aFile)
    throws IOException
{
    try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(aFile))) {
        CASCompleteSerializer serializer = (CASCompleteSerializer) is.readObject();
        deserializeCASComplete(serializer, (CASImpl) getRealCas(aCas));
    }
    catch (ClassNotFoundException e) {
        throw new IOException(e);
    }
}
 
Example #9
Source File: VinciBinaryAnalysisEngineServiceStub.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Call process.
 *
 * @param aCAS the a CAS
 * @throws ResourceServiceException the resource service exception
 * @see AnalysisEngineServiceStub#callProcess(CAS)
 */
public void callProcess(CAS aCAS) throws ResourceServiceException {
  try {
    AFrame requestFrame = new AFrame();
    requestFrame.fset(Constants.VINCI_COMMAND, Constants.ANNOTATE);
    // serialize CAS (including type system)
    CASMgr cas = (CASMgr) aCAS;
    CASCompleteSerializer serializer = Serialization.serializeCASComplete(cas);

    requestFrame.fsetTrueBinary("BinaryCAS", SerializationUtils.serialize(serializer));

    AFrame responseFrame = (AFrame) mVinciClient.sendAndReceive(requestFrame, mTimeout);

    // deserialize CAS from response frame
    byte[] responseCasBytes = responseFrame.fgetTrueBinary("BinaryCAS");
    CASSerializer responseSerializer = (CASSerializer) SerializationUtils
            .deserialize(responseCasBytes);
    ((CASImpl) cas).getBinaryCasSerDes().reinit(responseSerializer);

    // also read annotation time and enter into AnalysisEngineManagementMBean
    int annotationTime = responseFrame.fgetInt(Constants.ANNOTATION_TIME);
    if (annotationTime > 0) {
      AnalysisEngineManagementImpl mbean = (AnalysisEngineManagementImpl) mOwner
              .getManagementInterface();
      mbean.reportAnalysisTime(annotationTime);
    }
  } catch (Exception e) {
    throw new ResourceServiceException(e);
  }
}
 
Example #10
Source File: TypeSystemReinitTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testReinitCASCompleteSerializer() throws Exception {
  try {
    AnalysisEngineDescription aed = UIMAFramework.getXMLParser().parseAnalysisEngineDescription(
            new XMLInputSource(JUnitExtension
                    .getFile("TextAnalysisEngineImplTest/TestPrimitiveTae1.xml")));
    TypeSystemDescription tsd = UIMAFramework.getXMLParser().parseTypeSystemDescription(
            new XMLInputSource(getClass().getResource("/org/apache/uima/examples/SourceDocumentInformation.xml")));

    List<MetaDataObject> l = new ArrayList<>();
    l.add(aed);
    l.add(tsd);
    CAS cas1 = CasCreationUtils.createCas(l);
    cas1.setDocumentText("foo");
    CASCompleteSerializer ser = Serialization.serializeCASComplete((CASMgr) cas1);

    CAS tcas2 = CasCreationUtils.createCas(new TypeSystemDescription_impl(), null, null);
    CASImpl cas2 = ((CASImpl) tcas2).getBaseCAS();
    tcas2.setDocumentText("bar");

    // reinit
    //  This uses cas2 which only has a base type system to start, 
    //    and loads it from a complete serialization which has other new types
    cas2.getBinaryCasSerDes().reinit(ser);
    CAS tcas3 = cas2.getCurrentView();

    assertTrue(tcas2 == tcas3);
    assertNotNull(cas1.getTypeSystem().getType("NamedEntity"));
    assertNotNull(tcas3.getTypeSystem().getType("NamedEntity"));

    FeatureStructure fs = tcas3.createFS(tcas3.getTypeSystem().getType("NamedEntity"));
    tcas3.getIndexRepository().addFS(fs);
  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example #11
Source File: TypeSystemReinitTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testReinitCASCompleteSerializerWithArrays() throws Exception {
  try {
    AnalysisEngineDescription aed = UIMAFramework.getXMLParser().parseAnalysisEngineDescription(
            new XMLInputSource(JUnitExtension
                    .getFile("ExampleTae/arrayTypeSerialization.xml")));
   
    CAS cas1 = CasCreationUtils.createCas(aed);
    cas1.setDocumentText("foo");
    CASCompleteSerializer ser = Serialization.serializeCASComplete((CASMgr) cas1);

    CAS tcas2 = CasCreationUtils.createCas(new TypeSystemDescription_impl(), null, null);
    CASImpl cas2 = ((CASImpl) tcas2).getBaseCAS();
    tcas2.setDocumentText("bar");

    // reinit
    //  This uses cas2 which only has a base type system to start, 
    //    and loads it from a complete serialization which has other new types
    cas2.getBinaryCasSerDes().reinit(ser);
    CAS tcas3 = cas2.getCurrentView();

    assertTrue(tcas2 == tcas3);
    assertNotNull(cas1.getTypeSystem().getType("Test.ArrayType"));
    assertNotNull(tcas3.getTypeSystem().getType("Test.ArrayType"));
    
    TypeSystemImpl ts = (TypeSystemImpl)cas2.getTypeSystem();
    Type arrayType = ts.getType("Test.ArrayType");
    Feature arrayFeat = arrayType.getFeatureByBaseName("arrayFeature");
    TypeImpl featRange = (TypeImpl)(arrayFeat.getRange());
   
    assertTrue(ts.ll_isArrayType(featRange.getCode()));
    assertFalse(arrayFeat.isMultipleReferencesAllowed());
    
  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example #12
Source File: VinciBinaryAnalysisEngineService_impl.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Analyzes a given document by a CasObjectProcessor. 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 aRequestFrame          request frame
 * @return VinciFrame containing XCAS translated into a set of Vinci subframes.
 * @throws ServiceException the service exception
 */
private Transportable analyze(AFrame aRequestFrame) throws ServiceException {
  CAS cas = null;
  try {
    // get CAS object from pool
    cas = mCasPool.getCas(0);

    // deserialize into CAS object
    byte[] casBytes = aRequestFrame.fgetTrueBinary("BinaryCAS");
    CASCompleteSerializer serializer = (CASCompleteSerializer) SerializationUtils
            .deserialize(casBytes);
    Serialization.deserializeCASComplete(serializer, (CASMgr) cas);

    long annotStartTime = System.currentTimeMillis();
    // invoke Analysis Engine
    mAE.processCas(cas);
    int annotationTime = (int) (System.currentTimeMillis() - annotStartTime);
    if (debug) {
      System.out.println("Annotation took: " + annotationTime + "ms");
    }

    // serialize CAS
    AFrame responseFrame = new AFrame();
    CASSerializer responseSerializer = Serialization.serializeCAS(cas);
    byte[] responseCasBytes = SerializationUtils.serialize(responseSerializer);
    responseFrame.fsetTrueBinary("BinaryCAS", responseCasBytes);
    // also add annotation time
    responseFrame.fset(Constants.ANNOTATION_TIME, annotationTime);

    // 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.FINE, "CAS Annotation Count::" + totalAnnots);

    return responseFrame;
  } catch (Throwable ex) {
    UIMAFramework.getLogger().log(Level.SEVERE, "", ex);
    throw new ServiceException("Unexpected exception in analyze(): " + ex);
  } finally {
    // release CAS back to pool
    if (cas != null) {
      mCasPool.releaseCas(cas);
    }
  }
}
 
Example #13
Source File: CasTreeViewerApplet.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Called when the applet is initialized.
 */
@Override
public void init() {
  try {
    // get applet parameter - URL from which to get the CAS
    String casURL = getParameter("CasUrl");

    // open URL connection to get the serialized CAS
    URLConnection con = new URL(casURL).openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setRequestProperty("Content-Type", "application/octet-stream");
    // con.connect();

    InputStream in = con.getInputStream();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] buf = new byte[2048];
    int bytesRead = in.read(buf);
    while (bytesRead > 0) {
      byteStream.write(buf, 0, bytesRead);
      bytesRead = in.read(buf);
    }
    byte[] bytes = byteStream.toByteArray();
    in.close();
    byteStream.close();
    System.out.println("Got " + bytes.length + " bytes.");

    // deserialize CAS
    CASMgr casMgr = CASFactory.createCAS();
    CASCompleteSerializer serializer = (CASCompleteSerializer) SerializationUtils
            .deserialize(bytes);
    Serialization.deserializeCASComplete(serializer, casMgr);

    // create tree viewer component and add to this applet
    mTreeViewer = new CasTreeViewer(casMgr.getCAS().getView(CAS.NAME_DEFAULT_SOFA));
    getContentPane().add(mTreeViewer);

    // add a listener that detects resize events
    addComponentListener(new MyComponentListener());

    // set initial size of tree viewer panel
    resizeTreeViewer();

  } catch (Exception e) {
    e.printStackTrace();
  }

}
 
Example #14
Source File: CasAnnotationViewerApplet.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Called when the applet is initialized.
 */
@Override
public void init() {
  try {
    // get applet parameter - URL from which to get the CAS
    String casURL = getParameter("CasUrl");

    // open URL connection to get the serialized CAS
    URLConnection con = new URL(casURL).openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setRequestProperty("Content-Type", "application/octet-stream");
    // con.connect();

    InputStream in = con.getInputStream();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] buf = new byte[2048];
    int bytesRead = in.read(buf);
    while (bytesRead > 0) {
      byteStream.write(buf, 0, bytesRead);
      bytesRead = in.read(buf);
    }
    byte[] bytes = byteStream.toByteArray();
    in.close();
    byteStream.close();
    System.out.println("Got " + bytes.length + " bytes.");

    // deserialize CAS
    CASMgr casMgr = CASFactory.createCAS();
    CASCompleteSerializer serializer = (CASCompleteSerializer) SerializationUtils
            .deserialize(bytes);
    Serialization.deserializeCASComplete(serializer, casMgr);

    // get 2nd applet parameter - right-to-left text orientation
    boolean rightToLeft = false;
    String rightToLeftParam = getParameter("RightToLeftTextOrientation");
    if (rightToLeftParam != null && rightToLeftParam.equalsIgnoreCase("true")) {
      rightToLeft = true;
    }

    // create viewer component and add to this applet
    mViewer = new CasAnnotationViewer();
    // NOTE: it seems to be important to add the viewer to the frame
    // before calling setCAS. If we do it the other way around
    // we seem to frequently cause the browser to hang.
    getContentPane().add(mViewer);

    mViewer.setCAS(casMgr.getCAS().getView(CAS.NAME_DEFAULT_SOFA));
    mViewer.setRightToLeftTextOrientation(rightToLeft);

    // add a listener that detects resize events
    addComponentListener(new MyComponentListener());

    // set initial size of tree viewer panel
    resizeTreeViewer();

  } catch (Exception e) {
    e.printStackTrace();
  }

}
 
Example #15
Source File: CppUimajEngine.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public int initialize(String config, String dataPath, int[] typeInheritance,
        int[] typePriorities, int[] featureDefs, int[] featureOffset, String[] typeNames,
        String[] featureNames, int[] stringSubTypes, String[] stringSubTypeValues,
        int[] stringSubTypeValuePos, String[] indexIDs, int[] indexKinds, int[] compStarts,
        int[] compDefs) {
  int result = 0;
  try {
    // System.out.println("CppUimajEngine::initialize()");
    CASMgrSerializer serializer = new CASMgrSerializer();
    serializer.typeOrder = typePriorities;
    serializer.indexNames = indexIDs;

    // trivalliy construct the name to index map
    serializer.nameToIndexMap = new int[indexIDs.length];
    for (int i = 0; i < serializer.nameToIndexMap.length; ++i) {
      serializer.nameToIndexMap[i] = i;
    }

    serializer.indexingStrategy = indexKinds;
    serializer.comparatorIndex = compStarts;
    serializer.comparators = compDefs;

    serializer.typeNames = typeNames;
    serializer.featureNames = featureNames;
    serializer.typeInheritance = typeInheritance;
    serializer.featDecls = featureDefs;
    serializer.topTypeCode = 1;
    serializer.featureOffsets = featureOffset;
    serializer.stringSubtypes = stringSubTypes;
    serializer.stringSubtypeValues = stringSubTypeValues;
    serializer.stringSubtypeValuePos = stringSubTypeValuePos;

    byte[] bar = config.getBytes(StandardCharsets.UTF_16);
    ByteArrayInputStream bais = new ByteArrayInputStream(bar);
    XMLInputSource in = new XMLInputSource(bais, null);
    ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
    bais.close();

    ResourceManager resMgr = UIMAFramework.newDefaultResourceManager();
    resMgr.setDataPath(dataPath);

    if (specifier instanceof CasConsumerDescription) {
      cc = UIMAFramework.produceCasConsumer(specifier);
      CasConsumerDescription ccdesc = (CasConsumerDescription) specifier;
      Capability[] capabilities = ccdesc.getCasConsumerMetaData().getCapabilities();
      for (int i = 0; i < capabilities.length; i++) {
        String[] inputsofas = capabilities[i].getInputSofas();
        if (inputsofas.length > 0)
          requiresTCas = false;
      }
    } else {
      ae = UIMAFramework.produceAnalysisEngine(specifier, resMgr, null);
    }

    casImpl = (CASImpl) CASFactory.createCAS();
    casImpl.commitTypeSystem();

    // Create the Base indexes in order to deserialize
    casImpl.initCASIndexes();
    casImpl.getIndexRepositoryMgr().commit();

    // deserialize into this CAS
    CASCompleteSerializer completeSerializer = new CASCompleteSerializer();
    completeSerializer.setCasMgrSerializer(serializer);
    completeSerializer.setCasSerializer(Serialization.serializeCAS(casImpl));

    casImpl.getBinaryCasSerDes().reinit(completeSerializer);

    // System.out.println(cc.getProcessingResourceMetaData().getName());
  } catch (Exception exc) {
    result = 1;
    logException(exc);
  }

  return result;
}
 
Example #16
Source File: IndexSerializationTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Test driver.
 */
public void testMain() throws Exception {

  for (int i = 0; i < 10; i++) {
    cas.getIndexRepository().addFS(cas.createAnnotation(annotationType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(sentenceType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
  }
  for (int i = 19; i >= 10; i--) {
    cas.getIndexRepository().addFS(cas.createAnnotation(annotationType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(sentenceType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
    cas.getIndexRepository().addFS(cas.createAnnotation(tokenType, i * 2, (i * 2) + 1));
  }

  AnnotationFS searchAnnot = cas.createAnnotation(annotationType, 0, 1);
  assertTrue(cas.getAnnotationIndex().find(searchAnnot) != null);
  assertTrue(cas.getIndexRepository().getIndex(ANNOT_SET_INDEX).find(searchAnnot) != null);
  // find() does not produce useful results on bag indexes, since the comparator
  // is not defined.
  // assertTrue(cas.getIndexRepository().getIndex(ANNOT_BAG_INDEX).find(searchAnnot) != null);

  searchAnnot.setIntValue(endFeature, 4);
  assertTrue(cas.getAnnotationIndex().find(searchAnnot) == null);
  assertTrue(cas.getIndexRepository().getIndex(ANNOT_SET_INDEX).find(searchAnnot) == null);
  assertTrue(cas.getIndexRepository().getIndex(ANNOT_BAG_INDEX).find(searchAnnot) == null);

  final int ordSize = cas.getAnnotationIndex().size();
  final int setSize = cas.getIndexRepository().getIndex(ANNOT_SET_INDEX).size();
  final int bagSize = cas.getIndexRepository().getIndex(ANNOT_BAG_INDEX).size();
  // System.out.println("Before serialization\n");
  // System.out.println("Size of ordered index: " + ordSize);
  // System.out.println("Size of set index: " + setSize);
  // System.out.println("Size of bag index: " + bagSize);

  CASCompleteSerializer cs;
  cs = Serialization.serializeCASComplete(casMgr);
  // casMgr = CASFactory.createCAS();
  CASMgr realCasMgr = CASFactory.createCAS();  // creates base view, but no ts, so no ir
  ((CASImpl) realCasMgr).commitTypeSystem();   // also makes index repo (which will be replaced), but doesn't init the built-in indexes
  Serialization.deserializeCASComplete(cs, realCasMgr);
  cas = ((CASImpl) realCasMgr).getCurrentView();
  casMgr = (CASMgr) cas;

  // System.out.println("After serialization\n");
  FSIndex<? extends FeatureStructure> index = cas.getAnnotationIndex();
  assertTrue(index != null);
  assertTrue(index.getIndexingStrategy() == FSIndex.SORTED_INDEX);
  // System.out.println("Size of ordered index: " + index.size());
  assertTrue(index.size() == ordSize);

  index = cas.getIndexRepository().getIndex(ANNOT_BAG_INDEX);
  assertTrue(index != null);
  assertTrue(index.getIndexingStrategy() == FSIndex.BAG_INDEX);
  // System.out.println("Size of bag index: " + index.size());
  assertTrue(index.size() == bagSize);

  index = cas.getIndexRepository().getIndex(ANNOT_SET_INDEX);
  assertTrue(index != null);
  assertTrue(index.getIndexingStrategy() == FSIndex.SET_INDEX);
  // System.out.println("Size of set index: " + index.size());
  // System.out.println("Should be: " + setSize);
  assertTrue(index.size() == setSize);

}