Example usage for javax.xml.stream XMLEventWriter add

List of usage examples for javax.xml.stream XMLEventWriter add

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventWriter add.

Prototype


public void add(XMLEventReader reader) throws XMLStreamException;

Source Link

Document

Adds an entire stream to an output stream, calls next() on the inputStream argument until hasNext() returns false This should be treated as a convenience method that will perform the following loop over all the events in an event reader and call add on each event.

Usage

From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * This method processes the source file, replacing all of the 'import' tags
 * by the data from the relevant files./*from  ww  w. j  av  a2s.c  om*/
 *
 * @throws XMLStreamException on event writing error.
 * @throws IOException        if the destination file exists but is a directory
 *                            rather than a regular file, does not exist but cannot be created, or
 *                            cannot be opened for any other reason
 */
private void doUpdate() throws XMLStreamException, IOException {
    XMLEventReader reader = null;
    XMLEventWriter writer = null;

    Properties metadata = new Properties();

    try {
        writer = outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile, false)));
        reader = inputFactory.createXMLEventReader(new FileReader(sourceFile));

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

            if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) {
                processImportElement(xmlEvent.asStartElement(), writer, metadata);
                continue;
            }

            if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) {
                continue;
            }

            if (xmlEvent instanceof Comment)// skip comments.
            {
                continue;
            }

            if (xmlEvent.isCharacters())// skip whitespaces.
            {
                if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace())// skip
                // whitespaces.
                {
                    continue;
                }
            }

            writer.add(xmlEvent);

            if (xmlEvent.isStartDocument()) {
                writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n"));
            }
        }

        storeFileModifications(metadata, metaDataFile);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception ignored) {
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static Map.Entry<Integer, XmlElement> getAtomElement(final XMLEventReader reader,
        final XMLEventWriter discarded, final String name,
        final Collection<Map.Entry<String, String>> filterAttrs, final int initialDepth, final int minDepth,
        final int maxDepth, final boolean filterInOr) throws Exception {

    int depth = initialDepth;
    StartElement start = null;//from ww w  .j a v a  2s.  co m

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

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;

            if ((StringUtils.isBlank(name)
                    || name.trim().equals(event.asStartElement().getName().getLocalPart()))
                    && (minDepth < 0 || minDepth <= depth) && (maxDepth < 0 || maxDepth >= depth)) {

                boolean match = filterAttrs == null || filterAttrs.isEmpty() || !filterInOr;

                for (Map.Entry<String, String> filterAttr : filterAttrs == null
                        ? Collections.<Map.Entry<String, String>>emptySet()
                        : filterAttrs) {
                    final Attribute attr = event.asStartElement()
                            .getAttributeByName(new QName(filterAttr.getKey().trim()));

                    if (attr == null || !filterAttr.getValue().trim().equals(attr.getValue())) {
                        match = filterInOr ? match : false;
                    } else {
                        match = filterInOr ? true : match;
                    }
                }

                if (match) {
                    start = event.asStartElement();
                }
            }

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

        if (start == null) {
            if (discarded != null) {
                discarded.add(event);
            }
        }
    }

    if (start == null) {
        throw new Exception(String.format("Could not find an element named '%s'", name));
    }

    return new SimpleEntry<Integer, XmlElement>(Integer.valueOf(depth - 1), getAtomElement(start, reader));
}

From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java

/**
 * The actual injection procedure/*from w ww  .  j  a va  2  s . c  o  m*/
 * @param in the input stream where the XML is coming from (will be closed in the end) 
 * @param out the output stream where we write the annotated XML into (remains open)
 * @param refs a list of references
 * @throws IOException
 */
public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException {
    StringBuilder pb;
    XPathElement characters = null;
    int marked;
    interceptingElements = new ArrayList<Reference>();

    try {
        XMLEventReader r = getXMLInputFactory().createXMLEventReader(in);
        XMLEventWriter w = getXMLOutputFactory().createXMLEventWriter(out);

        while (r.hasNext()) {

            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {

            case XMLEvent.START_ELEMENT:
                StartElement se = (StartElement) e;
                if (super.getNamespaceContext() == null) {
                    super.updateNamespaceContext(se.getNamespaceContext());
                }

                if (references == null) {
                    // process the namespaces in the references
                    references = this.prepareReferences(refs);
                }
                // store location
                col = e.getLocation().getColumnNumber();

                // add to current xpath            
                updateCurrentPath(getGenerator().asXPathElement((StartElement) e));

                System.out.println(getCurrentPath());
                // check if the current xpath is in our list of attribute references
                for (XPathPattern p : references.keySet()) {
                    if (references.get(p) == null)
                        continue;

                    if (p.isAttribute()) {
                        if (getMatcher().matches(p, getCurrentPath())) {
                            se = this.handleAttribute(w, references.get(p), se);
                            references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        }
                    }
                }

                w.add(se);
                break;
            case XMLEvent.END_ELEMENT:
                updateCurrentPath(characters);

                // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now)
                XPathStack currentPath = getCurrentPath();

                for (XPathPattern p : references.keySet()) {

                    if (references.get(p) == null)
                        continue;

                    if (getMatcher().matches(p, currentPath)) {
                        if (p.isSiblingElement()) {
                            // injection happens below
                            this.interceptingElements.add(references.get(p));

                        } else if (p.isChildElement()) {
                            // we can add it directly
                            w.add(getXMLEventFactory().createSpace("\n"));
                            writeElementIntoStream(w, references.get(p));
                        } else {
                            throw new IOException("Invalid Reference: " + p);
                        }
                        references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        //references.remove(p);
                        //break; //otherwise ConcurrentModificationException

                    }

                }

                // clean up
                if (characters != null) {
                    getCurrentPath().pop();
                    characters = null;
                }

                getCurrentPath().pop();
                w.add(e); // do not change position

                // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element
                if (this.interceptingElements.size() > 0) {
                    // write all references into stream
                    for (Reference ref : this.interceptingElements) {
                        w.add(getXMLEventFactory().createSpace("\n"));
                        writeElementIntoStream(w, ref);
                    }

                    // reset list
                    this.interceptingElements.clear();
                }

                break;
            case XMLEvent.CHARACTERS:
                characters = getGenerator().asXPathElement((Characters) e);
                w.add(e);
                break;

            default:
                w.add(e);
                break;
            }
        }
    } catch (XPathExpressionException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Not a valid XPath", e);
        }
        throw new IOException(e);

    } catch (XMLStreamException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e);
        }
        throw new IOException(e);
    } finally {
        in.close();
    }

}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * The actual injection procedure/* w  ww .  j  a  v  a 2  s  . c  om*/
 * @param in the input stream where the XML is coming from (will be closed in the end) 
 * @param out the output stream where we write the annotated XML into (remains open)
 * @param refs a list of references
 * @throws IOException
 */
public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException {
    StringBuilder pb;
    String characters = null;
    NamespaceContext context = null;
    int marked;

    current_path = new Stack<String>();
    current_path.push("//");

    try {
        XMLEventReader r = inFac.createXMLEventReader(in);
        XMLEventWriter w = outFac.createXMLEventWriter(out);
        XMLStreamWriter ws = outFac.createXMLStreamWriter(System.out);

        while (r.hasNext()) {

            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {

            case XMLEvent.START_ELEMENT:
                StartElement se = (StartElement) e;
                context = se.getNamespaceContext();
                if (elementReferences == null) {
                    // process the namespaces in the references
                    this.prepareReferences(refs, context);
                }

                // store location
                col = e.getLocation().getColumnNumber();

                // add to current xpath

                current_path.add(generator.asXPathString((StartElement) e));

                //XPathHelper.addCurrentElementToStack(current_path, se);

                // check if the current xpath is in our list of attribute references
                if (attributeReferences.size() > 0) {
                    for (int i = 0; i < refs.size(); i++) {
                        Stack<String> stack = attributeReferences.get(refs.get(i));
                        if (matcher.matches(current_path, stack, true, context)) {
                            // yes, let's inject the reference (only valid for attributes here)
                            this.handleAttribute(w, refs.get(i));
                            attributeReferences.remove(refs.get(i));
                            refs.remove(i);
                        }
                    }
                }

                w.add(e);
                break;
            case XMLEvent.END_ELEMENT:

                // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now)
                if (characters != null)
                    this.current_path.push(characters);

                if (elementReferences.size() > 0) {
                    for (int i = 0; i < refs.size(); i++) {

                        Stack<String> stack = elementReferences.get(refs.get(i));

                        if (matcher.matches(current_path, stack, true, context)) {
                            // yes, let's inject the reference (only valid for attributes here)
                            this.interceptingElement = refs.get(i);
                            elementReferences.remove(refs.get(i));
                            refs.remove(i);
                        }
                    }
                }

                if (characters != null) {
                    // clean up
                    this.current_path.pop();
                    characters = null;
                }

                this.current_path.pop();

                w.add(e);

                // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element
                if (this.interceptingElement != null) {
                    w.add(eventFac.createSpace("\n"));
                    writeElementIntoStream(w, interceptingElement);
                }
                break;
            case XMLEvent.CHARACTERS:
                characters = generator.asXPathString((Characters) e);
                w.add(e);
                break;

            default:
                w.add(e);
                break;
            }
        }
    } catch (XPathExpressionException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Not a valid XPath", e);
        }
        throw new IOException(e);

    } catch (XMLStreamException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e);
        }
        throw new IOException(e);
    } finally {
        in.close();
    }

}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file and write them onto the {@link javax.xml.stream.XMLEventWriter}
 *
 * @param file     File to import//from www.  ja  va 2  s  . c o  m
 * @param skipRoot Skip-root flag
 * @param writer   Destenation writer
 * @throws XMLStreamException    On event reading/writing error.
 * @throws FileNotFoundException if the reading file does not exist,
 *                               is a directory rather than a regular file,
 *                               or for some other reason cannot be opened for
 *                               reading.
 */
private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata)
        throws XMLStreamException, IOException {
    logger.debug("Appending file " + file);
    metadata.setProperty(file.getPath(), makeHash(file));

    XMLEventReader reader = null;

    try {
        reader = inputFactory.createXMLEventReader(new FileReader(file));

        QName firstTagQName = null;

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

            // skip start and end of document.
            if (event.isStartDocument() || event.isEndDocument())
                continue;
            // skip all comments.
            if (event instanceof Comment)
                continue;
            // skip white-spaces and all ignoreable white-spaces.
            if (event.isCharacters()) {
                if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace())
                    continue;
            }

            // modify root-tag of imported file.
            if (firstTagQName == null && event.isStartElement()) {
                firstTagQName = event.asStartElement().getName();

                if (skipRoot) {
                    continue;
                } else {
                    StartElement old = event.asStartElement();

                    event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null);
                }
            }

            // if root was skipped - skip root end too.
            if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName))
                continue;

            // finally - write tag
            writer.add(event);
        }
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (Exception ignored) {
            }
    }
}

From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file
 * and write them onto the {@link javax.xml.stream.XMLEventWriter}
 *
 * @param file     File to import/*from   w w  w  .  j  a v a  2 s. c o m*/
 * @param skipRoot Skip-root flag
 * @param writer   Destenation writer
 * @throws XMLStreamException    On event reading/writing error.
 * @throws FileNotFoundException if the reading file does not exist, is a
 *                               directory rather than a regular file, or for some other reason cannot be
 *                               opened for reading.
 */
private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata)
        throws XMLStreamException, IOException {
    logger.debug("Appending file " + file);
    metadata.setProperty(file.getPath(), makeHash(file));

    XMLEventReader reader = null;

    try {
        reader = inputFactory.createXMLEventReader(new FileReader(file));

        QName firstTagQName = null;

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

            // skip start and end of document.
            if (event.isStartDocument() || event.isEndDocument()) {
                continue;
            }
            // skip all comments.
            if (event instanceof Comment) {
                continue;
            }
            // skip white-spaces and all ignoreable white-spaces.
            if (event.isCharacters()) {
                if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) {
                    continue;
                }
            }

            // modify root-tag of imported file.
            if (firstTagQName == null && event.isStartElement()) {
                firstTagQName = event.asStartElement().getName();

                if (skipRoot) {
                    continue;
                } else {
                    StartElement old = event.asStartElement();

                    event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null);
                }
            }

            // if root was skipped - skip root end too.
            if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) {
                continue;
            }

            // finally - write tag
            writer.add(event);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3,
            false);//from  w  ww . ja v a2s . c  o  m

    writer.flush();

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = getAtomElement(propertyReader, null, null);
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = xof.createXMLEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton(
                        new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

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

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = xof.createXMLEventWriter(bos);

    propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

private void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createDTD("\n");
    XMLEvent tab = eventFactory.createDTD("\t");
    // Create Start node
    StartElement sElement = eventFactory.createStartElement("", "", name);
    eventWriter.add(tab);
    eventWriter.add(sElement);/*  www  .jav a 2  s  . c  o m*/
    // Create Content
    Characters characters = eventFactory.createCharacters(value);
    eventWriter.add(characters);
    // Create End node
    EndElement eElement = eventFactory.createEndElement("", "", name);
    eventWriter.add(eElement);
    eventWriter.add(end);
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

/**
 * Based on http://www.vogella.de/articles/RSSFeed/article.html
 *///from  www  .  j  av  a2s. co m
private String generateRSS(AppUserInfo user, BaseReportInfo report, List<DataRowInfo> reportDataRows)
        throws XMLStreamException, ObjectNotFoundException {
    // Create a XMLOutputFactory
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    // Create XMLEventWriter
    StringWriter stringWriter = new StringWriter();
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter);
    // Create a EventFactory
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createDTD("\n");
    // Create and write Start Tag
    StartDocument startDocument = eventFactory.createStartDocument();
    eventWriter.add(startDocument);
    // Create open tag
    eventWriter.add(end);
    StartElement rssStart = eventFactory.createStartElement("", "", "rss");
    eventWriter.add(rssStart);
    eventWriter.add(eventFactory.createAttribute("version", "2.0"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createStartElement("", "", "channel"));
    eventWriter.add(end);
    // Write the different nodes
    this.createNode(eventWriter, "title", report.getModule().getModuleName() + " - " + report.getReportName());
    // TODO: Don't hard code host part of URL
    String reportLink = "https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=gui/display_application&set_table="
            + report.getParentTable().getInternalTableName() + "&set_report=" + report.getInternalReportName();
    this.createNode(eventWriter, "link", reportLink);
    this.createNode(eventWriter, "description", "A live data feed from www.agilebase.co.uk");
    DateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    Date lastDataChangeDate = new Date(getLastCompanyDataChangeTime(user.getCompany()));
    this.createNode(eventWriter, "pubdate", dateFormatter.format(lastDataChangeDate));
    for (DataRowInfo reportDataRow : reportDataRows) {
        eventWriter.add(eventFactory.createStartElement("", "", "item"));
        eventWriter.add(end);
        this.createNode(eventWriter, "title", buildEventTitle(report, reportDataRow, false));
        this.createNode(eventWriter, "description", reportDataRow.toString());
        String rowLink = reportLink + "&set_row_id=" + reportDataRow.getRowId();
        this.createNode(eventWriter, "link", rowLink);
        this.createNode(eventWriter, "guid", rowLink);
        eventWriter.add(end);
        eventWriter.add(eventFactory.createEndElement("", "", "item"));
        eventWriter.add(end);
    }
    eventWriter.add(eventFactory.createEndElement("", "", "channel"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createEndElement("", "", "rss"));
    eventWriter.add(end);
    return stringWriter.toString();
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

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

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;/*w  w  w .j  a v  a2 s  .co  m*/
    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
                && 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
                && LINK.equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (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 ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName) && (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());
}