package ogloszenia.klient;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;

public class Klient16_XmlSource {
	
	public static void main(String[] args) {
		
		Client klient = ClientBuilder.newClient();		
		WebTarget baseUri = klient.target(Ustawienia.URI_SERWISU);
		
		System.out.println("Zaraz wyślę zapytanie...");
		Response response = baseUri
			.path("/ogloszenia")
			.request()
			.accept("application/xml")
			.buildGet()
			.invoke();
		
		System.out.println("Odebrałem odpowiedź " + response);
		
		System.out.println("status: " + response.getStatus());
		System.out.println("typ danych: " + response.getMediaType());
		
		response.bufferEntity();
		Source dane = response.readEntity(Source.class);
		System.out.println("Mam wynik: " + dane);
		System.out.println();
		wypiszXmlZSource(dane);
	}
	
	static void wypiszXmlZSource(Source xml) {
		try {
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer t = tf.newTransformer();
			StreamResult res = new StreamResult(System.out);
			t.transform(xml, res);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

}
