/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2013 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 *  $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.tests.applications.wsadd.beans;

import java.util.Collections;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.w3c.dom.Node;

/**
 * @author Loic Albertin
 */
public class MultiplyHandler implements SOAPHandler<SOAPMessageContext> {
    @Override
    public Set<QName> getHeaders() {
        return Collections.emptySet();
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        try {
                   final SOAPMessage message = context.getMessage();
                   final SOAPBody body = message.getSOAPBody();
                   final String localName = body.getFirstChild().getLocalName();

                   if ("addFromBeanResponse".equals(localName)) {
                       final Node responseNode = body.getFirstChild();
                       final Node returnNode = responseNode.getFirstChild();
                       final Node intNode = returnNode.getFirstChild();

                       final int value = new Integer(intNode.getNodeValue());

                       intNode.setNodeValue(Integer.toString(value * 10));
                   }

                   return true;
               } catch (SOAPException e) {
                   return false;
               }
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return true;
    }

    @Override
    public void close(MessageContext context) {
    }
}
