Serializes output to a core data type object

@param out
Output writer
@param field
The field to serialize
@param getter
The getter method if not a field
@param object
Parent object
@param value
Object to serialize
506810
@SuppressWarnings("unchecked")
    public static void serialize(Output out, Field field, Method getter, Object object, Object value) {
        log.trace("serialize");
        if (value instanceof IExternalizable) {
            // make sure all IExternalizable objects are serialized as objects
            out.writeObject(value);
        } else if (value instanceof ByteArray) {
            // write ByteArray objects directly
            out.writeByteArray((ByteArray) value);
        } else if (value instanceof Vector) {
            log.trace("Serialize Vector");
            // scan the vector to determine the generic type
            Vector<?> vector = (Vector<?>) value;
            int ints = 0;
            int longs = 0;
            int dubs = 0;
            int nans = 0;
            for (Object o : vector) {
                if (o instanceof Integer) {
                    ints++;
                } else if (o instanceof Long) {
                    longs++;
                } else if (o instanceof Number || o instanceof Double) {
                    dubs++;
                } else {
                    nans++;
                }
            }
            // look at the type counts
            if (nans > 0) {
                // if we have non-number types, use object
                ((org.red5.io.amf3.Output) out).enforceAMF3();
                out.writeVectorObject((Vector<Object>) value);
            } else if (dubs == 0 && longs == 0) {
                // no doubles or longs
                out.writeVectorInt((Vector<Integer>) value);
            } else if (dubs == 0 && ints == 0) {
                // no doubles or ints
                out.writeVectorUInt((Vector<Long>) value);
            } else {
                // handle any other types of numbers
                ((org.red5.io.amf3.Output) out).enforceAMF3();
                out.writeVectorNumber((Vector<Double>) value);
            }
        } else {
            if (writeBasic(out, value)) {
                log.trace("Wrote as basic");
            } else if (!writeComplex(out, value)) {
                log.trace("Unable to serialize: {}", value);
            }
        }
    }
552699
public static <T extends BitWritable> void writeObject(final BitOutput output, final T value) throws IOException {
        if (output == null) {
            throw new NullPointerException("output is null");
        }
        if (value == null) {
            throw new NullPointerException("value is null");
        }
        value.write(output);
    }
112168
public static void write(Object value, MediaEncoder encoder, Writer out) throws IOException {
		if(encoder==null) {
			write(value, out);
		} else {
			// Otherwise, if A is null, then the result is "".
			// Write nothing
			if(value != null) {
				// Unwrap out to avoid unnecessary validation of known valid output
				while(true) {
					out = unwrap(out);
					if(out instanceof MediaValidator) {
						MediaValidator validator = (MediaValidator)out;
						if(validator.canSkipValidation(encoder.getValidMediaOutputType())) {
							// Can skip validation, write directly to the wrapped output through the encoder
							out = validator.getOut();
						} else {
							break;
						}
					} else {
						break;
					}
				}
				// Write through the given encoder
				if(value instanceof String) {
					// If A is a string, then the result is A.
					encoder.write((String)value, out);
				} else if(value instanceof Writable) {
					Writable writable = (Writable)value;
					if(writable.isFastToString()) {
						encoder.write(writable.toString(), out);
					} else {
						// Avoid intermediate String from Writable
						writable.writeTo(encoder, out);
					}
				} else if(value instanceof Node) {
					// Otherwise, if is a DOM node, serialize the output
					try {
						// Can use thread-local or pooled transformers if performance is ever an issue
						TransformerFactory transFactory = TransformerFactory.newInstance();
						Transformer transformer = transFactory.newTransformer();
						transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
						transformer.transform(
							new DOMSource((Node)value),
							new StreamResult(new MediaWriter(encoder, out))
						);
					} catch(TransformerException e) {
						throw new IOException(e);
					}
				} else {
					// Otherwise, if A.toString() throws an exception, then raise an error
					// Otherwise, the result is A.toString();
					encoder.write(value.toString(), out);
				}
			}
		}
	}
308524
static void serialize(DataOutput out, Serializers serializers)
      throws IOException {
    StringBuilder msg = new StringBuilder(String.format("Serialize %d serializer classes:", serializers.serializers.values().size()));
    int size = serializers.serializers.values().size();

    out.writeInt(size);
    if (size > 0) {
      for (SerializerWrapper sw : serializers.serializers.values()) {
        int index = sw.index;
        String name = sw.serializer.getClass().getName();

        out.writeInt(index);
        out.writeUTF(name);

        msg.append(String.format("%n  (%d) %s", index, name));
      }
      LOGGER.info(msg.toString());
    }
  }
191044
public static void writeObject(CodedOutputStream out, int order, FieldType type, Object o, boolean list)
            throws IOException {
        if (o == null) {
            return;
        }

        if (type == FieldType.OBJECT) {

            Class cls = o.getClass();
            Codec target = ProtobufProxy.create(cls);

            out.writeRawVarint32(makeTag(order, WireFormat.WIRETYPE_LENGTH_DELIMITED));
            out.writeRawVarint32(target.size(o));

            target.writeTo(o, out);
            return;
        }

        if (type == FieldType.BOOL) {
            out.writeBool(order, (Boolean) o);
        } else if (type == FieldType.BYTES) {
            byte[] bb = (byte[]) o;
            out.writeBytes(order, ByteString.copyFrom(bb));
        } else if (type == FieldType.DOUBLE) {
            out.writeDouble(order, (Double) o);
        } else if (type == FieldType.FIXED32) {
            out.writeFixed32(order, (Integer) o);
        } else if (type == FieldType.FIXED64) {
            out.writeFixed64(order, (Long) o);
        } else if (type == FieldType.FLOAT) {
            out.writeFloat(order, (Float) o);
        } else if (type == FieldType.INT32) {
            out.writeInt32(order, (Integer) o);
        } else if (type == FieldType.INT64) {
            out.writeInt64(order, (Long) o);
        } else if (type == FieldType.SFIXED32) {
            out.writeSFixed32(order, (Integer) o);
        } else if (type == FieldType.SFIXED64) {
            out.writeSFixed64(order, (Long) o);
        } else if (type == FieldType.SINT32) {
            out.writeSInt32(order, (Integer) o);
        } else if (type == FieldType.SINT64) {
            out.writeSInt64(order, (Long) o);
        } else if (type == FieldType.STRING) {
            out.writeBytes(order, ByteString.copyFromUtf8(String.valueOf(o)));
        } else if (type == FieldType.UINT32) {
            out.writeUInt32(order, (Integer) o);
        } else if (type == FieldType.UINT64) {
            out.writeUInt64(order, (Long) o);
        } else if (type == FieldType.ENUM) {
            int value = 0;
            if (o instanceof EnumReadable) {
                value = ((EnumReadable) o).value();
            } else if (o instanceof Enum) {
                value = ((Enum) o).ordinal();
            }
            out.writeEnum(order, value);
        }
    }
676510
public void writeObject(Object oldInstance, Encoder out)
    {
        // Override the default FieldPersistence algorithm for the encoder, so private fields
        // can also be encoded
        out.setPersistenceDelegate(Field.class, new FieldPersistenceDelegate());
        super.writeObject(oldInstance, out);
    }
232684
public static void write(Object value, Writer out) throws IOException {
		if(out instanceof MediaWriter) {
			// Unwrap media writer and use encoder directly
			MediaWriter mediaWriter = (MediaWriter)out;
			write(
				value,
				mediaWriter.getEncoder(),
				mediaWriter.getOut()
			);
		} else {
			if(value instanceof String) {
				// If A is a string, then the result is A.
				out.write((String)value);
			} else if(value == null) {
				// Otherwise, if A is null, then the result is "".
				// Write nothing
			} else if(value instanceof Writable) {
				Writable writable = (Writable)value;
				if(writable.isFastToString()) {
					out.write(writable.toString());
				} else {
					// Avoid intermediate String from Writable
					writable.writeTo(unwrap(out));
				}
			} else if(value instanceof Node) {
				// Otherwise, if is a DOM node, serialize the output
				try {
					// Can use thread-local or pooled transformers if performance is ever an issue
					TransformerFactory transFactory = TransformerFactory.newInstance();
					Transformer transformer = transFactory.newTransformer();
					transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
					transformer.transform(
						new DOMSource((Node)value),
						new StreamResult(unwrap(out))
					);
				} catch(TransformerException e) {
					throw new IOException(e);
				}
			} else {
				// Otherwise, if A.toString() throws an exception, then raise an error
				// Otherwise, the result is A.toString();
				out.write(value.toString());
			}
		}
	}
59198
public void writeToStream(OutputStream stream, Object object) throws SerializationException {
        try {
            mapper.writeValue(stream, object);
        } catch (IOException ex) {
            throw new SerializationException("Exception during serialization", ex);
        }
    }
908601
@SuppressWarnings("all")
    protected static boolean writeObjectType(Output out, Object obj) {
        if (obj instanceof ObjectMap || obj instanceof BeanMap) {
            out.writeObject((Map) obj);
        } else if (obj instanceof Map) {
            out.writeMap((Map) obj);
        } else if (obj instanceof RecordSet) {
            out.writeRecordSet((RecordSet) obj);
        } else {
            out.writeObject(obj);
        }
        return true;
    }
900564
@Deprecated
    static void field(final Field field, final Object obj, final Object value) throws ReflectiveOperationException {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        final Class<?> type = field.getType();
        if (type.isPrimitive()) {
            if (value == null) {
                // @todo: WARN
                return;
            }
            if (type == boolean.class) {
                field.setBoolean(obj, (Boolean) value);
                return;
            }
            if (type == byte.class) {
                field.setByte(obj, (Byte) value);
                return;
            }
            if (type == char.class) {
                field.setChar(obj, (Character) value);
                return;
            }
            if (type == double.class) {
                field.setDouble(obj, (Double) value);
                return;
            }
            if (type == float.class) {
                field.setFloat(obj, (Float) value);
                return;
            }
            if (type == int.class) {
                field.setInt(obj, (Integer) value);
                return;
            }
            if (type == long.class) {
//                field.setLong(obj, (Long) value);
                if (value instanceof Number) {
                    field.setLong(obj, ((Number) value).longValue());
                    return;
                }
                return;
            }
            if (type == short.class) {
                if (value instanceof Number) {
                    field.setShort(obj, ((Number) value).shortValue());
                    return;
                }
            }
        }
        try {
            field.set(obj, value);
        } catch (final IllegalArgumentException iae) {
            if (type == Boolean.class) {
            }
            if (type == Byte.class) {
            }
            if (type == Short.class) {
                if (value instanceof Number) {
                    field.set(obj, ((Number) value).shortValue());
                    return;
                }
            }
            if (type == Integer.class) {
                if (value instanceof Number) {
                    field.set(obj, ((Number) value).intValue());
                    return;
                }
            }
            if (type == Long.class) {
            }
            if (type == Character.class) {
            }
            if (type == Float.class) {
            }
            if (type == Double.class) {
            }
            throw iae;
        }
    }
1228077
void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // when using object serialization, write the json bytes
        byte[] bytes = toString().getBytes(StandardCharsets.UTF_8);
        out.writeInt(bytes.length);
        out.write(bytes);
    }
1257179
private static void writeField(ObjectOutput out, Fieldable field) throws IOException
   {
      // Name
      out.writeUTF(field.name());
      // Flags
      writeFlags(out, field);
      if (field.getBoost() != 1.0f)
      {
         // Boost
         out.writeFloat(field.getBoost());
      }
      // Value
      writeValue(out, field);
   }
854978
public void out2field(Object from, String from_out, Object o, String field) {
        controller.mapOutField(from, from_out, o, field);
    }
311999
@Override
	public void serialize(Record record, DataOutputView target) throws IOException {
		record.serialize(target);
	}
3459
private static void addFieldToJsonObject(Method getter, Object o,
                                             String fieldName, JsonObjectBuilder j) {
        try {
            Object fieldValue = getter.invoke(o);

            if (fieldValue == null) {
            } else if (fieldValue instanceof String) {
                j.add(fieldName, (String) fieldValue);
            } else if (fieldValue instanceof Boolean) {
                j.add(fieldName, (Boolean) fieldValue);
            } else if (fieldValue instanceof BigInteger) {
                j.add(fieldName, (BigInteger) fieldValue);
            } else if (fieldValue instanceof java.math.BigDecimal) {
                j.add(fieldName, (BigDecimal) fieldValue);
            } else if (fieldValue instanceof Double) {
                j.add(fieldName, (Double) fieldValue);
            } else if (fieldValue instanceof Integer) {
                j.add(fieldName, (Integer) fieldValue);
            } else if (fieldValue instanceof Long) {
                j.add(fieldName, (Long) fieldValue);
            } else if (fieldValue instanceof Short) {
                j.add(fieldName, (Short) fieldValue);
            } else if (fieldValue instanceof Byte) {
                j.add(fieldName, (Byte) fieldValue);

            } else if (fieldValue instanceof Enum) {
                try {
                    // enums need careful handling.. look for get/set Value to use.
                    Method getValueForEnumMethod = fieldValue.getClass().getMethod("getValue");
                    Object valueFromGetValueMethod = getValueForEnumMethod.invoke(fieldValue);
                    j.add(fieldName, valueFromGetValueMethod.toString());
                } catch (NoSuchMethodException e) {
                    // else fallback to toString
                    j.add(fieldName, fieldValue.toString());
                }
            } else if (fieldValue instanceof Collection
                       || fieldValue.getClass().getName().startsWith(DATA_MODEL_PACKAGE)) {
                JSONArtrifactPair fieldObjects = findFieldsToSerialize(fieldValue);
                j.add(fieldName, fieldObjects.mainObject);
                if (fieldObjects.incompatibleFieldsObject != null && !fieldObjects.incompatibleFieldsObject.isEmpty()) {
                    // As per the contract on the HasBreakingChanges interface store incompatible fields in a second object
                    j.add(fieldName + "2", fieldObjects.incompatibleFieldsObject);
                }
            } else if (fieldValue instanceof Calendar) {
                Date date = ((Calendar) fieldValue).getTime();
                j.add(fieldName, getDateFormat().format(date));
            } else if (fieldValue instanceof Date) {
                j.add(fieldName, getDateFormat().format((Date) fieldValue));
            } else if (fieldValue instanceof Locale) {
                //note that Locale toString is a bit fiddly to round trip, but it's the best we have for now.
                String localeString = ((Locale) fieldValue).toString();
                j.add(fieldName, localeString);
            } else {
                throw new IllegalStateException("Data Model Error: Unknown data model entity "
                                                + getter.getName() + " of type " + fieldValue.getClass().getName() + " on "
                                                + o.getClass().getName());
            }

        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Data Model Error: unable to invoke getter "
                                            + getter.getName() + " on "
                                            + o.getClass().getName(), e);
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException("Data Model Error: unable to invoke getter "
                                            + getter.getName() + " on "
                                            + o.getClass().getName(), e);
        } catch (InvocationTargetException e) {
            throw new IllegalStateException("Data Model Error: unable to invoke getter "
                                            + getter.getName() + " on "
                                            + o.getClass().getName(), e);
        } catch (JsonException e) {
            // Shouldn't happen unless field name is null or the value cannot be converted
            throw new IllegalStateException("Data Model Error: unable to invoke getter "
                                            + getter.getName() + " on "
                                            + o.getClass().getName(), e);
        }
    }
1087971
public static void toJSONString(OutputAccessor out, Map<String, ? extends Object> map) {

        writeObjectStart(out);
        boolean first = true;

        for (Map.Entry<String, ? extends Object> entry : map.entrySet()) {

            if (first) {
                first = false;
            } else {
                writeKeyValueSeparator(out);
            }

            writeMapEntry(out, entry.getKey(), entry.getValue());
        }

        writeObjectEnd(out);

    }
1114845
public void ser(Object datum, OutputStream output) throws IOException {
		Map<Class, Serializer> serializers = cachedSerializers.get();
		Serializer ser = serializers.get(datum.getClass());
		if(ser == null) {
			ser = serialization.getSerializer(datum.getClass());
			if(ser == null) {
				throw new IOException("Serializer for class " + datum.getClass() + " not found");
			}
			serializers.put(datum.getClass(), ser);
		}
		ser.open(output);
		ser.serialize(datum);
		ser.close();
	}