text:
define([
    'underscore',
    'backbone'
], function(_, Backbone) {
    'use strict';

    return Backbone.Collection.extend({
        initialize: function(models, options) {
            this.filterModel = options.filterModel;
            this.collection = options.collection;

            this.predicate = _.partial(options.predicate, _, this.filterModel);
            this.resetOnFilter = options.resetOnFilter || false;

            _.each(options.collectionFunctions, function(functionName) {
                this[functionName] = function() {
                    return options.collection[functionName].apply(this, arguments);
                }
            }, this);

            if(this.filterModel) {
                this.listenTo(this.filterModel, 'change', this.filterModels);
            }

            this.listenTo(this.collection, 'add', this.onAdd);
            this.listenTo(this.collection, 'remove', this.onRemove);
            this.listenTo(this.collection, 'change', this.onChange);
            this.listenTo(this.collection, 'reset', this.onReset);
            this.listenTo(this.collection, 'request', this.onRequest);
            this.listenTo(this.collection, 'error', this.onError);
            this.listenTo(this.collection, 'sync', this.onSync);

            this.collection.each(function(model) {
                if(this.predicate(model)) {
                    models.push(model);
                }
            }, this);
        },

        onAdd: function(model) {
            if(this.predicate(model)) {
                this.add(model);
            }
        },

        onRemove: function(model) {
            this.remove(model);
        },

        onChange: function(model) {
            if(!this.predicate(model)) {
                this.remove(model);
            }
        },

        onReset: function(collection) {
            this.reset(collection.filter(this.predicate))
        },

        onRequest: function() {
            this.trigger('request');
        },

        onError: function(collection, xhr) {
            this.trigger('error', collection, xhr);
        },

        onSync: function() {
            this.trigger('sync');
        },

        filterModels: function() {
            const models = this.collection.filter(this.predicate);

            if(this.resetOnFilter) {
                this.reset(models);
            } else {
                this.set(models);
            }
        },

        isProcessing: function() {
            return Boolean(this.collection.currentRequest);
        }
    })
});


text:
package ru.job4j.bank;

/**
 * class WrongAccountException.
 *
 * @author Evgeniy Ulanov(komrad1812@yandex.ru).
 * @version $Id$.
 * @since 0.1.
 */
class WrongAccountException extends Exception {
    /**
     * method AccountException.
     *
     * @param msg - message.
     */
    WrongAccountException(String msg) {
        super(msg);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.cute.xiaoy.entity;

import java.util.Date;

public class ChatMassage {
	private int id;
	private String name;
	private String msg;
	private Type type;
	private Date date;
	private int user_id;

	public ChatMassage(int id, String name, String msg, Type type, Date date,
			int user_id) {
		super();
		this.id = id;
		this.name = name;
		this.msg = msg;
		this.type = type;
		this.date = date;
		this.user_id = user_id;
	}
	public ChatMassage(String name, String msg, Type type, Date date,
			int user_id) {
		super();
		this.name = name;
		this.msg = msg;
		this.type = type;
		this.date = date;
		this.user_id = user_id;
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	public int getUser_id() {
		return user_id;
	}

	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}

	public ChatMassage() {
		super();
	}

	public ChatMassage( String msg, Type type, Date date) {
		super();

		this.msg = msg;
		this.type = type;
		this.date = date;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Type getType() {
		return type;
	}

	public void setType(Type type) {
		this.type = type;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public enum Type{
		INCOMING,OUTCOMING;
	}

	@Override
	public String toString() {
		return "ChatMassage [name=" + name + ", msg=" + msg + ", type=" + type
				+ ", date=" + date + "]";
	}

}


text:
package org.dasein.cloud.aws.network;

import org.dasein.cloud.*;
import org.dasein.cloud.aws.AWSCloud;
import org.dasein.cloud.network.*;
import org.dasein.cloud.util.NamingConstraints;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

/**
 * Describes the capabilities of AWS with respect to Dasein load balancer operations.
 *
Created by Stas Maksimov: 04/03/2014 13:12

 *
 * @author Stas Maksimov
 * @version 2014.03 initial version
 * @since 2014.03
 */
public class ElasticLoadBalancerCapabilities extends AbstractCapabilities<AWSCloud> implements LoadBalancerCapabilities {

    public ElasticLoadBalancerCapabilities(@Nonnull AWSCloud cloud) {
        super(cloud);
    }

    @Nonnull
    @Override
    public LoadBalancerAddressType getAddressType() throws CloudException, InternalException {
        return LoadBalancerAddressType.DNS;
    }

    @Override
    public int getMaxPublicPorts() throws CloudException, InternalException {
        return 100;
    }

    @Override
    public int getMaxHealthCheckTimeout() throws CloudException, InternalException {
        return 60;
    }

    @Override
    public int getMinHealthCheckTimeout() throws CloudException, InternalException {
        return 2;
    }

    @Override
    public int getMaxHealthCheckInterval() throws CloudException, InternalException {
        return 300;
    }

    @Override
    public int getMinHealthCheckInterval() throws CloudException, InternalException {
        return 5;
    }

    @Nonnull
    @Override
    public String getProviderTermForLoadBalancer(@Nonnull Locale locale) {
        return "load balancer";
    }

    @Nullable
    @Override
    public VisibleScope getLoadBalancerVisibleScope() {
        return null;
    }

    @Override
    public boolean healthCheckRequiresLoadBalancer() throws CloudException, InternalException {
        return true;
    }

    @Override
    public boolean healthCheckRequiresListener() throws CloudException, InternalException {
        return false;
    }

    @Override
    public Requirement healthCheckRequiresName() throws CloudException, InternalException {
        return Requirement.NONE;
    }

    @Nonnull
    @Override
    public Requirement healthCheckRequiresPort() throws CloudException, InternalException {
        return Requirement.REQUIRED;
    }

    @Nonnull
    @Override
    public Requirement identifyEndpointsOnCreateRequirement() throws CloudException, InternalException {
        return Requirement.OPTIONAL;
    }

    @Nonnull
    @Override
    public Requirement identifyListenersOnCreateRequirement() throws CloudException, InternalException {
        return Requirement.REQUIRED;
    }

    @Override
    public Requirement identifyVlanOnCreateRequirement() { return Requirement.NONE; }

    @Override
    public @Nonnull Requirement identifyHealthCheckOnCreateRequirement() throws CloudException, InternalException {
        return Requirement.OPTIONAL;
    }

    @Override
    public boolean isAddressAssignedByProvider() throws CloudException, InternalException {
        return true;
    }

    @Override
    public boolean isDataCenterLimited() throws CloudException, InternalException {
        return true;
    }

    @Nonnull
    @Override
    public Iterable<LbAlgorithm> listSupportedAlgorithms() throws CloudException, InternalException {
        return Collections.singletonList(LbAlgorithm.ROUND_ROBIN);
    }

    @Nonnull
    @Override
    public Iterable<LbEndpointType> listSupportedEndpointTypes() throws CloudException, InternalException {
        return Collections.singletonList(LbEndpointType.VM);
    }

    static private volatile List<IPVersion> versions;

    @Nonnull
    @Override
    public Iterable<IPVersion> listSupportedIPVersions() throws CloudException, InternalException {
        if( versions == null ) {
            versions = Collections.unmodifiableList(Arrays.asList(
                    IPVersion.IPV4,
                    IPVersion.IPV6
            ));
        }
        return versions;
    }

    @Nonnull
    @Override
    public Iterable<LbPersistence> listSupportedPersistenceOptions() throws CloudException, InternalException {
        return Collections.singletonList(LbPersistence.NONE);
    }

    static private volatile List<LbProtocol> protocols;

    @Nonnull
    @Override
    public Iterable<LbProtocol> listSupportedProtocols() throws CloudException, InternalException {
        if( protocols == null ) {
            protocols = Collections.unmodifiableList(Arrays.asList(
                    LbProtocol.HTTP,
                    LbProtocol.HTTPS,
                    LbProtocol.RAW_TCP
            ));
        }
        return protocols;
    }

    @Override
    public boolean supportsAddingEndpoints() throws CloudException, InternalException {
        return true;
    }

    @Override
    public boolean supportsMonitoring() throws CloudException, InternalException {
        return true;
    }

    @Override
    public boolean supportsMultipleTrafficTypes() throws CloudException, InternalException {
        return true;
    }

    @Override
    public boolean supportsSslCertificateStore() throws CloudException, InternalException {
        return true;
    }

    @Override
    public @Nonnull NamingConstraints getLoadBalancerNamingConstraints() {
        return NamingConstraints.getAlphaOnly(1, 32).constrainedBy('-');
    }
}


text:
/*************************************************
*           Unicode Property Table handler       *
*************************************************/

/* Internal header file defining the layout of the bits in each pair of 32-bit
words that form a data item in the table. */

typedef struct cnode {
  unsigned f0;
  unsigned f1;
} cnode;

/* Things for the f0 field */

#define f0_scriptmask   0xff000000  /* Mask for script field */
#define f0_scriptshift          24  /* Shift for script value */
#define f0_rangeflag    0x00f00000  /* Flag for a range item */
#define f0_charmask     0x001fffff  /* Mask for code point value */

/* Things for the f1 field */

#define f1_typemask     0xfc000000  /* Mask for char type field */
#define f1_typeshift            26  /* Shift for the type field */
#define f1_rangemask    0x0000ffff  /* Mask for a range offset */
#define f1_casemask     0x0000ffff  /* Mask for a case offset */
#define f1_caseneg      0xffff8000  /* Bits for negation */

/* The data consists of a vector of structures of type cnode. The two unsigned
32-bit integers are used as follows:

(f0) (1) The most significant byte holds the script number. The numbers are
         defined by the enum in ucp.h.

     (2) The 0x00800000 bit is set if this entry defines a range of characters.
         It is not set if this entry defines a single character

     (3) The 0x00600000 bits are spare.

     (4) The 0x001fffff bits contain the code point. No Unicode code point will
         ever be greater than 0x0010ffff, so this should be OK for ever.

(f1) (1) The 0xfc000000 bits contain the character type number. The numbers are
         defined by an enum in ucp.h.

     (2) The 0x03ff0000 bits are spare.

     (3) The 0x0000ffff bits contain EITHER the unsigned offset to the top of
         range if this entry defines a range, OR the *signed* offset to the
         character's "other case" partner if this entry defines a single
         character. There is no partner if the value is zero.

-------------------------------------------------------------------------------
| script (8) |.|.|.| codepoint (21) || type (6) |.|.| spare (8) | offset (16) |
-------------------------------------------------------------------------------
              | | |                              | |
              | | |-> spare                      | |-> spare
              | |                                |
              | |-> spare                        |-> spare
              |
              |-> range flag

The upper/lower casing information is set only for characters that come in
pairs. The non-one-to-one mappings in the Unicode data are ignored.

When searching the data, proceed as follows:

(1) Set up for a binary chop search.

(2) If the top is not greater than the bottom, the character is not in the
    table. Its type must therefore be "Cn" ("Undefined").

(3) Find the middle vector element.

(4) Extract the code point and compare. If equal, we are done.

(5) If the test character is smaller, set the top to the current point, and
    goto (2).

(6) If the current entry defines a range, compute the last character by adding
    the offset, and see if the test character is within the range. If it is,
    we are done.

(7) Otherwise, set the bottom to one element past the current point and goto
    (2).
*/

/* End of ucpinternal.h */


text:
This is experimental library which implements _Binary Decision Diagrams_
(_BDD_) in [Racket](https://racket-lang.org) programming language.
This is not production library. It will be changed without preserving
backward compatibility in the future. Library implements **Reduced
Ordered Binary Decision Diagrams** (**ROBDD**) and  **Zero-Suppressed
Binary Decision Diagrams** (**ZDD**). My intent is to add implementation of
functions transforming ROBDD into ZDD and vice versa. I was inspired
by papers [1], [2].

## License

This code is released under MIT License.
Copyright (c) 2016 Peter Cerman (https://github.com/pcerman)

## Example of use

_ROBDD_
```Racket
(require "bdd.rkt" "robdd.rkt")

(define ex '(xor (xor x y) z))

;; create ROBDD for this boolean expression
(define bdd (make-robdd ex '(x y z)))

;; create graph representation of this ROBDD and write it into the file
(bdd->tgf bdd "bdd.tgf" '(x y z))

;; count number of solutions which evaluates to boolean value true
(robdd-sat-count bdd 3)
;; it returns: 4

;; transform ROBDD into boolean expression
(robdd->b-expr bdd '(x y z))
;; it returns: '(or (and x (or (and y z) (and (not y) (not z))))
;;                  (and (not x) (or (and y (not z)) (and (not y) z))))
```
Graph representation of the ROBDD from example:
![bdd.tgf](examples/bdd.png)

_ZDD_
```Racket
(require "bdd.rkt" "zdd.rkt")

(define ex '(xor (xor x y) z))

;; create ZDD for this boolean expression
(define zdd (make-zdd ex '(x y z)))

;; create graph representation of this ZDD and write it into the file
(bdd->tgf zdd "zdd.tgf" '(x y z))

;; count number of solutions which evaluates to boolean value true
(zdd-count zdd)
;; it returns: 4

;; transform ZDD into boolean expression
(zdd->b-expr zdd '(x y z))
;; it returns: '(or (and x (or (and y z) (and (not y) (not z))))
;;                  (and (not x) (or (and y (not z)) (and (not y) z))))
```
Graph representation of the ZDD from example. It represents subset
{ {x}, {y}, {z}, {x,y,z} } of powerset from {x,y,z}.
![zdd.tgf](examples/zdd.png)

### References

1. Henrik Reif Andersen, An Introduction to Binary Decision Diagrams, Lecture
   notes for 49285 Advanced Algorithms E97, October 1997, Department of
   Information Technology, Technical University of Denmark
2. Shin-ichi Minato, Zero-suppressed BDDs and their applications, International
   Journal on Software Tools for Technology Transfer, May 2001, Volume 3,
   Issue 2, pp 156–170, doi:10.1007/s100090100038


text:
package io.fabric8.camel.tooling.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerFactory;

import de.pdark.decentxml.Attribute;
import de.pdark.decentxml.Document;
import de.pdark.decentxml.Element;
import de.pdark.decentxml.Namespace;
import de.pdark.decentxml.Node;
import de.pdark.decentxml.NodeWithChildren;
import de.pdark.decentxml.XMLIOSource;
import de.pdark.decentxml.XMLSource;
import de.pdark.decentxml.XMLStringSource;
import de.pdark.decentxml.XMLWriter;
import io.fabric8.camel.tooling.util.parser.PatchedXMLParser;
import org.apache.camel.CamelContext;
import org.apache.camel.model.Constants;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.RoutesDefinition;
import org.apache.camel.spring.CamelContextFactoryBean;
import org.apache.camel.spring.CamelRouteContextFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ErrorHandler;

import static io.fabric8.camel.tooling.util.CamelNamespaces.*;

/**
 * Helper class for loading and saving XML for use at design time
 */
public class RouteXml {

    public static Logger LOG = LoggerFactory.getLogger(RouteXml.class);

    private JAXBContext _jaxbContext;
    private ClassLoader classLoader = CamelContextFactoryBean.class.getClassLoader();

    protected TransformerFactory transformerFactory = TransformerFactory.newInstance();
    protected DocumentBuilder documentBuilder = createDocumentBuilder();

    protected DocumentBuilder documentBuilder(ErrorHandler handler) {
        DocumentBuilder db = createDocumentBuilder();
        db.setErrorHandler(handler);
        return db;
    }

    public JAXBContext jaxbContext() throws JAXBException {
        if (_jaxbContext == null) {
            String packageName = Constants.JAXB_CONTEXT_PACKAGES + ":org.apache.camel.spring";
            _jaxbContext = JAXBContext.newInstance(packageName, classLoader);
        }
        return _jaxbContext;
    }

    public void setJaxbContext(JAXBContext jaxbContext) {
        this._jaxbContext = jaxbContext;
    }

    protected Document createExemplarDoc() throws IOException {
        String exemplar = "io/fabric8/camel/tooling/exemplar.xml";
        URL url = findResource(exemplar, null);
        if (url != null) {
            return parse(new XMLIOSource(url));
        } else {
            LOG.warn("Could not find file {} on the class path", exemplar);
            Document d = new Document();
            d.addNode(new Element("beans", springNamespace));
            return d;
        }
    }

    private Document parse(XMLSource source) {
        PatchedXMLParser parser = new PatchedXMLParser();
        return parser.parse(source);
    }

    public XmlModel unmarshal(File file) throws Exception {
        Document doc;
        if (file.exists()) {
            doc = parse(new XMLIOSource(file));
/*
      // lets find the header stuff
      val root = doc.getRootElement
      if (root != null) {
        val name = root.getNodeName()
        println("====== node name is: " + name)
        val text = IOUtil.loadTextFile(file)
        val idx = text.indexOf("<" + name)
        if (idx > 0) {
          header = text.substring(0, idx)
          println("header: " + header)
        }
      }
*/
        } else {
            doc = createExemplarDoc();
        }

        return unmarshal(doc, "XML File " + file);
    }

    public XmlModel unmarshal(String text) throws Exception {
        Document doc;
        if (text != null && text.trim().length() > 0) {
            doc = parse(new XMLStringSource(text));
        } else {
            doc = createExemplarDoc();
        }
        return unmarshal(doc, "Text");
    }

    public XmlModel unmarshal(Document doc) throws Exception {
        return unmarshal(doc, "XML document " + doc);
    }

    public XmlModel unmarshal(Document doc, String message) throws Exception {
        Unmarshaller unmarshaller = jaxbContext().createUnmarshaller();

        // ("bean", springNamespace)
        Map<String, String> beans = new HashMap<String, String>();

        // lets pull out the spring beans...
        // TODO: shouldn't we use http://www.springframework.org/schema/beans namespace instead??
        List<Node> beanElems = nodesByNamespace(doc, springNS, "bean");

        for (Node n: beanElems) {
            if (n instanceof Element) {
                String id = ((Element) n).getAttributeValue("id");
                String cn = ((Element) n).getAttributeValue("class");
                if (id != null && cn != null) {
                    beans.put(id, cn);
                }
            }
        }

        // now lets pull out the jaxb routes...
        List<String[]> search = Arrays.asList(
            new String[] { springNS, "routeContext" },
            new String[] { springNS, "camelContext" },
            new String[] { springNS, "routes" },
            new String[] { blueprintNS, "routeContext" },
            new String[] { blueprintNS, "camelContext" },
            new String[] { blueprintNS, "routes" }
        );

        List<Node> found = new LinkedList<Node>();

        for (String[] pair : search) {
            List<Node> nodes = nodesByNamespace(doc, pair[0], pair[1]);
            int n = nodes.size();
            if (n != 0) {
                if (n > 1) {
                    LOG.warn(message + " contains " + n + " <" + pair[1] + "> elements. Only the first one will be used");
                }
                Node node = nodes.get(0);
                found.add(node);
            }
        }

        if (found.size() > 0) {
            Node n = found.get(0);
            if (n != null) {
                String ns = getNamespaceURI(n);
                Node parseNode;
                if (!ns.equals(springNS)) {
                    parseNode = cloneAndReplaceNamespace(n, ns, springNS);
                } else {
                    parseNode = n;
                }

                boolean justRoutes = false;
                boolean routesContext = false;
                String xmlText = nodeWithNamespacesToText(parseNode, (Element) n);
                Object object = unmarshaller.unmarshal(new StringReader(xmlText));
                CamelContextFactoryBean sc;
                if (object instanceof CamelContextFactoryBean) {
                    LOG.debug("Found a valid CamelContextFactoryBean! {}", object);
                    sc = (CamelContextFactoryBean) object;
                } else if (object instanceof RoutesDefinition) {
                    justRoutes = true;
                    sc = new CamelContextFactoryBean();
                    sc.setRoutes(((RoutesDefinition) object).getRoutes());
                } else if (object instanceof CamelRouteContextFactoryBean) {
                    routesContext = true;
                    sc = new CamelContextFactoryBean();
                    sc.setRoutes(((CamelRouteContextFactoryBean) object).getRoutes());
                } else if (object instanceof org.apache.camel.blueprint.CamelRouteContextFactoryBean) {
                    routesContext = true;
                    sc = new CamelContextFactoryBean();
                    sc.setRoutes(((org.apache.camel.blueprint.CamelRouteContextFactoryBean) object).getRoutes());
                } else {
                    LOG.warn("Unmarshalled not a CamelContext: {}", object);
                    sc = new CamelContextFactoryBean();
                }
                return new XmlModel(sc, doc, beans, n, ns, justRoutes, routesContext);
            } else {
                LOG.info(message + " does not contain a CamelContext. Maybe the XML namespace is not spring: '{}' or blueprint: '{}'?", springNS, blueprintNS);
                // lets create a new collection
                return new XmlModel(new CamelContextFactoryBean(), doc, beans, null, CamelNamespaces.springNS, false, false);
            }
        }
        return null; // ?
    }

    protected Node cloneAndReplaceNamespace(Node node, String oldNS, String newNS) {
        Node answer = node.copy();
        return replaceNamespace(answer, oldNS, newNS);
    }

    protected Node replaceNamespace(Node node, String oldNS, String newNS) {
        if (node instanceof Element) {
            String ns = getNamespaceURI(node);
            if (ns != null && ns.equals(oldNS)) {
                Namespace namespace = ((Element) node).getNamespace();
                if (namespace != null) {
                    if (namespace.getURI() != null && namespace.getURI().equals(oldNS)) {
                        ((Element) node).setNamespace(new Namespace(namespace.getPrefix(), newNS));
                    }
                }

                for (Attribute attr : ((Element) node).getAttributes()) {
                    if (attr.getName().startsWith("xmlns")) {
                        String value = attr.getValue();
                        if (value != null && value.equals(oldNS)) {
                            attr.setValue(newNS);
                        }
                    }
                }
            }
        }

        if (node instanceof NodeWithChildren) {
            for (Node n : ((NodeWithChildren) node).getNodes()) {
                replaceNamespace(n, oldNS, newNS);
            }
        }

        return node;
    }

    public void marshal(File file, final CamelContextFactoryBean context) throws Exception {
        marshal(file, new Model2Model() {
            @Override
            public XmlModel transform(XmlModel model) {
                model.update(context);
                return model;
            }
        });
    }

    public void marshal(File file, final CamelContext context) throws Exception {
        marshal(file, new Model2Model() {
            @Override
            public XmlModel transform(XmlModel model) {
                copyRoutesToElement(context, model.getContextElement());
                return model;
            }
        });
    }

    public void copyRoutesToElement(List<RouteDefinition> routeDefinitionList, CamelContextFactoryBean contextElement) {
        List<RouteDefinition> routes = contextElement.getRoutes();
        routes.clear();
        routes.addAll(routeDefinitionList);
    }

    public void copyRoutesToElement(CamelContext context, CamelContextFactoryBean contextElement) {
        if (context instanceof ModelCamelContext) {
            copyRoutesToElement(((ModelCamelContext)context).getRouteDefinitions(), contextElement);
        } else {
            LOG.error("Invalid camel context! ({})", context.getClass().getName());
        }
    }

    /**
     * Loads the given file then updates the route definitions from the given list then stores the file again
     */
    public void marshal(File file, final List<RouteDefinition> routeDefinitionList) throws Exception {
        marshal(file, new Model2Model() {
            @Override
            public XmlModel transform(XmlModel model) {
                copyRoutesToElement(routeDefinitionList, model.getContextElement());
                return model;
            }
        });
    }

    public void marshal(File file, Model2Model transformer) throws Exception {
        // lets load the file first in case its been edited since we last loaded it
        XmlModel model = unmarshal(file);
        marshal(file, transformer.transform(model));
    }

    public String marshalToText(String text, final List<RouteDefinition> routeDefinitionList) throws Exception {
        return marshalToText(text, new Model2Model() {
            @Override
            public XmlModel transform(XmlModel model) {
                copyRoutesToElement(routeDefinitionList, model.getContextElement());
                return model;
            }
        });
    }

    public String marshalToText(String text, Model2Model transformer) throws Exception {
        XmlModel model = unmarshal(text);
        return marshalToText(transformer.transform(model));
    }

    public void marshal(File file, XmlModel model) throws JAXBException, IOException {
        marshalToDoc(model);
        writeXml(model.getDoc(), file);
    }

    public String marshalToText(XmlModel model) throws JAXBException, IOException {
        marshalToDoc(model);
        return xmlToText(model.getDoc());
    }

    protected void replaceCamelElement(Element docElem, Node camelElem, Node oldNode) {
        replaceChild(docElem, camelElem, oldNode);

        // lets replace the camel namespace, copying any namespace from the old node as well
        if (camelElem instanceof Element && oldNode instanceof Element) {
            for (Attribute attr : ((Element) oldNode).getAttributes()) {
                if (attr.getName().startsWith("xmlns")) {
                    ((Element) camelElem).setAttribute(attr.getName(), attr.getValue());
                }
            }
        }
    }

    /**
     * Marshals the model to XML and updates the model's doc property to contain the
     * new marshalled model
     *
     * @param model
     */
    public void marshalToDoc(XmlModel model) throws JAXBException {
        Marshaller marshaller = jaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, java.lang.Boolean.TRUE);
        try {
            marshaller.setProperty("com.sun.xml.bind.indentString", "  ");
        } catch (Exception e) {
            LOG.debug("Property not supported: {}", e);
        }

        Object value = model.marshalRootElement();
        Document doc = model.getDoc();
        Element docElem = doc.getRootElement();

        // JAXB only seems to do nice whitespace/namespace stuff when writing to stream
        // rather than DOM directly
        // marshaller.marshal(value, docElem);

        StringWriter buffer = new StringWriter();
        marshaller.marshal(value, buffer);

        // now lets parse the XML and insert the root element into the doc
        String xml = buffer.toString();
        if (!model.getNs().equals(springNS)) {
            // !!!
            xml = xml.replaceAll(springNS, model.getNs());
        }
        Document camelDoc = parse(new XMLStringSource(xml));
        Node camelElem = camelDoc.getRootElement();

        // TODO
        //val camelElem = doc.importNode(element, true)

        if (model.isRoutesContext() && camelDoc.getRootElement().getName().equals("camelContext")) {
            camelDoc.getRootElement().setName("routeContext");
        }
        if (model.isJustRoutes()) {
            replaceChild(doc, camelElem, docElem);
        } else {
            if (model.getNode() != null) {
                replaceCamelElement(docElem, camelElem, model.getNode());
            } else {
                docElem.addNode(camelElem);
            }
        }
    }

    public void writeXml(Document doc, File file) throws IOException {
        File parentDir = file.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs();
        }

        XMLWriter writer = new XMLWriter(new FileWriter(file));
        doc.toXML(writer);
        writer.close();
    }

    protected DocumentBuilder createDocumentBuilder() {
//        String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
//        String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
//        String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

//        boolean validating = false;
//        if (validating) {
//            try {
//                dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
//                dbf.setAttribute(JAXP_SCHEMA_SOURCE, CamelNamespaces.camelSchemas());
//                dbf.setValidating(validating);
//            } catch (Exception e) {
//                // ignore
//            }
//        }

        dbf.setExpandEntityReferences(false);
        dbf.setIgnoringComments(false);
        dbf.setIgnoringElementContentWhitespace(false);
        dbf.setCoalescing(false);
        dbf.setNamespaceAware(true);
        try {
            dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
            dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        } catch (Exception e) { /* Ignore errors */ }

        try {
            return dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * XmlModel => XmlModel
     */
    private static interface Model2Model {

        public XmlModel transform(XmlModel model);

    }

}