Exemple #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;
  }
Exemple #2
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);
   }
 }
Exemple #3
0
 private static Book readBook(XMLEventReader eventReader) throws XMLStreamException {
   while (eventReader.hasNext()) {
     XMLEvent event = eventReader.nextEvent();
     if (event.isEndElement()) {}
   }
   return null;
 }
  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());
      }
    }
  }
  @Override
  public InputStream deleteProperty(final InputStream src, final List<String> path)
      throws Exception {
    final XMLEventReader reader = getEventReader(src);

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

    final XMLEventReader changesReader =
        new XMLEventReaderWrapper(
            IOUtils.toInputStream(
                String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)),
                Constants.ENCODING));

    writer.add(changesReader);
    changesReader.close();

    writer.add(reader);

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

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  private Object unmarshal0(XMLEventReader reader, JaxBeanInfo expectedType) throws JAXBException {
    if (reader == null) {
      throw new IllegalArgumentException(Messages.format(Messages.NULL_READER));
    }

    try {
      XMLEvent event = reader.peek();

      if (!event.isStartElement() && !event.isStartDocument()) {
        // TODO: convert event into event name
        throw new IllegalStateException(
            Messages.format(Messages.ILLEGAL_READER_STATE, event.getEventType()));
      }

      // Quick hack until SJSXP fixes 6270116
      boolean isZephyr = reader.getClass().getName().equals("com.sun.xml.stream.XMLReaderImpl");
      XmlVisitor h = createUnmarshallerHandler(null, false, expectedType);
      if (!isZephyr) {
        h = new InterningXmlVisitor(h);
      }
      new StAXEventConnector(reader, h).bridge();
      return h.getContext().getResult();
    } catch (XMLStreamException e) {
      throw handleStreamException(e);
    }
  }
  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);
    }
  }
  public void testInvalidUsage() throws XMLStreamException {
    String XML = "<?xml version='1.0' ?><root />";
    for (int i = 0; i < 4; ++i) {
      boolean ns = (i & 1) != 0;
      boolean coal = (i & 2) != 0;
      XMLEventReader er = getReader(XML, ns, coal);

      XMLEvent evt = er.nextEvent();

      // Let's try removal:
      String msg = null;
      try {
        er.remove();
        msg = "Was expecting UnsupportedOperationException for XMLEventReader.remove()";
      } catch (UnsupportedOperationException e) {; // good
      } catch (Throwable t) {
        msg =
            "Was expecting UnsupportedOperationException for XMLEventReader.remove(); instead got: "
                + t;
      }
      if (msg != null) {
        fail(msg);
      }
    }
  }
Exemple #9
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;
 }
 protected Object wbxmlStream2Object(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     if (jc == null) {
       jc = JAXBContext.newInstance(Class.forName(this.def.getClazz()));
     }
     Unmarshaller unmarshaller = jc.createUnmarshaller();
     if (event) {
       return unmarshaller.unmarshal(xmlEventReader);
     } else {
       return unmarshaller.unmarshal(xmlStreamReader);
     }
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
Exemple #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);
  }
  public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException {
    InputStream input = new ByteArrayInputStream(xml.getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    JsonXMLConfig config =
        new JsonXMLConfigBuilder()
            .autoArray(true)
            .autoPrimitive(true)
            .prettyPrint(formatted)
            .build();

    try {
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      writer.add(reader);
      reader.close();
      writer.close();
      try {
        return output.toString("UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new XMLStreamException(e.getMessage());
      }
    } finally {
      // dp nothing
    }
  }
  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());
  }
 protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     StAXSource staxSource =
         event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader);
     DOMResult domResult = new DOMResult();
     xformer.transform(staxSource, domResult);
     Document doc = (Document) domResult.getNode();
     doc.normalize();
     return doc;
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
  @Override
  public InputStream addEditLink(final InputStream content, final String title, final String href)
      throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);
    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

    final String editLinkElement =
        String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

    try {
      // check edit link existence
      extractElement(
          reader,
          writer,
          Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
          Collections.<Map.Entry<String, String>>singletonList(
              new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
          false,
          0,
          -1,
          -1);

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);
      writer.add(reader);

    } catch (Exception e) {
      reader.close();
      reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

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

      writer.add(entryElement.getStart());

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);

      writer.add(entryElement.getContentReader());
      writer.add(entryElement.getEnd());

      writer.add(reader);

      writer.flush();
      writer.close();
    } finally {
      reader.close();
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Exemple #16
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();
    }
  }
  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;
  }
  /** {@inheritDoc } */
  @Override
  protected Set<String> retrieveAllLinkNames(final InputStream is) throws Exception {
    final Set<String> links = new HashSet<String>();

    final XMLEventReader reader = getEventReader(is);

    try {

      int startDepth = 0;

      while (true) {
        final Map.Entry<Integer, XMLElement> linkInfo =
            extractElement(
                reader,
                null,
                Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                startDepth,
                2,
                2);

        startDepth = linkInfo.getKey();

        links.add(linkInfo.getValue().getStart().getAttributeByName(new QName("title")).getValue());
      }
    } catch (Exception ignore) {
      // ignore
    } finally {
      reader.close();
      IOUtils.closeQuietly(is);
    }

    return links;
  }
  /** {@inheritDoc } */
  @Override
  protected InputStream addLinks(
      final String entitySetName,
      final String entitykey,
      final InputStream is,
      final Set<String> links)
      throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final XMLEventReader reader = getEventReader(is);
    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);
    // -----------------------------------------
    final Map.Entry<Integer, XMLElement> entry =
        extractElement(reader, writer, Collections.singletonList("entry"), 0, 1, 1);

    writer.add(entry.getValue().getStart());

    final Map<String, NavigationProperty> navigationProperties =
        metadata.getNavigationProperties(entitySetName);

    // add for links
    for (String link : links) {
      final Set<Attribute> attributes = new HashSet<Attribute>();
      attributes.add(eventFactory.createAttribute(new QName("title"), link));
      attributes.add(
          eventFactory.createAttribute(
              new QName("href"), Commons.getLinksURI(entitySetName, entitykey, link)));
      attributes.add(
          eventFactory.createAttribute(
              new QName("rel"), Constants.get(ConstantKey.ATOM_LINK_REL) + link));
      attributes.add(
          eventFactory.createAttribute(
              new QName("type"),
              navigationProperties.get(link).isEntitySet()
                  ? Constants.get(ConstantKey.ATOM_LINK_FEED)
                  : Constants.get(ConstantKey.ATOM_LINK_ENTRY)));

      writer.add(
          eventFactory.createStartElement(
              new QName(Constants.get(ConstantKey.LINK)), attributes.iterator(), null));
      writer.add(eventFactory.createEndElement(new QName(Constants.get(ConstantKey.LINK)), null));
    }

    writer.add(entry.getValue().getContentReader());
    writer.add(entry.getValue().getEnd());
    writer.add(reader);
    IOUtils.closeQuietly(is);

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
Exemple #20
0
 private static FeldXml createFeldXmlFrom(final String resource) throws XMLStreamException {
   XMLEventReader parser = createXMLEventReader(resource);
   try {
     return new FeldXml(parser);
   } finally {
     parser.close();
   }
 }
Exemple #21
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;
        }
      }
    }
  }
 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;
  }
Exemple #24
0
  public void testNextTagInvalid() throws XMLStreamException {
    String XML = "<root>   non-empty<leaf /></root>";
    String XML2 = "<root><leaf></leaf>text   </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.nextEvent().getEventType());
      String msg = null;
      try {
        XMLEvent evt = er.nextTag();
        msg =
            "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on non-empty CHARACTERS";
      } catch (XMLStreamException sex) {
        // fine!
      } catch (Throwable t) {
        msg =
            "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on non-empty CHARACTERS; got ("
                + t.getClass()
                + "): "
                + t;
      }
      if (msg != null) {
        fail(msg);
      }
      er.close();

      /* any other easily failing cases? Maybe if we are on top of
       * END_ELEMENT, and will hit another one?
       */
      er = getReader(XML2, ns, coal);
      assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
      assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
      assertTokenType(END_ELEMENT, er.nextEvent().getEventType());

      try {
        XMLEvent evt = er.nextTag();
        msg =
            "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on END_ELEMENT and hitting non-ws text; got event "
                + tokenTypeDesc(evt);
      } catch (XMLStreamException sex) {
        msg = null; // fine!
      } catch (Throwable t) {
        msg =
            "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on END_ELEMENT and hitting non-ws text; got: "
                + t;
      }
      if (msg != null) {
        fail(msg);
      }
      er.close();
    }
  }
Exemple #25
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());
    }
  }
Exemple #26
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);
    }
  }
 static XmlResourceValue parseStyle(XMLEventReader eventReader, StartElement start)
     throws XMLStreamException {
   Map<String, String> values = new HashMap<>();
   for (XMLEvent element = eventReader.nextTag();
       !isEndTag(element, TAG_STYLE);
       element = eventReader.nextTag()) {
     if (isItem(element)) {
       values.put(getElementName(element.asStartElement()), eventReader.getElementText());
     }
   }
   return StyleXmlResourceValue.of(parseReferenceFromElementAttribute(start, ATTR_PARENT), values);
 }
  @SuppressWarnings({"unchecked"})
  private JaxbHibernateConfiguration unmarshal(
      XMLEventReader staxEventReader, final Origin origin) {
    XMLEvent event;
    try {
      event = staxEventReader.peek();
      while (event != null && !event.isStartElement()) {
        staxEventReader.nextEvent();
        event = staxEventReader.peek();
      }
    } catch (Exception e) {
      throw new HibernateException("Error accessing stax stream", e);
    }

    if (event == null) {
      throw new HibernateException("Could not locate root element");
    }

    if (!isNamespaced(event.asStartElement())) {
      // if the elements are not namespaced, wrap the reader in a reader which will namespace them
      // as pulled.
      log.debug(
          "cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information");
      staxEventReader =
          new NamespaceAddingEventReader(staxEventReader, HIBERNATE_CONFIGURATION_URI);
    }

    final Object target;
    final ContextProvidingValidationEventHandler handler =
        new ContextProvidingValidationEventHandler();
    try {
      JAXBContext jaxbContext = JAXBContext.newInstance(JaxbHibernateConfiguration.class);
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      unmarshaller.setSchema(schema());
      unmarshaller.setEventHandler(handler);
      target = unmarshaller.unmarshal(staxEventReader);
      return (JaxbHibernateConfiguration) target;
    } catch (JAXBException e) {
      StringBuilder builder = new StringBuilder();
      builder
          .append("Unable to perform unmarshalling at line number ")
          .append(handler.getLineNumber())
          .append(" and column ")
          .append(handler.getColumnNumber())
          .append(" in ")
          .append(origin.getType().name())
          .append(" ")
          .append(origin.getName())
          .append(". Message: ")
          .append(handler.getMessage());
      throw new ConfigurationException(builder.toString(), e);
    }
  }
Exemple #30
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();
     }
   }
 }