List of usage examples for javax.xml.stream XMLStreamException XMLStreamException
public XMLStreamException(Throwable th)
From source file:org.mobicents.servlet.restcomm.http.client.Downloader.java
private HttpResponseDescriptor validateXML(final HttpResponseDescriptor descriptor) throws XMLStreamException { if (descriptor.getContentLength() > 0) { try {/*from w w w .j a v a2 s .co m*/ // parse an XML document into a DOM tree String xml = descriptor.getContentAsString().trim().replaceAll("&([^;]+(?!(?:\\w|;)))", "&$1"); DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); parser.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); return descriptor; } catch (final Exception e) { throw new XMLStreamException("Error parsing the RCML:" + e); } } return descriptor; }
From source file:com.autonomy.aci.client.services.impl.ErrorProcessorTest.java
@Test(expected = ProcessorException.class) public void testXMLStreamException() throws XMLStreamException, AciErrorException, ProcessorException { final XMLStreamReader mockXmlStreamReader = mock(XMLStreamReader.class); when(mockXmlStreamReader.hasNext()).thenThrow(new XMLStreamException("JUnit test exception")); processor.process(mockXmlStreamReader); fail("Should have raised a ProcessorException."); }
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static Result parseMaxLatencyResult(XMLEventReader reader) throws XMLStreamException { Long maxLatency = null;/*from w w w . j av a 2s . c o m*/ while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isCharacters()) { maxLatency = Long.parseLong(xmlEvent.asCharacters().getData()); } else if (xmlEvent.isEndElement()) { EndElement endElement = xmlEvent.asEndElement(); if (!MAX_LATENCY.matches(endElement.getName().getLocalPart())) { throw new XMLStreamException("Unexpected end element " + endElement.getName()); } if (maxLatency == null) { throw new XMLStreamException("Unexpected end element " + MAX_LATENCY.getName()); } return new MaxLatencyResult(maxLatency); } } throw new XMLStreamException("Unexpected end of stream"); }
From source file:com.carvoyant.modularinput.Program.java
@Override public void streamEvents(InputDefinition inputs, EventWriter ew) throws MalformedDataException, XMLStreamException, IOException { Service splunkSvc = getService(inputs.getServerUri(), inputs.getSessionKey()); for (String inputName : inputs.getInputs().keySet()) { String clientId = ((SingleValueParameter) inputs.getInputs().get(inputName).get("clientId")).getValue(); String clientSecret = ((SingleValueParameter) inputs.getInputs().get(inputName).get("clientSecret")) .getValue();//from w w w . j a v a 2 s . c om String token = ((SingleValueParameter) inputs.getInputs().get(inputName).get("token")).getValue(); String refreshToken = ((SingleValueParameter) inputs.getInputs().get(inputName).get("refreshToken")) .getValue(); SingleValueParameter expDate = (SingleValueParameter) inputs.getInputs().get(inputName) .get("expirationDate"); long expirationDate = expDate.getLong(); long expirationWindow = TimeUnit.DAYS.toMillis(1); long currentTime = System.currentTimeMillis(); // If the access token is going to expire, then refresh it if ((expirationDate - currentTime) < expirationWindow) { JSONObject tokenJson = getRefreshToken(ew, clientId, clientSecret, refreshToken); if (tokenJson != null) { token = tokenJson.getString("access_token"); refreshToken = tokenJson.getString("refresh_token"); int ttl = tokenJson.getInt("expires_in"); expirationDate = System.currentTimeMillis() + (long) ttl * 1000; // Update this configuration with the new settings String[] splunkApiInputName = inputName.split("://"); updateInput(ew, splunkSvc, splunkApiInputName[1], clientId, clientSecret, token, refreshToken, expirationDate); } else { throw new XMLStreamException("Cannot not refresh the token for " + inputName); } } // Get Carvoyant Data try { URL url = new URL("https://api.carvoyant.com/v1/api/account/data/?sinceLastCall=true"); // URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/api/account/data/?sinceLastCall=true"); URLConnection urlConnection = url.openConnection(); String basicAuth = "Bearer " + token; urlConnection.setRequestProperty("Authorization", basicAuth); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { JSONObject obj = new JSONObject(inputLine); JSONArray arr = obj.getJSONArray("data"); for (int i = 0; i < arr.length(); i++) { String timeString = arr.getJSONObject(i).getString("timestamp"); DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ"); Date date = format.parse(timeString); Event event = new Event(); event.setStanza(inputName); event.setTime(date); event.setData(arr.getJSONObject(i).toString()); ew.writeEvent(event); } } in.close(); } catch (IOException ioe) { throw new XMLStreamException("Could not retrieve Carvoyant Data", ioe); } catch (ParseException pe) { throw new XMLStreamException("Could not parse Carvoyant Data", pe); } } }
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static Result parseHdrLatencyProbeResult(XMLEventReader reader) throws XMLStreamException { String encodedData = null;//from ww w. j a v a2 s . co m while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isCharacters()) { encodedData = xmlEvent.asCharacters().getData(); } else if (xmlEvent.isEndElement()) { EndElement endElement = xmlEvent.asEndElement(); if (!HDR_LATENCY_DATA.matches(endElement.getName().getLocalPart()) || encodedData == null) { throw new XMLStreamException("Unexpected end element " + endElement.getName()); } try { byte[] bytes = Base64.decodeBase64(encodedData); Histogram histogram = Histogram.decodeFromCompressedByteBuffer(ByteBuffer.wrap(bytes), 0); return new HdrLatencyDistributionResult(histogram); } catch (DataFormatException e) { throw new RuntimeException(e); } } } throw new XMLStreamException("Unexpected end of stream"); }
From source file:lux.search.highlight.XmlHighlighter.java
@Override public void handleEvent(XMLStreamReader reader, int eventType) throws XMLStreamException { switch (eventType) { case XMLStreamConstants.START_DOCUMENT: xmlStreamReader = reader; // cache the reader so we can pull events super.handleEvent(reader, eventType); break;//from www .j a va 2 s . co m case XMLStreamConstants.START_ELEMENT: super.handleEvent(reader, eventType); xmlStreamTokens .pushElement(new QName(reader.getNamespaceURI(), reader.getLocalName(), reader.getPrefix())); break; case XMLStreamConstants.END_ELEMENT: super.handleEvent(reader, eventType); xmlStreamTokens.popElement(); break; case XMLStreamConstants.COMMENT: case XMLStreamConstants.PROCESSING_INSTRUCTION: super.handleEvent(reader, eventType); break; case XMLStreamConstants.CDATA: throw new XMLStreamException("unexpected CDATA event"); case XMLStreamConstants.SPACE: super.handleEvent(reader, eventType); break; case XMLStreamConstants.CHARACTERS: textReader.text(); try { highlightTextNode(); } catch (IOException e) { throw new XMLStreamException(e); } break; case XMLStreamConstants.ENTITY_REFERENCE: throw new XMLStreamException("unexpected entity reference event"); default: super.handleEvent(reader, eventType); } }
From source file:com.thalesgroup.sonar.plugins.tusar.sensors.TUSARTestsDataExtractor.java
private static Double getTimeAttributeInMS(String stringTime) throws XMLStreamException { // hardcoded to Locale.ENGLISH see http://jira.codehaus.org/browse/SONAR-602 try {/* www.ja v a2 s . c om*/ Double time = ParsingUtils.parseNumber(stringTime, Locale.ENGLISH); return !Double.isNaN(time) ? ParsingUtils.scaleValue(time * 1000, 3) : 0; } catch (ParseException e) { throw new XMLStreamException(e); } }
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static Result parseLatencyDistributionResult(XMLEventReader reader) throws XMLStreamException { Integer step = null;//w w w .ja va 2 s . c o m Integer maxValue = null; while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (LATENCY_DIST_STEP.matches(startElement.getName().getLocalPart())) { if (step != null) { throw new XMLStreamException("Unexpected element " + LATENCY_DIST_STEP.getName()); } step = Integer.parseInt(parseCharsAndEndCurrentElement(reader)); } else if (LATENCY_DIST_MAX_VALUE.matches(startElement.getName().getLocalPart())) { if (maxValue != null) { throw new XMLStreamException("Unexpected element " + LATENCY_DIST_MAX_VALUE.getName()); } maxValue = Integer.parseInt(parseCharsAndEndCurrentElement(reader)); } else if (LATENCY_DIST_BUCKETS.matches(startElement.getName().getLocalPart())) { if (step == null || maxValue == null) { throw new XMLStreamException("Unexpected element " + LATENCY_DIST_BUCKETS.getName()); } LinearHistogram histogram = new LinearHistogram(maxValue, step); parseBuckets(reader, histogram); return new LatencyDistributionResult(histogram); } } } throw new XMLStreamException("Unexpected end of the document"); }
From source file:davmail.exchange.dav.ExchangeDavMethod.java
protected String getTagContent(XMLStreamReader reader) throws XMLStreamException { String value = null;/*from ww w. jav a 2 s . c o m*/ 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; }
From source file:com.prowidesoftware.swift.model.mx.XmlEventWriter.java
public void add(final XMLEvent event) throws XMLStreamException { if (event != null) { log.finest("XmlEventType: " + event.getEventType()); try {/*from w ww . jav a 2s . c o m*/ final int type = event.getEventType(); switch (type) { case XMLEvent.START_DOCUMENT: if (this.includeXMLDeclaration) { log.finer(">> START_DOCUMENT"); log.finer("START_DOCUMENT XMLEvent " + ToStringBuilder.reflectionToString(event)); final String str = "<?xml version=\"1.0\" encoding=\"" + ((StartDocument) event).getCharacterEncodingScheme() + "\"?>"; out.write(str); logStep(str); } else { log.finer("skipping xml declaration"); } break; case XMLEvent.START_ELEMENT: this.startElementCount++; closeStartTagIfNeeded(); log.finer(">> START_ELEMENT"); indent.append(' '); final StartElement se = event.asStartElement(); @SuppressWarnings("rawtypes") final Iterator it = se.getNamespaces(); while (it.hasNext()) { log.fine("ns: " + it.next()); } /*--------------------------------------------------------------------------------------- * 2015.03 miguel * Cuidado con esta condicion! esto generaba el bug de que no abria el Document anidado dentro del xs:any * Esto es porque este document delayed solo se completa cuando recibe un namespace, pensado como elemento inicial * esto DEEEEBEEEEEEEEEEe corregirse cuando se cambie la serializacion, si se cambia * porque si el document queda dentro de un elemento payload, entonces en count es != 1 y debe revisarse como se identifica el primer * document y un document anidado. * */ if (StringUtils.equals(se.getName().getLocalPart(), this.rootElement) && this.startElementCount == 1) { // 2015.03 miguel: ESTE era el bug de esprow, que aparecian tags anidados de document cerrando que no abria, era porque entraban por aca sin esta condicion de depth count delayedStart = se; log.finer("local part is Document, initializing delayed start, startElementCount=" + this.startElementCount); } else { final String s = "\n" + indent + "<" + prefix() + se.getName().getLocalPart() /* + ">" */; out.write(s); logStep(s); /* 2014.11 miguel * para soportar atributos en lugar de cerrar aca seteamos un flag para indicar * que hace falta cerrar el startTag */ startTagIncomplete = true; if (se.isNamespace()) { log.fine("is ns in start XMLEvent " + ToStringBuilder.reflectionToString(event)); } } break; case XMLEvent.NAMESPACE: log.finer(">> NAMESPACE"); final Namespace ne = (Namespace) event; if (delayedStart != null) { final String s = "\n" + indent + "<" + prefix() + delayedStart.getName().getLocalPart() + " " + "xmlns" + (this.prefix != null ? ":" + this.prefix : "") + "=\"" + ne.getValue() + "\" xmlns:xsi=\"" + ne.getName() + "\"" + ">"; out.write(s); logStep(s); delayedStart = null; } else { log.fine("NAMESPACE XMLEvent " + ToStringBuilder.reflectionToString(event)); } break; case XMLEvent.CHARACTERS: log.finer(">> CHARACTERS"); closeStartTagIfNeeded(); final Characters ce = event.asCharacters(); final char[] arr = ce.getData().toCharArray(); out.write(escape(arr)); logStep(ce.getData()); break; case XMLEvent.END_ELEMENT: log.finer(">> END_ELEMENT"); closeStartTagIfNeeded(); indent.deleteCharAt(0); final EndElement ee = event.asEndElement(); final String str2 = "</" + prefix() + ee.getName().getLocalPart() + ">\n" + indent; out.write(str2); logStep(str2); break; case XMLEvent.END_DOCUMENT: log.finer(">> END_DOCUMENT"); closeStartTagIfNeeded(); /* 2014.10 miguel * No need to do anything while writing to a string */ log.finer("END_DOCUMENT XMLEvent " + ToStringBuilder.reflectionToString(event)); break; case XMLEvent.ATTRIBUTE: log.finer(">> ATTRIBUTE"); final Attribute a = (Attribute) event; final String str3 = " " + a.getName() + "=\"" + a.getValue() + "\" "; out.write(str3); log.fine(ToStringBuilder.reflectionToString(a)); logStep(str3); break; default: log.info("getEventType " + event.getEventType()); log.info("PW Unhandled XMLEvent " + ToStringBuilder.reflectionToString(event)); break; } } catch (IOException e) { log.log(Level.SEVERE, "PW I/O error: " + e); log.log(Level.FINER, "PW I/O error: ", e); throw new XMLStreamException(e); } } }