package com.dbxml.db.server.services;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: DBService.java,v 1.2 2004/02/12 00:17:58 bradford Exp $
 */

import com.dbxml.db.common.security.NoSecurityManager;
import com.dbxml.db.core.Database;
import com.dbxml.db.core.security.SecurityManager;
import com.dbxml.db.server.SimpleService;
import com.dbxml.db.server.labrador.BasicAuthFilter;
import com.dbxml.db.server.labrador.ContentResolver;
import com.dbxml.labrador.Filter;
import com.dbxml.labrador.broker.Broker;
import com.dbxml.util.Configuration;
import com.dbxml.util.dbXMLException;

/**
 * DBService represents a dbXML Database that is registered as a Service.
 */

public class DBService extends SimpleService {
   static {
      ContentResolver.initialize();
   }

   public void setConfig(Configuration config) throws dbXMLException {
      super.setConfig(config);
      if ( Database.getInstance() != null )
         throw new dbXMLException("Only one Database instance allowed per Server");
   }

   public synchronized int initialize() {
      try {
         Database db = new Database();
         db.setConfig(config);
         SecurityManager security = db.getSecurityManager();

			if ( !(security instanceof NoSecurityManager) ) {
				Filter authFilter = new BasicAuthFilter(security);
				Broker.getInstance().addFilter(authFilter);
			}
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
         System.exit(1);
      }

      return RESULT_OK;
   }

   public void dispose() {
      Database db = Database.getInstance();
      if ( db != null )
         db.dispose();
   }
}
