private void handleEvent(XMLEvent event, XMLEventReader reader, ParserTarget<T> target) throws Exception { XMLEvent nextEvent = null; if (event.isStartElement()) { xmlEventAdapter.setEvent(event); StartElement element = xmlEventAdapter.asStartElement(); String name = element.getName().getLocalPart(); elementStack.push(name); nextEvent = startElement(name, element, reader, target); } else if (event.isEndElement()) { EndElement element = event.asEndElement(); String name = element.getName().getLocalPart(); nextEvent = endElement(name, element, reader, target); Set<String> attributes = startElementAdapter.attributes; Iterator<Attribute> iterator = startElementAdapter.element.getAttributes(); while (iterator.hasNext()) { Attribute attribute = iterator.next(); if (!attributes.contains(attribute.getName().getLocalPart())) { notHandled(attribute.getName().getLocalPart(), Type.Attribute); } } elementStack.pop(); } if (nextEvent != null && !cancel) { handleEvent(nextEvent, reader, target); } }
/** * Parse a {@code NameIDType} * * @param xmlEventReader * @return * @throws ParsingException */ public static NameIDType parseNameIDType(XMLEventReader xmlEventReader) throws ParsingException { StartElement nameIDElement = StaxParserUtil.getNextStartElement(xmlEventReader); NameIDType nameID = new NameIDType(); Attribute nameQualifier = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.NAME_QUALIFIER.get())); if (nameQualifier != null) { nameID.setNameQualifier(StaxParserUtil.getAttributeValue(nameQualifier)); } Attribute format = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.FORMAT.get())); if (format != null) { nameID.setFormat(URI.create(StaxParserUtil.getAttributeValue(format))); } Attribute spProvidedID = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.SP_PROVIDED_ID.get())); if (spProvidedID != null) { nameID.setSPProvidedID(StaxParserUtil.getAttributeValue(spProvidedID)); } Attribute spNameQualifier = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.SP_NAME_QUALIFIER.get())); if (spNameQualifier != null) { nameID.setSPNameQualifier(StaxParserUtil.getAttributeValue(spNameQualifier)); } String nameIDValue = StaxParserUtil.getElementText(xmlEventReader); nameID.setValue(nameIDValue); return nameID; }
private XMLEvent handleAnchorElement(StartElement se, XMLEventFactory xef) { Set<Attribute> attrs = new HashSet<Attribute>(); Attribute href = AttributeByName.get(new QName("href"), se); if (href != null) { String value = "http"; if (href.getValue().toLowerCase().contains(("mailto"))) { value = "mailto:[email protected]"; } else if (href.getValue().trim().startsWith("#")) { value = href.getValue(); } else if (href.getValue().toLowerCase().contains("smil")) { value = href.getValue(); } else { value = "http://dummy.org"; } attrs.add(xef.createAttribute(href.getName(), value)); } Iterator<?> i = se.getAttributes(); while (i.hasNext()) { Attribute a = (Attribute) i.next(); if (!a.getName().getLocalPart().equals("href")) { attrs.add(a); } } return xef.createStartElement(se.getName(), attrs.iterator(), se.getNamespaces()); }
protected void parseTu(StartElement element) throws Exception { currentTu.clear(); currentTu.changeid = getAttributeValue(element, "changeid"); currentTu.changedate = parseISO8601date(getAttributeValue(element, "changedate")); currentTu.creationid = getAttributeValue(element, "creationid"); currentTu.creationdate = parseISO8601date(getAttributeValue(element, "creationdate")); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("tuv".equals(eStart.getName().getLocalPart())) { parseTuv(eStart); } else if ("prop".equals(eStart.getName().getLocalPart())) { parseProp(eStart); } else if ("note".equals(eStart.getName().getLocalPart())) { parseNote(eStart); } break; case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("tu".equals(eEnd.getName().getLocalPart())) { return; } break; } } }
private Definition parseEvent(XMLEvent event, Definition def) { StartElement se = event.asStartElement(); String elementName = se.getName().getLocalPart(); if (elementName.equals("catalog")) { return null; } Iterator<Attribute> attributes = se.getAttributes(); if (def == null) { Attribute id = attributes.next(); if (id.getName().toString() != ID) { throw new RuntimeException( "At line " + event.getLocation().getLineNumber() + ", problem with definition '" + elementName + "'. The first attribute of a definition must be called '" + ID + "'."); } def = new Definition(elementName, id.getValue()); // LogUtil.logger.info("def cree "+def.type+" - "+def.id); } else { DefElement de = new DefElement(elementName); while (attributes.hasNext()) { Attribute a = attributes.next(); de.addVal(a.getName().toString(), a.getValue()); } def.getElements().add(de); // LogUtil.logger.info(" element ajouté : "+de.name+" - "+de.getVal()); } return def; }
/** * Parse the {@link SAML11AttributeQueryType} * * @param xmlEventReader * @return * @throws ParsingException */ public static SAML11AuthenticationQueryType parseSAML11AuthenticationQuery( XMLEventReader xmlEventReader) throws ParsingException { SAML11AuthenticationQueryType query = new SAML11AuthenticationQueryType(); StartElement startElement; // There may be additional things under subject confirmation while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent instanceof EndElement) { EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader); if (StaxParserUtil.matches(endElement, SAML11Constants.AUTHENTICATION_QUERY)) break; else throw logger.parserUnknownEndElement(StaxParserUtil.getEndElementName(endElement)); } if (xmlEvent instanceof StartElement) { startElement = (StartElement) xmlEvent; String startTag = StaxParserUtil.getStartElementName(startElement); if (startTag.equals(JBossSAMLConstants.SUBJECT.get())) { SAML11SubjectParser parser = new SAML11SubjectParser(); query.setSubject((SAML11SubjectType) parser.parse(xmlEventReader)); } else throw logger.parserUnknownTag(startTag, startElement.getLocation()); } } return query; }
private static void readStartElement(XMLEventReader eventReader) throws XMLStreamException { XMLEvent event = eventReader.nextEvent(); StartElement startElement = event.asStartElement(); QName elementName = startElement.getName(); System.out.println("Tag: " + elementName.getLocalPart()); }
/** @see {@link ParserNamespaceSupport#parse(XMLEventReader)} */ public Object parse(XMLEventReader xmlEventReader) throws ParsingException { // Get the startelement StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, RESPONSE); ResponseType response = (ResponseType) parseBaseAttributes(startElement); while (xmlEventReader.hasNext()) { // Let us peek at the next start element startElement = StaxParserUtil.peekNextStartElement(xmlEventReader); if (startElement == null) break; String elementName = StaxParserUtil.getStartElementName(startElement); if (JBossSAMLConstants.ISSUER.get().equals(elementName)) { startElement = StaxParserUtil.getNextStartElement(xmlEventReader); NameIDType issuer = new NameIDType(); issuer.setValue(StaxParserUtil.getElementText(xmlEventReader)); response.setIssuer(issuer); } else if (JBossSAMLConstants.SIGNATURE.get().equals(elementName)) { Element sig = StaxParserUtil.getDOMElement(xmlEventReader); response.setSignature(sig); } else if (JBossSAMLConstants.ASSERTION.get().equals(elementName)) { SAMLAssertionParser assertionParser = new SAMLAssertionParser(); response.addAssertion( new RTChoiceType((AssertionType) assertionParser.parse(xmlEventReader))); } else if (JBossSAMLConstants.STATUS.get().equals(elementName)) { response.setStatus(parseStatus(xmlEventReader)); } else if (JBossSAMLConstants.ENCRYPTED_ASSERTION.get().equals(elementName)) { Element encryptedAssertion = StaxParserUtil.getDOMElement(xmlEventReader); response.addAssertion(new RTChoiceType(new EncryptedAssertionType(encryptedAssertion))); } else throw logger.parserUnknownTag(elementName, startElement.getLocation()); } return response; }
// first analyzing of XML input, creating hash map for holding backfire redirects public dataSending firstAnalyzing(String fileName) { Map<String, ReverseRedirects> map = new HashMap<String, ReverseRedirects>(); int pages = 0; String filePath = fileName; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); try { XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(filePath)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (startElement.getName().getLocalPart().toLowerCase().equals("page")) { pages++; } else if (startElement.getName().getLocalPart().toLowerCase().equals("title")) { xmlEvent = xmlEventReader.nextEvent(); map.put(xmlEvent.asCharacters().getData(), new ReverseRedirects(true)); } } } } catch (Exception e) { System.out.println("error: " + e); e.printStackTrace(); return null; } dataSending Result = new dataSending(); Result.map = map; Result.pages = pages; return Result; }
/** * Parse an {@code AttributeStatementType} * * @param xmlEventReader * @return * @throws ParsingException */ public static AttributeStatementType parseAttributeStatement(XMLEventReader xmlEventReader) throws ParsingException { AttributeStatementType attributeStatementType = new AttributeStatementType(); StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); String ATTRIBSTATEMT = JBossSAMLConstants.ATTRIBUTE_STATEMENT.get(); StaxParserUtil.validate(startElement, ATTRIBSTATEMT); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent instanceof EndElement) { EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader); StaxParserUtil.validate(endElement, JBossSAMLConstants.ATTRIBUTE_STATEMENT.get()); break; } // Get the next start element startElement = StaxParserUtil.peekNextStartElement(xmlEventReader); String tag = startElement.getName().getLocalPart(); if (JBossSAMLConstants.ATTRIBUTE.get().equals(tag)) { AttributeType attribute = parseAttribute(xmlEventReader); attributeStatementType.addAttribute(new ASTChoiceType(attribute)); } else throw logger.parserUnknownTag(tag, startElement.getLocation()); } return attributeStatementType; }
private static RSAKeyValueType parseRSAKeyValue(XMLEventReader xmlEventReader) throws ParsingException { StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, WSTrustConstants.XMLDSig.RSA_KEYVALUE); XMLEvent xmlEvent = null; String tag = null; RSAKeyValueType rsaKeyValue = new RSAKeyValueType(); while (xmlEventReader.hasNext()) { xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent instanceof EndElement) { tag = StaxParserUtil.getEndElementName((EndElement) xmlEvent); if (tag.equals(WSTrustConstants.XMLDSig.RSA_KEYVALUE)) { xmlEvent = StaxParserUtil.getNextEndElement(xmlEventReader); break; } else throw logger.parserUnknownEndElement(tag); } startElement = (StartElement) xmlEvent; tag = StaxParserUtil.getStartElementName(startElement); if (tag.equals(WSTrustConstants.XMLDSig.MODULUS)) { startElement = StaxParserUtil.getNextStartElement(xmlEventReader); String text = StaxParserUtil.getElementText(xmlEventReader); rsaKeyValue.setModulus(text.getBytes()); } else if (tag.equals(WSTrustConstants.XMLDSig.EXPONENT)) { startElement = StaxParserUtil.getNextStartElement(xmlEventReader); String text = StaxParserUtil.getElementText(xmlEventReader); rsaKeyValue.setExponent(text.getBytes()); } else throw logger.parserUnknownTag(tag, startElement.getLocation()); } return rsaKeyValue; }
/** * @param element the XML element to parse * @param parent the parent tag * @param stream the stream to read more elements from @return the parsed resource * @throws SPFormatException on SP format problems */ @Override public HarvestableFixture read( final StartElement element, final QName parent, final Iterable<XMLEvent> stream) throws SPFormatException { requireTag( element, parent, "cache", "grove", "orchard", "field", "meadow", "mine", "mineral", "shrub", "stone"); final int idNum = getOrGenerateID(element); final HarvestableFixture retval; switch (element.getName().getLocalPart().toLowerCase()) { case "cache": retval = new CacheFixture( getParameter(element, KIND_PAR), getParameter(element, "contents"), idNum); break; case "field": retval = createMeadow(element, true, idNum); break; case "grove": retval = createGrove(element, false, idNum); break; case "meadow": retval = createMeadow(element, false, idNum); break; case "mine": retval = new Mine( getParamWithDeprecatedForm(element, KIND_PAR, "product"), TownStatus.parseTownStatus(getParameter(element, STATUS_PAR)), idNum); break; case "mineral": retval = new MineralVein( getParamWithDeprecatedForm(element, KIND_PAR, "mineral"), parseBoolean(getParameter(element, "exposed")), getDC(element), idNum); break; case "orchard": retval = createGrove(element, true, idNum); break; case "shrub": retval = new Shrub(getParamWithDeprecatedForm(element, KIND_PAR, "shrub"), idNum); break; case "stone": retval = new StoneDeposit( StoneKind.parseStoneKind(getParamWithDeprecatedForm(element, KIND_PAR, "stone")), getDC(element), idNum); break; default: throw new IllegalArgumentException("Unhandled harvestable tag"); } spinUntilEnd(element.getName(), stream); retval.setImage(getParameter(element, "image", "")); return retval; }
private void parseTerm(StartElement root, XMLEventReader r) throws IOException, XMLStreamException { Attribute aboutAtt = root.getAttributeByName(rdfAbout); if (aboutAtt == null) { throw new IOException("no rdf:about"); } TermImpl term = uri2term.get(aboutAtt.getValue()); if (term == null) { term = new TermImpl(); term.accession = aboutAtt.getValue(); if (term.accession.startsWith(PREFIX)) { term.accession = term.accession.substring(PREFIX.length()); } term.name = term.accession; uri2term.put(aboutAtt.getValue(), term); } while (r.hasNext()) { XMLEvent evt = r.nextEvent(); if (evt.isStartElement()) { StartElement E = evt.asStartElement(); QName qN = E.getName(); if (NS.equals(qN.getNamespaceURI())) { if (qN.getLocalPart().equals("accession")) { term.accession = r.getElementText(); } else if (qN.getLocalPart().equals("name")) { term.name = r.getElementText(); } else if (qN.getLocalPart().equals("is_a")) { Attribute rsrc = E.getAttributeByName(rdfRsrc); if (rsrc == null) throw new IOException("att missing " + rdfRsrc + " for " + aboutAtt.getValue()); String parentUri = rsrc.getValue(); term.parents.add(parentUri); TermImpl parentTerm = this.uri2term.get(parentUri); if (parentTerm == null) { parentTerm = new TermImpl(); parentTerm.accession = parentUri; if (parentTerm.accession.startsWith(PREFIX)) { parentTerm.accession = parentTerm.accession.substring(PREFIX.length()); } parentTerm.name = parentTerm.accession; uri2term.put(parentUri, parentTerm); } parentTerm.children.add(aboutAtt.getValue()); } } } else if (evt.isEndElement()) { EndElement E = evt.asEndElement(); QName qN = E.getName(); if (qN.getLocalPart().equals("term") && NS.equals(qN.getNamespaceURI())) { break; } } } }
public static KeyInfoType parseKeyInfo(XMLEventReader xmlEventReader) throws ParsingException { KeyInfoType keyInfo = new KeyInfoType(); StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, WSTrustConstants.XMLDSig.KEYINFO); XMLEvent xmlEvent = null; String tag = null; while (xmlEventReader.hasNext()) { xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent instanceof EndElement) { tag = StaxParserUtil.getEndElementName((EndElement) xmlEvent); if (tag.equals(WSTrustConstants.XMLDSig.KEYINFO)) { xmlEvent = StaxParserUtil.getNextEndElement(xmlEventReader); break; } else throw logger.parserUnknownEndElement(tag); } startElement = (StartElement) xmlEvent; tag = StaxParserUtil.getStartElementName(startElement); if (tag.equals(WSTrustConstants.XMLEnc.ENCRYPTED_KEY)) { keyInfo.addContent(StaxParserUtil.getDOMElement(xmlEventReader)); } else if (tag.equals(WSTrustConstants.XMLDSig.X509DATA)) { startElement = StaxParserUtil.getNextStartElement(xmlEventReader); X509DataType x509 = new X509DataType(); // Let us go for the X509 certificate startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, WSTrustConstants.XMLDSig.X509CERT); X509CertificateType cert = new X509CertificateType(); String certValue = StaxParserUtil.getElementText(xmlEventReader); cert.setEncodedCertificate(certValue.getBytes()); x509.add(cert); EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader); StaxParserUtil.validate(endElement, WSTrustConstants.XMLDSig.X509DATA); keyInfo.addContent(x509); } else if (tag.equals(WSTrustConstants.XMLDSig.KEYVALUE)) { startElement = StaxParserUtil.getNextStartElement(xmlEventReader); KeyValueType keyValue = null; startElement = StaxParserUtil.peekNextStartElement(xmlEventReader); tag = StaxParserUtil.getStartElementName(startElement); if (tag.equals(WSTrustConstants.XMLDSig.RSA_KEYVALUE)) { keyValue = parseRSAKeyValue(xmlEventReader); } else if (tag.equals(WSTrustConstants.XMLDSig.DSA_KEYVALUE)) { keyValue = parseDSAKeyValue(xmlEventReader); } else throw logger.parserUnknownTag(tag, startElement.getLocation()); EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader); StaxParserUtil.validate(endElement, WSTrustConstants.XMLDSig.KEYVALUE); keyInfo.addContent(keyValue); } } return keyInfo; }
protected Map<String, Preference> toPreferencesMap(String xml) { if (Validator.isNull(xml)) { return Collections.emptyMap(); } Map<String, Preference> preferencesMap = _preferencesMapPortalCache.get(xml); if (preferencesMap != null) { return preferencesMap; } XMLEventReader xmlEventReader = null; try { XMLInputFactory xmlInputFactory = StAXReaderUtil.getXMLInputFactory(); xmlEventReader = xmlInputFactory.createXMLEventReader(new UnsyncStringReader(xml)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (elementName.equals("preference")) { Preference preference = readPreference(xmlEventReader); if (preferencesMap == null) { preferencesMap = new HashMap<String, Preference>(); } preferencesMap.put(preference.getName(), preference); } } } } catch (XMLStreamException xse) { throw new SystemException(xse); } finally { if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (XMLStreamException xse) { } } } if (preferencesMap == null) { preferencesMap = Collections.emptyMap(); } _preferencesMapPortalCache.put(xml, preferencesMap); return preferencesMap; }
/** Read TMX file. */ public void readTMX( File file, final Language sourceLanguage, final Language targetLanguage, boolean isSegmentingEnabled, final boolean forceOmegaTMX, final boolean extTmxLevel2, final boolean useSlash, final LoadCallback callback) throws Exception { this.extTmxLevel2 = extTmxLevel2; this.useSlash = useSlash; this.isSegmentingEnabled = isSegmentingEnabled; // log the parsing attempt Log.logRB("TMXR_INFO_READING_FILE", new Object[] {file.getAbsolutePath()}); boolean allFound = true; InputStream in; if (file.getName().endsWith(".gz")) { in = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file))); } else { in = new BufferedInputStream(new FileInputStream(file)); } xml = factory.createXMLEventReader(in); try { while (xml.hasNext()) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("tu".equals(eStart.getName().getLocalPart())) { parseTu(eStart); ParsedTuv origTuv = getTuvByLang(sourceLanguage); ParsedTuv targetTuv = getTuvByLang(targetLanguage); allFound &= callback.onEntry(currentTu, origTuv, targetTuv, isParagraphSegtype); } else if ("header".equals(eStart.getName().getLocalPart())) { parseHeader(eStart, sourceLanguage); } break; } } } finally { xml.close(); in.close(); } if (!allFound) { Log.logWarningRB("TMXR_WARNING_SOURCE_NOT_FOUND"); warningsCount++; } Log.logRB("TMXR_INFO_READING_COMPLETE"); Log.log(""); }
/** * Parse the attributes that are common to all SAML Request Types * * @param startElement * @param request * @throws ParsingException */ protected void parseBaseAttributes(StartElement startElement, RequestAbstractType request) throws ParsingException { Attribute destinationAttr = startElement.getAttributeByName(new QName(JBossSAMLConstants.DESTINATION.get())); if (destinationAttr != null) request.setDestination(URI.create(StaxParserUtil.getAttributeValue(destinationAttr))); Attribute consent = startElement.getAttributeByName(new QName(JBossSAMLConstants.CONSENT.get())); if (consent != null) request.setConsent(StaxParserUtil.getAttributeValue(consent)); }
private boolean isEqual(StartElement e1, StartElement e2) { if (e1 == e2) return true; if (!isEqual(e1.getName(), e2.getName())) return false; if (!compareAttributes(e1.getAttributes(), e2.getAttributes())) return false; // Do not isEqual namespace declarations for now, it is not relevent // namespaces are propogated into the attribute and element QName return true; }
/** * Write a new element with the specified name and text * * @return the end element */ private XMLEvent getAddedEvent( XMLEvent event, XMLEventWriter writer, String elementName, String text) throws XMLStreamException { StartElement oldStartEvent = event.asStartElement(); StartElement newStartEvent = xmlEventFactory.createStartElement( new QName(elementName), null, oldStartEvent.getNamespaces()); writer.add(newStartEvent); writer.add(xmlEventFactory.createCharacters(text)); return xmlEventFactory.createEndElement(newStartEvent.getName(), newStartEvent.getNamespaces()); }
private StartElement withNamespace(StartElement startElement) { // otherwise, wrap the start element event to provide a default namespace mapping final List<Namespace> namespaces = new ArrayList<Namespace>(); namespaces.add(xmlEventFactory.createNamespace("", namespaceUri)); Iterator<?> originalNamespaces = startElement.getNamespaces(); while (originalNamespaces.hasNext()) { namespaces.add((Namespace) originalNamespaces.next()); } return xmlEventFactory.createStartElement( new QName(namespaceUri, startElement.getName().getLocalPart()), startElement.getAttributes(), namespaces.iterator()); }
/** * Create a new start element based on the original but that does not include the specified * attribute. */ private StartElement getSkippedElementStartEvent(XMLEvent event) { Set attributes = new HashSet(); for (java.util.Iterator i = event.asStartElement().getAttributes(); i.hasNext(); ) { Attribute a = (Attribute) i.next(); if (!DISABLE_SUB_ELEMENTS.contains(a.getName().getLocalPart())) { attributes.add(a); } } StartElement oldStartEvent = event.asStartElement(); return xmlEventFactory.createStartElement( oldStartEvent.getName(), attributes.iterator(), oldStartEvent.getNamespaces()); }
public static void main(String[] args) { for (String arg : args) { try { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setXMLReporter( new XMLReporter() { @Override public void report( String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException { System.err.println("Problem in " + location); System.err.println( "at line " + location.getLineNumber() + ", column " + location.getColumnNumber()); System.err.println(message); System.err.println("errorType = " + errorType); System.err.println("relatedInformation = " + relatedInformation); } }); XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new FileReader(arg)); while (eventReader.hasNext()) { XMLEvent event = (XMLEvent) eventReader.next(); switch (event.getEventType()) { case XMLEvent.START_DOCUMENT: { StartElement startElement = event.asStartElement(); if (startElement.getName().getLocalPart().equals("target")) { Attribute attribute = startElement.getAttributeByName(new QName("name")); System.out.println(attribute.getValue()); } break; } // case XMLEvent.COMMENT:{ event.} } } } catch (XMLStreamException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (FileNotFoundException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } }
/** * Parse an {@code AttributeType} * * @param xmlEventReader * @return * @throws ParsingException */ public static AttributeType parseAttribute(XMLEventReader xmlEventReader) throws ParsingException { StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, JBossSAMLConstants.ATTRIBUTE.get()); AttributeType attributeType = null; Attribute name = startElement.getAttributeByName(new QName(JBossSAMLConstants.NAME.get())); if (name == null) throw logger.parserRequiredAttribute("Name"); attributeType = new AttributeType(StaxParserUtil.getAttributeValue(name)); parseAttributeType( xmlEventReader, startElement, JBossSAMLConstants.ATTRIBUTE.get(), attributeType); return attributeType; }
/** * Parses the {@code ServiceProviders} section of the STS configuration file. * * @param xmlEventReader the reader used to parse the XML configuration file. * @return a {@code ServiceProvidersType} instance that contains the parsed data. * @throws ParsingException if an error occurs while parsing the XML file. */ private ServiceProvidersType parseServiceProviders(XMLEventReader xmlEventReader) throws ParsingException { StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(startElement, SERVICE_PROVIDERS_ELEMENT); ServiceProvidersType serviceProviders = new ServiceProvidersType(); // parse all token providers one by one. while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent == null) break; if (xmlEvent instanceof EndElement) { EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader); String endElementName = StaxParserUtil.getEndElementName(endElement); if (endElementName.equals(SERVICE_PROVIDERS_ELEMENT)) break; else throw logger.parserUnknownEndElement(endElementName); } StartElement subEvent = StaxParserUtil.peekNextStartElement(xmlEventReader); if (subEvent == null) break; String elementName = StaxParserUtil.getStartElementName(subEvent); if (SERVICE_PROVIDER_ELEMENT.equalsIgnoreCase(elementName)) { subEvent = StaxParserUtil.getNextStartElement(xmlEventReader); StaxParserUtil.validate(subEvent, SERVICE_PROVIDER_ELEMENT); ServiceProviderType serviceProvider = new ServiceProviderType(); // parse the provider attributes (endpoint, token type and truststore alias). QName attributeQName = new QName("", TOKEN_TYPE_ATTRIB); Attribute attribute = subEvent.getAttributeByName(attributeQName); if (attribute != null) serviceProvider.setTokenType(StaxParserUtil.getAttributeValue(attribute)); attributeQName = new QName("", ENDPOINT_ATTRIB); attribute = subEvent.getAttributeByName(attributeQName); if (attribute != null) serviceProvider.setEndpoint(StaxParserUtil.getAttributeValue(attribute)); attributeQName = new QName("", TRUSTSTORE_ALIAS_ATTRIB); attribute = subEvent.getAttributeByName(attributeQName); if (attribute != null) serviceProvider.setTruststoreAlias(StaxParserUtil.getAttributeValue(attribute)); EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader); StaxParserUtil.validate(endElement, SERVICE_PROVIDER_ELEMENT); serviceProviders.add(serviceProvider); } else throw logger.parserUnknownTag(elementName, subEvent.getLocation()); } return serviceProviders; }
/** * Parse an {@code AttributeType} * * @param xmlEventReader * @throws ParsingException */ public static void parseAttributeType( XMLEventReader xmlEventReader, StartElement startElement, String rootTag, AttributeType attributeType) throws ParsingException { // Look for X500 Encoding QName x500EncodingName = new QName( JBossSAMLURIConstants.X500_NSURI.get(), JBossSAMLConstants.ENCODING.get(), JBossSAMLURIConstants.X500_PREFIX.get()); Attribute x500EncodingAttr = startElement.getAttributeByName(x500EncodingName); if (x500EncodingAttr != null) { attributeType .getOtherAttributes() .put(x500EncodingAttr.getName(), StaxParserUtil.getAttributeValue(x500EncodingAttr)); } Attribute friendlyName = startElement.getAttributeByName(new QName(JBossSAMLConstants.FRIENDLY_NAME.get())); if (friendlyName != null) attributeType.setFriendlyName(StaxParserUtil.getAttributeValue(friendlyName)); Attribute nameFormat = startElement.getAttributeByName(new QName(JBossSAMLConstants.NAME_FORMAT.get())); if (nameFormat != null) attributeType.setNameFormat(StaxParserUtil.getAttributeValue(nameFormat)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader); if (xmlEvent instanceof EndElement) { EndElement end = StaxParserUtil.getNextEndElement(xmlEventReader); if (StaxParserUtil.matches(end, rootTag)) break; } startElement = StaxParserUtil.peekNextStartElement(xmlEventReader); if (startElement == null) break; String tag = StaxParserUtil.getStartElementName(startElement); if (JBossSAMLConstants.ATTRIBUTE.get().equals(tag)) break; if (JBossSAMLConstants.ATTRIBUTE_VALUE.get().equals(tag)) { Object attributeValue = parseAttributeValue(xmlEventReader); attributeType.addAttributeValue(attributeValue); } else throw logger.parserUnknownTag(tag, startElement.getLocation()); } }
private void skipElement( final StartElement start, final XMLEventReader reader, final XMLEventWriter writer, final boolean excludeStart) throws Exception { if (!excludeStart) { writeEvent(start, writer); } int depth = 1; boolean found = false; while (reader.hasNext() && !found) { final XMLEvent event = reader.nextEvent(); writeEvent(event, writer); if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { depth++; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) { depth--; found = depth == 0 && start.getName().equals(event.asEndElement().getName()); } } }
/** * Pars the STAX attributes into the Bails attribute map. * * @param element a STAX @link javax.xml.stream.events.StartElement that may or may not contain * attributes. * @return a map of string object key value pairs that represent the Bails attributes. */ private Map<String, Object> parsAttributes(StartElement element) { Map<String, Object> attributes = new HashMap<String, Object>(); // Initialise the attributes map. // Get the attributes iterator from the STAX start element object. Iterator<Attribute> attributeIterator = element.getAttributes(); Attribute attribute = null; // Place holder for each attribute. bailsTag = false; // Prepare the element to be checked for a bails id. while (attributeIterator.hasNext()) { // Iterate over the attributes... attribute = attributeIterator.next(); // ...recording each one, ... QName qName = attribute.getName(); // ...taking the qName then... // ...recording the name as a string. // A check is done on the attribute prefix. If it exists it is added to the attributes name // separated by a // colon (:). String nameString = qName.getPrefix().equals("") ? qName.getLocalPart() : qName.getPrefix() + ":" + qName.getLocalPart(); if (!bailsTag) { // If this isn't yet a bails tag keep checking to see if it is. bailsTag = TagElement.BAILS_ID_NAME.equals(nameString); } attributes.put(nameString, attribute.getValue()); } return attributes; }
/** * Read the numeric format string out of the styles table for this cell. Stores the result in the * Cell. * * @param startElement * @param cell */ void setFormatString(StartElement startElement, StreamingCell cell) { Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if (cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if (stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if (style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if (formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
public static Set<Integer> extract(String fileName, String word) throws IOException { Set<Integer> ids = new HashSet<Integer>(); BufferedReader reader = new BufferedReader(new FileReader(fileName), 4 * 1024 * 1024); String line = null; int lineCount = 0; System.out.println("Reading file..."); while ((line = reader.readLine()) != null) { lineCount++; if (lineCount % 2000 == 0) System.out.print("."); if (lineCount % 100000 == 0) { System.out.println(lineCount); } try { if (!line.trim().startsWith("<row")) continue; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(line)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (startElement.getName().getLocalPart().equalsIgnoreCase("row")) { int id = XMLUtil.getIntElement(startElement, "Id"); String title = XMLUtil.getStringElement(startElement, "Title"); if (title == null) { title = ""; continue; } String tags = XMLUtil.getStringElement(startElement, "Tags"); if ((tags == null) || (tags.trim().length() == 0)) { return null; } if (!SOUtil.hasJavaTag(tags)) continue; if (title.contains(word)) { ids.add(id); } } } } } catch (Exception e) { e.printStackTrace(); } } return ids; }
/** @deprecated */ public static List<AndroidString> getAndroidStringsList(InputStream xml) { List<AndroidString> result = new ArrayList<AndroidString>(); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = inputFactory.createXMLEventReader(xml); AndroidString androidString = null; while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); if (startElement.getName().getLocalPart().equals("string")) { androidString = new AndroidString(); Iterator<Attribute> attributes = startElement.getAttributes(); while (attributes.hasNext()) { Attribute attribute = attributes.next(); if (attribute.getName().toString().equals("name")) { androidString.setKey(attribute.getValue()); } } event = eventReader.nextEvent(); String value = event.asCharacters().getData().trim(); // todo: if the value starts with xml tags(<u>), the value will be empty androidString.setValue(value); continue; } } if (event.isEndElement()) { EndElement endElement = event.asEndElement(); if (endElement.getName().getLocalPart().equals("string")) { result.add(androidString); } } } } catch (XMLStreamException e) { e.printStackTrace(); } return result; }