예제 #1
0
  public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
    final XMLEventReader reader = getEventReader(feed);

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

    try {

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

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

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

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @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();
  }
예제 #3
0
  @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());
  }
예제 #4
0
  @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());
  }
예제 #5
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();
  }
예제 #6
0
  /** {@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());
  }
예제 #7
0
  @Override
  public InputStream replaceProperty(
      final InputStream src,
      final InputStream replacement,
      final List<String> path,
      final boolean justValue)
      throws Exception {

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

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

    final XMLEventReader reader = getEventReader(src);

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

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

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

    final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);

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

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

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

    writer.add(reader);

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

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  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);
    }
  }
예제 #9
0
  @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());
  }
예제 #10
0
  /** Format a JournalEntry object and write a JournalEntry tag to the journal. */
  protected void writeJournalEntry(CreatorJournalEntry journalEntry, XMLEventWriter writer)
      throws JournalException {
    try {
      writeJournaEntryStartTag(journalEntry, writer);

      new ContextXmlWriter().writeContext(journalEntry.getContext(), writer);

      writeArguments(journalEntry.getArgumentsMap(), writer);

      putEndTag(writer, QNAME_TAG_JOURNAL_ENTRY);
      writer.flush();
    } catch (XMLStreamException e) {
      throw new JournalException(e);
    }
  }
예제 #11
0
  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();
  }
 public void testFlush() throws XMLStreamException {
   xmlEventWriter.flush();
   eventWriterWrapper.flush();
 }
예제 #14
0
  private InputStream addAtomContent(
      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);

    try {
      // check edit link existence
      XMLElement contentElement =
          extractElement(reader, writer, Collections.<String>singletonList("content"), 0, 2, 2)
              .getValue();
      writer.add(contentElement.getStart());
      writer.add(contentElement.getContentReader());
      writer.add(contentElement.getEnd());
      writer.add(reader);
    } catch (Exception e) {
      reader.close();
      reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

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

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

        addAtomElement(
            IOUtils.toInputStream(
                String.format("<content type=\"*/*\" src=\"%s/$value\" />", href)),
            writer);

        writer.add(entryElement.getEnd());
      } else {
        try {
          final XMLElement entryElement =
              extractElement(
                      reader,
                      writer,
                      Collections.<String>singletonList(Constants.get(ConstantKey.PROPERTIES)),
                      0,
                      2,
                      3)
                  .getValue();

          addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\">"), writer);

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

          addAtomElement(IOUtils.toInputStream("</content>"), writer);
        } catch (Exception nf) {
          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());
          writer.add(entryElement.getContentReader());

          addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\"/>"), writer);

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

      writer.add(reader);

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
예제 #15
0
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    RequestURIParts parts = parseParts(request);
    if (parts != null) {
      String realBaseAddress = parts.getBaseAddress();
      String idlPath = parts.getFilePath();
      InputStream idl = this.servletContext.getResourceAsStream(idlPath);
      if (idl != null) {
        servletResponse.setContentType("text/xml");
        String assumedBaseAddress = null;
        try {
          XMLEventReader eventReader = this.inputFactory.createXMLEventReader(idl);
          XMLEventWriter eventWriter =
              this.outputFactory.createXMLEventWriter(servletResponse.getWriter());
          while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isProcessingInstruction()) {
              String target = ((ProcessingInstruction) event).getTarget();
              if ("enunciate-assumed-base-uri".equals(target)) {
                assumedBaseAddress = ((ProcessingInstruction) event).getData();
                if (assumedBaseAddress.endsWith("/")) {
                  assumedBaseAddress =
                      assumedBaseAddress.substring(0, assumedBaseAddress.length() - 1);
                }
              }
              continue;
            } else if (event.getEventType() == XMLStreamConstants.CDATA
                || event.getEventType() == XMLStreamConstants.CHARACTERS) {
              String data = ((Characters) event).getData();
              if (assumedBaseAddress != null && data.contains(assumedBaseAddress)) {
                data = data.replace(assumedBaseAddress, realBaseAddress);
                event = new DelegatingCharacters(((Characters) event), data);
              }
            } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
              List<Attribute> attributes = new ArrayList<Attribute>();
              Iterator attributesIt = ((StartElement) event).getAttributes();
              while (attributesIt.hasNext()) {
                Attribute attribute = (Attribute) attributesIt.next();
                String value = attribute.getValue();
                if (assumedBaseAddress != null && value.contains(assumedBaseAddress)) {
                  value = value.replace(assumedBaseAddress, realBaseAddress);
                  attribute = new DelegatingAttribute(attribute, value);
                  event = new DelegatingStartElement(((StartElement) event), attributes);
                }
                attributes.add(attribute);
              }
            }

            eventWriter.add(event);
          }

          eventReader.close();
          eventWriter.flush();
          eventWriter.close();
          return;
        } catch (XMLStreamException e) {
          throw new ServletException(e);
        }
      }
    }

    chain.doFilter(servletRequest, servletResponse);
  }
  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);
    }
  }
예제 #17
0
  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;
  }
예제 #18
0
  @Override
  public InputStream selectEntity(final InputStream entity, final String[] propertyNames)
      throws Exception {
    final XMLEventReader reader = getEventReader(entity);

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

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
      final XMLEvent event = reader.nextEvent();
      if (event.getEventType() == XMLStreamConstants.START_ELEMENT
          && Constants.get(ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart())
          && !fieldToBeSaved.contains(
              event.asStartElement().getAttributeByName(new QName("title")).getValue())
          && !"edit"
              .equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
        writeCurrent = false;
      } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
          && Constants.get(ConstantKey.LINK)
              .equals(event.asEndElement().getName().getLocalPart())) {
        writeNext = true;
      } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
          && (Constants.get(ConstantKey.PROPERTIES))
              .equals(event.asStartElement().getName().getLocalPart())) {
        writeCurrent = true;
        writeNext = false;
        inProperties = true;
      } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
          && (Constants.get(ConstantKey.PROPERTIES))
              .equals(event.asEndElement().getName().getLocalPart())) {
        writeCurrent = true;
      } else if (inProperties) {
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
          final String elementName = event.asStartElement().getName().getLocalPart();

          for (String propertyName : propertyNames) {
            if ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim())
                .equals(elementName)) {
              writeCurrent = true;
              found.remove(propertyName);
              currentName = propertyName;
            }
          }

        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
            && StringUtils.isNotBlank(currentName)
            && (Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim())
                .equals(event.asEndElement().getName().getLocalPart())) {
          writeNext = false;
          currentName = null;
        }
      }

      if (writeCurrent) {
        writer.add(event);
      }

      if (writeNext != null) {
        writeCurrent = writeNext;
        writeNext = null;
      }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    // throw new Exception(String.format("Could not find a properties '%s'", found));
    // }
    return new ByteArrayInputStream(bos.toByteArray());
  }