Generate serialize on xml.

@param context
the context
@param entity
the entity
548955
private static void generateSerializeOnXml(BindTypeContext context, BindEntity entity) {
		// @formatter:off
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("serializeOnXml")
				.addJavadoc("method for xml serialization\n").addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC)
				// .addParameter(typeName(KriptonXmlContext.class), "context")
				.addParameter(typeName(entity.getElement()), "object")
				.addParameter(typeName(XMLSerializer.class), "xmlSerializer")
				.addParameter(typeName(Integer.TYPE), "currentEventType").returns(Void.TYPE)
				.addException(Exception.class);
		// @formatter:on

		methodBuilder.beginControlFlow("if (currentEventType == 0)");
		methodBuilder.addStatement("xmlSerializer.writeStartElement(\"$L\")", entity.xmlInfo.label);

		// write namespace
		for (Pair<String, String> namespace : entity.xmlInfo.namespaces) {
			if (StringUtils.hasText(namespace.value0)) {
				methodBuilder.addStatement("xmlSerializer.writeAttribute(\"\", $S, $S)", "xmlns:" + namespace.value0,
						namespace.value1);
			} else {
				methodBuilder.addStatement("xmlSerializer.writeAttribute(\"\", $S, $S)", "xmlns", namespace.value1);
			}

		}

		methodBuilder.endControlFlow();

		BindTransform bindTransform;

		methodBuilder.addCode("\n");

		// attributes
		methodBuilder.addCode("// Persisted fields:\n\n");
		for (BindProperty item : entity.getCollection()) {
			bindTransform = BindTransformer.lookup(item);

			methodBuilder.addCode("// field $L (mapped with $S)\n", item.getName(), BindProperty.xmlName(item));
			if (item.hasTypeAdapter()) {
				methodBuilder.addCode("// field trasformation $L $L \n", item.typeAdapter.dataType,
						item.typeAdapter.adapterClazz);
			}
			bindTransform.generateSerializeOnXml(context, methodBuilder, "xmlSerializer",
					item.getPropertyType().getTypeName(), "object", item);
			methodBuilder.addCode("\n");
		}

		methodBuilder.beginControlFlow("if (currentEventType == 0)");
		methodBuilder.addStatement("xmlSerializer.writeEndElement()");
		methodBuilder.endControlFlow();

		// methodBuilder.nextControlFlow("catch($T e)",
		// typeName(Exception.class));
		// methodBuilder.addStatement("e.printStackTrace()");
		// methodBuilder.addStatement("throw (new $T(e))",
		// typeName(KriptonRuntimeException.class));
		// methodBuilder.endControlFlow();

		context.builder.addMethod(methodBuilder.build());
	}
578927
protected void generateEntityListener(EntityListenerDesc entityListenerDesc) {
    File javaFile =
        FileUtil.createJavaFile(entityConfig.getDestDir(), entityListenerDesc.getQualifiedName());
    GenerationContext context =
        new GenerationContext(
            entityListenerDesc,
            javaFile,
            entityListenerDesc.getTemplateName(),
            entityConfig.getEncoding(),
            entityConfig.isOverwriteListener());
    generator.generate(context);
  }
1007951
private static void generateParserOnXmlStartElement(BindTypeContext context, MethodSpec.Builder methodBuilder,
			String instanceName, String parserName, BindEntity entity) {
		BindTransform bindTransform;
		// start and inner bean
		methodBuilder.addStatement("currentTag = xmlParser.getName().toString()");

		int count = 0;
		// count property to manage
		{
			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					count++;
				}
			}
		}

		if (count > 0) {
			// switch for tag elements
			// @formatter:off
			methodBuilder.beginControlFlow("switch(currentTag)$>");

			// for each elements
			for (BindProperty property : entity.getCollection()) {
				if (property.xmlInfo.xmlType != XmlType.TAG)
					continue;

				bindTransform = BindTransformer.lookup(property);

				// here we manage only property of bean type
				if (bindTransform != null) {
					methodBuilder.addCode("case $S:\n$>", BindProperty.xmlName(property));
					methodBuilder.addCode("// property $L (mapped on $S)\n", property.getName(),
							BindProperty.xmlName(property));

					// methodBuilder.beginControlFlow("if
					// (!xmlParser.isEmptyElement())");
					bindTransform.generateParseOnXml(context, methodBuilder, "xmlParser",
							property.getPropertyType().getTypeName(), "instance", property);
					// methodBuilder.endControlFlow();

					methodBuilder.addStatement("$<break");
				}
			}

			methodBuilder.addCode("default:\n$>");
			// methodBuilder.addStatement("$L.skipElement()", parserName);

			methodBuilder.addStatement("$<break");
			methodBuilder.endControlFlow();
		} else {
			methodBuilder.addCode("// No property to manage here\n");
		}
		// @formatter:on

	}
1253897
def serialize(self, entity, request=None):
        

        def should_we_insert(value, field_spec):
            return value not in self.missing or field_spec.required

        errors = {}
        ret = {}

        for field_name, field_spec in self.spec.fields.items():
            value = self._get_value_for_serialization(entity, field_name, field_spec)
            func = self._get_serialize_func(field_name, self.spec)
            try:
                # perform serialization
                value = func(value, entity, request)
                if should_we_insert(value, field_spec):
                    ret[field_name] = value
            except ValidationError, e:
                if hasattr(e, 'message_dict'):
                    # prefix error keys with top level field name
                    errors.update(dict(zip(
                        [field_name + '.' + key for key in e.message_dict.keys()],
                        e.message_dict.values())))
                else:
                    errors[field_name] = e.messages

        if errors:
            raise ValidationError(errors)

        return None if ret == {} else ret
823128
private function configureContext(Context $context)
    {
        foreach ($this->attributes as $key => $value) {
            $context->setAttribute($key, $value);
        }
        if (!empty($this->groups)) {
            $context->setGroups($this->groups);
        }

        if (($context instanceof SerializationContext) && $this->serializeNulls !== null) {
            $context->setSerializeNull($this->serializeNulls);
        }

        if ($this->enableMaxDepthChecks === true) {
            $context->enableMaxDepthChecks();
        }

        if ($this->version !== null) {
            $context->setVersion($this->version);
        }

        return $context;
    }
1364767
protected void _generate(SarlClass clazz, IExtraLanguageGeneratorContext context) {
		final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(clazz);
		final PyAppendable appendable = createAppendable(jvmType, context);
		if (generateTypeDeclaration(
				this.qualifiedNameProvider.getFullyQualifiedName(clazz).toString(),
				clazz.getName(), clazz.isAbstract(),
				getSuperTypes(clazz.getExtends(), clazz.getImplements()),
				getTypeBuilder().getDocumentation(clazz),
				true,
				clazz.getMembers(), appendable, context, null)) {
			final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(clazz);
			writeFile(name, appendable, context);
		}
	}
986033
public static String getEntityEncoding(HttpEntity entity) {
		final Header header = entity.getContentEncoding();
		if (header == null)
			return null;
		return header.getValue();
	}
647631
private void writeObject(JsonGenerator jsonGenerator, Object entity) throws IOException {
        jsonGenerator.writeStartObject();

        writeName(jsonGenerator, entity);
        writeKind(jsonGenerator, entity);
        writeURL(jsonGenerator, entity);

        jsonGenerator.writeEndObject();
    }
851585
protected void _generate(SarlEvent event, IExtraLanguageGeneratorContext context) {
		final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(event);
		final PyAppendable appendable = createAppendable(jvmType, context);
		final List<JvmTypeReference> superTypes;
		if (event.getExtends() != null) {
			superTypes = Collections.singletonList(event.getExtends());
		} else {
			superTypes = Collections.singletonList(getTypeReferences().getTypeForName(Event.class, event));
		}
		if (generateTypeDeclaration(
				this.qualifiedNameProvider.getFullyQualifiedName(event).toString(),
				event.getName(), event.isAbstract(), superTypes,
				getTypeBuilder().getDocumentation(event),
				true,
				event.getMembers(), appendable, context, null)) {
			final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(event);
			writeFile(name, appendable, context);
		}
	}
1090048
private static void generateParseOnXml(BindTypeContext context, BindEntity entity) {
		// @formatter:off
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("parseOnXml").addJavadoc("parse xml\n")
				.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
				// .addParameter(typeName(KriptonXmlContext.class), "context")
				.addParameter(typeName(XMLParser.class), "xmlParser")
				.addParameter(typeName(Integer.TYPE), "currentEventType").returns(typeName(entity.getElement()))
				.addException(Exception.class);
		// @formatter:on

		boolean mutableObject = entity.isMutablePojo();

		if (mutableObject) {
			methodBuilder.addStatement("$T instance = new $T()", entity.getElement(), entity.getElement());
		} else {
			ImmutableUtility.generateImmutableVariableInit(entity, methodBuilder);
		}

		methodBuilder.addStatement("int eventType = currentEventType");
		methodBuilder.addStatement("boolean read=true");

		methodBuilder.addCode("\n");
		methodBuilder.beginControlFlow("if (currentEventType == 0)");
		methodBuilder.addStatement("eventType = xmlParser.next()");
		methodBuilder.nextControlFlow("else");
		methodBuilder.addStatement("eventType = xmlParser.getEventType()");
		methodBuilder.endControlFlow();
		methodBuilder.addStatement("String currentTag = xmlParser.getName().toString()");

		methodBuilder.addStatement("String elementName = currentTag");

		generateParseOnXmlAttributes(context, methodBuilder, entity);

		methodBuilder.addCode("\n");
		methodBuilder.addCode("//sub-elements\n");
		methodBuilder.beginControlFlow("while (xmlParser.hasNext() && elementName!=null)");

		methodBuilder.beginControlFlow("if (read)");
		methodBuilder.addStatement("eventType = xmlParser.next()");
		methodBuilder.nextControlFlow("else");
		methodBuilder.addStatement("eventType = xmlParser.getEventType()");
		methodBuilder.endControlFlow();
		methodBuilder.addStatement("read=true");

		methodBuilder.beginControlFlow("switch(eventType)$>");
		methodBuilder.addCode("case $T.START_TAG:\n$>", XmlPullParser.class);
		generateParserOnXmlStartElement(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("case $T.END_TAG:\n$>", XmlPullParser.class);
		generateParserOnXmlEndElement(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("case $T.CDSECT:\n", XmlPullParser.class);
		methodBuilder.addCode("case $T.TEXT:\n$>", XmlPullParser.class);
		generateParserOnXmlCharacters(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("default:\n$>");
		methodBuilder.addStatement("$<break");
		methodBuilder.addCode("$<");
		methodBuilder.endControlFlow();
		// @formatter:on

		methodBuilder.endControlFlow();

		if (!mutableObject) {
			ImmutableUtility.generateImmutableEntityCreation(entity, methodBuilder, "instance", true);
		}

		methodBuilder.addStatement("return instance");

		context.builder.addMethod(methodBuilder.build());
	}
123808
public VPackSlice serialize(final Object entity, final SerializeOptions options) throws VPackParserException {
		Type type = options.getType();
		if (type == null) {
			type = entity.getClass();
		}
		if (type == VPackSlice.class) {
			return (VPackSlice) entity;
		}
		final VPackBuilder builder = new VPackBuilder(builderOptions);
		serialize(null, entity, type, builder, new HashMap<String, Object>(options.getAdditionalFields()));
		return builder.slice();
	}
813663
public JComponent render(Object entity)
    {
        JTextArea text = new JTextArea(entity.toString());
        text.setEditable(false);
        text.setBackground(null);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
        return text;
    }
795018
protected void _generate(SarlCapacity capacity, IExtraLanguageGeneratorContext context) {
		final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(capacity);
		final PyAppendable appendable = createAppendable(jvmType, context);
		final List<? extends JvmTypeReference> superTypes;
		if (!capacity.getExtends().isEmpty()) {
			superTypes = capacity.getExtends();
		} else {
			superTypes = Collections.singletonList(getTypeReferences().getTypeForName(Capacity.class, capacity));
		}
		if (generateTypeDeclaration(
				this.qualifiedNameProvider.getFullyQualifiedName(capacity).toString(),
				capacity.getName(), true, superTypes,
				getTypeBuilder().getDocumentation(capacity),
				true,
				capacity.getMembers(), appendable, context, null)) {
			final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(capacity);
			writeFile(name, appendable, context);
		}
	}
60723
public void store(Object entity) {
        Reference<String> stringReference = new Reference<>();
        boolean hasId = generateEntityIdOnTheClient.tryGetIdFromInstance(entity, stringReference);
        storeInternal(entity, null, null, !hasId ? ConcurrencyCheckMode.FORCED : ConcurrencyCheckMode.AUTO);
    }
1374388
public void setContext(Context context) {
        context.put(JavacTypes.class, this);
        syms = Symtab.instance(context);
        types = Types.instance(context);
    }
276258
static void serialize(final Document doc, final OutputStream os, final String encoding)
        throws TransformerFactoryConfigurationError, TransformerException, IOException
  {
    if (doc == null)
      throw new IllegalArgumentException("No document provided.");

    if (os == null)
      throw new IllegalArgumentException("No output stream provided");

    if (encoding == null || encoding.isEmpty())
      throw new IllegalArgumentException("No encoding provided.");

    final TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", Integer.valueOf(2));
    final Transformer t = transformerFactory.newTransformer();

    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.ENCODING, encoding);

    final OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
    t.transform(new DOMSource(doc), new StreamResult(osw));
    osw.flush();
  }
1035835
public void generate(Context context) {
        Appendable target = context.getTarget();

        for (ProcTemplateElement element : elements) {
            try {
                target.append(element.generate(context));
            } catch (IOException e) {
                // Nothing! Because StringBuilder doesn't catch IOException
            }
        }
    }