/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package userguide.example4;


import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ServiceGroupContext;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.SessionContext;

import org.apache.axis2.deployment.FileSystemConfigurator;
import org.apache.axis2.engine.AxisConfiguration;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;

import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.XMLStreamException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;



/**
 * Created by IntelliJ IDEA.
 * User: Jaliya
 * Date: Jun 2, 2005
 * Time: 2:17:58 PM
 */
public class MyService {
    
    private static final Log log = LogFactory.getLog(MyService.class);
    
    private static int i = 0;
    private static Integer intObj = new Integer(i);
    
    // get the instance date-time (get time-stamp when this web-service is born)
    private static String sDate = new Date().toString();
    
    private static ServiceContext sc = null;
    private static OperationContext oc = null;
    
    public void MyService() {
        this.log.info("MyService4.MyService() called ***************************");
    }
    
    public void init(ServiceContext sCtx) {
        
        /**
         * MessageContext msgCtx = MessageContext.getCurrentMessageContext();
         * HttpServletRequest request = (HttpServletRequest) msgCtx.getProperty("transport.http.servletRequest");
         * HttpSession session = request.getSession(true);
         * if(session.isNew()){
         * this.log.info("MyService4.init() called and session IS NEW *********");
         * } else {
         * this.log.info("MyService4.init() called and session IS NOT NEW *****");
         * }
         * this.sc = sCtx;
         **/
        this.log.info("MyService4.init() called ********************************");
        
    }
    
    
    public void destroy(ServiceContext sCtx) {
        if(!this.sc.toString().equals(sCtx.toString())){
            this.log.error("ServiceContext on init() and destroy() not equal in ");
        }
        this.log.info(sc.toString()+" destroy() called *************************");
    }
    
    
    // said to be removed (by e-mail), taken out.
    // but in fact it's never called
    // but the interface is still available to compile
    //
    public void setOperationContext(OperationContext oCtx) {
        this.oc = oCtx;
        this.log.info(oc.toString()+" setOperationContext() called *************");
    }
    
    public OMElement start(OMElement element) throws XMLStreamException {
        
        this.log.info("MyService4.start() called *******************************");
        
        //Prepare the OMElement so that it can be attached to another OM Tree.
        
        //First the OMElement should be completely build in case it is not fully built and still
        //some of the xml is in the stream.
        element.build();
        
        //Secondly the OMElement should be detached from the current OMTree so that it can be attached
        //some other OM Tree. Once detached the OmTree will remove its connections to this OMElement.
        element.detach();
        
        element = null;
        
        return getStartOMElement();
    }
    
    
    public OMElement echo(OMElement element) throws XMLStreamException {
        
        
        this.log.info("MyService4.echo() called ********************************");
        
        //Prepare the OMElement so that it can be attached to another OM Tree.
        //First the OMElement should be completely build in case it is not fully built and still
        //some of the xml is in the stream.
        element.build();
        //Secondly the OMElement should be detached from the current OMTree so that it can be attached
        //some other OM Tree. Once detached the OmTree will remove its connections to this OMElement.
        element.detach();
        
        
        XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
        element.serialize(writer);
        writer.flush();               // write every-thing out
        System.out.println("");       // and add a CRLF
        
        
        element = null;
        
        return getEchoOMElement();
    }
    
    
    public void ping(OMElement element) throws XMLStreamException {
        //Do some processing
        this.log.info("MyService4.ping() called ********************************");
    }
    
    
    public void pingF(OMElement element) throws AxisFault{
        this.log.info("MyService4.pingF() called *******************************");
        throw new AxisFault("Fault being thrown");
    }
    
    
    private static OMElement getStartOMElement() {
        
        log.info("MyService4.getStartOMElement() called ************************");
        
        OMFactory factory = OMAbstractFactory.getOMFactory();
        
        OMNamespace ns1 = factory.createOMNamespace("workspace","ws");
        OMElement root = factory.createOMElement("root",ns1);
        OMText timeStamp = factory.createOMText(root,sDate);
        
        OMNamespace ns2 = root.declareNamespace("feld","f");
        OMElement wsin = factory.createOMElement("in",ns1);
        root.addChild(wsin);
        
        MessageContext msgCtx = MessageContext.getCurrentMessageContext();
        HttpServletRequest request = (HttpServletRequest) msgCtx.getProperty("transport.http.servletRequest");
        HttpServletResponse response = (HttpServletResponse) msgCtx.getProperty("transport.http.servletResponse");
        
        HttpSession session = request.getSession(true);
        
        Date created = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());
        
        
        for(i=0;i<1;i++){
            String s = intObj.toString(i);
            OMElement elem = factory.createOMElement("yuck"+s,ns2);
            OMText txt1 = factory.createOMText(elem,"blah"+s);
            elem.addChild(txt1);
            wsin.addChild(elem);
        }
        
        OMElement wsold = factory.createOMElement("old",ns1);
        root.addChild(wsold);
        for(i=1;i<2;i++){
            String s = intObj.toString(i);
            OMElement elem = factory.createOMElement("yuck"+s,ns2);
            OMText txt1 = factory.createOMText(elem,"blah"+s);
            elem.addChild(txt1);
            wsold.addChild(elem);
        }
        
        OMElement wsout = factory.createOMElement("out",ns1);
        root.addChild(wsout);
        Enumeration e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = session.getAttribute(name).toString();
            OMElement elem = factory.createOMElement(name,ns2);
            OMText sID = factory.createOMText(elem,value);
            elem.addChild(sID);
            wsout.addChild(elem);
        }
        
        OMElement elem = factory.createOMElement("sessionCreated",ns2);
        OMText sID = factory.createOMText(elem,created.toString());
        elem.addChild(sID);
        wsout.addChild(elem);
        
        elem = factory.createOMElement("sessionAccessed",ns2);
        sID = factory.createOMText(elem,accessed.toString());
        elem.addChild(sID);
        wsout.addChild(elem);
        
        return root;
    }
    
    private static OMElement getEchoOMElement() {
        
        log.info("MyService4.getEchoOMElement() called *************************");
        /**
         * MessageContext msgCtx = MessageContext.getCurrentMessageContext();
         * HttpServletRequest request = (HttpServletRequest) msgCtx.getProperty("transport.http.servletRequest");
         * HttpServletResponse response = (HttpServletResponse) msgCtx.getProperty("transport.http.servletResponse");
         * //response.setContentType("text/html");
         *
         * HttpSession session = request.getSession(true);
         *
         * // print/get session information
         *
         * Date created = new Date(session.getCreationTime());
         * Date accessed = new Date(session.getLastAccessedTime());
         * String sId = session.getId();
         **/
        OMFactory factory = OMAbstractFactory.getOMFactory();
        
        OMNamespace ns1 = factory.createOMNamespace("workspace","ws");
        OMElement root = factory.createOMElement("root",ns1);
        OMText timeStamp = factory.createOMText(root,sDate);
        OMNamespace ns2 = root.declareNamespace("feld","f");
        
        OMElement wsin = factory.createOMElement("in",ns1);
        root.addChild(wsin);
        for(i=0;i<4;i++){
            String s = intObj.toString(i);
            OMElement elem = factory.createOMElement("yuck"+s,ns2);
            OMText txt1 = factory.createOMText(elem,"blah"+s);
            elem.addChild(txt1);
            wsin.addChild(elem);
        }
        
        OMElement wsold = factory.createOMElement("old",ns1);
        root.addChild(wsold);
        for(i=4;i<8;i++){
            String s = intObj.toString(i);
            OMElement elem = factory.createOMElement("yuck"+s,ns2);
            OMText txt1 = factory.createOMText(elem,"blah"+s);
            elem.addChild(txt1);
            wsold.addChild(elem);
        }
        
        // this code used to return information about the session we are in
        OMElement wsout = factory.createOMElement("out",ns1);
        root.addChild(wsout);
        
        /**
         * // add the sessionID
         * OMElement elem = factory.createOMElement("SessionID",ns2);
         * OMText omt = factory.createOMText(elem,session.getId());
         * elem.addChild(omt);
         * wsout.addChild(elem);
         *
         * elem = factory.createOMElement("createDate",ns2);
         * omt = factory.createOMText(elem, new Date(session.getCreationTime()).toString());
         * elem.addChild(omt);
         * wsout.addChild(elem);
         *
         * elem = factory.createOMElement("accessDate",ns2);
         * omt = factory.createOMText(elem,new Date(session.getLastAccessedTime()).toString());
         * elem.addChild(omt);
         * wsout.addChild(elem);
         *
         * Enumeration e = session.getAttributeNames();
         * while (e.hasMoreElements()) {
         * String name = (String)e.nextElement();
         * String value = session.getAttribute(name).toString();
         * elem = factory.createOMElement(name,ns2);
         * omt = factory.createOMText(elem,value);
         * elem.addChild(omt);
         * wsout.addChild(elem);
         * }
         *
         * elem = factory.createOMElement("sessionSerialized",ns2);
         * omt = factory.createOMText(elem,session.toString());
         * elem.addChild(omt);
         * wsout.addChild(elem);
         **/
        
        // for performance testing add some data to the structure
        for(i=8;i<12;i++){
            String s = intObj.toString(i);
            OMElement elem = factory.createOMElement("yuck"+s,ns2);
            OMText omt = factory.createOMText(elem,"blah"+s);
            elem.addChild(omt);
            wsout.addChild(elem);
        }
        
        
        return root;
    }
}
