Exemplo n.º 1
0
  // 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;
  }
Exemplo n.º 2
0
  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;
  }
Exemplo n.º 3
0
 public static XmlMessage read(InputStream in) {
   try {
     XMLInputFactory inputFactory = XMLInputFactory.newInstance();
     XMLEventReader eventReader;
     eventReader = inputFactory.createXMLEventReader(in);
     String id = null;
     String value = null;
     while (eventReader.hasNext()) {
       XMLEvent event = eventReader.nextEvent();
       if (event.isStartElement()) {
         String tag = event.asStartElement().getName().getLocalPart();
         if (ID_TAG.equals(tag)) {
           event = eventReader.nextEvent();
           id = event.asCharacters().getData();
           continue;
         }
         if (VALUE_TAG.equals(tag)) {
           event = eventReader.nextEvent();
           value = event.asCharacters().getData();
           continue;
         }
       }
     }
     return new XmlMessage(id, value);
   } catch (XMLStreamException e) {
     throw new IllegalStateException(e);
   }
 }
Exemplo n.º 4
0
  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());
      }
    }
  }
Exemplo n.º 5
0
  /** @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;
  }
Exemplo n.º 6
0
  /**
   * 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;
  }
Exemplo n.º 7
0
 private static Book readBook(XMLEventReader eventReader) throws XMLStreamException {
   while (eventReader.hasNext()) {
     XMLEvent event = eventReader.nextEvent();
     if (event.isEndElement()) {}
   }
   return null;
 }
Exemplo n.º 8
0
  public void testNextTagOk() throws XMLStreamException {
    String XML = "<root>\n" + "<branch>   <leaf>  </leaf></branch>" + "</root>";

    for (int i = 0; i < 4; ++i) {
      boolean ns = (i & 1) != 0;
      boolean coal = (i & 2) != 0;
      XMLEventReader er = getReader(XML, ns, coal);

      assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());

      assertTokenType(START_ELEMENT, er.nextTag().getEventType());
      assertTokenType(START_ELEMENT, er.nextTag().getEventType());
      /* Ok, let's mix in bit of peeking to ensure reader won't
       * be confused too badly...
       */
      // This should be space between <branch> and <leaf>...
      assertTokenType(CHARACTERS, er.peek().getEventType());

      // And then the leaf
      assertTokenType(START_ELEMENT, er.nextTag().getEventType());

      assertTokenType(END_ELEMENT, er.nextTag().getEventType());
      assertTokenType(END_ELEMENT, er.nextTag().getEventType());
      assertTokenType(END_ELEMENT, er.nextTag().getEventType());

      assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
      assertFalse(er.hasNext());
    }
  }
Exemplo n.º 9
0
  public void testSimpleValid() throws XMLStreamException {
    /* Whether prolog/epilog white space is reported is not defined
     * by StAX specs, thus, let's not add any
     */
    String XML =
        "<?xml version='1.0' ?>"
            + "<!DOCTYPE root [  ]>"
            + "<root attr='123'><!-- comment -->\n"
            + "</root>";

    for (int i = 0; i < 4; ++i) {
      boolean ns = (i & 1) != 0;
      boolean coal = (i & 2) != 0;
      XMLEventReader er = getReader(XML, ns, coal);

      assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
      assertTokenType(DTD, er.nextEvent().getEventType());
      assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(COMMENT, er.nextEvent().getEventType());
      // for fun, let's just use next() instead of nextEvent()
      XMLEvent evt = (XMLEvent) er.next();
      assertTokenType(CHARACTERS, evt.getEventType());
      assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
      assertFalse(er.hasNext());
      er.close();
    }
  }
Exemplo n.º 10
0
  public XMLElement getXmlElement(final StartElement start, final XMLEventReader reader)
      throws Exception {

    final XMLElement res = new XMLElement();
    res.setStart(start);

    final Charset encoding = Charset.forName(org.apache.olingo.commons.api.Constants.UTF8);
    final ByteArrayOutputStream content = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(content, encoding);

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
      final XMLEvent event = reader.nextEvent();

      if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
        depth++;
      } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
        depth--;
      }

      if (depth == 0) {
        res.setEnd(event.asEndElement());
      } else {
        event.writeAsEncodedUnicode(writer);
      }
    }

    writer.flush();
    writer.close();

    res.setContent(new ByteArrayInputStream(content.toByteArray()));

    return res;
  }
Exemplo n.º 11
0
  public static void lerPeloStax() throws Exception {
    FileInputStream fileInputStream = new FileInputStream("src/venda.xml");
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader eventos = factory.createXMLEventReader(fileInputStream);
    Produto produto = new Produto();
    List<Produto> produtos = new ArrayList<>();

    while (eventos.hasNext()) {
      XMLEvent evento = eventos.nextEvent();

      if (evento.isStartElement()
          && evento.asStartElement().getName().getLocalPart().equals("produto")) {
        produto = new Produto();
      } else if (evento.isStartElement()
          && evento.asStartElement().getName().getLocalPart().equals("nome")) {
        evento = eventos.nextEvent();
        String nome = evento.asCharacters().getData();
        produto.setNome(nome);
      } else if (evento.isStartElement()
          && evento.asStartElement().getName().getLocalPart().equals("preco")) {
        evento = eventos.nextEvent();
        String nome = evento.asCharacters().getData();
        produto.setPreco(Double.parseDouble(nome));
      } else if (evento.isEndElement()
          && evento.asEndElement().getName().getLocalPart().equals("produto")) {
        produtos.add(produto);
      }
    }

    System.out.println(produtos);
  }
Exemplo n.º 12
0
 public static Address readConfig(InputStream in) {
   Address address = new Address();
   try {
     // First create a new XMLInputFactory
     XMLInputFactory inputFactory = XMLInputFactory.newInstance();
     // Setup a new eventReader
     // InputStream in = new FileInputStream(configFile);
     XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
     // Read the XML document
     while (eventReader.hasNext()) {
       XMLEvent event = eventReader.nextEvent();
       if (event.isStartElement()) {
         if (event.asStartElement().getName().getLocalPart() == ("country")) {
           event = eventReader.nextEvent();
           address.setCountry(event.asCharacters().getData());
           continue;
         }
         if (event.asStartElement().getName().getLocalPart() == ("county")) {
           event = eventReader.nextEvent();
           address.setCity(event.asCharacters().getData());
           continue;
         }
       }
     }
   } catch (XMLStreamException e) {
     e.printStackTrace();
   }
   return address;
 }
Exemplo n.º 13
0
  public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    try {

      final XMLElement feedElement =
          extractElement(reader, writer, Collections.<String>singletonList("feed"), 0, 1, 1)
              .getValue();

      writer.add(feedElement.getStart());
      addAtomElement(
          IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING),
          writer);
      writer.add(feedElement.getContentReader());
      writer.add(feedElement.getEnd());

      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }

    } finally {
      writer.flush();
      writer.close();
      reader.close();
      IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Exemplo n.º 14
0
  /**
   * 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;
  }
Exemplo n.º 15
0
  private void addAtomElement(final InputStream content, final XMLEventWriter writer)
      throws Exception {
    final XMLEventReader reader = getEventReader(content);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {
      writer.add(newLine);

      while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() != XMLStreamConstants.START_DOCUMENT
            && event.getEventType() != XMLStreamConstants.END_DOCUMENT
            && event.getEventType() != XMLStreamConstants.COMMENT) {
          writer.add(event);
        }
      }
      writer.add(newLine);
    } finally {
      reader.close();
      IOUtils.closeQuietly(content);
    }
  }
Exemplo n.º 16
0
  /** The main purpose of this test is to ensure that an exception is thrown at the end. */
  public void testIterationEndException() throws XMLStreamException {
    String XML = "<root />";

    for (int i = 0; i < 4; ++i) {
      boolean coal = (i & 1) != 0;
      boolean checkHasNext = (i & 2) != 0;
      XMLEventReader er = getReader(XML, true, coal);

      assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
      assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());

      if (checkHasNext) {
        assertFalse(er.hasNext());
      }

      XMLEvent ev = null;
      try {
        ev = er.nextEvent();
      } catch (NoSuchElementException nex) {
        continue; // good
      } catch (Throwable t) {
        fail("Expected a NoSuchElementException after iterating through the document; got " + t);
      }

      // Shouldn't get this far...
      fail(
          "Expected a NoSuchElementException after iterating through the document; got event: "
              + ev);
    }
  }
Exemplo n.º 17
0
  /**
   * Parse {@link org.keycloak.dom.saml.v1.assertion.SAML11ConditionsType}
   *
   * @param xmlEventReader
   * @return
   * @throws ParsingException
   */
  public static SAML11ConditionsType parseSAML11Conditions(XMLEventReader xmlEventReader)
      throws ParsingException {
    StartElement startElement;
    SAML11ConditionsType conditions = new SAML11ConditionsType();
    StartElement conditionsElement = StaxParserUtil.getNextStartElement(xmlEventReader);
    StaxParserUtil.validate(conditionsElement, JBossSAMLConstants.CONDITIONS.get());

    String assertionNS = SAML11Constants.ASSERTION_11_NSURI;

    QName notBeforeQName = new QName("", JBossSAMLConstants.NOT_BEFORE.get());
    QName notBeforeQNameWithNS = new QName(assertionNS, JBossSAMLConstants.NOT_BEFORE.get());

    QName notAfterQName = new QName("", JBossSAMLConstants.NOT_ON_OR_AFTER.get());
    QName notAfterQNameWithNS = new QName(assertionNS, JBossSAMLConstants.NOT_ON_OR_AFTER.get());

    Attribute notBeforeAttribute = conditionsElement.getAttributeByName(notBeforeQName);
    if (notBeforeAttribute == null)
      notBeforeAttribute = conditionsElement.getAttributeByName(notBeforeQNameWithNS);

    Attribute notAfterAttribute = conditionsElement.getAttributeByName(notAfterQName);
    if (notAfterAttribute == null)
      notAfterAttribute = conditionsElement.getAttributeByName(notAfterQNameWithNS);

    if (notBeforeAttribute != null) {
      String notBeforeValue = StaxParserUtil.getAttributeValue(notBeforeAttribute);
      conditions.setNotBefore(XMLTimeUtil.parse(notBeforeValue));
    }

    if (notAfterAttribute != null) {
      String notAfterValue = StaxParserUtil.getAttributeValue(notAfterAttribute);
      conditions.setNotOnOrAfter(XMLTimeUtil.parse(notAfterValue));
    }

    while (xmlEventReader.hasNext()) {
      XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
      if (xmlEvent instanceof EndElement) {
        EndElement end = StaxParserUtil.getNextEndElement(xmlEventReader);
        if (StaxParserUtil.matches(end, JBossSAMLConstants.CONDITIONS.get())) break;
      }
      startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
      if (startElement == null) break;
      String tag = StaxParserUtil.getStartElementName(startElement);

      if (SAML11Constants.AUDIENCE_RESTRICTION_CONDITION.equals(tag)) {
        startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
        SAML11AudienceRestrictionCondition restrictCond = new SAML11AudienceRestrictionCondition();

        startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
        if (StaxParserUtil.getStartElementName(startElement)
            .equals(JBossSAMLConstants.AUDIENCE.get())) {
          restrictCond.add(URI.create(StaxParserUtil.getElementText(xmlEventReader)));
        }
        EndElement theEndElement = StaxParserUtil.getNextEndElement(xmlEventReader);
        StaxParserUtil.validate(theEndElement, SAML11Constants.AUDIENCE_RESTRICTION_CONDITION);
        conditions.add(restrictCond);
      } else throw logger.parserUnknownTag(tag, startElement.getLocation());
    }
    return conditions;
  }
Exemplo n.º 18
0
 static boolean moveToResources(XMLEventReader eventReader) throws XMLStreamException {
   while (eventReader.hasNext()) {
     if (findNextStart(eventReader).getName().equals(TAG_RESOURCES)) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 19
0
  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;
        }
      }
    }
  }
Exemplo n.º 20
0
  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;
  }
Exemplo n.º 21
0
 static StartElement findNextStart(XMLEventReader eventReader) throws XMLStreamException {
   while (eventReader.hasNext()) {
     XMLEvent event = eventReader.nextEvent();
     if (event.isStartElement()) {
       return event.asStartElement();
     }
   }
   return null;
 }
  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;
  }
Exemplo n.º 23
0
  @Override
  public InputStream replaceProperty(
      final InputStream src,
      final InputStream replacement,
      final List<String> path,
      final boolean justValue)
      throws Exception {

    final List<String> pathElements = new ArrayList<String>();

    for (String element : path) {
      pathElements.add(Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + element);
    }

    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final Map.Entry<Integer, XMLElement> element =
        extractElement(reader, writer, pathElements, 0, 3, 4);

    if (justValue) {
      writer.add(element.getValue().getStart());
    }

    final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);

    while (changesReader.hasNext()) {
      final XMLEvent event = changesReader.nextEvent();
      if (event.isStartElement()
          && event.asStartElement().getName().equals(element.getValue().getStart().getName())) {
        writer.add(element.getValue().getStart());
        writer.add(changesReader);
      } else {
        writer.add(event);
      }
    }

    changesReader.close();
    IOUtils.closeQuietly(replacement);

    if (justValue) {
      writer.add(element.getValue().getEnd());
    }

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
  }
Exemplo n.º 24
0
  /** 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("");
  }
  private void copyEvents(int length) throws IOException {
    try {
      while (reader.hasNext() && stream.getInputStream().available() < length) {
        writer.add(reader.nextEvent());
      }

      writer.flush();
    } catch (XMLStreamException e) {
      throw new be.re.io.IOException(e);
    }
  }
Exemplo n.º 26
0
  public DataMetadata parse(XMLEventReader xmlEventReader, StartElement start)
      throws GraphIOException {

    try {
      // Create the new port.
      DataMetadata data = new DataMetadata();

      // Parse the attributes.
      @SuppressWarnings("unchecked")
      Iterator<Attribute> iterator = start.getAttributes();
      while (iterator.hasNext()) {
        Attribute attribute = (Attribute) iterator.next();
        String name = attribute.getName().getLocalPart();
        String value = attribute.getValue();
        if (data.getKey() == null && GraphMLConstants.KEY_NAME.equals(name)) {
          data.setKey(value);
        }
      }

      // Make sure the key has been set.
      if (data.getKey() == null) {
        throw new GraphIOException("Element 'data' is missing attribute 'key'");
      }

      while (xmlEventReader.hasNext()) {

        XMLEvent event = xmlEventReader.nextEvent();
        if (event.isStartElement()) {
          StartElement element = (StartElement) event;

          // Treat any child elements as unknown
          getUnknownParser().parse(xmlEventReader, element);
        }
        if (event.isCharacters()) {
          Characters characters = (Characters) event;
          data.setValue(characters.getData());
        }
        if (event.isEndElement()) {
          EndElement end = (EndElement) event;
          verifyMatch(start, end);
          break;
        }
      }

      return data;

    } catch (Exception e) {
      ExceptionConverter.convert(e);
    }

    return null;
  }
Exemplo n.º 27
0
 public Amplitude(XMLEventReader reader) throws XMLStreamException, SeisFileException {
   StartElement startE = StaxUtil.expectStartElement(ELEMENT_NAME, reader);
   publicID = StaxUtil.pullAttribute(startE, QuakeMLTagNames.publicId);
   while (reader.hasNext()) {
     XMLEvent e = reader.peek();
     if (e.isStartElement()) {
       String elName = e.asStartElement().getName().getLocalPart();
       if (elName.equals(QuakeMLTagNames.comment)) {
         commentList.add(new Comment(reader));
       } else if (elName.equals(QuakeMLTagNames.type)) {
         type = StaxUtil.pullText(reader, QuakeMLTagNames.type);
       } else if (elName.equals(QuakeMLTagNames.category)) {
         category = StaxUtil.pullText(reader, QuakeMLTagNames.category);
       } else if (elName.equals(QuakeMLTagNames.unit)) {
         unit = StaxUtil.pullText(reader, QuakeMLTagNames.unit);
       } else if (elName.equals(QuakeMLTagNames.methodID)) {
         methodID = StaxUtil.pullText(reader, QuakeMLTagNames.methodID);
       } else if (elName.equals(QuakeMLTagNames.snr)) {
         snr = StaxUtil.pullFloat(reader, QuakeMLTagNames.snr);
       } else if (elName.equals(QuakeMLTagNames.scalingTime)) {
         scalingTime = new Time(reader, QuakeMLTagNames.scalingTime);
       } else if (elName.equals(QuakeMLTagNames.timeWindow)) {
         timeWindow = new TimeWindow(reader);
       } else if (elName.equals(QuakeMLTagNames.waveformID)) {
         waveformID = new WaveformStreamID(reader, QuakeMLTagNames.waveformID);
       } else if (elName.equals(QuakeMLTagNames.filterID)) {
         filterID = StaxUtil.pullText(reader, QuakeMLTagNames.filterID);
       } else if (elName.equals(QuakeMLTagNames.magnitudeHint)) {
         magnitudeHint = StaxUtil.pullText(reader, QuakeMLTagNames.magnitudeHint);
       } else if (elName.equals(QuakeMLTagNames.pickID)) {
         pickID = StaxUtil.pullText(reader, QuakeMLTagNames.pickID);
       } else if (elName.equals(QuakeMLTagNames.period)) {
         period = new RealQuantity(reader, QuakeMLTagNames.period);
       } else if (elName.equals(QuakeMLTagNames.evaluationMode)) {
         evaluationMode = StaxUtil.pullText(reader, QuakeMLTagNames.evaluationMode);
       } else if (elName.equals(QuakeMLTagNames.evaluationStatus)) {
         evaluationStatus = StaxUtil.pullText(reader, QuakeMLTagNames.evaluationStatus);
       } else if (elName.equals(QuakeMLTagNames.genericAmplitude)) {
         genericAmplitude = new RealQuantity(reader, QuakeMLTagNames.genericAmplitude);
       } else if (elName.equals(QuakeMLTagNames.creationInfo)) {
         creationInfo = new CreationInfo(reader);
       } else {
         StaxUtil.skipToMatchingEnd(reader);
       }
     } else if (e.isEndElement()) {
       reader.nextEvent();
       return;
     } else {
       e = reader.nextEvent();
     }
   }
 }
Exemplo n.º 28
0
 /**
  * Read through a number of rows equal to the rowCacheSize field or until there is no more data to
  * read
  *
  * @return true if data was read
  */
 private boolean getRow() {
   try {
     rowCache.clear();
     while (rowCache.size() < rowCacheSize && parser.hasNext()) {
       handleEvent(parser.nextEvent());
     }
     rowCacheIterator = rowCache.iterator();
     return rowCacheIterator.hasNext();
   } catch (XMLStreamException | SAXException e) {
     LOGGER.debug("End of stream");
   }
   return false;
 }
Exemplo n.º 29
0
  public static void main(String[] args) {
    try {
      // FLUJO DE ESCRITURA
      XMLStreamWriter sw =
          XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream("autores.xml"));

      // ESCRITURA
      sw.writeStartDocument("1.0");
      sw.writeStartElement("autores");
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a1");
      sw.writeStartElement("nome");
      sw.writeCharacters("Alexandre Dumas");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("El conde de montecristo");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Los miserables");
      sw.writeEndElement();
      sw.writeEndElement();
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a2");
      sw.writeStartElement("nome");
      sw.writeCharacters("Fiodor Dostoyevski");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters(" El idiota");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Noches blancas");
      sw.writeEndDocument();
      sw.flush();
      sw.close();

      // FLUJO DE LECTURA
      XMLEventReader er =
          XMLInputFactory.newInstance()
              .createXMLEventReader("autores.xml", new FileInputStream("autores.xml"));

      // LECTURA
      while (er.hasNext()) {
        System.out.println(er.nextEvent().toString());
      }
      er.close();

    } catch (XMLStreamException | FileNotFoundException ex) {
      Logger.getLogger(XMLprueba0.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  public final ParserResult<T> parse(InputStream is, ParserTarget<T> target) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    XMLEventReader reader = factory.createXMLEventReader(is);

    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();
      handleEvent(event, reader, target);

      if (cancel) {
        break;
      }
    }
    return new ParserResult<>(target.getElementCount(), target.getElements(), type);
  }