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

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

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

/* Copyright (c) 2003 Oracle Corporation.  All rights reserved.  */
package com.sun.ts.tests.jaxrpc.sharedwebservices.simpleservice;

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 ConformanceClaimHandler extends GenericHandler implements WSIConstants{
    public QName [] getHeaders(){
        return new QName[]{new QName(WSI_CLAIM_NAMESPACE_URI, WSI_CLAIM_LOCAL_NAME)};
    }

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

        return true;
    }

    private void addConformanceClaims(SOAPMessage message) throws SOAPException{
        addBP10ConformanceClaim(message);
        addDummyConformanceClaim(message);
    }

    private void addBP10ConformanceClaim(SOAPMessage message) throws SOAPException {
        SOAPEnvelope env = message.getSOAPPart().getEnvelope();
        SOAPHeader conformanceClaim = getHeader(env);
        Name claimName = env.createName(WSI_CLAIM_LOCAL_NAME,
                                        WSI_CLAIM_PREFIX,
                                        WSI_CLAIM_NAMESPACE_URI);
        SOAPHeaderElement claim = conformanceClaim.addHeaderElement(claimName);
        claim.addAttribute(env.createName(WSI_CLAIM_CONFORMS_TO_ATTR),
                                          WSI_CLAIM_CONFORMS_TO_VALUE);
        message.saveChanges();
    }

     private void addDummyConformanceClaim(SOAPMessage message) throws SOAPException {
        SOAPEnvelope env = message.getSOAPPart().getEnvelope();
        SOAPHeader conformanceClaim = getHeader(env);
        Name claimName = env.createName(WSI_CLAIM_LOCAL_NAME,
                                        WSI_CLAIM_PREFIX,
                                        WSI_CLAIM_NAMESPACE_URI);
        SOAPHeaderElement claim = conformanceClaim.addHeaderElement(claimName);
        claim.addAttribute(env.createName(WSI_CLAIM_CONFORMS_TO_ATTR),
                                          "http://dummy/conformanceClaim");
        message.saveChanges();
    }

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