Example #1
0
  private static void eventWriter(OutputStream out) throws XMLStreamException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    // factory.setProperty(name, value);

    XMLEventWriter writer = factory.createXMLEventWriter(out);
    XMLEventFactory ef = XMLEventFactory2.newInstance();

    StartDocument startDocument = ef.createStartDocument("UTF-8", "1.0");
    writer.add(startDocument);

    StartElement booksStartElement = ef.createStartElement("bk", Const.NSURI_BOOK, "books");
    writer.add(booksStartElement);
    writer.add(ef.createNamespace("bk", Const.NSURI_BOOK));

    for (int i = 0; i < Const.NODE_COUNTS_L; ++i) {
      writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "book"));
      writer.add(ef.createAttribute("id", String.valueOf(i + 1)));

      writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "name"));
      writer.add(ef.createCharacters("Name" + (i + 1)));
      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "name"));

      writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "author"));
      writer.add(ef.createCharacters("author" + (i + 1)));
      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "author"));

      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "book"));
    }
    writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "books"));
    writer.add(ef.createEndDocument());
    writer.close();
  }
Example #2
0
  public XmlWriter(File output) throws FileNotFoundException, WriterException {
    this.xmlFile = output;
    System.out.println("setting up xml");
    if (output.exists()) {
      System.out.println("deleting existing file: " + output);
      output.delete();
    }

    try {
      FileOutputStream fos = new FileOutputStream(output);
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      eventWriter = outputFactory.createXMLEventWriter(fos);

      eventFactory = XMLEventFactory.newInstance();

      end = eventFactory.createDTD("\n");

      // Create and write Start Tag
      StartDocument startDocument = eventFactory.createStartDocument();
      eventWriter.add(startDocument);

      StartElement configStartElement = eventFactory.createStartElement("", "", DOC_ELEMENT_NAME);
      eventWriter.add(configStartElement);
      eventWriter.add(end);
    } catch (XMLStreamException e) {
      throw new WriterException("unable to instantiate writer to file: " + output, e);
    }
  }
Example #3
0
  public static String marshal(
      Object msg, String msgQName, String msgLocalName, String[] userPackages) throws Exception {

    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
      String userPackage = userPackages[i];
      contextPackages.add(userPackage);
    }

    JAXBContext jaxbContext =
        JAXBUtils.getJAXBContext(
            contextPackages,
            constructionType,
            contextPackages.toString(),
            XmlUtils.class.getClassLoader(),
            new HashMap<String, Object>());
    Marshaller marshaller = JAXBUtils.getJAXBMarshaller(jaxbContext);

    JAXBElement jaxbRequest =
        new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);
    Writer writer = new StringWriter();

    // Support XMLDsig
    XMLEventWriter xmlWriter = staxOF.createXMLEventWriter(writer);
    marshaller.marshal(jaxbRequest, xmlWriter);
    xmlWriter.flush();
    JAXBUtils.releaseJAXBMarshaller(jaxbContext, marshaller);

    return writer.toString();
  }
 public void dumpTo(OutputStream outputStream)
     throws FileNotFoundException, UnsupportedEncodingException, XMLStreamException, SQLException {
   out = outputFactory.createXMLEventWriter(new OutputStreamWriter(outputStream, "UTF-8"));
   startDocument();
   dumpTo(profile.rootTable(), 0);
   endDocument();
 }
  @Test
  public void testMailWithNamespacePrefix() throws FileNotFoundException, XMLStreamException {
    final String XMLNS = "http://sourceforge.org";
    final String XMLNS_FHJ = "http://fh-joanneum.at";

    XMLEventWriter writer = factory.createXMLEventWriter(System.out);
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    writer.add(eventFactory.createStartDocument("UTF-8", "1.0", true));

    writer.add(eventFactory.createStartElement("fhj", XMLNS_FHJ, "mail"));
    writer.add(eventFactory.createNamespace(XMLNS));
    writer.add(eventFactory.createNamespace("fhj", XMLNS_FHJ));
    writer.add(eventFactory.createAttribute("from", "*****@*****.**"));

    writer.add(eventFactory.createStartElement("fhj", XMLNS, "to"));
    writer.add(eventFactory.createCharacters("*****@*****.**"));
    writer.add(eventFactory.createEndElement("fhj", XMLNS, "to"));

    writer.add(eventFactory.createStartElement("", XMLNS, "subject"));
    writer.add(eventFactory.createCharacters("Some Informations"));
    writer.add(eventFactory.createEndElement("", XMLNS, "subject"));

    // ...

    writer.add(eventFactory.createEndElement("", XMLNS, "mail"));

    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }
  protected static XMLEventWriter getEventWriter(final OutputStream os) throws XMLStreamException {
    if (ofactory == null) {
      ofactory = XMLOutputFactory.newInstance();
    }

    return ofactory.createXMLEventWriter(os, "UTF-8");
  }
Example #7
0
 @Converter
 public XMLEventWriter createXMLEventWriter(Writer writer) throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLEventWriter(IOHelper.buffered(writer));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
Example #8
0
 @Converter
 public XMLEventWriter createXMLEventWriter(OutputStream out, Exchange exchange)
     throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLEventWriter(
         IOHelper.buffered(out), IOHelper.getCharsetName(exchange));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
 protected byte[] object2WbXml(
     Object o,
     WbXmlDefinition def,
     WbXmlVersion version,
     WbXmlEncoder.StrtblType encoderType,
     boolean skipSpaces,
     boolean event)
     throws Exception {
   XMLStreamWriter xmlStreamWriter = null;
   XMLEventWriter xmlEventWriter = null;
   ByteArrayOutputStream out = null;
   try {
     out = new ByteArrayOutputStream();
     outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType);
     outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces);
     outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version);
     outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def);
     if (event) {
       xmlEventWriter = outFact.createXMLEventWriter(out);
     } else {
       xmlStreamWriter = outFact.createXMLStreamWriter(out);
     }
     JAXBContext jc = JAXBContext.newInstance(o.getClass());
     Marshaller marshaller = jc.createMarshaller();
     if (event) {
       marshaller.marshal(o, xmlEventWriter);
     } else {
       marshaller.marshal(o, xmlStreamWriter);
     }
     return out.toByteArray();
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (Exception e) {
       }
     }
     if (xmlStreamWriter != null) {
       try {
         xmlStreamWriter.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventWriter != null) {
       try {
         xmlEventWriter.close();
       } catch (Exception e) {
       }
     }
   }
 }
  public void testXMLEventWriter() throws Exception {
    FlushRoot control = getControlObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    XMLOutputFactory xof = XMLOutputFactory.newFactory();
    XMLEventWriter xew = xof.createXMLEventWriter(baos);
    marshaller.marshal(control, xew);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLEventReader xer = xif.createXMLEventReader(new ByteArrayInputStream(baos.toByteArray()));
    Object test = unmarshaller.unmarshal(xer);

    assertEquals(control, test);
  }
 protected byte[] doc2WbXml(
     Document doc,
     WbXmlDefinition def,
     WbXmlVersion version,
     WbXmlEncoder.StrtblType encoderType,
     boolean skipSpaces,
     boolean event)
     throws Exception {
   XMLStreamWriter xmlStreamWriter = null;
   XMLEventWriter xmlEventWriter = null;
   ByteArrayOutputStream out = null;
   try {
     out = new ByteArrayOutputStream();
     outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType);
     outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces);
     outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version);
     outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def);
     if (event) {
       xmlEventWriter = outFact.createXMLEventWriter(out);
     } else {
       xmlStreamWriter = outFact.createXMLStreamWriter(out);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     Source domSource = new DOMSource(doc);
     StAXResult staxResult =
         (event) ? new StAXResult(xmlEventWriter) : new StAXResult(xmlStreamWriter);
     xformer.transform(domSource, staxResult);
     return out.toByteArray();
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (Exception e) {
       }
     }
     if (xmlStreamWriter != null) {
       try {
         xmlStreamWriter.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventWriter != null) {
       try {
         xmlEventWriter.close();
       } catch (Exception e) {
       }
     }
   }
 }
Example #12
0
 @Converter
 public XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     if (result instanceof DOMResult && !isWoodstox(factory)) {
       // FIXME - if not woodstox, this will likely not work well
       // likely should copy CXF's W3CDOM stuff
       LOG.info(
           "DOMResult is known to have issues with {0}. We suggest using Woodstox",
           factory.getClass());
     }
     return factory.createXMLEventWriter(result);
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
  public void testObjectToXMLEventWriter() throws Exception {
    if (XML_OUTPUT_FACTORY != null) {
      StringWriter writer = new StringWriter();

      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      factory.setProperty(factory.IS_REPAIRING_NAMESPACES, new Boolean(false));
      XMLEventWriter eventWriter = factory.createXMLEventWriter(writer);

      Object objectToWrite = getWriteControlObject();
      XMLDescriptor desc = null;
      if (objectToWrite instanceof XMLRoot) {
        desc =
            (XMLDescriptor)
                xmlContext
                    .getSession(0)
                    .getProject()
                    .getDescriptor(((XMLRoot) objectToWrite).getObject().getClass());
      } else {
        desc =
            (XMLDescriptor)
                xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass());
      }
      jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/xml");

      int sizeBefore = getNamespaceResolverSize(desc);
      try {
        jaxbMarshaller.marshal(objectToWrite, eventWriter);
      } catch (Exception e) {
        assertMarshalException(e);
        return;
      }
      if (expectsMarshalException) {
        fail("An exception should have occurred but didn't.");
        return;
      }

      eventWriter.flush();
      int sizeAfter = getNamespaceResolverSize(desc);

      assertEquals(sizeBefore, sizeAfter);
      Document testDocument = getTestDocument(writer.toString());
      writer.close();
      objectToXMLDocumentTest(testDocument);
    }
  }
  @Test
  public void testMail() throws FileNotFoundException, XMLStreamException {
    // XMLEventWriter instances are created using the XMLOutputFactory.
    XMLEventWriter writer = factory.createXMLEventWriter(System.out);

    // To add an XMLEvent object, we must obtain an EMLEvent object
    // using an implementation of the abstract class XMLEventFactory.
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    // The XMLEventFactory has a series of methods for creating
    // various event objects.
    writer.add(eventFactory.createStartDocument("UTF-8", "1.0", true));
    writer.add(eventFactory.createStartElement("", "", "mail"));
    writer.add(eventFactory.createAttribute("from", "*****@*****.**"));

    writer.add(eventFactory.createStartElement("", "", "to"));
    writer.add(eventFactory.createCharacters("*****@*****.**"));
    writer.add(eventFactory.createEndElement("", "", "to"));

    writer.add(eventFactory.createStartElement("", "", "to"));
    writer.add(eventFactory.createCharacters("*****@*****.**"));
    writer.add(eventFactory.createEndElement("", "", "to"));

    writer.add(eventFactory.createStartElement("", "", "cc"));
    writer.add(eventFactory.createEndElement("", "", "cc"));

    writer.add(eventFactory.createStartElement("", "", "subject"));
    writer.add(eventFactory.createCharacters("Some Informations"));
    writer.add(eventFactory.createEndElement("", "", "subject"));

    writer.add(eventFactory.createStartElement("", "", "text"));
    writer.add(
        eventFactory.createCData(
            "\n" + "<p>\n" + "    <h1> This is a simple mail message! </h1>\n" + "</p>\n" + "\n"));
    writer.add(eventFactory.createEndElement("", "", "text"));

    writer.add(eventFactory.createEndElement("", "", "mail"));
    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }
Example #15
0
  static {
    ssoContextPackages.add(JossoConstants.JOSSO_PROTOCOL_PKG);

    javax.xml.parsers.DocumentBuilderFactory dbf =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();

    javax.xml.parsers.SAXParserFactory saxf = SAXParserFactory.newInstance();

    try {
      logger.debug("DocumentBuilder = " + dbf.newDocumentBuilder());
      logger.debug("SAXParser = " + saxf.newSAXParser());
      logger.debug(
          "XMLEventReader = " + staxIF.createXMLEventReader(new StringSource("<a>Hello</a>")));
      logger.debug("XMLEventWriter = " + staxOF.createXMLEventWriter(new ByteArrayOutputStream()));
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage(), e);
    } catch (SAXException e) {
      logger.error(e.getMessage(), e);
    } catch (XMLStreamException e) {
      logger.error(e.getMessage(), e);
    }
  }
  private void scramble(EFile input) throws XMLStreamException, IOException {
    File output =
        new File(
            input.getParentFile(),
            input.getNameMinusExtension() + ".scrambled." + input.getExtension());

    Map<String, Object> xifProperties = null;
    Map<String, Object> xofProperties = null;
    XMLInputFactory xif = null;
    XMLOutputFactory xof = null;
    XMLEventWriter writer = null;
    XMLEventFactory xef = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      xifProperties = StAXInputFactoryPool.getInstance().getDefaultPropertyMap(false);
      xofProperties = StAXOutputFactoryPool.getInstance().getDefaultPropertyMap();
      xif = StAXInputFactoryPool.getInstance().acquire(xifProperties);
      xif.setXMLResolver(new StaxEntityResolver(CatalogEntityResolver.getInstance()));
      xof = StAXOutputFactoryPool.getInstance().acquire(xofProperties);
      xef = StAXEventFactoryPool.getInstance().acquire();
      fis = new FileInputStream(input);
      fos = new FileOutputStream(output);

      XMLEventReader baseReader = xif.createXMLEventReader(fis);
      writer = xof.createXMLEventWriter(fos);
      BookmarkedXMLEventReader reader = new BookmarkedXMLEventReader(baseReader);
      ContextStack context = new ContextStack(true);

      boolean skipElemTextScrambling = false;
      int c = 0;
      while (reader.hasNext()) {
        XMLEvent xe = reader.nextEvent();
        context.addEvent(xe);
        if (xe.isStartElement()) {
          skipElemTextScrambling = shouldSkip(xe.asStartElement());
          if (isMetaElement(xe.asStartElement())) {
            xe = handleMetaElement(xe.asStartElement(), xef);
          } else if (isImageElement(xe.asStartElement())) {
            xe = handleImageElement(xe.asStartElement(), xef);
          } else if (isAcronymElement(xe.asStartElement())) {
            xe = handleAcronymElement(xe.asStartElement(), xef);
          } else if (isLinkElement(xe.asStartElement())) {
            xe = handleLinkElement(xe.asStartElement(), xef);
          } else if (isAnchorElement(xe.asStartElement())) {
            xe = handleAnchorElement(xe.asStartElement(), xef);
          }
        } else if (xe.isCharacters()
            && !skipElemTextScrambling
            && !CharUtils.isXMLWhiteSpace(xe.asCharacters().getData())) {
          xe =
              xef.createCharacters(
                  "["
                      + Integer.toString(++c)
                      + "] "
                      + context.getContextXPath(
                          ContextStack.XPATH_SELECT_ELEMENTS_ONLY,
                          ContextStack.XPATH_PREDICATES_NONE));
        } else if (xe.getEventType() == XMLEvent.PROCESSING_INSTRUCTION) {
          xe = handleProcessingInstruction((ProcessingInstruction) xe, xef);
        } else if (xe.isEndElement()) {
          skipElemTextScrambling = false;
        }
        if (xe != null) writer.add(xe);
      }

    } catch (CatalogExceptionNotRecoverable e) {
      e.printStackTrace();
    } finally {
      fis.close();
      fos.close();
      writer.flush();
      writer.close();
      StAXInputFactoryPool.getInstance().release(xif, xifProperties);
      StAXOutputFactoryPool.getInstance().release(xof, xofProperties);
      StAXEventFactoryPool.getInstance().release(xef);
    }
  }
  /**
   * Write to xml.
   *
   * @param d the d
   * @return the string
   * @throws XMLStreamException the xML stream exception
   */
  public final String writeToXML(final DatatypeDesc d) throws XMLStreamException {
    // Create a XMLOutputFactory
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    // Create XMLEventWriter
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(bout);
    // Create a EventFactory
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    //		end = eventFactory.createDTD("\n");
    XMLEvent end = eventFactory.createCharacters("\n");
    //		XMLEvent tab = eventFactory.createCharacters("\t");
    // Create and write Start Tag
    StartDocument startDocument = eventFactory.createStartDocument();
    eventWriter.add(startDocument);

    // Create config open tag
    StartElement startElement = eventFactory.createStartElement(PREFIX, URI, "datatypeDesc");
    eventWriter.add(startElement);
    eventWriter.add(eventFactory.createNamespace(PREFIX, URI));

    // TODO namespace und schema einkommentieren
    // eventWriter.add(eventFactory.createAttribute("xmlns:xsi",
    // "http://www.w3.org/2001/XMLSchema-instance"));
    // eventWriter.add(eventFactory.createAttribute("xsi:schemaLocation",
    // "http://pdr.bbaw.de/namespaces/dtdl/ http://pdr.bbaw.de/schema/dtdl.xsd"));
    eventWriter.add(eventFactory.createAttribute("provider", d.getProvider()));

    eventWriter.add(end);

    // Write the different nodes
    if (d.getDocumentation() != null) {
      createNode(eventWriter, "documentation", d.getDocumentation(), PREFIX, URI);
    }
    if (d.getUsage() != null) {
      startElement = eventFactory.createStartElement(PREFIX, URI, "usage");
      eventWriter.add(startElement);
      eventWriter.add(end);

      if (d.getUsage().getDocumentation() != null) {
        createNode(eventWriter, "documentation", d.getUsage().getDocumentation(), PREFIX, URI);
      }
      if (d.getUsage().getUsageDisplay() != null) {
        startElement = eventFactory.createStartElement(PREFIX, URI, "display");
        eventWriter.add(startElement);
        eventWriter.add(end);
        if (d.getUsage().getUsageDisplay().getDocumentation() != null) {
          createNode(
              eventWriter,
              "documentation",
              d.getUsage().getUsageDisplay().getDocumentation(),
              PREFIX,
              URI);
        }
        if (d.getUsage().getUsageDisplay().getPersonNameTag() != null) {
          for (String s : d.getUsage().getUsageDisplay().getPersonNameTag()) {
            createNode(eventWriter, "nameTag", s, PREFIX, URI);
          }
        }
        if (d.getUsage().getUsageDisplay().getPersonNormNameTag() != null) {
          for (String s : d.getUsage().getUsageDisplay().getPersonNormNameTag()) {
            createNode(eventWriter, "displayNameTag", s, PREFIX, URI);
          }
        }
        eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "display"));
        eventWriter.add(end);
      }
      if (d.getUsage().getTemplates() != null) {
        startElement = eventFactory.createStartElement(PREFIX, URI, "templates");
        eventWriter.add(startElement);
        eventWriter.add(end);

        if (d.getUsage().getTemplates() != null
            && !d.getUsage().getTemplates().getChildren().isEmpty()) {
          for (String key : d.getUsage().getTemplates().getChildren().keySet()) {
            ConfigData cd = d.getUsage().getTemplates().getChildren().get(key); // aspectTemplates
            startElement = eventFactory.createStartElement(PREFIX, URI, key);
            eventWriter.add(startElement);
            eventWriter.add(end);

            if (cd.getChildren() != null) {
              for (String key2 : cd.getChildren().keySet()) {

                ConfigData cd2 = cd.getChildren().get(key2);
                startElement =
                    eventFactory.createStartElement(PREFIX, URI, key2); // semanticTemplates
                // and
                // complexTemplates
                eventWriter.add(startElement);
                eventWriter.add(
                    eventFactory.createAttribute("ignore", new Boolean(cd2.isIgnore()).toString()));
                eventWriter.add(end);

                if (cd2.getChildren() != null) {

                  for (String key3 : cd2.getChildren().keySet()) {
                    ConfigData cd3 = cd2.getChildren().get(key3);
                    if (cd3 instanceof SemanticTemplate) {
                      SemanticTemplate semanticTemplate = (SemanticTemplate) cd3;
                      createNode(eventWriter, semanticTemplate);
                    } else {

                      if (cd3 instanceof ComplexSemanticTemplate) // complexTemplate
                      {
                        ComplexSemanticTemplate complexTemplate = (ComplexSemanticTemplate) cd3;
                        startElement =
                            eventFactory.createStartElement(
                                PREFIX, URI, "complexTemplate"); // semanticTemplates

                        eventWriter.add(startElement);
                        eventWriter.add(
                            eventFactory.createAttribute("value", complexTemplate.getValue()));
                        eventWriter.add(
                            eventFactory.createAttribute("label", complexTemplate.getLabel()));
                        eventWriter.add(
                            eventFactory.createAttribute(
                                "priority", new Integer(complexTemplate.getPriority()).toString()));

                        eventWriter.add(end);
                        if (cd3.getChildren() != null) {
                          for (String key4 : cd3.getChildren().keySet()) {
                            ConfigData cd4 = cd3.getChildren().get(key4);
                            if (cd4 instanceof SemanticTemplate) {
                              SemanticTemplate semanticTemplate = (SemanticTemplate) cd4;
                              createNode(eventWriter, semanticTemplate);
                            } else {

                            }
                          }
                        }
                        if (complexTemplate.getDocumentation() != null) {
                          createNode(
                              eventWriter,
                              "documentation",
                              complexTemplate.getDocumentation(),
                              PREFIX,
                              URI);
                        }
                        eventWriter.add(
                            eventFactory.createEndElement(PREFIX, URI, "complexTemplate"));
                        eventWriter.add(end);
                      } else {
                        startElement =
                            eventFactory.createStartElement(PREFIX, URI, key3); // semanticTemplates
                        eventWriter.add(startElement);
                        eventWriter.add(end);

                        if (cd3.getChildren() != null) {
                          for (String key4 : cd3.getChildren().keySet()) {
                            ConfigData cd4 = cd3.getChildren().get(key4);
                            if (cd4 instanceof SemanticTemplate) {
                              SemanticTemplate semanticTemplate = (SemanticTemplate) cd4;
                              createNode(eventWriter, semanticTemplate);
                            } else {

                            }
                          }
                        }
                        eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key3));
                        eventWriter.add(end);
                      }
                    }
                  }
                }
                eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key2));
                eventWriter.add(end);
              }
            }

            eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key));
            eventWriter.add(end);
          }
        }

        eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "templates"));
        eventWriter.add(end);
      }
      if (d.getUsage().getIdentifiers() != null
          && d.getUsage().getIdentifiers().getChildren().size() > 0) {
        startElement =
            eventFactory.createStartElement(
                PREFIX, URI, "personIdentifiers"); // "personIdentifiers"
        eventWriter.add(startElement);
        eventWriter.add(end);

        for (String key : d.getUsage().getIdentifiers().getChildren().keySet()) {
          ConfigData ci = (ConfigData) d.getUsage().getIdentifiers().getChildren().get(key);

          if (ci != null && ci instanceof IdentifierConfig) {
            IdentifierConfig ic = (IdentifierConfig) ci;
            startElement =
                eventFactory.createStartElement(PREFIX, URI, "identifier"); // "identifier"
            eventWriter.add(startElement);

            if (ic.getValue() != null) {
              eventWriter.add(eventFactory.createAttribute("value", ic.getValue()));
            }
            if (ic.getLabel() != null) {
              eventWriter.add(eventFactory.createAttribute("label", ic.getLabel()));
            }

            eventWriter.add(
                eventFactory.createAttribute("ignore", new Boolean(ic.isIgnore()).toString()));
            eventWriter.add(
                eventFactory.createAttribute(
                    "mandatory", new Boolean(ic.isMandatory()).toString()));
            eventWriter.add(
                eventFactory.createAttribute("priority", String.format("%03d", ic.getPriority())));

            if (ic.getUrl() != null) {
              eventWriter.add(eventFactory.createAttribute("url", ic.getUrl()));
            }
            if (ic.getPrefix() != null) {
              eventWriter.add(eventFactory.createAttribute("prefix", ic.getPrefix()));
            }
            if (ic.getSuffix() != null) {
              eventWriter.add(eventFactory.createAttribute("suffix", ic.getSuffix()));
            }
            if (ic.getRegex() != null) {
              eventWriter.add(eventFactory.createAttribute("regex", ic.getRegex()));
            }
            eventWriter.add(end);
            if (ic.getDocumentation() != null) {
              createNode(eventWriter, "documentation", ic.getDocumentation(), PREFIX, URI);
            }
            if (ic.getChildren() != null) {
              for (String str2 : ic.getChildren().keySet()) {
                createNode(eventWriter, "item", ic.getChildren().get(str2));
              }
            }

            eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "identifier"));
            eventWriter.add(end);
          }
        }

        eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "personIdentifiers"));
        eventWriter.add(end);
      }
      eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "usage"));
      eventWriter.add(end);
    }
    if (d.getChildren() != null) {
      for (String str : d.getChildren().keySet()) {
        DataType dt = (DataType) d.getChildren().get(str);
        startElement = eventFactory.createStartElement(PREFIX, URI, "datatype");
        eventWriter.add(startElement);
        eventWriter.add(eventFactory.createAttribute("element", dt.getValue()));
        if (dt.getLabel() != null) {
          eventWriter.add(eventFactory.createAttribute("label", dt.getLabel()));
        }

        //			if (d.getChildren().get(str).isMyHaveChildren())
        //			{
        if (dt.getPos() != null) {
          eventWriter.add(eventFactory.createAttribute("type", dt.getPos()));
        } else {
          //				System.out.println("dt pos = null " + dt.getValue());
        }
        //			}
        //			else
        //			{
        //				eventWriter.add(eventFactory.createAttribute("type", "list"));
        //			}
        eventWriter.add(end);
        if (dt.getDocumentation() != null) {
          createNode(eventWriter, "documentation", dt.getDocumentation(), PREFIX, URI);
        }
        if (dt.getChildren() != null) {
          for (String str2 : dt.getChildren().keySet()) {
            createNode(eventWriter, "item", dt.getChildren().get(str2));
          }
        }
        eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "datatype"));
        eventWriter.add(end);
      }

      eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "datatypeDesc"));
      eventWriter.add(end);

      eventWriter.add(eventFactory.createEndDocument());
      eventWriter.close();
    }
    // System.out.println(bout.toString());
    return bout.toString();
  }
  public File transform(boolean keepPorts) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    XMLEventReader parser = null;
    XMLEventWriter writer = null;
    XMLInputFactory xif =
        (XMLInputFactory.class.getClassLoader() == null)
            ? XMLInputFactory.newInstance()
            : XMLInputFactory.newInstance(
                XMLInputFactory.class.getName(), XMLInputFactory.class.getClassLoader());

    Set<String> empty_elements = (keepPorts) ? EMPTY_ELEMENTS_KEEP_PORTS : EMPTY_ELEMENTS;
    Set<String> skip_elements = (keepPorts) ? SKIP_ELEMENTS_KEEP_PORTS : SKIP_ELEMENTS;
    try {
      fis = new FileInputStream(in);
      out = File.createTempFile("domain", "xml");
      if (_logger.isLoggable(Level.FINE)) {
        _logger.fine("[DomainXmlTransformer] Creating temp domain file: " + out);
      }

      if (System.getProperty(EJBContainerProviderImpl.KEEP_TEMPORARY_FILES) == null) {
        out.deleteOnExit();
      }

      fos = new FileOutputStream(out);
      parser = xif.createXMLEventReader(fis);

      writer = xof.createXMLEventWriter(fos);
      boolean fixedDasConfig = false;
      while (parser.hasNext()) {
        XMLEvent event = parser.nextEvent();
        if (event.isStartElement()) {
          String name = event.asStartElement().getName().getLocalPart();
          if (skip_elements.contains(name)) {
            if (_logger.isLoggable(Level.FINE)) {
              _logger.fine("[DomainXmlTransformer] Skipping all of: " + name);
            }
            getEndEventFor(parser, name);
            continue;
          }

          boolean skip_to_end = false;
          if (empty_elements.contains(name)) {
            if (_logger.isLoggable(Level.FINE)) {
              _logger.fine("[DomainXmlTransformer] Skipping details of: " + name);
            }
            skip_to_end = true;
          } else if (SKIP_SETTINGS_ELEMENTS.contains(name)) {
            // Make sure lazy init is not enabled by creating a new start element
            // based on the original but that never includes the lazy init attribute
            event = getSkippedElementStartEvent(event);
            skip_to_end = true;
          } else if (DISABLE_ELEMENTS.contains(name)) {
            // Disable this element
            event = getReplaceAttributeInStartEvent(event, ENABLED, FALSE);
            skip_to_end = true;
          } else if (JMS_HOST.equals(name)) {
            // Set lazy-init to false
            event = getReplaceAttributeInStartEvent(event, LAZY_INIT_ATTR, FALSE);
            skip_to_end = true;
          } else if (DAS_CONFIG.equals(name)) {
            // Set dynamic-reload-enabled to false
            event = getReplaceAttributeInStartEvent(event, DYNAMIC_RELOAD_ENABLED, FALSE);
            fixedDasConfig = true;
            skip_to_end = true;
          } else if (JAVA_CONFIG.equals(name)) {
            // Add jvm-options
            writer.add(event);
            event = getAddedEvent(event, writer, JVM_OPTIONS, INITIALIZE_ON_DEMAND);
          }

          if (skip_to_end) {
            writer.add(event);
            event = getEndEventFor(parser, name);
          }
        } else if (event.isEndElement()) {
          String name = event.asEndElement().getName().getLocalPart();
          if (ADMIN_SERVICE.equals(name)) {
            if (!fixedDasConfig) {
              writer.add(
                  getAddedEventBeforeEndElement(
                      event, writer, DAS_CONFIG, DYNAMIC_RELOAD_ENABLED, FALSE));
            }
            fixedDasConfig = false; // for the next config
          }
        }
        if (_logger.isLoggable(Level.FINEST)) {
          _logger.finest("[DomainXmlTransformer] Processing: " + event);
        }
        writer.add(event);
      }
      writer.flush();
      writer.close();

    } catch (Exception e) {
      _logger.log(Level.SEVERE, "ejb.embedded.tmp_file_create_error", e.getMessage());
      _logger.log(Level.FINE, e.getMessage(), e);
      return null;
    } finally {
      try {
        if (parser != null) {
          parser.close();
        }
      } catch (Exception e) {
      }
      try {
        if (fis != null) {
          fis.close();
        }
      } catch (Exception e) {
      }
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (Exception e) {
      }
      try {
        if (fos != null) {
          fos.close();
        }
      } catch (Exception e) {
      }
    }

    if (_logger.isLoggable(Level.FINE)) {
      _logger.fine("[DomainXmlTransformer] Created temp domain file: " + out);
    }
    return out;
  }
  public void process(SlingHttpServletResponse response, ProxyResponse proxyResponse)
      throws IOException {
    Map<String, String[]> headers = proxyResponse.getResponseHeaders();

    // Check if the content-length is smaller than the maximum (if any).
    String[] contentLengthHeader = headers.get("Content-Length");
    if (contentLengthHeader != null) {
      int length = Integer.parseInt(contentLengthHeader[0]);
      if (length > MAX_RSS_LENGTH) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "This RSS feed is too big. The maximum for a feed is: " + MAX_RSS_LENGTH);
        return;
      }
    }

    // Check if the Content-Type we get is valid (if any).
    String[] contentTypeHeader = headers.get("Content-Type");
    if (contentTypeHeader != null) {
      String contentType = contentTypeHeader[0];
      if (contentType.contains(";")) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
      }
      if (!contentTypes.contains(contentType)) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN, "This URL doesn't send a proper Content-Type back");
        return;
      }
    }

    boolean isValid = false;
    InputStream in = proxyResponse.getResponseBodyAsInputStream();
    InputStreamReader reader = new InputStreamReader(in);

    // XMLStreamWriter writer = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream out = null;

    int i = 0;
    try {
      XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader);
      // Create a temporary outputstream where we can write to.
      out = new ByteArrayOutputStream();

      Map<String, Boolean> checkedElements = new HashMap<String, Boolean>();
      checkedElements.put("rss", false);
      checkedElements.put("channel", false);
      checkedElements.put("title", false);
      checkedElements.put("link", false);
      checkedElements.put("item", false);
      checkedElements.put("title", false);
      checkedElements.put("link", false);

      XMLOutputFactory outputFactory = new WstxOutputFactory();
      writer = outputFactory.createXMLEventWriter(out);

      while (eventReader.hasNext()) {
        XMLEvent e = eventReader.nextEvent();
        // Stream it to an output stream.
        writer.add(e);

        if (!isValid) {
          if (e.getEventType() == XMLEvent.START_ELEMENT) {
            StartElement el = e.asStartElement();
            String name = el.getName().toString().toLowerCase();
            if (checkedElements.containsKey(name)) {
              checkedElements.put(name, true);
            }

            boolean all = true;
            for (Entry<String, Boolean> es : checkedElements.entrySet()) {
              if (!checkedElements.get(es.getKey())) {
                all = false;
                break;
              }
            }
            if (all) isValid = true;
          }

          if (i > 100) {
            response.sendError(
                HttpServletResponse.SC_FORBIDDEN,
                "This file does not match an RSS formatted XML file..");
            break;
          }
          i++;
        }
      }

      if (!isValid) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid RSS file.");
        return;
      }

      // Check if we are not streaming a gigantic file..
      if (out.size() > MAX_RSS_LENGTH) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "This file is to big.");
        return;
      }

      for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) {
        for (String v : h.getValue()) {
          response.setHeader(h.getKey(), v);
        }
      }
      // We always return 200 when we get to this point.
      response.setStatus(200);
      response.setHeader("Content-Length", "" + out.size());
      // Write the cached stream to the output.
      out.writeTo(response.getOutputStream());

    } catch (XMLStreamException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN, "This is not a valid XML file.");
    } catch (Exception e) {
      logger.warn("Exception reading RSS feed.");
      response.sendError(HttpServletResponse.SC_FORBIDDEN, "General exception caught.");
    } finally {
      out.close();
      reader.close();
      try {
        writer.close();
      } catch (XMLStreamException e) {
        // Not much we can do?
        e.printStackTrace();
      }
    }
  }