Java Code Examples for javax.xml.stream.XMLStreamException

The following examples show how to use javax.xml.stream.XMLStreamException. These examples are extracted from open source projects. 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 Project: netcdf-java   Source File: Bufr2Xml.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Bufr2Xml(Message message, NetcdfFile ncfile, OutputStream os, boolean skipMissing) throws IOException {
  indent = new Indent(2);
  indent.setIndentLevel(0);

  try {
    XMLOutputFactory fac = XMLOutputFactory.newInstance();
    staxWriter = fac.createXMLStreamWriter(os, CDM.UTF8);

    staxWriter.writeStartDocument(CDM.UTF8, "1.0");
    // staxWriter.writeCharacters("\n");
    // staxWriter.writeStartElement("bufrMessage");

    writeMessage(message, ncfile);

    staxWriter.writeCharacters("\n");
    staxWriter.writeEndDocument();
    staxWriter.flush();

  } catch (XMLStreamException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example 2
public void writeCharacters(char[] text, int start, int len)
    throws XMLStreamException
{
     try {
        if (len <= 0) {
            return;
        }

        if (getIgnoreWhiteSpaceTextContent() &&
                isWhiteSpace(text, start, len)) return;

        encodeTerminationAndCurrentElement(true);

        encodeCharacters(text, start, len);
    }
    catch (IOException e) {
        throw new XMLStreamException(e);
    }
}
 
Example 3
void loadSheets(XSSFReader reader, SharedStringsTable sst, StylesTable stylesTable, int rowCacheSize)
        throws IOException, InvalidFormatException, XMLStreamException {
  lookupSheetNames(reader);

  //Some workbooks have multiple references to the same sheet. Need to filter
  //them out before creating the XMLEventReader by keeping track of their URIs.
  //The sheets are listed in order, so we must keep track of insertion order.
  SheetIterator iter = (SheetIterator) reader.getSheetsData();
  Map<URI, InputStream> sheetStreams = new LinkedHashMap<>();
  while(iter.hasNext()) {
    InputStream is = iter.next();
    sheetStreams.put(iter.getSheetPart().getPartName().getURI(), is);
  }

  //Iterate over the loaded streams
  int i = 0;
  for(URI uri : sheetStreams.keySet()) {
    XMLEventReader parser = StaxHelper.newXMLInputFactory().createXMLEventReader(sheetStreams.get(uri));
    sheets.add(new StreamingSheet(sheetProperties.get(i++).get("name"), new StreamingSheetReader(sst, stylesTable, parser, use1904Dates, rowCacheSize)));
  }
}
 
Example 4
public void writeBoundedQueueThreadPool(final XMLExtendedStreamWriter writer, final Property property, final String elementName,
                                        final boolean includeName, final boolean blocking)
        throws XMLStreamException {
    writer.writeStartElement(elementName);
    ModelNode node = property.getValue();
    if (includeName) {
        writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
    }
    PoolAttributeDefinitions.ALLOW_CORE_TIMEOUT.marshallAsAttribute(node, writer);
    writeCountElement(PoolAttributeDefinitions.CORE_THREADS, node, writer);
    writeCountElement(PoolAttributeDefinitions.QUEUE_LENGTH, node, writer);
    writeCountElement(PoolAttributeDefinitions.MAX_THREADS, node, writer);

    writeTime(writer, node, Element.KEEPALIVE_TIME);
    writeRef(writer, node, Element.THREAD_FACTORY, THREAD_FACTORY);
    if (!blocking) {
        writeRef(writer, node, Element.HANDOFF_EXECUTOR, HANDOFF_EXECUTOR);
    }
    writer.writeEndElement();
}
 
Example 5
Source Project: woodstox   Source File: RepairingNsStreamWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeStartElement(StartElement elem)
    throws XMLStreamException
{
    // In repairing mode this is simple: let's just pass info
    // we have, and things should work... a-may-zing!
    QName name = elem.getName();
    writeStartElement(name.getPrefix(), name.getLocalPart(),
                      name.getNamespaceURI());
    Iterator<Attribute> it = elem.getAttributes();
    while (it.hasNext()) {
        Attribute attr = it.next();
        name = attr.getName();
        writeAttribute(name.getPrefix(), name.getNamespaceURI(),
                       name.getLocalPart(), attr.getValue());
    }
}
 
Example 6
public void writeNamespace(String prefix, String namespaceURI)
    throws XMLStreamException
{
    if (prefix == null || prefix.length() == 0 || prefix.equals(EncodingConstants.XMLNS_NAMESPACE_PREFIX)) {
        writeDefaultNamespace(namespaceURI);
    }
    else {
        if (!_inStartElement) {
            throw new IllegalStateException(CommonResourceBundle.getInstance().getString("message.attributeWritingNotAllowed"));
        }

        if (_namespacesArrayIndex == _namespacesArray.length) {
            final String[] namespacesArray = new String[_namespacesArrayIndex * 2];
            System.arraycopy(_namespacesArray, 0, namespacesArray, 0, _namespacesArrayIndex);
            _namespacesArray = namespacesArray;
        }

        _namespacesArray[_namespacesArrayIndex++] = prefix;
        _namespacesArray[_namespacesArrayIndex++] = namespaceURI;
        setPrefix(prefix, namespaceURI);
    }
}
 
Example 7
private GXMacDirectTable[] loadDirectTable(GXXmlReader reader)
        throws XMLStreamException {
    List<GXMacDirectTable> list = new ArrayList<GXMacDirectTable>();
    if (reader.isStartElement("DirectTable", true)) {
        while (reader.isStartElement("Item", true)) {
            GXMacDirectTable it = new GXMacDirectTable();
            list.add(it);
            it.setSourceSId(
                    (short) reader.readElementContentAsInt("SourceSId"));
            it.setSourceLnId(
                    (short) reader.readElementContentAsInt("SourceLnId"));
            it.setSourceLcId(
                    (short) reader.readElementContentAsInt("SourceLcId"));
            it.setDestinationSId((short) reader
                    .readElementContentAsInt("DestinationSId"));
            it.setDestinationLnId((short) reader
                    .readElementContentAsInt("DestinationLnId"));
            it.setDestinationLcId((short) reader
                    .readElementContentAsInt("DestinationLcId"));
            it.setDid(GXCommon
                    .hexToBytes(reader.readElementContentAsString("Did")));
        }
        reader.readEndElement("DirectTable");
    }
    return list.toArray(new GXMacDirectTable[list.size()]);
}
 
Example 8
/**
 * Rewind to the start so we can run through again.
 *
 * @throws XMLStreamException when things go wrong.
 */
public void rewind()
    throws XMLStreamException
{
    backing = factory.createXMLEventReader( new StringReader( pom.toString() ) );
    nextEnd = 0;
    nextDelta = 0;
    for ( int i = 0; i < MAX_MARKS; i++ )
    {
        markStart[i] = -1;
        markEnd[i] = -1;
        markDelta[i] = 0;
    }
    lastStart = -1;
    lastEnd = -1;
    lastDelta = 0;
    next = null;
}
 
Example 9
Source Project: sis   Source File: PooledUnmarshaller.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delegates the unmarshalling to the wrapped unmarshaller.
 */
@Override
public <T> JAXBElement<T> unmarshal(final Node input, final Class<T> declaredType) throws JAXBException {
    final TransformVersion version = getTransformVersion();
    if (version != null) try {
        return unmarshal(InputFactory.createXMLEventReader(input), version, declaredType);
    } catch (XMLStreamException e) {
        throw new JAXBException(e);
    } else {
        final Context context = begin();
        try {
            return unmarshaller.unmarshal(input, declaredType);
        } finally {
            context.finish();
        }
    }
}
 
Example 10
@Override
public void doRecycle(XMLStreamWriter r) {
    if (r instanceof HasEncodingWriter) {
        r = ((HasEncodingWriter)r).getWriter();
    }
    if(zephyrClass.isInstance(r)) {
        // this flushes the underlying stream, so it might cause chunking issue
        try {
            r.close();
        } catch (XMLStreamException e) {
            throw new WebServiceException(e);
        }
        pool.set(r);
    }
    if(r instanceof RecycleAware)
        ((RecycleAware)r).onRecycled();
}
 
Example 11
Source Project: keycloak   Source File: KeycloakSubsystemParser.java    License: Apache License 2.0 6 votes vote down vote up
private void readSpi(final List<ModelNode> list, final XMLExtendedStreamReader reader) throws XMLStreamException {
    String spiName = ParseUtils.requireAttributes(reader, "name")[0];
    ModelNode addSpi = new ModelNode();
    addSpi.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
    PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, KeycloakExtension.SUBSYSTEM_NAME),
                                               PathElement.pathElement(SpiResourceDefinition.TAG_NAME, spiName));
    addSpi.get(ModelDescriptionConstants.OP_ADDR).set(addr.toModelNode());
    list.add(addSpi);
    
    while (reader.hasNext() && nextTag(reader) != END_ELEMENT) {
        if (reader.getLocalName().equals(DEFAULT_PROVIDER.getXmlName())) {
            DEFAULT_PROVIDER.parseAndSetParameter(reader.getElementText(), addSpi, reader);
        } else if (reader.getLocalName().equals(ProviderResourceDefinition.TAG_NAME)) {
            readProvider(list, spiName, reader);
        }
    }
}
 
Example 12
Source Project: softwarecave   Source File: BooksReader.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<String> readAuthors(XMLStreamReader reader) throws XMLStreamException {
    List<String> authors = new ArrayList<>();
    while (reader.hasNext()) {
        int eventType = reader.next();
        switch (eventType) {
            case XMLStreamReader.START_ELEMENT:
                String elementName = reader.getLocalName();
                if (elementName.equals("author"))
                    authors.add(readCharacters(reader));
                break;
            case XMLStreamReader.END_ELEMENT:
                return authors;
        }
    }
    throw new XMLStreamException("Premature end of file");

}
 
Example 13
Source Project: mpxj   Source File: MapFileGenerator.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Add classes to the map file.
 *
 * @param writer XML stream writer
 * @param jarFile jar file
 * @param mapClassMethods true if we want to produce .Net style class method names
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws XMLStreamException
 * @throws IntrospectionException
 */
private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException
{
   ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();

   URLClassLoader loader = new URLClassLoader(new URL[]
   {
      jarFile.toURI().toURL()
   }, currentThreadClassLoader);

   JarFile jar = new JarFile(jarFile);
   Enumeration<JarEntry> enumeration = jar.entries();
   while (enumeration.hasMoreElements())
   {
      JarEntry jarEntry = enumeration.nextElement();
      if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(".class"))
      {
         addClass(loader, jarEntry, writer, mapClassMethods);
      }
   }
   jar.close();
}
 
Example 14
/**
 * Is not supported in this version of the implementation.
 * @param uri {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void setDefaultNamespace(String uri) throws XMLStreamException {
    namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri);
    if(!needContextPop[depth]){
        needContextPop[depth] = true;
    }
}
 
Example 15
private void parseHostExcludes(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
    requireNoAttributes(reader);
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
        requireNamespace(reader, namespace);
        final Element element = Element.forName(reader.getLocalName());
        switch (element) {
            case HOST_EXCLUDE:
                parseHostExclude(reader, list);
                break;
            default: {
                throw unexpectedElement(reader);
            }
        }
    }
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: SAXOutput.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void text(Pcdata value, boolean needsSP) throws IOException, SAXException, XMLStreamException {
    int vlen = value.length();
    if(buf.length<=vlen) {
        buf = new char[Math.max(buf.length*2,vlen+1)];
    }
    if(needsSP) {
        value.writeTo(buf,1);
        buf[0] = ' ';
    } else {
        value.writeTo(buf,0);
    }
    out.characters(buf,0,vlen+(needsSP?1:0));
}
 
Example 17
private static void parseModuleExclusion(final XMLStreamReader reader, final ModuleStructureSpec specBuilder) throws XMLStreamException {
    String name = null;
    String slot = "main";
    final Set<Attribute> required = EnumSet.of(Attribute.NAME);
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        final Attribute attribute = Attribute.of(reader.getAttributeName(i));
        required.remove(attribute);
        switch (attribute) {
            case NAME:
                name = reader.getAttributeValue(i);
                break;
            case SLOT:
                slot = reader.getAttributeValue(i);
                break;
            default:
                throw unexpectedContent(reader);
        }
    }
    if (!required.isEmpty()) {
        throw missingAttributes(reader.getLocation(), required);
    }
    specBuilder.getExclusions().add(ModuleIdentifier.create(name, slot));
    if (reader.hasNext()) {
        switch (reader.nextTag()) {
            case XMLStreamConstants.END_ELEMENT:
                return;
            default:
                throw unexpectedContent(reader);
        }
    }
}
 
Example 18
/**
 * creates a DOM Element and appends it to the current element in the tree.
 * @param localName {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeEmptyElement(String localName) throws XMLStreamException {
    if(ownerDoc != null){
        Element element = ownerDoc.createElement(localName);
        if(currentNode!=null){
            currentNode.appendChild(element);
        }else{
            ownerDoc.appendChild(element);
        }
    }

}
 
Example 19
Source Project: freecol   Source File: Monarch.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void writeChildren(FreeColXMLWriter xw) throws XMLStreamException {
    super.writeChildren(xw);

    if (xw.validFor(this.player)) {

        getExpeditionaryForce().toXML(xw, EXPEDITIONARY_FORCE_TAG);

        getInterventionForce().toXML(xw, INTERVENTION_FORCE_TAG);
    }
}
 
Example 20
Source Project: hottub   Source File: WSEndpointReference.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates from the spec version of {@link EndpointReference}.
 *
 * <p>
 * This method performs the data conversion, so it's slow.
 * Do not use this method in a performance critical path.
 */
public WSEndpointReference(EndpointReference epr, AddressingVersion version) {
    try {
        MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();
        epr.writeTo(new XMLStreamBufferResult(xsb));
        this.infoset = xsb;
        this.version = version;
        this.rootElement = new QName("EndpointReference", version.nsUri);
        parse();
    } catch (XMLStreamException e) {
        throw new WebServiceException(ClientMessages.FAILED_TO_PARSE_EPR(epr),e);
    }
}
 
Example 21
Source Project: keycloak   Source File: KeycloakSubsystemParser.java    License: Apache License 2.0 5 votes vote down vote up
private void writeList(XMLExtendedStreamWriter writer, ModelNode context, AttributeDefinition def, String elementName) throws XMLStreamException {
    if (!context.get(def.getName()).isDefined()) {
        return;
    }

    writer.writeStartElement(def.getXmlName());
    ModelNode modules = context.get(def.getName());
    for (ModelNode module : modules.asList()) {
        writer.writeStartElement(elementName);
        writer.writeCharacters(module.asString());
        writer.writeEndElement();
    }
    writer.writeEndElement();
}
 
Example 22
Source Project: pentaho-kettle   Source File: XMLOutputTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSpecialSymbolsInAttributeValuesAreEscaped() throws KettleException, XMLStreamException {
  xmlOutput.init( xmlOutputMeta, xmlOutputData );

  xmlOutputData.writer = mock( XMLStreamWriter.class );
  xmlOutput.writeRowAttributes( rowWithData );
  xmlOutput.dispose( xmlOutputMeta, xmlOutputData );
  verify( xmlOutputData.writer, times( rowWithData.length ) ).writeAttribute( any(), any() );
  verify( xmlOutput, atLeastOnce() ).closeOutputStream( any() );
}
 
Example 23
Source Project: staedi   Source File: StaEDIXMLStreamWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testSetNamespaceContext_AfterDocumentStart() throws XMLStreamException {
    NamespaceContext ctx = Mockito.mock(NamespaceContext.class);
    Mockito.when(ctx.getNamespaceURI(NS_PFX_TEST)).thenReturn(NS_URI_TEST);
    Mockito.when(ctx.getPrefix(NS_URI_TEST)).thenReturn(NS_PFX_TEST);
    it.writeStartDocument();
    it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS);
    Throwable thrown = assertThrows(XMLStreamException.class, () -> it.setNamespaceContext(ctx));
    assertEquals("NamespaceContext must only be called at the start of the document", thrown.getMessage());
}
 
Example 24
Source Project: micro-integrator   Source File: ManagementApiParser.java    License: Apache License 2.0 5 votes vote down vote up
private static OMElement getInternalApisElement() throws IOException, CarbonException, XMLStreamException {
    File mgtApiUserConfig = getConfigurationFile();
    try (InputStream fileInputStream = new FileInputStream(mgtApiUserConfig)) {
        OMElement documentElement = getOMElementFromFile(fileInputStream);
        createSecretResolver(documentElement);
        return documentElement;
    }
}
 
Example 25
Source Project: woodstox   Source File: DTDNmTokenAttr.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method called by the validator
 * to ask attribute to verify that the default it has (if any) is
 * valid for such type.
 */
@Override
public void validateDefault(InputProblemReporter rep, boolean normalize)
    throws XMLStreamException
{
    String def = validateDefaultNmToken(rep, normalize);
    if (normalize) {
        mDefValue.setValue(def);
    }
}
 
Example 26
Source Project: woodstox   Source File: ValidatingStreamReader.java    License: Apache License 2.0 5 votes vote down vote up
private ValidatingStreamReader(InputBootstrapper bs,
                               BranchingReaderSource input, ReaderCreator owner,
                               ReaderConfig cfg, InputElementStack elemStack,
                               boolean forER)
    throws XMLStreamException
{
    super(bs, input, owner, cfg, elemStack, forER);
}
 
Example 27
Source Project: ews-java-api   Source File: GetInboxRulesRequest.java    License: MIT License 5 votes vote down vote up
/**
 * Writes XML elements.
 *
 * @param writer The writer.
 * @throws XMLStreamException the XML stream exception
 * @throws ServiceXmlSerializationException
 */
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
    throws ServiceXmlSerializationException, XMLStreamException {
  if (!(this.mailboxSmtpAddress == null ||
      this.mailboxSmtpAddress.isEmpty())) {
    writer.writeElementValue(
        XmlNamespace.Messages,
        XmlElementNames.MailboxSmtpAddress,
        this.mailboxSmtpAddress);
  }
}
 
Example 28
javax.xml.stream.XMLStreamWriter createXMLStreamWriter(javax.xml.transform.stream.StreamResult sr, String encoding) throws javax.xml.stream.XMLStreamException {
    //if factory is configured to reuse the instance & this instance can be reused
    //& the setProperty() hasn't been called
    try{
        if(fReuseInstance && fStreamWriter != null && fStreamWriter.canReuse() && !fPropertyChanged){
            fStreamWriter.reset();
            fStreamWriter.setOutput(sr, encoding);
            if(DEBUG)System.out.println("reusing instance, object id : " + fStreamWriter);
            return fStreamWriter;
        }
        return fStreamWriter = new XMLStreamWriterImpl(sr, encoding, new PropertyManager(fPropertyManager));
    }catch(java.io.IOException io){
        throw new XMLStreamException(io);
    }
}
 
Example 29
@Override
public void writeCharacters(char[] data, int start, int len)
    throws XMLStreamException {
    try {
        if (fStartTagOpened) {
            closeStartTag();
        }

        writeXMLContent(data, start, len, fEscapeCharacters);
    } catch (IOException e) {
        throw new XMLStreamException(e);
    }
}
 
Example 30
@Override
public void writeFooter() throws XMLStreamException {
  staxWriter.writeCharacters("\n");
  staxWriter.writeEndElement();
  staxWriter.writeCharacters("\n");
  staxWriter.writeEndDocument();

  staxWriter.close(); // This should flush the writer. The underlying output stream remains open.
}