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

com.github.gkutiel.flip.web.Formatter Maven / Gradle / Ivy

package com.github.gkutiel.flip.web;

import java.text.MessageFormat;

import org.w3c.dom.Document;

import com.github.gkutiel.flip.utils.Utils;
import com.github.gkutiel.flip.web.annotation.Xsl;

enum Formatter {

	JSON("application/json") {
		@Override
		public String format(final Object result, final Object ignore) {
			return Utils.Json.toString(result);
		}
	},

	XML("text/xml;charset=utf-8") {

		private void addXsl(final Document doc, final String xsl) {
			final String stylesheet = MessageFormat.format("type=''text/xsl'' href=''/{0}''", xsl);
			doc.insertBefore(doc.createProcessingInstruction("xml-stylesheet", stylesheet), doc.getDocumentElement());
		}

		@Override
		public String format(final Object result, final Object arg) {
			try {
				final Document doc = Utils.Xml.toXml(result);
				if (arg != null && arg instanceof Xsl) this.addXsl(doc, ((Xsl) arg).value());
				return Utils.Xml.toString(doc);
			} catch (final Exception e) {
				throw new RuntimeException(e);
			}
		}
	};

	private String mimeType;

	private Formatter(final String mimeType) {
		this.mimeType = mimeType;
	}

	abstract String format(Object result, Object arg);

	String mimeType() {
		return this.mimeType;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy