下面列出了怎么用javax.xml.stream.XMLStreamException的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
}
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);
}
}
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)));
}
}
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();
}
@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());
}
}
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);
}
}
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()]);
}
/**
* 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;
}
/**
* 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();
}
}
}
@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();
}
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);
}
}
}
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");
}
/**
* 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();
}
/**
* 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;
}
}
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);
}
}
}
}
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));
}
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);
}
}
}
/**
* 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);
}
}
}
/**
* {@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);
}
}
/**
* 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);
}
}
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();
}
@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() );
}
@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());
}
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;
}
}
/**
* 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);
}
}
private ValidatingStreamReader(InputBootstrapper bs,
BranchingReaderSource input, ReaderCreator owner,
ReaderConfig cfg, InputElementStack elemStack,
boolean forER)
throws XMLStreamException
{
super(bs, input, owner, cfg, elemStack, forER);
}
/**
* 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);
}
}
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);
}
}
@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);
}
}
@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.
}