All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.aguacate.http.impl.HttpBodyBuilerImpl Maven / Gradle / Ivy

There is a newer version: 0.10.9
Show newest version
package net.sf.aguacate.http.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.aguacate.configuration.field.format.FieldFormat;
import net.sf.aguacate.http.HttpBodyBuiler;
import net.sf.aguacate.util.codec.bridge.CodecBridge;
import net.sf.aguacate.util.codec.bridge.CodecCoupling;

public class HttpBodyBuilerImpl implements HttpBodyBuiler {

	@Override
	public void build(HttpServletResponse response, Object object) throws IOException {
		CodecBridge codec = CodecCoupling.jsonCodecBridge();
		response.setContentType(codec.mimetype());
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		PrintWriter writer = response.getWriter();
		try {
			codec.encode(writer, object);
		} finally {
			writer.close();
		}
	}

	@Override
	public void build(HttpServletResponse response, Object object, Map outputFields)
			throws IOException {
		CodecBridge codec = CodecCoupling.jsonCodecBridge();
		response.setContentType(codec.mimetype());
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		PrintWriter writer = response.getWriter();
		try {
			Class klass = object.getClass();
			if (Map.class.isAssignableFrom(klass)) {
				@SuppressWarnings("unchecked")
				Map map = (Map) object;
				Map temp = new HashMap<>();
				process(outputFields, map, temp);
				codec.encode(writer, temp);
			} else {
				if (List.class.isAssignableFrom(klass)) {
					@SuppressWarnings("unchecked")
					List> list = (List>) object;
					int size = list.size();
					writer.write('[');
					if (size > 0) {
						Map temp = new HashMap<>();

						process(outputFields, list.get(0), temp);
						codec.encode(writer, temp);

						for (int i = 1; i < size; i++) {
							temp.clear();
							writer.write(',');
							process(outputFields, list.get(i), temp);
							codec.encode(writer, temp);
						}
					}
					writer.write(']');
				} else {
					throw new IllegalStateException(klass.getName());
				}
			}
		} finally {
			writer.close();
		}
	}

	void process(Map outputFields, Map source, Map target) {
		for (Map.Entry entry : outputFields.entrySet()) {
			String outputField = entry.getKey();
			Object value = source.get(outputField);
			if (value != null) {
				target.put(outputField, entry.getValue().format(value));
			}
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy