serialize a Query

@param query Query to serialize
@param done
@return serialized query
@throws ConverterException
333787
private String _serializeQuery(Query query, Set<Object> done) throws ConverterException {

	// fieldnames
	PageContext pc = ThreadLocalPageContext.get();
	boolean upperCase = false;
	if (pc != null) upperCase = pc.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML && !((ConfigWebImpl) pc.getConfig()).preserveCase();

	StringBuilder fn = new StringBuilder();
	Collection.Key[] keys = CollectionUtil.keys(query);
	for (int i = 0; i < keys.length; i++) {
	    if (i > 0) fn.append(',');
	    fn.append(XMLUtil.escapeXMLString(upperCase ? keys[i].getUpperString() : keys[i].getString()));
	}

	StringBuilder sb = new StringBuilder(
		goIn() + "<recordset rowCount=" + del + query.getRecordcount() + del + " fieldNames=" + del + fn + del + " type=" + del + "coldfusion.sql.QueryTable" + del + ">");

	deep++;
	int len = query.getRecordcount();
	for (int i = 0; i < keys.length; i++) {
	    sb.append(goIn() + "<field name=" + del + XMLUtil.escapeXMLString(keys[i].getString()) + del + ">");
	    for (int y = 1; y <= len; y++) {
		try {
		    sb.append(_serialize(query.getAt(keys[i], y), done));
		}
		catch (PageException e) {
		    sb.append(_serialize(e.getMessage(), done));
		}
	    }

	    sb.append(goIn() + "</field>");
	}
	deep--;

	sb.append(goIn() + "</recordset>");
	return sb.toString();
    }
1127696
private void _serializeSerializable(Serializable serializable, StringBuilder sb) throws ConverterException {

	sb.append(goIn());
	sb.append("evaluateJava(").append(QUOTE_CHR);
	try {
	    sb.append(JavaConverter.serialize(serializable));
	}
	catch (IOException e) {
	    throw toConverterException(e);
	}
	sb.append(QUOTE_CHR).append(')');
    }
667824
public void _serializeStruct(Struct struct, StringBuilder sb, Set<Object> done) throws ConverterException {
	sb.append(goIn());
	sb.append('{');
	Iterator it = struct.keyIterator();
	boolean doIt = false;
	deep++;
	while (it.hasNext()) {
	    String key = Caster.toString(it.next(), "");
	    if (doIt) sb.append(',');
	    doIt = true;
	    sb.append(QUOTE_CHR);
	    sb.append(escape(key));
	    sb.append(QUOTE_CHR);
	    sb.append(':');
	    _serialize(struct.get(key, null), sb, done);
	}
	deep--;

	sb.append('}');
    }
288321
private Object _deserializeQuery(Element recordset) throws ConverterException {
	try {
	    // create Query Object
	    Query query = new QueryImpl(lucee.runtime.type.util.ListUtil.listToArray(recordset.getAttribute("fieldNames"), ','),
		    Caster.toIntValue(recordset.getAttribute("rowCount")), "query");

	    NodeList list = recordset.getChildNodes();
	    int len = list.getLength();
	    for (int i = 0; i < len; i++) {
		Node node = list.item(i);
		if (node instanceof Element) {
		    _deserializeQueryField(query, (Element) node);
		}
	    }
	    return query;
	}
	catch (PageException e) {
	    throw toConverterException(e);
	}

    }
82278
private String _serializeArray(Array array, Set<Object> done) throws ConverterException {
	return _serializeList(array.toList(), done);
    }
606889
@Override
	protected void serializeTo(RawDataBuffer out)
    {
    	super.serializeTo(out);
        out.writeInt(browserId.asInt());
    }
51531
public static void serializeTo( Destination destination , RawDataBuffer out )
    {
    	try
    	{
    		if (destination == null)
    		{
    			out.writeByte(NO_DESTINATION);
    		}
    		else
	        if (destination instanceof Queue)
	        {
	            out.writeByte(TYPE_QUEUE);
	            out.writeUTF(((Queue)destination).getQueueName());
	        }
	        else
            if (destination instanceof Topic)
            {
            	out.writeByte(TYPE_TOPIC);
                out.writeUTF(((Topic)destination).getTopicName());
            }
            else
                throw new IllegalArgumentException("Unsupported destination : "+destination);
    	}
    	catch (JMSException e)
    	{
    		throw new IllegalArgumentException("Cannot serialize destination : "+e.getMessage());
    	}
    }
266354
def serialize_query(func):
        
        @functools.wraps(func)
        def wrapper(self, query, *args, **kwargs):
            if hasattr(query, 'serialize'):
                query = query.serialize()

            assert isinstance(query, basestring), 'Expected query to be string'
            if self.debug:
                print('SQL:', query)

            return func(self, query, *args, **kwargs)
        return wrapper
755577
private Map<String, Object> parseInsertIntoQuery(String query)
    {
        Map<String, Object> persistDetails = new HashMap<String, Object>();
        String insertReg = "(?i)^insert\\s+into\\s+(\\S+)\\s+(?:as\\s+(\\S+)\\s+)?FROM\\s+\\((.*)\\)$";
        Pattern r = Pattern.compile(insertReg);

        Matcher m = r.matcher(query);
        if (m.find())
        {
            try
            {
                parsePersistClause(m.group(1), persistDetails);
                persistDetails.put("format", m.group(2));
                persistDetails.put("fetchQuery", m.group(3));
            }
            catch (Exception e)
            {
                throw new KunderaException("Invalid Query");
            }
        }
        else
        {
            throw new KunderaException("Invalid Query");
        }

        return persistDetails;
    }
716196
private String _serialize(Object object, Map<Object, String> done) throws ConverterException {

	type = "OBJECT";

	String rtn;
	deep++;
	// NULL
	if (object == null) {
	    rtn = goIn() + "";
	    deep--;
	    type = "NULL";
	    return rtn;
	}
	// String
	if (object instanceof String) {
	    rtn = goIn() + XMLUtil.escapeXMLString(object.toString());
	    deep--;
	    type = "STRING";
	    return rtn;
	}
	// Number
	if (object instanceof Number) {
	    rtn = goIn() + ((Number) object).doubleValue();
	    deep--;
	    type = "NUMBER";
	    return rtn;
	}
	// Boolean
	if (object instanceof Boolean) {
	    rtn = goIn() + ((Boolean) object).booleanValue();
	    deep--;
	    type = "BOOLEAN";
	    return rtn;
	}
	// DateTime
	if (object instanceof DateTime) {
	    rtn = _serializeDateTime((DateTime) object);
	    deep--;
	    type = "DATE";
	    return rtn;
	}
	// Date
	if (object instanceof Date) {
	    rtn = _serializeDate((Date) object);
	    deep--;
	    type = "DATE";
	    return rtn;
	}

	Object raw = LazyConverter.toRaw(object);
	String strId = done.get(raw);
	if (strId != null) {
	    rtn = goIn() + "<REF id=\"" + strId + "\"\\>";
	    deep--;
	    type = "NULL";
	    return rtn;
	}
	strId = Caster.toString(++this.id);
	done.put(raw, strId);
	try {
	    // Component
	    if (object instanceof Component) {
		rtn = _serializeComponent((Component) object, done);
		deep--;
		return rtn;
	    }
	    // Struct
	    if (object instanceof Struct) {
		rtn = _serializeStruct((Struct) object, done, strId);
		deep--;
		return rtn;
	    }
	    // Map
	    if (object instanceof Map) {
		rtn = _serializeMap((Map) object, done);
		deep--;
		return rtn;
	    }
	    // Array
	    if (object instanceof Array) {
		rtn = _serializeArray((Array) object, done, strId);
		deep--;
		return rtn;
	    }
	    // List
	    if (object instanceof List) {
		rtn = _serializeList((List) object, done, strId);
		deep--;
		return rtn;
	    }
	    // Query
	    if (object instanceof Query) {
		rtn = _serializeQuery((Query) object, done, strId);
		deep--;
		return rtn;
	    }
	}
	finally {
	    done.remove(raw);
	}
	// Others
	rtn = "<STRUCT ID=\"" + strId + "\" TYPE=\"" + Caster.toTypeName(object) + "\"></STRUCT>";
	deep--;
	return rtn;
    }
273955
private String _serializeComponent(Component component, Map<Object, String> done) throws ConverterException {
	StringBuilder sb = new StringBuilder();
	Component ca;
	component = new ComponentSpecificAccess(Component.ACCESS_PRIVATE, ca = component);
	boolean isPeristent = ca.isPersistent();

	deep++;
	Object member;
	Iterator<Key> it = component.keyIterator();
	Collection.Key key;
	while (it.hasNext()) {
	    key = it.next();
	    member = component.get(key, null);
	    if (member instanceof UDF) continue;
	    sb.append(goIn() + "<var scope=\"this\" name=" + del + key.toString() + del + ">");
	    sb.append(_serialize(member, done));
	    sb.append(goIn() + "</var>");
	}

	Property p;
	Boolean remotingFetch;
	Struct props = ignoreRemotingFetch ? null : ComponentUtil.getPropertiesAsStruct(ca, false);
	ComponentScope scope = ca.getComponentScope();
	it = scope.keyIterator();
	while (it.hasNext()) {
	    key = Caster.toKey(it.next(), null);
	    if (!ignoreRemotingFetch) {
		p = (Property) props.get(key, null);
		if (p != null) {
		    remotingFetch = Caster.toBoolean(p.getDynamicAttributes().get(REMOTING_FETCH, null), null);
		    if (remotingFetch == null) {
			if (isPeristent && ORMUtil.isRelated(p)) continue;
		    }
		    else if (!remotingFetch.booleanValue()) continue;
		}
	    }

	    member = scope.get(key, null);
	    if (member instanceof UDF || key.equals(KeyConstants._this)) continue;
	    sb.append(goIn() + "<var scope=\"variables\" name=" + del + key.toString() + del + ">");
	    sb.append(_serialize(member, done));
	    sb.append(goIn() + "</var>");
	}

	deep--;
	try {
	    // return goIn()+"<struct>"+sb+"</struct>";
	    return goIn() + "<component md5=\"" + ComponentUtil.md5(component) + "\" name=\"" + component.getAbsName() + "\">" + sb + "</component>";
	}
	catch (Exception e) {
	    throw toConverterException(e);
	}
    }
1300373
public void serialize(@Nonnull Iterable<QueryResult> results, @Nonnull OutputStream out) throws IOException {
		JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
		g.writeStartObject();
		g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
		g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
		g.writeArrayFieldStart("data");

		for (QueryResult metric : results) {
			g.writeStartObject();
			g.writeStringField("name", metric.getName());
			if (instanceId != null && !instanceId.isEmpty()) {
				g.writeStringField("instance", instanceId);
			}
			g.writeNumberField("collected_at", metric.getEpoch(TimeUnit.SECONDS));
			if (metric.getValue() instanceof Integer) {
				g.writeNumberField("value", (Integer) metric.getValue());
			} else if (metric.getValue() instanceof Long) {
				g.writeNumberField("value", (Long) metric.getValue());
			} else if (metric.getValue() instanceof Float) {
				g.writeNumberField("value", (Float) metric.getValue());
			} else if (metric.getValue() instanceof Double) {
				g.writeNumberField("value", (Double) metric.getValue());
			}
			g.writeEndObject();
		}

		g.writeEndArray();
		g.writeEndObject();
		g.flush();
		g.close();
	}
640373
protected String transformQuery(String query, QueryTransformer ... qts) {
        String result = query;
        for (QueryTransformer qt : qts) {
            result = transformQuery(result, qt);
        }
        return result;
    }
122004
public PaginatedResult execute(final Query query) {
        final long count = getCount(query);
        decorate(query);
        return new PaginatedResult()
                .objects(query.execute())
                .total(count);
    }
1272554
private String _serializeStruct(String name, Struct struct, StringBuilder sb, Set<Object> done) throws ConverterException {
	if (useShortcuts) sb.append("{};");
	else sb.append("new Object();");

	Iterator<Entry<Key, Object>> it = struct.entryIterator();
	Entry<Key, Object> e;
	while (it.hasNext()) {
	    e = it.next();
	    // lower case ist ok!
	    String key = StringUtil.escapeJS(Caster.toString(e.getKey().getLowerString(), ""), '"');
	    sb.append(name + "[" + key + "]=");
	    _serialize(name + "[" + key + "]", e.getValue(), sb, done);
	}
	return sb.toString();
    }
843355
private void _serialize(PageContext pc, Set test, Object object, StringBuilder sb, boolean serializeQueryByColumns, Set done) throws ConverterException {

	// NULL
	if (object == null || object == NULL) {
	    sb.append(goIn());
	    sb.append("null");
	    return;
	}
	// String
	if (object instanceof String || object instanceof StringBuilder) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(object.toString(), '"', charsetEncoder));
	    return;
	}
	// TimeZone
	if (object instanceof TimeZone) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(((TimeZone) object).getID(), '"', charsetEncoder));
	    return;
	}
	// Locale
	if (object instanceof Locale) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(LocaleFactory.toString((Locale) object), '"', charsetEncoder));
	    return;
	}
	// Character
	if (object instanceof Character) {
	    sb.append(goIn());
	    sb.append(StringUtil.escapeJS(String.valueOf(((Character) object).charValue()), '"', charsetEncoder));
	    return;
	}
	// Number
	if (object instanceof Number) {
	    sb.append(goIn());
	    sb.append(Caster.toString(((Number) object)));
	    return;
	}
	// Boolean
	if (object instanceof Boolean) {
	    sb.append(goIn());
	    sb.append(Caster.toString(((Boolean) object).booleanValue()));
	    return;
	}
	// DateTime
	if (object instanceof DateTime) {
	    _serializeDateTime((DateTime) object, sb);
	    return;
	}
	// Date
	if (object instanceof Date) {
	    _serializeDate((Date) object, sb);
	    return;
	}
	// XML
	if (object instanceof Node) {
	    _serializeXML((Node) object, sb);
	    return;
	}
	// Timespan
	if (object instanceof TimeSpan) {
	    _serializeTimeSpan((TimeSpan) object, sb);
	    return;
	}
	// File
	if (object instanceof File) {
	    _serialize(pc, test, ((File) object).getAbsolutePath(), sb, serializeQueryByColumns, done);
	    return;
	}
	// String Converter
	if (object instanceof ScriptConvertable) {
	    sb.append(((ScriptConvertable) object).serialize());
	    return;
	}
	// byte[]
	if (object instanceof byte[]) {
	    sb.append("\"" + Base64Coder.encode((byte[]) object) + "\"");
	    return;
	}
570545
public function serialize()
    {
        return serialize(array(
            'records' => serialize($this->records),
            'done' => $this->done,
            'queryLocator' => serialize($this->queryLocator),
            'size' => $this->size
        ));
    }