Java Code Examples for javax.xml.stream.XMLStreamReader#getText()

The following examples show how to use javax.xml.stream.XMLStreamReader#getText() . 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: OverloadSecurityIndex.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
public static OverloadSecurityIndex fromXml(String contingencyId, XMLStreamReader xmlsr) throws XMLStreamException {
    String text = null;
    while (xmlsr.hasNext()) {
        int eventType = xmlsr.next();
        switch (eventType) {
            case XMLEvent.CHARACTERS:
                text = xmlsr.getText();
                break;
            case XMLEvent.END_ELEMENT:
                if ("fx".equals(xmlsr.getLocalName())) {
                    return new OverloadSecurityIndex(contingencyId, Double.parseDouble(text));
                }
                break;
            default:
                break;
        }
    }
    throw new AssertionError("fx element not found");
}
 
Example 2
Source File: XmlReaderInstanceEventImpl.java    From SODS with Apache License 2.0 6 votes vote down vote up
XmlReaderInstanceEventImpl(XMLStreamReader reader, String tag)
{
    this.reader = reader;
    this.tag = tag;

    if (reader.isStartElement())
        for (int i = 0; i < reader.getAttributeCount(); i++) {
            String name = qNameToString(reader.getAttributeName(i));
            String value = reader.getAttributeValue(i);
            atributes.put(name, value);
        }
    else if (reader.isCharacters()) {
        characters = reader.getText();
        end = true;
    }
}
 
Example 3
Source File: ExchangeDavRequest.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected String getTagContent(XMLStreamReader reader) throws XMLStreamException {
    String value = null;
    String tagLocalName = reader.getLocalName();
    while (reader.hasNext() &&
            !((reader.getEventType() == XMLStreamConstants.END_ELEMENT) && tagLocalName.equals(reader.getLocalName()))) {
        reader.next();
        if (reader.getEventType() == XMLStreamConstants.CHARACTERS) {
            value = reader.getText();
        }
    }
    // empty tag
    if (!reader.hasNext()) {
        throw new XMLStreamException("End element for " + tagLocalName + " not found");
    }
    return value;
}
 
Example 4
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 6 votes vote down vote up
@Test
void testGetTextString() throws Exception {
    XMLStreamReader xmlReader = getXmlReader(DUMMY_X12);

    assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType());
    assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next());
    assertEquals("INTERCHANGE", xmlReader.getLocalName());

    assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next());
    assertEquals("ISA", xmlReader.getLocalName());
    assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA01;
    assertEquals(XMLStreamConstants.CHARACTERS, xmlReader.next()); // ISA01 content;
    assertNull(xmlReader.getNamespaceURI());
    assertThrows(IllegalStateException.class, () -> xmlReader.getName());

    String textString = xmlReader.getText();
    assertEquals("00", textString);
    char[] textArray = xmlReader.getTextCharacters();
    assertArrayEquals(new char[] { '0', '0' }, textArray);
    char[] textArray2 = xmlReader.getTextCharacters(); // 2nd call should be the same characters
    assertArrayEquals(textArray, textArray2);
    char[] textArrayLocal = new char[3];
    xmlReader.getTextCharacters(xmlReader.getTextStart(), textArrayLocal, 0, xmlReader.getTextLength());
    assertArrayEquals(new char[] { '0', '0', '\0' }, textArrayLocal);
}
 
Example 5
Source File: BasicJavaClientREST.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
/**
 * Convert XMLStreamReader To String
 * 
 * @param XMLStreamReader
 * @return String
 * @throws XMLStreamException
 *           , TransformerException, IOException,
 *           ParserConfigurationException, SAXException
 */
public String convertXMLStreamReaderToString(XMLStreamReader reader) throws XMLStreamException, TransformerException, IOException, ParserConfigurationException, SAXException {
  String str = null;
  while (reader.hasNext())
  {
    reader.next();
    int a = reader.getEventType();
    if (reader.hasText())
      if (reader.getText() != "null")
        str = str + reader.getText().trim();
  }
  return str;
}
 
Example 6
Source File: CatalogTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "supportXMLResolver")
public void supportXMLResolver(URI catalogFile, String xml, String expected) throws Exception {
    String xmlSource = getClass().getResource(xml).getFile();

    CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);

    XMLInputFactory xifactory = XMLInputFactory.newInstance();
    xifactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    xifactory.setProperty(XMLInputFactory.RESOLVER, cr);
    File file = new File(xmlSource);
    String systemId = file.toURI().toASCIIString();
    InputStream entityxml = new FileInputStream(file);
    XMLStreamReader streamReader = xifactory.createXMLStreamReader(systemId, entityxml);
    String result = null;
    while (streamReader.hasNext()) {
        int eventType = streamReader.next();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            eventType = streamReader.next();
            if (eventType == XMLStreamConstants.CHARACTERS) {
                result = streamReader.getText();
            }
        }
    }
    System.out.println(": expected [" + expected + "] <> actual [" + result.trim() + "]");

    Assert.assertEquals(result.trim(), expected);
}
 
Example 7
Source File: BaseStAXUT.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected static String tokenTypeDesc(int tt, XMLStreamReader sr) {
    String desc = tokenTypeDesc(tt);
    // Let's show first 8 chars or so...
    if (tt == CHARACTERS || tt == SPACE || tt == CDATA) {
        String str = sr.getText();
        if (str.length() > MAX_DESC_TEXT_CHARS) {
            desc = "\"" + str.substring(0, MAX_DESC_TEXT_CHARS) + "\"[...]";
        } else {
            desc = "\"" + desc + "\"";
        }
        desc = " (" + desc + ")";
    }
    return desc;
}
 
Example 8
Source File: XMLStreamReaderUtil.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read spaces from the reader as long as to the next element, starting from
 * current position. Comments are ignored.
 * @param reader
 * @return
 */
public static String currentWhiteSpaceContent(XMLStreamReader reader) {

    // since the there might be several valid chunks (spaces/comment/spaces)
    // StringBuilder must be used; it's initialized lazily, only when needed
    StringBuilder whiteSpaces = null;

    for (;;) {
        switch (reader.getEventType()) {
            case START_ELEMENT:
            case END_ELEMENT:
            case END_DOCUMENT:
                return whiteSpaces == null ? null : whiteSpaces.toString();
            case CHARACTERS:
                if (reader.isWhiteSpace()) {
                    if (whiteSpaces == null) {
                        whiteSpaces = new StringBuilder();
                    }
                    whiteSpaces.append(reader.getText());
                } else {
                    throw new XMLStreamReaderException(
                            "xmlreader.unexpectedCharacterContent", reader.getText());
                }
        }
        next(reader);
    }
}
 
Example 9
Source File: XMLStreamReaderUtil.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static int nextElementContent(XMLStreamReader reader) {
    int state = nextContent(reader);
    if (state == CHARACTERS) {
        throw new XMLStreamReaderException(
            "xmlreader.unexpectedCharacterContent", reader.getText());
    }
    return state;
}
 
Example 10
Source File: XMLStreamReaderUtil.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static int nextElementContent(XMLStreamReader reader) {
    int state = nextContent(reader);
    if (state == CHARACTERS) {
        throw new XMLStreamReaderException(
            "xmlreader.unexpectedCharacterContent", reader.getText());
    }
    return state;
}
 
Example 11
Source File: MusicPlayer.java    From MusicPlayer with MIT License 5 votes vote down vote up
private static int xmlMusicDirFileNumFinder() {
    try {
        // Creates reader for xml file.
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isCoalescing", true);
        FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
        XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");

        String element = null;
        String fileNum = null;

        // Loops through xml file looking for the music directory file path.
        while(reader.hasNext()) {
            reader.next();
            if (reader.isWhiteSpace()) {
                continue;
            } else if (reader.isStartElement()) {
                element = reader.getName().getLocalPart();
            } else if (reader.isCharacters() && element.equals("fileNum")) {
                fileNum = reader.getText();
                break;
            }
        }
        // Closes xml reader.
        reader.close();

        // Converts the file number to an int and returns the value.
        return Integer.parseInt(fileNum);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}
 
Example 12
Source File: XMLStreamReaderUtil.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read spaces from the reader as long as to the next element, starting from
 * current position. Comments are ignored.
 * @param reader
 * @return
 */
public static String currentWhiteSpaceContent(XMLStreamReader reader) {

    // since the there might be several valid chunks (spaces/comment/spaces)
    // StringBuilder must be used; it's initialized lazily, only when needed
    StringBuilder whiteSpaces = null;

    for (;;) {
        switch (reader.getEventType()) {
            case START_ELEMENT:
            case END_ELEMENT:
            case END_DOCUMENT:
                return whiteSpaces == null ? null : whiteSpaces.toString();
            case CHARACTERS:
                if (reader.isWhiteSpace()) {
                    if (whiteSpaces == null) {
                        whiteSpaces = new StringBuilder();
                    }
                    whiteSpaces.append(reader.getText());
                } else {
                    throw new XMLStreamReaderException(
                            "xmlreader.unexpectedCharacterContent", reader.getText());
                }
        }
        next(reader);
    }
}
 
Example 13
Source File: StAXEncoder.java    From exificient with MIT License 4 votes vote down vote up
public void encode(XMLStreamReader xmlStream) throws XMLStreamException,
		EXIException, IOException {

	// StartDocument should be initial state
	assert (xmlStream.getEventType() == XMLStreamConstants.START_DOCUMENT);

	writeStartDocument();

	while (xmlStream.hasNext()) {
		int event = xmlStream.next();
		switch (event) {
		case XMLStreamConstants.START_DOCUMENT:
			// should have happened beforehand
			throw new EXIException("Unexpected START_DOCUMENT event");
		case XMLStreamConstants.END_DOCUMENT:
			this.writeEndDocument();
			break;
		case XMLStreamConstants.START_ELEMENT:
			QName qn = xmlStream.getName();
			String pfx = qn.getPrefix();
			writeStartElement(pfx, qn.getLocalPart(), qn.getNamespaceURI());
			// parse NS declarations
			int nsCnt = xmlStream.getNamespaceCount();
			for (int i = 0; i < nsCnt; i++) {
				String nsPfx = xmlStream.getNamespacePrefix(i);
				nsPfx = nsPfx == null ? Constants.XML_DEFAULT_NS_PREFIX
						: nsPfx;
				String nsUri = xmlStream.getNamespaceURI(i);
				this.writeNamespace(nsPfx, nsUri);
			}
			// parse attributes
			int atCnt = xmlStream.getAttributeCount();
			for (int i = 0; i < atCnt; i++) {
				QName atQname = xmlStream.getAttributeName(i);
				this.writeAttribute(atQname.getPrefix(),
						atQname.getNamespaceURI(), atQname.getLocalPart(),
						xmlStream.getAttributeValue(i));
			}

			break;
		case XMLStreamConstants.END_ELEMENT:
			writeEndElement();
			break;
		case XMLStreamConstants.NAMESPACE:
			break;
		case XMLStreamConstants.CHARACTERS:
			this.writeCharacters(xmlStream.getTextCharacters(),
					xmlStream.getTextStart(), xmlStream.getTextLength());
			break;
		case XMLStreamConstants.SPACE:
			// @SuppressWarnings("unused")
			String ignorableSpace = xmlStream.getText();
			writeCharacters(ignorableSpace);
			break;
		case XMLStreamConstants.ATTRIBUTE:
			// @SuppressWarnings("unused")
			// int attsX = xmlStream.getAttributeCount();
			break;
		case XMLStreamConstants.PROCESSING_INSTRUCTION:
			this.writeProcessingInstruction(xmlStream.getPITarget(),
					xmlStream.getPIData());
			break;
		case XMLStreamConstants.COMMENT:
			this.writeComment(xmlStream.getText());
			break;
		case XMLStreamConstants.DTD:
			// TODO DTD
			break;
		case XMLStreamConstants.ENTITY_REFERENCE:
			// TODO ER
			break;
		default:
			System.out.println("Event '" + event + "' not supported!");
		}
	}

	// this.flush();
}
 
Example 14
Source File: Library.java    From MusicPlayer with MIT License 4 votes vote down vote up
public static ObservableList<Playlist> getPlaylists() {
    if (playlists == null) {

        playlists = new ArrayList<>();
        int id = 0;

        try {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            factory.setProperty("javax.xml.stream.isCoalescing", true);
            FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
            XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");

            String element;
            boolean isPlaylist = false;
            String title = null;
            ArrayList<Song> songs = new ArrayList<>();

            while(reader.hasNext()) {
                reader.next();
                if (reader.isWhiteSpace()) {
                    continue;
                } else if (reader.isStartElement()) {
                    element = reader.getName().getLocalPart();

                    // If the element is a play list, reads the element attributes to retrieve
                    // the play list id and title.
                    if (element.equals("playlist")) {
                        isPlaylist = true;

                        id = Integer.parseInt(reader.getAttributeValue(0));
                        title = reader.getAttributeValue(1);
                    }
                } else if (reader.isCharacters() && isPlaylist) {
                    // Retrieves the reader value (song ID), gets the song and adds it to the songs list.
                    String value = reader.getText();
                    songs.add(getSong(Integer.parseInt(value)));
                } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlist")) {
                    // If the play list id, title, and songs have been retrieved, a new play list is created
                    // and the values reset.
                    playlists.add(new Playlist(id, title, songs));
                    id = -1;
                    title = null;
                    songs = new ArrayList<>();
                } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlists")) {
                    reader.close();
                    break;
                }
            }
            reader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        playlists.sort((x, y) -> {
            if (x.getId() < y.getId()) {
                return 1;
            } else if (x.getId() > y.getId()) {
                return -1;
            } else {
                return 0;
            }
        });

        playlists.add(new MostPlayedPlaylist(-2));
        playlists.add(new RecentlyPlayedPlaylist(-1));
    } else {
        playlists.sort((x, y) -> {
            if (x.getId() < y.getId()) {
                return 1;
            } else if (x.getId() > y.getId()) {
                return -1;
            } else {
                return 0;
            }
        });
    }
    return FXCollections.observableArrayList(playlists);
}
 
Example 15
Source File: XMLToImportantChemicals.java    From act with GNU General Public License v3.0 4 votes vote down vote up
private void process(XMLStreamReader xml) throws XMLStreamException {
  String tag;
  String root = null;
  Stack<DBObject> json = new Stack<DBObject>();
  DBObject js;
  while (xml.hasNext()) {
    int eventType = xml.next();
    while (xml.isWhiteSpace() || eventType == XMLEvent.SPACE)
      eventType = xml.next();

    switch (eventType) {
      case XMLEvent.START_ELEMENT:
        tag = xml.getLocalName();
        if (root == null) {
          root = tag;
        } else {
          json.push(new BasicDBObject());
        }
        break;
      case XMLEvent.END_ELEMENT:
        tag = xml.getLocalName();
        if (tag.equals(root)) {
          // will terminate in next iteration
        } else {
          js = json.pop();
          if (json.size() == 0) {
            if (tag.equals(rowTag))
              printEntry(js);
            else
              printUnwantedEntry(js);
          } else {
            putListStrOrJSON(json.peek(), tag, js);
          }
        }
        break;

      case XMLEvent.CHARACTERS:
        String txt = xml.getText();
        js = json.peek();
        if (js.containsField(strTag)) {
          txt = js.get(strTag) + txt;
          js.removeField(strTag);
        }
        js.put(strTag, txt);
        break;

      case XMLEvent.START_DOCUMENT:
        break;
      case XMLEvent.END_DOCUMENT:
        break;
      case XMLEvent.COMMENT:
      case XMLEvent.ENTITY_REFERENCE:
      case XMLEvent.ATTRIBUTE:
      case XMLEvent.PROCESSING_INSTRUCTION:
      case XMLEvent.DTD:
      case XMLEvent.CDATA:
      case XMLEvent.SPACE:
        System.out.format("%s --\n", eventType);
        break;
    }
  }
}
 
Example 16
Source File: XmlEntryConsumer.java    From cloud-odata-java with Apache License 2.0 4 votes vote down vote up
private void readCustomElement(final XMLStreamReader reader, final String tagName, final EntityInfoAggregator eia) throws EdmException, EntityProviderException, XMLStreamException {
  EntityPropertyInfo targetPathInfo = eia.getTargetPathInfo(tagName);
  NamespaceContext nsctx = reader.getNamespaceContext();

  boolean skipTag = true;
  if (!Edm.NAMESPACE_ATOM_2005.equals(reader.getName().getNamespaceURI())) {

    if (targetPathInfo != null) {
      final String customPrefix = targetPathInfo.getCustomMapping().getFcNsPrefix();
      final String customNamespaceURI = targetPathInfo.getCustomMapping().getFcNsUri();

      if (customPrefix != null && customNamespaceURI != null) {
        String xmlPrefix = nsctx.getPrefix(customNamespaceURI);
        String xmlNamespaceUri = reader.getNamespaceURI(customPrefix);

        if (customNamespaceURI.equals(xmlNamespaceUri) && customPrefix.equals(xmlPrefix)) {
          skipTag = false;
          reader.require(XMLStreamConstants.START_ELEMENT, customNamespaceURI, tagName);
          reader.next();
          reader.require(XMLStreamConstants.CHARACTERS, null, null);
          final String text = reader.getText();
          reader.nextTag();
          reader.require(XMLStreamConstants.END_ELEMENT, customNamespaceURI, tagName);

          final EntityPropertyInfo propertyInfo = getValidatedPropertyInfo(eia, tagName);
          final Class<?> typeMapping = typeMappings.getMappingClass(propertyInfo.getName());
          final EdmSimpleType type = (EdmSimpleType) propertyInfo.getType();
          final Object value = type.valueOfString(text, EdmLiteralKind.DEFAULT, propertyInfo.getFacets(),
              typeMapping == null ? type.getDefaultType() : typeMapping);
          properties.put(tagName, value);
        }
      }
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_PROPERTY.addContent(tagName));
    }
  }

  if (skipTag) {
    skipStartedTag(reader);
  }
}
 
Example 17
Source File: XmlFile.java    From Strata with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the tree from the StAX stream reader, capturing references.
 * <p>
 * The reader should be created using {@link #XML_FACTORY}.
 * <p>
 * This method supports capturing attribute references, such as an id/href pair.
 * Wherever the parser finds an attribute with the specified name, the element is added
 * to the specified map. Note that the map is mutated.
 * 
 * @param reader  the StAX stream reader, positioned at or before the element to be parsed
 * @param refAttr  the attribute name that should be parsed as a reference, null if not applicable
 * @param refs  the mutable map of references to update, null if not applicable
 * @return the parsed element
 * @throws IllegalArgumentException if the input cannot be parsed
 */
private static XmlElement parse(XMLStreamReader reader, String refAttr, Map<String, XmlElement> refs) {
  try {
    // parse start element
    String elementName = parseElementName(reader);
    ImmutableMap<String, String> attrs = parseAttributes(reader);

    // parse children or content
    ImmutableList.Builder<XmlElement> childBuilder = ImmutableList.builder();
    String content = "";
    int event = reader.next();
    while (event != XMLStreamConstants.END_ELEMENT) {
      switch (event) {
        // parse child when start element found
        case XMLStreamConstants.START_ELEMENT:
          childBuilder.add(parse(reader, refAttr, refs));
          break;
        // append content when characters found
        // since XMLStreamReader has IS_COALESCING=true means there should only be one content call
        case XMLStreamConstants.CHARACTERS:
        case XMLStreamConstants.CDATA:
          content += reader.getText();
          break;
        default:
          break;
      }
      event = reader.next();
    }
    ImmutableList<XmlElement> children = childBuilder.build();
    XmlElement parsed = children.isEmpty() ?
        XmlElement.ofContent(elementName, attrs, content) :
        XmlElement.ofChildren(elementName, attrs, children);
    String ref = attrs.get(refAttr);
    if (ref != null) {
      refs.put(ref, parsed);
    }
    return parsed;

  } catch (XMLStreamException ex) {
    throw new IllegalArgumentException(ex);
  }
}
 
Example 18
Source File: EntityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void handleComment(XMLStreamReader xmlr) {
    if (xmlr.hasText())
        output += xmlr.getText();
}
 
Example 19
Source File: NodeParser.java    From galleon with Apache License 2.0 4 votes vote down vote up
public ElementNode parseNode(XMLStreamReader reader, String nodeName) throws XMLStreamException {
    if (reader.getEventType() != START_ELEMENT) {
        throw new XMLStreamException("Expected START_ELEMENT", reader.getLocation());
    }
    if (!reader.getLocalName().equals(nodeName)) {
        throw new XMLStreamException("Expected <" + nodeName + ">", reader.getLocation());
    }

    ElementNode rootNode = createNodeWithAttributesAndNs(reader, null);
    ElementNode currentNode = rootNode;
    while (reader.hasNext()) {
        int type = reader.next();
        switch (type) {
        case END_ELEMENT:
            currentNode = currentNode.getParent();
            String name = reader.getLocalName();
            //TODO this looks wrong
            if (name.equals(nodeName)) {
                return rootNode;
            }
            break;
        case START_ELEMENT:
            ElementNode childNode = createNodeWithAttributesAndNs(reader, currentNode);
            currentNode.addChild(childNode);
            currentNode = childNode;
            break;
        case COMMENT:
            String comment = reader.getText();
            currentNode.addChild(new CommentNode(comment));
            break;
        case CDATA:
            currentNode.addChild(new CDataNode(reader.getText()));
            break;
        case CHARACTERS:
            if (!reader.isWhiteSpace()) {
                currentNode.addChild(new TextNode(reader.getText()));
            }
            break;
        case PROCESSING_INSTRUCTION:
            ProcessingInstructionNode node = parseProcessingInstruction(reader, currentNode);
            if (node != null) {
                currentNode.addChild(node);
            }

            break;
        default:
            break;
        }
    }

    throw new XMLStreamException("Element was not terminated", reader.getLocation());
}
 
Example 20
Source File: S3ErrorResponseHandler.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
private AmazonServiceException createException(HttpResponse httpResponse) throws
                                                                          XMLStreamException {
    final InputStream is = httpResponse.getContent();
    String xmlContent = null;
    /*
     * We don't always get an error response body back from S3. When we send
     * a HEAD request, we don't receive a body, so we'll have to just return
     * what we can.
     */
    if (is == null
            || httpResponse.getRequest().getHttpMethod() == HttpMethodName.HEAD) {
        return createExceptionFromHeaders(httpResponse, null);
    }

    String content = null;
    try {
        content = IOUtils.toString(is);
    } catch (IOException ioe) {
        if (log.isDebugEnabled())
            log.debug("Failed in parsing the error response : ", ioe);
        return createExceptionFromHeaders(httpResponse, null);
    }

    XMLStreamReader reader
        = XmlUtils.getXmlInputFactory().createXMLStreamReader(new ByteArrayInputStream(content.getBytes(UTF8)));

    try {
        /*
         * target depth is to determine if the XML Error response from the
         * server has any element inside <Error> tag have child tags.
         * Parsing such tags is not supported now. target depth is
         * incremented for every start tag and decremented after every end
         * tag is encountered.
         */
        int targetDepth = 0;
        final AmazonS3ExceptionBuilder exceptionBuilder = new AmazonS3ExceptionBuilder();
        exceptionBuilder.setErrorResponseXml(content);
        exceptionBuilder.setStatusCode(httpResponse.getStatusCode());
        exceptionBuilder.setCloudFrontId(httpResponse.getHeaders().get(Headers.CLOUD_FRONT_ID));
        String bucketRegion = httpResponse.getHeader(Headers.S3_BUCKET_REGION);
        if (bucketRegion != null) {
            exceptionBuilder.addAdditionalDetail(Headers.S3_BUCKET_REGION, bucketRegion);
        }

        boolean hasErrorTagVisited = false;
        while (reader.hasNext()) {
            int event = reader.next();

            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                targetDepth++;
                String tagName = reader.getLocalName();
                if (targetDepth == 1
                        && !S3ErrorTags.Error.toString().equals(tagName))
                    return createExceptionFromHeaders(httpResponse,
                            "Unable to parse error response. Error XML Not in proper format."
                                    + content);
                if (S3ErrorTags.Error.toString().equals(tagName)) {
                    hasErrorTagVisited = true;
                }
                continue;
            case XMLStreamConstants.CHARACTERS:
                xmlContent = reader.getText();
                if (xmlContent != null)
                    xmlContent = xmlContent.trim();
                continue;
            case XMLStreamConstants.END_ELEMENT:
                tagName = reader.getLocalName();
                targetDepth--;
                if (!(hasErrorTagVisited) || targetDepth > 1) {
                    return createExceptionFromHeaders(httpResponse,
                            "Unable to parse error response. Error XML Not in proper format."
                                    + content);
                }
                if (S3ErrorTags.Message.toString().equals(tagName)) {
                    exceptionBuilder.setErrorMessage(xmlContent);
                } else if (S3ErrorTags.Code.toString().equals(tagName)) {
                    exceptionBuilder.setErrorCode(xmlContent);
                } else if (S3ErrorTags.RequestId.toString().equals(tagName)) {
                    exceptionBuilder.setRequestId(xmlContent);
                } else if (S3ErrorTags.HostId.toString().equals(tagName)) {
                    exceptionBuilder.setExtendedRequestId(xmlContent);
                } else {
                    exceptionBuilder.addAdditionalDetail(tagName, xmlContent);
                }
                continue;
            case XMLStreamConstants.END_DOCUMENT:
                return exceptionBuilder.build();
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Failed in parsing the error response : " + content,
                    e);
    }
    return createExceptionFromHeaders(httpResponse, content);
}