@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());
  }
  @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());
  }
  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();
    }
  }
  @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());
  }
 public void close() {
   try {
     parser.close();
   } catch (XMLStreamException e) {
     throw new CloseException(e);
   }
 }
  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());
  }
  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);
    }
  }
  /** {@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;
  }
  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();
    }
  }
 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) {
       }
     }
   }
 }
 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) {
       }
     }
   }
 }
  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
    }
  }
  /** {@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());
  }
 /** @see IBailsStream#close() */
 @Override
 public void close() {
   try {
     parser.close(); // Close the STAX stream.
   } catch (XMLStreamException e) {
     System.out.println("SORT THIS OUT!: " + e.getMessage());
   }
 }
Exemple #15
0
 private static FeldXml createFeldXmlFrom(final String resource) throws XMLStreamException {
   XMLEventReader parser = createXMLEventReader(resource);
   try {
     return new FeldXml(parser);
   } finally {
     parser.close();
   }
 }
  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;
  }
 /**
  * Close the current opened stream.
  *
  * @throws IOException
  */
 protected void closeStream() throws IOException {
   try {
     beforeEndDocument();
     reader.close();
   } catch (XMLStreamException e) {
     throw new IOException(e);
   } finally {
     reader = null;
   }
 }
Exemple #18
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("");
  }
  @Override
  protected InputStream replaceLink(
      final InputStream toBeChanged, final String linkName, final InputStream replacement)
      throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

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

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

    try {
      final XMLElement linkElement =
          extractElement(
                  reader,
                  writer,
                  Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                  Collections.<Map.Entry<String, String>>singletonList(
                      new SimpleEntry<String, String>("title", linkName)),
                  false,
                  0,
                  -1,
                  -1)
              .getValue();
      writer.add(linkElement.getStart());

      // ------------------------------------------
      // write inline ...
      // ------------------------------------------
      writer.add(newLine);
      writer.add(eventFactory.createStartElement("m", null, "inline"));

      addAtomElement(replacement, writer);

      writer.add(eventFactory.createEndElement("m", null, "inline"));
      writer.add(newLine);
      // ------------------------------------------

      writer.add(linkElement.getEnd());

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @Override
  public Map.Entry<String, List<String>> extractLinkURIs(final InputStream is) throws Exception {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(is, bos);
    IOUtils.closeQuietly(is);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));
    final List<String> links = new ArrayList<String>();
    try {
      while (true) {
        links.add(
            IOUtils.toString(
                extractElement(reader, null, Collections.<String>singletonList("uri"), 0, -1, -1)
                    .getValue()
                    .getContent()));
      }
    } catch (Exception ignore) {
      // End document reached ...
    }
    reader.close();

    String next;

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));
    try {
      next =
          IOUtils.toString(
              extractElement(reader, null, Collections.<String>singletonList("next"), 0, -1, -1)
                  .getValue()
                  .getContent());
    } catch (Exception ignore) {
      // next link is not mandatory
      next = null;
    }
    reader.close();

    return new AbstractMap.SimpleEntry<String, List<String>>(next, links);
  }
  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 JaxbHibernateConfiguration unmarshal(InputStream stream, Origin origin) {
   try {
     XMLEventReader staxReader = staxFactory().createXMLEventReader(stream);
     try {
       return unmarshal(staxReader, origin);
     } finally {
       try {
         staxReader.close();
       } catch (Exception ignore) {
       }
     }
   } catch (XMLStreamException e) {
     throw new HibernateException("Unable to create stax reader", e);
   }
 }
    public FilePath[] invoke(File f, VirtualChannel channel)
        throws IOException, InterruptedException {
      FilePath[] r = new FilePath(f).list(reportFilePath);

      XMLInputFactory factory = XMLInputFactory.newInstance();
      factory.setProperty("javax.xml.stream.supportDTD", false);

      for (FilePath filePath : r) {
        InputStream is = null;
        XMLEventReader reader = null;
        try {
          is = filePath.read();
          reader = factory.createXMLEventReader(is);
          while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
              StartElement start = (StartElement) event;
              if (start.getName().getLocalPart().equals("coverage")) {
                // This is a cobertura coverage report file
                break;
              } else {
                throw new IOException(
                    filePath
                        + " is not a cobertura coverage report, please check your report pattern");
              }
            }
          }
        } catch (XMLStreamException e) {
          throw new IOException(filePath + " is not an XML file, please check your report pattern");
        } finally {
          try {
            if (reader != null) {
              try {
                reader.close();
              } catch (XMLStreamException ex) {
                //
              }
            }
          } finally {
            IOUtils.closeQuietly(is);
          }
        }
      }
      return r;
    }
  private int countFeedElements(final InputStream is, final String elementName)
      throws XMLStreamException {
    final XMLEventReader reader = getEventReader(is);

    int count = 0;

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

      if (event.getEventType() == XMLStreamConstants.START_ELEMENT
          && elementName.equals(event.asStartElement().getName().getLocalPart())) {
        count++;
      }
    }

    reader.close();
    return count;
  }
Exemple #25
0
 public static GoTree parse(Reader xmlIn) throws IOException, XMLStreamException {
   GoTree tree = new GoTree();
   XMLInputFactory fact = XMLInputFactory.newFactory();
   fact.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
   XMLEventReader r = fact.createXMLEventReader(xmlIn);
   while (r.hasNext()) {
     XMLEvent evt = r.nextEvent();
     if (evt.isStartElement()) {
       StartElement E = evt.asStartElement();
       QName qN = E.getName();
       if (qN.getLocalPart().equals("term") && NS.equals(qN.getNamespaceURI())) {
         tree.parseTerm(E, r);
       }
     }
   }
   r.close();
   return tree;
 }
 public static void parse(
     XMLInputFactory xmlInputFactory,
     Path source,
     FullyQualifiedName fileKey,
     FullyQualifiedName.Factory fqnFactory,
     KeyValueConsumer<DataKey, DataResource> overwritingConsumer,
     KeyValueConsumer<DataKey, DataResource> combiningConsumer)
     throws IOException, XMLStreamException {
   ImmutableSet.Builder<String> newIds = ImmutableSet.builder();
   try (BufferedInputStream inStream = new BufferedInputStream(Files.newInputStream(source))) {
     XMLEventReader eventReader =
         xmlInputFactory.createXMLEventReader(inStream, StandardCharsets.UTF_8.toString());
     // Go through every start tag and look at the values of all attributes (the attribute does
     // not need to be android:id, e.g., android:layout_above="@+id/UpcomingView").
     // If the any attribute's value begins with @+id/, then track it, since aapt seems to be
     // forgiving and allow even non-android namespaced attributes to define a new ID.
     while (eventReader.hasNext()) {
       XMLEvent event = eventReader.nextEvent();
       if (event.isStartElement()) {
         StartElement start = event.asStartElement();
         Iterator<Attribute> attributes = XmlResourceValues.iterateAttributesFrom(start);
         while (attributes.hasNext()) {
           Attribute attribute = attributes.next();
           String value = attribute.getValue();
           if (value.startsWith(SdkConstants.NEW_ID_PREFIX)) {
             String idName = value.substring(SdkConstants.NEW_ID_PREFIX.length());
             newIds.add(idName);
           }
         }
       }
     }
     eventReader.close();
   }
   ImmutableSet<String> idResources = newIds.build();
   overwritingConsumer.consume(fileKey, DataValueFile.of(source));
   for (String id : idResources) {
     combiningConsumer.consume(
         fqnFactory.create(ResourceType.ID, id),
         DataResourceXml.createWithNoNamespace(source, IdXmlResourceValue.of()));
   }
 }
  private void read(Source source) throws IOException, XMLStreamException {

    // Read in XML, extracting and removing the updates list in the process
    StringWriter buffer = new StringWriter(BUFFER_SIZE);
    XMLEventWriter eventWriter = this.xmlOutputFactory.createXMLEventWriter(buffer);
    XMLEventReader eventReader = this.xmlInputFactory.createXMLEventReader(source);
    UpdatesXMLEventReader updatesReader = new UpdatesXMLEventReader(eventReader);
    eventWriter.add(updatesReader);
    eventWriter.close();
    eventReader.close();

    // Was the update list found?
    List<String> updateNames = updatesReader.getUpdates();
    if (updateNames == null)
      throw new PersistentObjectException("XML file does not contain an updates list");

    // Save current content (without updates) and updates list
    this.current = buffer.toString();
    this.updates.clear();
    this.updates.addAll(updateNames);
  }
  public void testEncodingXmlEventReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();
    XMLEventReader reader = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
      // enter text encoded with Latin1
      reader =
          context
              .getTypeConverter()
              .mandatoryConvertTo(
                  XMLEventReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);

      output = new ByteArrayOutputStream();
      // ensure UTF-8 encoding
      Exchange exchange = new DefaultExchange(context);
      exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
      writer =
          context.getTypeConverter().mandatoryConvertTo(XMLEventWriter.class, exchange, output);
      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    assertNotNull(output);

    String result = new String(output.toByteArray(), UTF_8.name());

    boolean equals =
        TEST_XML_WITH_XML_HEADER.equals(result)
            || TEST_XML_WITH_XML_HEADER_ISO_8859_1.equals(result);
    assertTrue("Should match header", equals);
  }
Exemple #29
0
  private int xml_cmp(InputPort f1, InputPort f2)
      throws InvalidArgumentException, CoreException, XMLStreamException {

    /*
    XMLInputFactory inputFactory=XMLInputFactory.newInstance();


    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.valueOf(true));
    inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.valueOf(false));
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.valueOf(false));
     */

    SerializeOpts opts = getSerializeOpts().clone();
    opts.setSupports_dtd(false);

    XMLEventReader xmlreader1 = f1.asXMLEventReader(opts);

    XMLEventReader xmlreader2 = f2.asXMLEventReader(opts);

    try {

      while (xmlreader1.hasNext() && xmlreader2.hasNext()) {

        XMLEvent e1 = xmlreader1.nextEvent();

        /*
         * DAL: Note: skip START_DOCUMENT tags on either e1 or e2
         * StAX only produdes START_DOCUMENT tags if there is an <?xml?> declaration
         * which doesnt change the logical meaning of the document wrt to comparison
         */
        if (e1.getEventType() == XMLStreamConstants.START_DOCUMENT && xmlreader1.hasNext())
          e1 = xmlreader1.nextEvent();
        XMLEvent e2 = xmlreader2.nextEvent();
        if (e2.getEventType() == XMLStreamConstants.START_DOCUMENT && xmlreader2.hasNext())
          e2 = xmlreader2.nextEvent();

        /*
         * If ignoring blanks then entirely skip any element which is charactors and entirely blank
         */
        if (bopt || copt || popt) {
          while (((bopt
                      && (e1.getEventType() == XMLStreamConstants.CHARACTERS)
                      && isBlank(e1.asCharacters()))
                  || (copt && e1.getEventType() == XMLStreamConstants.COMMENT)
                  || (popt && e1.getEventType() == XMLStreamConstants.PROCESSING_INSTRUCTION))
              && xmlreader1.hasNext()) e1 = xmlreader1.nextEvent();

          while (((bopt
                      && (e2.getEventType() == XMLStreamConstants.CHARACTERS)
                      && isBlank(e2.asCharacters()))
                  || (copt && e2.getEventType() == XMLStreamConstants.COMMENT)
                  || (popt && e2.getEventType() == XMLStreamConstants.PROCESSING_INSTRUCTION))
              && xmlreader2.hasNext()) e2 = xmlreader2.nextEvent();
        }

        if (!isEqual(e1, e2)) {
          Location loc = e1.getLocation();
          if (!nopt) printErr("xml diff at file1: " + loc.toString());

          return 2;
        }
      }
      return ((!xmlreader1.hasNext()) && (!xmlreader2.hasNext())) ? 0 : 1;
    } finally {
      try {
        xmlreader1.close();

      } finally {
      }
      try {
        xmlreader2.close();

      } finally {
      }
    }
  }
Exemple #30
0
  private void loadWorld() throws IOException, XMLStreamException {
    Source source;
    warning("openingg " + svgMapUri);
    if (IOUtils.isRemoteURI(svgMapUri)) {
      source = new StreamSource(svgMapUri);
    } else {
      source = new StreamSource(new File(svgMapUri));
    }

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLEventReader xef = xif.createXMLEventReader(source);
    while (xef.hasNext()) {
      XMLEvent evt = xef.nextEvent();
      if (!evt.isStartElement()) {
        continue;
      }
      StartElement E = evt.asStartElement();
      String localName = E.getName().getLocalPart();
      if (!localName.equals("path")) continue;
      Attribute att = E.getAttributeByName(new QName("id"));
      if (att == null) continue;
      String country = att.getValue().toLowerCase().replaceAll("[ ]+", "");
      att = E.getAttributeByName(new QName("d"));
      if (att == null) continue;
      GeneralPath path = null;
      char op = '\0';
      Scanner scanner = new Scanner(att.getValue().replaceAll("[ \t\n\r,]+", " "));
      path = new GeneralPath();

      while (scanner.hasNext()) {
        if (op == '\0') {
          op = scanner.next().charAt(0);
        }
        switch (op) {
          case 'M':
            path.moveTo(scanner.nextDouble(), scanner.nextDouble());
            break;
          case 'C':
            path.curveTo(
                scanner.nextDouble(),
                scanner.nextDouble(),
                scanner.nextDouble(),
                scanner.nextDouble(),
                scanner.nextDouble(),
                scanner.nextDouble());
            break;
          case 'Z':
            {
              path.closePath();

              break;
            }
          default:
            throw new IOException("bad operator " + op);
        }
        if (scanner.hasNext("[MCZ]")) {
          op = scanner.next().charAt(0);
        }
      }
      scanner.close();
      this.country2shape.put(country, scaleWorld(path));
    }
    xef.close();
  }