// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package ws.rest.basic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.google.gson.Gson;

public class Util {
    public static String Object2XML(Object o) throws IOException {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext jxbctx = JAXBContext.newInstance(o.getClass());
            Marshaller m = jxbctx.createMarshaller();
            m.marshal(o, sw);
        } catch (JAXBException e) {
            throw new IOException("JAXB exception: " + e.getMessage(), e);
        }
        return sw.toString();
    }
    @SuppressWarnings("unchecked")
    public static <T> T XML2Object(Class<T> clz, String xml) throws IOException {
        try {
            JAXBContext jxbctx = JAXBContext.newInstance(clz);
            Unmarshaller um = jxbctx.createUnmarshaller();
            return (T)um.unmarshal(new StringReader(xml));
        } catch (JAXBException e) {
            throw new IOException("JAXB exception: " + e.getMessage(), e);
        }
    }
    public static String Object2JSON(Object o) throws IOException {
        Gson g = new Gson();
        return g.toJson(o);
    }
    public static <T> T JSON2Object(Class<T> clz, String json) {
        Gson g = new Gson();
        return g.fromJson(json, clz);
    }
    public static String Object2String(Object o, String typ) throws IOException {
        if(typ.equals("application/xml")) {
            return Object2XML(o);
        } else if(typ.equals("application/json")) {
            return Object2JSON(o);
        } else {
            throw new IOException("Unknown type: " + typ);
        }
    }
    public static <T> T String2Object(Class<T> clz, String s, String typ) throws IOException {
        if(typ.equals("application/xml")) {
            return XML2Object(clz, s);
        } else if(typ.equals("application/json")) {
            return JSON2Object(clz, s);
        } else {
            throw new IOException("Unknown type: " + typ);
        }
    }
    public static String getAllLines(Reader rdr) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(rdr);
        String line;
        while((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(System.getProperty("line.separator"));
        }
        return sb.toString();
    }
}
