Java Code Examples for org.xml.sax.ContentHandler#endDocument()

The following examples show how to use org.xml.sax.ContentHandler#endDocument() . 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: MessageStreamCapTest.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Test
/*
 * if used as a ContentHandler, then the underlying buffer must be a Writer, probably a StringWriter
 */
public void testContentHandlerCap() throws Exception {
	INamedObject owner = new Owner();
	IForwardTarget forward = null;
	String expectedResponseMessage = "<root/>";
	try (MessageOutputStreamCap cap = new MessageOutputStreamCap(owner,forward)) {
		ContentHandler capContentHandler = cap.asContentHandler();
		
		Object capNative = cap.asNative();
		
		assertTrue(capNative instanceof Writer);
		
		capContentHandler.startDocument();
		capContentHandler.startElement("", "root", "root", new AttributesImpl());
		capContentHandler.endElement("", "root", "root");
		capContentHandler.endDocument();

		PipeRunResult result = cap.getPipeRunResult();
		
		assertEquals(expectedResponseMessage,result.getResult().asString());
	}
}
 
Example 2
Source File: XmiCasSerializer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Write the CAS data to a SAX content handler.
 * 
 * @param cas
 *          The CAS to be serialized.
 * @param contentHandler
 *          The SAX content handler the data is written to.
 * @param errorHandler the SAX Error Handler to use
 * @param sharedData
 *          data structure used to allow the XmiCasSerializer and XmiCasDeserializer to share
 *          information.
 * @param marker
 *        an object used to filter the FSs and Views to determine if these were created after
 *          the mark was set. Used to serialize a Delta CAS consisting of only new FSs and views and
 *          preexisting FSs and Views that have been modified.
 *          
 * @throws SAXException if there was a SAX exception
 */
public void serialize(CAS cas, ContentHandler contentHandler, ErrorHandler errorHandler,
        XmiSerializationSharedData sharedData, Marker marker) throws SAXException {
  
  contentHandler.startDocument();
  if (errorHandler != null) {
    css.setErrorHandler(errorHandler);
  }
  XmiDocSerializer ser = new XmiDocSerializer(contentHandler, ((CASImpl) cas).getBaseCAS(), sharedData, (MarkerImpl) marker);
  try {
    ser.cds.serialize();
  } catch (Exception e) {
    if (e instanceof SAXException) {
      throw (SAXException) e;
    } else {
      throw new UIMARuntimeException(e);
    }
  }  
  contentHandler.endDocument();
}
 
Example 3
Source File: XmlWriterTest.java    From iaf with Apache License 2.0 6 votes vote down vote up
private void sendEvents(ContentHandler handler) throws SAXException {
	String line;
	handler.startDocument();
	handler.startElement("","root","root", new AttributesImpl());
		AttributesImpl atts = new AttributesImpl();
		atts.addAttribute("", "name", "name", "string", "P & Q €");
		handler.startElement("","sub","sub", atts);
			line="abc&€";
			handler.characters(line.toCharArray(),0,line.length());
		handler.endElement("","sub","sub");
		handler.startElement("","sub","sub", new AttributesImpl());
			((LexicalHandler)handler).startCDATA();
			line="<a>a&amp;b€</a>";
			handler.characters(line.toCharArray(),0,line.length());
			((LexicalHandler)handler).endCDATA();
		handler.endElement("","sub","sub");
		line="this is comment";
		((LexicalHandler)handler).comment(line.toCharArray(),0,line.length());
	handler.endElement("","root","root");
	handler.endDocument();
}
 
Example 4
Source File: ForkContentHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void endDocument() throws SAXException {
   ContentHandler[] arr$ = this.handlers;
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      ContentHandler handler = arr$[i$];
      handler.endDocument();
   }

}
 
Example 5
Source File: JsonXmlReader.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(InputSource input) throws IOException, SAXException {
	ContentHandler ch=getContentHandler();
	ch.startDocument();
	ch.startPrefixMapping("", TARGETNAMESPACE);
	parse(null, Json.createParser(input.getCharacterStream()));
	ch.endPrefixMapping("");
	ch.endDocument();
}
 
Example 6
Source File: SAXEventBuffer.java    From citygml4j with Apache License 2.0 5 votes vote down vote up
public void send(ContentHandler handler, boolean release) throws SAXException {
	if (isEmpty())
		throw new IllegalStateException("buffer is empty.");

	eventBuffer = eventBuffer.rewindToHeadBuffer();
	stringBuffer = stringBuffer.rewindToHeadBuffer();
	charactersBuffer = charactersBuffer.rewindToHeadBuffer();
	tmpBuffer = new ArrayBuffer<String>(String.class);
	atts = new AttributesImpl();

	Byte currentEvent = null;
	while (eventBuffer.peek() != null) {
		currentEvent = nextEvent(release);

		if (currentEvent == START_ELEMENT)
			sendStartElement(handler, release);
		else if (currentEvent == END_ELEMENT)
			sendEndElement(handler);
		else if (currentEvent == CHARACTERS)
			sendCharacters(handler, release);
		else if (currentEvent == NAMESPACE_PREFIX_MAPPING)
			sendStartPrefixMapping(handler, release);
		else if (currentEvent == START_DOCUMENT)
			handler.startDocument();
		else if (currentEvent == END_DOCUMENT)
			handler.endDocument();
		else if (currentEvent == QUALIFIED_END_ELEMENT)
			sendQualifiedEndElement(handler, release);
	}

	// clean up
	eventBuffer.decrementPtr();
	stringBuffer.decrementPtr();
	charactersBuffer.decrementPtr();		

	if (release)
		reset();
}
 
Example 7
Source File: XmiCasSerializer.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
void serialize(CAS cas, ContentHandler contentHandler, XmiDocSerializer ser) throws SAXException {
  contentHandler.startDocument();
  try {
    ser.cds.serialize();
  } catch (Exception e) {
    throw (SAXException) e;
  }
  contentHandler.endDocument();
}
 
Example 8
Source File: OBRXMLWriter.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
public static void writeManifests(Iterable<ManifestAndLocation> manifestAndLocations,
        ContentHandler handler, boolean quiet) throws SAXException {
    int level = quiet ? Message.MSG_DEBUG : Message.MSG_WARN;
    handler.startDocument();
    AttributesImpl atts = new AttributesImpl();
    handler.startElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY, atts);
    int nbOk = 0;
    int nbRejected = 0;
    for (ManifestAndLocation manifestAndLocation : manifestAndLocations) {
        BundleInfo bundleInfo;
        try {
            bundleInfo = ManifestParser.parseManifest(manifestAndLocation.getManifest());
            bundleInfo
                    .addArtifact(new BundleArtifact(false, manifestAndLocation.getUri(), null));
            if (manifestAndLocation.getSourceURI() != null) {
                bundleInfo.addArtifact(new BundleArtifact(true, manifestAndLocation
                        .getSourceURI(), null));
            }
            nbOk++;
        } catch (ParseException e) {
            nbRejected++;
            IvyContext
                    .getContext()
                    .getMessageLogger()
                    .log("Rejected " + manifestAndLocation.getUri() + ": " + e.getMessage(),
                        level);
            continue;
        }
        saxBundleInfo(bundleInfo, handler);
    }
    handler.endElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY);
    handler.endDocument();
    Message.info(nbOk + " bundle" + (nbOk > 1 ? "s" : "") + " added, " + nbRejected + " bundle"
            + (nbRejected > 1 ? "s" : "") + " rejected.");
}
 
Example 9
Source File: CanonicalTopicMapWriter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
/**
 * PUBLIC: Exports the topic map to the given ContentHandler.
 */

public void export(TopicMapIF topicmap, ContentHandler dh)
  throws IOException, SAXException {

  dh.startDocument();

  AttributesImpl atts = new AttributesImpl();
  atts.addAttribute("", "", "xmlns", CDATA,
                    "http://www.topicmaps.org/cxtm/1.0/");
  dh.startElement("", "", "topicMap", atts);
  atts.clear();

  // topics
  ContextHolder context = createContext(topicmap);
  Iterator<TopicIF> it = context.topicsInOrder(topicmap.getTopics());
  while (it.hasNext()) 
    writeTopic(it.next(), dh, context);

  // associations
  Iterator<AssociationIF> ait = context.assocsInOrder(topicmap.getAssociations());
  while (ait.hasNext()) 
    writeAssociation(ait.next(), dh, context);
      
  dh.endElement("", "", "topicMap");
  dh.endDocument();
}
 
Example 10
Source File: XMLSerializerTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testXml10() throws Exception {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  XMLSerializer sax2xml = new XMLSerializer(baos, false);
  ContentHandler ch = sax2xml.getContentHandler();    
  ch.startDocument();
  ch.startElement("","foo","foo", new AttributesImpl());
  ch.endElement("", "foo", "foo");
  ch.endDocument();
  String xmlStr = new String(baos.toByteArray(), StandardCharsets.UTF_8);
  assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo/>", xmlStr);    
}
 
Example 11
Source File: XMLSerializerTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testXml11() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLSerializer sax2xml = new XMLSerializer(baos, false);
    sax2xml.setOutputProperty(OutputKeys.VERSION, "1.1");
    ContentHandler ch = sax2xml.getContentHandler();    
    ch.startDocument();
    ch.startElement("","foo","foo", new AttributesImpl());
    ch.endElement("", "foo", "foo");
    ch.endDocument();
    String xmlStr = new String(baos.toByteArray(), StandardCharsets.UTF_8);
//    if (xmlStr.contains("1.0")) {
    // useful to investigate issues when bad XML output is produced
    //   related to which Java implementation is being used
      TransformerFactory transformerFactory = XMLUtils.createTransformerFactory();
      Transformer t = transformerFactory.newTransformer();
      t.setOutputProperty(OutputKeys.VERSION, "1.1");
      
      System.out.println("Java version is " + 
                            System.getProperty("java.vendor") + " " +
                            System.getProperty("java.version") + " " +
                            System.getProperty("java.vm.name") + " " +
                            System.getProperty("java.vm.version") + 
                         "\n  javax.xml.transform.TransformerFactory: " +
                            System.getProperty("javax.xml.transform.TransformerFactory") + 
                         "\n  Transformer version: " +
                            t.getOutputProperty(OutputKeys.VERSION));
//    }
    assertEquals("<?xml version=\"1.1\" encoding=\"UTF-8\"?><foo/>", xmlStr);
  }
 
Example 12
Source File: ForkContentHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void endDocument() throws SAXException {
   ContentHandler[] arr$ = this.handlers;
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      ContentHandler handler = arr$[i$];
      handler.endDocument();
   }

}
 
Example 13
Source File: DOMContentHandlerDecoratorImpl.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void endDocument() throws SAXException {
    for (ContentHandler contentHandler : contentHandlerSet) {
        contentHandler.endDocument();
    }
}
 
Example 14
Source File: MetaDataObject_impl.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void toXML(XMLSerializer sax2xml) throws SAXException, IOException {
  ContentHandler contentHandler = sax2xml.getContentHandler();
  contentHandler.startDocument();
  toXML(contentHandler, true);  // no reason to create a new content handler
  contentHandler.endDocument();
}
 
Example 15
Source File: AnalysisEngine_implTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void manyDelegatesCommon() throws Exception {
  // Test that an aggregate can be copied preserving all comments and ordering of delegates
  XMLParser.ParsingOptions parsingOptions = new XMLParser.ParsingOptions(false);
  parsingOptions.preserveComments = true;
  XMLParser parser = UIMAFramework.getXMLParser();
  File inFile = JUnitExtension.getFile("TextAnalysisEngineImplTest/AggregateWithManyDelegates.xml");
  AnalysisEngineDescription desc = parser.parseAnalysisEngineDescription(new XMLInputSource(inFile), parsingOptions);

  // Write out descriptor
  File cloneFile = new File(inFile.getParentFile(), "CopyOfAggregateWithManyDelegates.xml");
  try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(cloneFile))) {
    XMLSerializer xmlSerializer = new XMLSerializer(false);
    xmlSerializer.setOutputStream(os);
    // set the amount to a value which will show up if used
    // indent should not be used because we're using a parser mode which preserves
    // comments and ignorable white space.
    // NOTE: Saxon appears to force the indent to be 3 - which is what the input file now uses.
    xmlSerializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    ContentHandler contentHandler = xmlSerializer.getContentHandler();
    contentHandler.startDocument();
    desc.toXML(contentHandler, true);
    contentHandler.endDocument();
  }
  
  String inXml = FileCompare.file2String(inFile);
  String cloneXml = FileCompare.file2String(cloneFile);
  XMLAssert.assertXMLEqual(inXml,  cloneXml);
  // When building from a source distribution the descriptor may not have
  // appropriate line-ends so compute the length as if always 1 byte.
  int diff = fileLength(cloneFile) - fileLength(inFile);
  // One platform inserts a blank line and a final newline, so don't insist on perfection
  // NOTE:  This fails with Saxon as it omits the xmlns attribute (why?) and omits the newlines between adjacent comments.
  // It also produces many differences in indentation if the input is not indented by 3
  assertTrue("File size changed by "+diff+" should be no more than 2", diff >= -2 && diff <= 2);

  // Initialize all delegates and check the initialization order (should be declaration order)
  TestAnnotator2.allContexts = "";
  UIMAFramework.produceAnalysisEngine(desc);
  assertEquals("D/C/B/A/F/E/", TestAnnotator2.allContexts);
  
  // Check that copying aggregate preserved the order of the delegates
  desc = parser.parseAnalysisEngineDescription(new XMLInputSource(cloneFile), parsingOptions);
  TestAnnotator2.allContexts = "";
  UIMAFramework.produceAnalysisEngine(desc);
  assertEquals("D/C/B/A/F/E/", TestAnnotator2.allContexts);
  cloneFile.delete();
}
 
Example 16
Source File: RelationMapping.java    From ontopia with Apache License 2.0 4 votes vote down vote up
protected void write(ContentHandler dh) throws SAXException {

    // initialize attributes
    AttributesImpl atts = new AttributesImpl();

    // <db2tm name="...">
    if (name != null) addAttribute(atts, "name", "CDATA", name);

    dh.startDocument();
    dh.startElement("", "", "db2tm", atts);
    atts.clear();

    // prefixes
    for (Prefix prefix : iprefixes.values()) {
      addAttribute(atts, "prefix", "CDATA", prefix.getId());

      switch (prefix.getType()) {
      case Prefix.TYPE_SUBJECT_IDENTIFIER:
        addAttribute(atts, "subject-identifier", "CDATA", prefix.getLocator());
        break;
      case Prefix.TYPE_ITEM_IDENTIFIER:
        addAttribute(atts, "item-identifier", "CDATA", prefix.getLocator());
        break;
      case Prefix.TYPE_SUBJECT_LOCATOR:
        addAttribute(atts, "subject-locator", "CDATA", prefix.getLocator());
        break;
      }
             
      dh.startElement("", "", "using", atts);
      atts.clear();
      dh.endElement("", "", "using");
    }

    // relations
    for (Relation rel : getRelations()) {
      // <relation>
      addAttribute(atts, "name", "CDATA", rel.getName());
      addAttribute(atts, "columns", "CDATA", rel.getColumns());
      dh.startElement("", "", "relation", atts);
      atts.clear();

      outputEntities(rel, dh);

      // </relation>
      dh.endElement("", "", "relation");
    }

    // </db2tm>
    dh.endElement("", "", "db2tm");
    dh.endDocument();
  }
 
Example 17
Source File: SAXEndDocument.java    From edireader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void saxCall(ContentHandler contentHandler) throws SAXException {
    contentHandler.endDocument();
}
 
Example 18
Source File: Processor.java    From tajo with Apache License 2.0 4 votes vote down vote up
public int process() throws TransformerException, IOException, SAXException {
    ZipInputStream zis = new ZipInputStream(input);
    final ZipOutputStream zos = new ZipOutputStream(output);
    final OutputStreamWriter osw = new OutputStreamWriter(zos);

    Thread.currentThread().setContextClassLoader(
            getClass().getClassLoader());

    TransformerFactory tf = TransformerFactory.newInstance();
    if (!tf.getFeature(SAXSource.FEATURE)
            || !tf.getFeature(SAXResult.FEATURE)) {
        return 0;
    }

    SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
    Templates templates = null;
    if (xslt != null) {
        templates = saxtf.newTemplates(xslt);
    }

    // configuring outHandlerFactory
    // ///////////////////////////////////////////////////////

    EntryElement entryElement = getEntryElement(zos);

    ContentHandler outDocHandler = null;
    switch (outRepresentation) {
    case BYTECODE:
        outDocHandler = new OutputSlicingHandler(
                new ASMContentHandlerFactory(zos), entryElement, false);
        break;

    case MULTI_XML:
        outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw,
                true), entryElement, true);
        break;

    case SINGLE_XML:
        ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
        zos.putNextEntry(outputEntry);
        outDocHandler = new SAXWriter(osw, false);
        break;

    }

    // configuring inputDocHandlerFactory
    // /////////////////////////////////////////////////
    ContentHandler inDocHandler;
    if (templates == null) {
        inDocHandler = outDocHandler;
    } else {
        inDocHandler = new InputSlicingHandler("class", outDocHandler,
                new TransformerHandlerFactory(saxtf, templates,
                        outDocHandler));
    }
    ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(
            inDocHandler);

    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.startDocument();
        inDocHandler.startElement("", "classes", "classes",
                new AttributesImpl());
    }

    int i = 0;
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        update(ze.getName(), n++);
        if (isClassEntry(ze)) {
            processEntry(zis, ze, inDocHandlerFactory);
        } else {
            OutputStream os = entryElement.openEntry(getName(ze));
            copyEntry(zis, os);
            entryElement.closeEntry();
        }

        i++;
    }

    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.endElement("", "classes", "classes");
        inDocHandler.endDocument();
    }

    if (outRepresentation == SINGLE_XML) {
        zos.closeEntry();
    }
    zos.flush();
    zos.close();

    return i;
}
 
Example 19
Source File: AdditionalObjectsHandler.java    From web-feature-service with Apache License 2.0 4 votes vote down vote up
protected void writeObjects() {
    if (!shouldRun)
        return;

    try {
        // close writers to flush buffers
        for (CityModelWriter tempWriter : tempWriters.values())
            tempWriter.close();

        CityGMLInputFactory in = cityGMLBuilder.createCityGMLInputFactory();
        in.setProperty(CityGMLInputFactory.FEATURE_READ_MODE, FeatureReadMode.SPLIT_PER_COLLECTION_MEMBER);

        startAdditionalObjects();

        Attributes dummyAttributes = new AttributesImpl();
        String propertyName = "member";
        String propertyQName = saxWriter.getPrefix(Constants.WFS_NAMESPACE_URI) + ":" + propertyName;

        // iterate over temp files and send additional objects to response stream
        for (Path tempFile : tempFiles.values()) {
            try (CityGMLReader tempReader = in.createCityGMLReader(tempFile.toFile())) {
                while (tempReader.hasNext()) {
                    XMLChunk chunk = tempReader.nextChunk();
                    if ("CityModel".equals(chunk.getTypeName().getLocalPart())
                            && Modules.isCityGMLModuleNamespace(chunk.getTypeName().getNamespaceURI()))
                        continue;

                    ContentHandler handler;
                    if (transformerChainFactory == null)
                        handler = saxWriter;
                    else {
                        TransformerChain chain = transformerChainFactory.buildChain();
                        chain.tail().setResult(new SAXResult(saxWriter));
                        handler = chain.head();
                        handler.startDocument();
                    }

                    handler.startElement(Constants.WFS_NAMESPACE_URI, propertyName, propertyQName, dummyAttributes);
                    chunk.send(handler, true);
                    handler.endElement(Constants.WFS_NAMESPACE_URI, propertyName, propertyQName);

                    if (transformerChainFactory != null)
                        handler.endDocument();
                }
            }
        }

    } catch (CityGMLWriteException | CityGMLBuilderException | CityGMLReadException | SAXException | TransformerConfigurationException e) {
        eventDispatcher.triggerSyncEvent(new InterruptEvent("Failed to write additional objects.", LogLevel.ERROR, e, eventChannel, this));
    }
}
 
Example 20
Source File: XCASSerializer.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Write the CAS data to a SAX content handler.
 * 
 * @param cas
 *          The CAS to be serialized.
 * @param contentHandler
 *          The SAX content handler the data is written to.
 * @param encodeDoc
 *          If set to false, no uima.tcas.Document structure will be created, and the document
 *          text will not be serialized.
 * @param outOfTypeSystemData
 *          data not part of the CAS type system, which should be inserted into the XCAS output
 * 
 * @throws IOException passed thru
 * @throws SAXException passed thru
 */
public void serialize(CAS cas, ContentHandler contentHandler, boolean encodeDoc,
        OutOfTypeSystemData outOfTypeSystemData) throws IOException, SAXException {
  contentHandler.startDocument();
  XCASDocSerializer ser = new XCASDocSerializer(contentHandler, ((CASImpl) cas).getBaseCAS());
  ser.serialize(encodeDoc, outOfTypeSystemData);
  contentHandler.endDocument();
  // System.out.println("Done serializing " + ser.fsCount + " FSs.");
}