/*
 * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * $Id: MustUnderstandHeaderHandler.java 62536 2011-04-15 16:35:14Z af70133 $
 */

/*
 * @(#)MustUnderstandHeaderHandler.java	1.2 03/05/16
 */

/* Copyright (c) 2003 Oracle Corporation.  All rights reserved.  */
package com.sun.ts.tests.jaxrpc.wsi.w2j.rpc.literal.R1027;

import javax.xml.rpc.handler.GenericHandler;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.namespace.QName;
import javax.xml.soap.*;

public class MustUnderstandHeaderHandler extends GenericHandler{

    public QName [] getHeaders(){return new QName[]{};}

    public boolean handleResponse(MessageContext context){
        try{
            addMustUnderstandHeader((SOAPMessageContext)context);
        }catch(SOAPException se){
            com.sun.ts.lib.util.TestUtil.printStackTrace(se);
        }
        return true;
    }

    private void addMustUnderstandHeader(SOAPMessageContext context)throws SOAPException{
        SOAPHeader header = getHeader(context.getMessage().getSOAPPart().getEnvelope());
        SOAPHeaderElement mustUnderstand = header.addHeaderElement(getHeaderName());
        mustUnderstand.addTextNode("baz");
        mustUnderstand.setMustUnderstand(true);
	context.getMessage().saveChanges();
    }

    private SOAPHeader getHeader(SOAPEnvelope env) throws SOAPException{
        SOAPHeader header = env.getHeader();
        if(header == null){
            return env.addHeader();
        }
        else{
            return header;
        }
    }

    private Name getHeaderName() throws SOAPException{
        SOAPFactory factory = SOAPFactory.newInstance();
        return factory.createName("foo", "bar", "http://baz.org");
    }
}
