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

/*
 * $Id: TestImpl.java 62602 2011-04-21 14:51:41Z kgrucci $
 */
package com.sun.ts.tests.jaxws.ee.j2w.document.literal.sessionmaintaintest.server;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import javax.jws.WebMethod;
import javax.jws.WebService;

import javax.xml.ws.handler.MessageContext;

import java.lang.reflect.*;

import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceContext;

@WebService(name="Test", serviceName="TestService", targetNamespace="http://test.org/wsdl")
public class TestImpl {

    @Resource private WebServiceContext wsc;

    public TestImpl() {}

    @WebMethod
    public String getSessionId(){
        System.out.println("Entering getSessionId()");
        String id = getClientId();
        System.out.println("** session id: " + id);
        System.out.println("Leaving getSessionId()");
        return id;
    }

    @WebMethod
    public boolean compareSessionId(String sessionId) {
        System.out.println("Enter  doesSessionExist()");
        System.out.println("session id passed in by client: "+sessionId);
        String id = getClientId();
        System.out.println("** current session id: " + id);
        boolean exists=false;
        if (id.equals(sessionId)){
            exists=true;
        } else {
            exists=false;
        }
        System.out.println("returning result of:"+exists);
        System.out.println("Leave doesSessionExist()");
        return exists;
    }

    private String getClientId() {
	String id = null;

        Object o1 = wsc.getMessageContext().get(MessageContext.SERVLET_REQUEST);

	try {
	  if (o1 != null) {
	    Class c1 = o1.getClass();
	    Method getSession = c1.getMethod("getSession");
	    Object o2 = getSession.invoke(o1);
	    Class c2 = o2.getClass();
	    Method getId = c2.getMethod("getId");
	    id = (String) getId.invoke(o2);
	  }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return id;
    }

}
