
/*
 * Copyright (c) 2004, ADAPT project partners (IST-2001-37126).
 *
 * LoggingServiceImpl.java
 */

package org.eu.adapt.demonstrator.ws.demo;

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.server.ServiceLifecycle;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.LoggingFacility_xsd.*;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.LoggingFacility_wsdl.LoggingFacilityLogPortType;
import org.eu.adapt.demonstrator.eb.demo.DemoUserHomeLocal;
import org.eu.adapt.demonstrator.eb.demo.DemoUserLocal;
import org.eu.adapt.demonstrator.eb.demo.RepositoryHomeLocal;
import org.eu.adapt.demonstrator.eb.demo.RepositoryLocal;
import org.eu.adapt.demonstrator.eb.demo.LogEventHomeLocal;
import org.eu.adapt.demonstrator.eb.demo.LogEventLocal;

public class LoggingServiceImpl implements LoggingFacilityLogPortType, ServiceLifecycle
{
    public void init(Object context)
        throws ServiceException
    {
        _repositoryId = "MainLog";

        try
        {
            InitialContext initialContext = new InitialContext();

//            _userTransaction = (UserTransaction) initialContext.lookup("java:comp/UserTransaction");
//            _demoUserHome    = (DemoUserHomeLocal) initialContext.lookup("java:comp/env/ejb/DemoUserHomeLocal");
//            _repositoryHome  = (RepositoryHomeLocal) initialContext.lookup("java:comp/env/ejb/RepositoryHomeLocal");
//            _logEventHome    = (LogEventHomeLocal) initialContext.lookup("java:comp/env/ejb/LogEventHomeLocal");
            _userTransaction = (UserTransaction) initialContext.lookup("UserTransaction");
            _demoUserHome    = (DemoUserHomeLocal) initialContext.lookup("local/Demo_DemoUserEB");
            _repositoryHome  = (RepositoryHomeLocal) initialContext.lookup("local/Demo_RepositoryEB");
            _logEventHome    = (LogEventHomeLocal) initialContext.lookup("local/Demo_LogEventEB");
 
            initialContext.close();
        }
        catch (NamingException namingException)
        {
            System.out.println("Name lookup problem: \"" + namingException + "\"");

            throw new ServiceException("Name lookup problem: \"" + namingException + "\"");
        }
        catch (Exception exception)
        {
            System.out.println("Problem: \"" + exception + "\"");

            throw new ServiceException("Problem: \"" + exception + "\"");
        }
        catch (Error error)
        {
            System.out.println("Problem: \"" + error + "\"");
            
            throw new ServiceException("Problem: \"" + error + "\"");
        }
    }

    public void destroy()
    {
        _demoUserHome   = null;
        _repositoryHome = null;
        _logEventHome   = null;
        _repositoryId   = null;
    }

    public void logEvent(LogEventRequestType logEventRequest)
        throws RemoteException
    {
        try
        {
            try
            {
                _userTransaction.begin();
        
                DemoUserLocal   demoUser   = _demoUserHome.findByPrimaryKey(logEventRequest.getDemoUserID());
                RepositoryLocal repository = _repositoryHome.findByPrimaryKey(_repositoryId);

                _logEventHome.create(demoUser, repository, logEventRequest.getServiceID(), Integer.parseInt(logEventRequest.getEventID()), logEventRequest.getEventDescription());

                _userTransaction.commit();
            }
            catch (Exception exception)
            {
                _userTransaction.rollback();

                throw exception;
            }
            catch (Error error)
            {
                _userTransaction.rollback();

                throw error;
            }
        }
        catch (CreateException createException)
        {
            System.out.println("Failed to create log entry: " + createException);
            throw new RemoteException("Failed to create log entry", createException);
        }
        catch (FinderException finderException)
        {
            System.out.println("Failed to find home: " + finderException);
            throw new RemoteException("Failed to find home", finderException);
        }
        catch (Exception exception)
        {
            System.out.println("Unexpected Exception: " + exception);
            throw new RemoteException("Unexpected Exception", exception);
        }
        catch (Error error)
        {
            System.out.println("Unexpected Error: " + error);
            throw new RemoteException("UnexpectedError", error);
        }
    }

    public GetEventsResponseType getEvents(GetEventsRequestType getEventsRequest)
        throws RemoteException, GetEventsFaultType
    {
        GetEventsResponseType getEventsResponse = new GetEventsResponseType();

        try
        {
            try
            {
                _userTransaction.begin();
    
                DemoUserLocal                    demoUser         = _demoUserHome.findByPrimaryKey(getEventsRequest.getDemoUserID());
                Collection                       logEvents        = demoUser.getLogEvents();
                Iterator                         logEventIterator = logEvents.iterator();
                GetEventsResponseType_LogEntry[] logEntries       = new GetEventsResponseType_LogEntry[logEvents.size()];

                int index = 0;
                while (logEventIterator.hasNext())
                {
                    LogEventLocal logEvent = (LogEventLocal) logEventIterator.next();

                    logEntries[index] = new GetEventsResponseType_LogEntry();
                    logEntries[index].setServiceID(logEvent.getServiceId());
                    logEntries[index].setEventID(String.valueOf(logEvent.getEventId()));
                    logEntries[index].setEventDescription(logEvent.getEventDescription());
                    logEntries[index].setTimestamp(logEvent.getTimestamp());

                    index++;
                }
                getEventsResponse.setLogEntry(logEntries);

                _userTransaction.commit();
            }
            catch (Exception exception)
            {
                _userTransaction.rollback();

                throw exception;
            }
            catch (Error error)
            {
                _userTransaction.rollback();

                throw error;
            }
        }
        catch (FinderException finderException)
        {
            System.out.println("Failed to find home: " + finderException);
            throw new RemoteException("Failed to find home", finderException);
        }
        catch (SystemException systemException)
        {
            System.out.println("Unexpected SystemException: \"" + systemException + "\"");
            throw new GetEventsFaultType(GetEventsFaultType_Reason.fromString("Unexpected SystemException: " + systemException));
        }
        catch (Exception exception)
        {
            System.out.println("Unexpected Exception: \"" + exception + "\"");
            throw new GetEventsFaultType(GetEventsFaultType_Reason.fromString("Unexpected Exception: " + exception));
        }
        catch (Error error)
        {
            System.out.println("Unexpected Error: \"" + error + "\"");
            throw new GetEventsFaultType(GetEventsFaultType_Reason.fromString("Unexpected Error: " + error));
        }

        return getEventsResponse;
    }

    private UserTransaction     _userTransaction = null;
    private DemoUserHomeLocal   _demoUserHome    = null;
    private RepositoryHomeLocal _repositoryHome  = null;
    private LogEventHomeLocal   _logEventHome    = null;
    private String              _repositoryId    = null;
}