/*
 * Copyright (c) eHealth
 */
package be.ehealth.technicalconnector.handler;

import java.io.ByteArrayOutputStream;
import java.net.URI;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.ehealth.technicalconnector.enumeration.Charset;
import be.ehealth.technicalconnector.handler.domain.WsAddressingHeader;
import be.ehealth.technicalconnector.idgenerator.IdGeneratorFactory;
import be.ehealth.technicalconnector.ws.impl.SOAPMessageContextImpl;


/**
 * tests the creation of the addressing header.
 * 
 * @author EHP
 * 
 * 
 * 
 */
public class WsAddressingHandlerV200508Test {

    private static final Logger LOG = LoggerFactory.getLogger(WsAddressingHandlerV200508Test.class);

    @Test
    public void test() throws Exception {
        MessageFactory mf = MessageFactory.newInstance();

        SOAPMessage soapMessage = mf.createMessage();
        SOAPMessageContext context = new SOAPMessageContextImpl(soapMessage);


        context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE);
        context.put(WsAddressingHandlerV200508.WS_ADDRESSING_V200508_USE, Boolean.TRUE);

        soapMessage.getSOAPHeader()
                   .addChildElement(new QName("dch", "RelatesTo", "dch"));


        WsAddressingHeader addressingHeader = new WsAddressingHeader(new URI("urn:be:cin:nip:async:generic:post:msg"));
        addressingHeader.setReplyTo("http://www.w3.org/2005/08/addressing/anonymous");
        addressingHeader.setFaultTo("http://www.w3.org/2005/08/addressing/anonymous");
        addressingHeader.setMessageID(new URI("uuid:" + IdGeneratorFactory.getIdGenerator("uuid")
                                                                          .generateId()));

        context.put(WsAddressingHandlerV200508.MESSAGECONTEXT_WS_ADDRESSING_V200508, addressingHeader);

        WsAddressingHandlerV200508 handler = new WsAddressingHandlerV200508();
        handler.handleMessage(context);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapMessage.writeTo(out);
        out.flush();
        String outMsg = out.toString(Charset.UTF_8.getName());
        out.close();
        Assert.assertTrue("header doesn't contain wsa:Action : header :" + outMsg, StringUtils.contains(outMsg, "<wsa:Action"));
        Assert.assertTrue("header doesn't contain dch:RelatesTo : header :" + outMsg, StringUtils.contains(outMsg, "<dch:RelatesTo xmlns:dch=\"dch\"/>"));

        LOG.debug("WsAddressingHandlerV200508Test : test : outMsg = " + outMsg);
    }
}
