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

The following examples show how to use org.apache.uima.cas.impl.XmiCasSerializer. 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: CTAKESClinicalPipelineFactory.java    From ctakes-clinical-pipeline with Apache License 2.0 6 votes vote down vote up
private static void serialize(JCas jcas, File file) throws SAXException, IOException {
  OutputStream outputStream = null;
  try {
    outputStream = new BufferedOutputStream(new FileOutputStream(file));

    XmiCasSerializer xmiSerializer = new XmiCasSerializer(
        jcas.getTypeSystem());
    XMLSerializer xmlSerializer = new XMLSerializer(outputStream, true);
    xmiSerializer.serialize(jcas.getCas(),
        xmlSerializer.getContentHandler());

  } catch (FileNotFoundException fnfe) {
    throw new FileNotFoundException(fnfe.getMessage());
  } catch (SAXException saxe) {
    throw new SAXException(saxe.getMessage());
  } finally {
    try {
      outputStream.close();
    } catch (IOException ioe) {
      throw new IOException(ioe.getMessage());
    }
  }
}
 
Example #2
Source File: JsonCasSerializerTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private String serialize() throws Exception {    
  StringWriter sw = null;
  ByteArrayOutputStream baos = null;
  try {
    if (doJson) {
      sw = new StringWriter();
      jcs.serialize(cas, sw);
      return sw.toString();
    } else {
      XmiCasSerializer xcs = new XmiCasSerializer(jcs.getCss().getFilterTypes());
      baos = new ByteArrayOutputStream();
      
      XMLSerializer sax2xml = new XMLSerializer(baos, jcs.getCss().isFormattedOutput);
      xcs.serialize(cas, sax2xml.getContentHandler(), null);
      return baos.toString("UTF-8");
    }
  } catch (Exception e) {
    System.err.format("Exception occurred. The string produced so far was: %n%s%n",
        (sw == null) ? baos.toString("UTF-8") : sw.toString());
    throw e;
  }
}
 
Example #3
Source File: ExternalRecommender.java    From inception with Apache License 2.0 5 votes vote down vote up
private String serializeCas(CAS aCas) throws RecommendationException
{
    try (StringWriter out = new StringWriter()) {
        // Passing "null" as the type system to the XmiCasSerializer means that we want 
        // to serialize all types (i.e. no filtering for a specific target type system).
        XmiCasSerializer xmiCasSerializer = new XmiCasSerializer(null);
        XMLSerializer sax2xml = new XMLSerializer(out, true);
        xmiCasSerializer.serialize(getRealCas(aCas), sax2xml.getContentHandler(), null, null,
                null);
        return out.toString();
    }
    catch (CASRuntimeException | SAXException | IOException e) {
        throw new RecommendationException("Error while serializing CAS!", e);
    }
}
 
Example #4
Source File: RemoteStringMatchingNerRecommender.java    From inception with Apache License 2.0 5 votes vote down vote up
private String buildPredictionResponse(CAS aCas) throws SAXException, IOException
{
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        XmiCasSerializer.serialize(aCas, null, out, true, null);
        PredictionResponse response = new PredictionResponse();
        response.setDocument(new String(out.toByteArray(), UTF_8));
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(response);
    }
}
 
Example #5
Source File: CompressedXmiWriter.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
@Override
public void process(JCas aJCas)
        throws AnalysisEngineProcessException
{
    try {
        java.io.ByteArrayOutputStream jCasOutputStream = new java.io.ByteArrayOutputStream();
        XmiCasSerializer.serialize(aJCas.getCas(), jCasOutputStream);

        // get name = id + .xmi
        String singleEntryName = DocumentMetaData.get(aJCas).getDocumentId() + ".xmi";
        // convert output stream to input stream
        //            InputStream inputStream = new ByteArrayInputStream(jCasOutputStream.toByteArray());

        // add to the tar
        addSingleEntryToTar(jCasOutputStream.toByteArray(), singleEntryName);

        if (!typeSystemWritten) {
            writeTypeSystem(aJCas);
            typeSystemWritten = true;
        }

        counter++;
    }
    catch (IOException | SAXException ex) {
        throw new AnalysisEngineProcessException(ex);
    }
}
 
Example #6
Source File: StandaloneArgument.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
public void setJCas(JCas jCas)
        throws IOException
{
    // now convert to XMI
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    try {
        XmiCasSerializer.serialize(jCas.getCas(), byteOutputStream);
    }
    catch (SAXException e) {
        throw new IOException(e);
    }

    // encode to base64
    this.base64JCas = new BASE64Encoder().encode(byteOutputStream.toByteArray());
}
 
Example #7
Source File: PreprocessorService.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
public JCas toXMICas(JCas cas, Path filePath) {
	try {
		logger.debug("Exporting CAS to {}", filePath);
		XmiCasSerializer.serialize(cas.getCas(), new FileOutputStream(makeParentDirs(filePath).toFile()));
		logger.debug("XMI CAS export succeeded");
		return cas;
	} catch (FileNotFoundException | SAXException e) {
		throw new TermSuiteException(e);
	}
}
 
Example #8
Source File: CreateSampleXMIFile.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws UIMAException, SAXException, IOException {
  TokenBuilder<Token, Sentence> tokenBuilder = new TokenBuilder<Token, Sentence>(Token.class,
          Sentence.class, "pos", "stem");
  JCas jCas = JCasFactory.createJCas();
  String text = "Me and all my friends are non-conformists.";
  tokenBuilder.buildTokens(jCas, text, "Me and all my friends are non - conformists .",
          "M A A M F A N - C .", "me and all my friend are non - conformist .");

  FileOutputStream out = new FileOutputStream("src/test/resources/data/docs/test.xmi");
  XmiCasSerializer ser = new XmiCasSerializer(jCas.getTypeSystem());
  XMLSerializer xmlSer = new XMLSerializer(out, false);
  ser.serialize(jCas.getCas(), xmlSer.getContentHandler());
  out.close();

}
 
Example #9
Source File: NewPrimitiveTypesTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testXmiSerialization() throws Exception {

    // create FS
    createExampleFS(cas);

    // serialize

    StringWriter sw = new StringWriter();
    XMLSerializer xmlSer = new XMLSerializer(sw, false);
    XmiCasSerializer xmiSer = new XmiCasSerializer(cas.getTypeSystem());
    xmiSer.serialize(cas, xmlSer.getContentHandler());
    String xml = sw.getBuffer().toString();
    // System.out.println(xml);
    // reset
    cas.reset();

    // deserialize
    XmiCasDeserializer deser = new XmiCasDeserializer(cas.getTypeSystem());
    ContentHandler deserHandler = deser.getXmiCasHandler(cas);
    SAXParserFactory fact = SAXParserFactory.newInstance();
    SAXParser parser = fact.newSAXParser();
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setContentHandler(deserHandler);
    xmlReader.parse(new InputSource(new StringReader(xml)));

    // check values
    validateFSData(cas);

  }
 
Example #10
Source File: UimaTypeSystem2Ecore.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Uima namespace 2 namespace uri.
 *
 * @param uimaNamespace the uima namespace
 * @return the string
 */
private static String uimaNamespace2NamespaceUri(String uimaNamespace) {
  if (uimaNamespace == null || uimaNamespace.length() == 0) {
    return XmiCasSerializer.DEFAULT_NAMESPACE_URI;
  }
  // Our convention is that the Namespace URI is "http:///", followed by the UIMA namespace, with
  // dots converted to slashes, and with ".ecore" appended. (This is EMF's convention for
  // constructing a namespace URI from a Java package name.)
  return "http:///" + uimaNamespace.replace('.', '/') + ".ecore";
}
 
Example #11
Source File: Ecore2UimaTypeSystem.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
  * Namespace uri 2 uima namespace.
  *
  * @param nsUri the ns uri
  * @return the string
  * @throws URISyntaxException the URI syntax exception
  */
 private static String namespaceUri2UimaNamespace(String nsUri) throws URISyntaxException {
   // Check for the special "no namespace URI", which maps to the null UIMA namespace
   if (XmiCasSerializer.DEFAULT_NAMESPACE_URI.equals(nsUri)) {
     return null;
   }
   // Our convention is that the UIMA namespace is the URI path, with leading slashes
   // removed, trailing ".ecore" removed, and internal slashes converted to dots
   java.net.URI uri = new java.net.URI(nsUri);
   String uimaNs = uri.getPath();
   if (uimaNs == null) {
     // The URI is a URN
     uimaNs = uri.getSchemeSpecificPart();
     uimaNs = uimaNs.replace(':', '.');
   } else {
     // The URI is a URL
     while (uimaNs.startsWith("/")) {
uimaNs = uimaNs.substring(1);
     }
     if (uimaNs.endsWith(".ecore")) {
uimaNs = uimaNs.substring(0, uimaNs.length() - 6);
     }
     uimaNs = uimaNs.replace('/', '.');
   }
   uimaNs = uimaNs.replace('-', '_');
   return uimaNs;
 }
 
Example #12
Source File: XmiWriterCasConsumer.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Serialize a CAS to a file in XMI format
 * 
 * @param aCas
 *          CAS to serialize
 * @param name
 *          output file
 * @throws SAXException -
 * @throws Exception -
 * 
 * @throws ResourceProcessException -
 */
private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException {

  try (FileOutputStream out = new FileOutputStream(name)) {
    // write XMI
    XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem());
    XMLSerializer xmlSer = new XMLSerializer(out, false);
    ser.serialize(aCas, xmlSer.getContentHandler());
  }
}
 
Example #13
Source File: XmiWriterCasConsumer.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Serialize a CAS to a file in XMI format
 * 
 * @param aCas
 *          CAS to serialize
 * @param name
 *          output file
 * @throws SAXException -
 * @throws Exception -
 * 
 * @throws ResourceProcessException -
 */
private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException {

  try (OutputStream out = new FileOutputStream(name)) {
    // write XMI
    XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem());
    XMLSerializer xmlSer = new XMLSerializer(out, false);
    ser.serialize(aCas, xmlSer.getContentHandler());
  }
}
 
Example #14
Source File: XmlCasSerializer.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Serializes a CAS to XMI format and writes it to an output stream.
 * 
 * @param aCAS
 *          CAS to serialize.
 * @param aStream
 *          output stream to which to write the XMI document
 * 
 * @throws SAXException
 *           if a problem occurs during XMI serialization
 * @throws IOException
 *           if an I/O failure occurs
 */
public static void serialize(CAS aCAS, OutputStream aStream) throws SAXException, IOException {
  XmiCasSerializer.serialize(aCAS, aStream);
}
 
Example #15
Source File: XmlCasSerializer.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Serializes a CAS to XMI format and writes it to an output stream. Allows a TypeSystem to be
 * specified, to which the produced XMI will conform. Any types or features not in the target type
 * system will not be serialized.
 * 
 * @param aCAS
 *          CAS to serialize.
 * @param aTargetTypeSystem
 *          type system to which the produced XMI will conform. Any types or features not in the
 *          target type system will not be serialized.
 *          
 * @param aStream
 *          output stream to which to write the XMI document
 * 
 * @throws SAXException
 *           if a problem occurs during XMI serialization
 * @throws IOException
 *           if an I/O failure occurs
 */
public static void serialize(CAS aCAS, TypeSystem aTargetTypeSystem, OutputStream aStream)
        throws SAXException, IOException {
  XmiCasSerializer.serialize(aCAS, aTargetTypeSystem, aStream);
}