package com.dbxml.db.server.labrador;

/*
 * 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: ContentResolver.java,v 1.3 2004/02/12 00:17:58 bradford Exp $
 */

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.Container;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.Database;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.labrador.Discovery;
import com.dbxml.labrador.ID;
import com.dbxml.labrador.Instance;
import com.dbxml.labrador.Resolver;
import com.dbxml.labrador.broker.Broker;
import com.dbxml.labrador.objects.ObjectInstance;

/**
 * ContentResolver
 */

public final class ContentResolver implements Resolver {
   public static void initialize() {
		Broker.getInstance().addResolver(new ContentResolver());
   }

   private ContentResolver() {
   }

   public boolean isIDValid(ID id) {
      try {
         return getContent(id) != null;
      }
      catch ( DBException e ) {
         return false;
      }
   }

   public Instance getInstance(ID id) {
      try {
         return getContent(id);
      }
      catch ( DBException e ) {
         return null;
      }
   }

   public Discovery getDiscovery(ID id) {
      try {
         return getContent(id).getDiscovery();
      }
      catch ( DBException e ) {
         return null;
      }
   }

   private ObjectInstance getContent(ID id) throws DBException {
		String name = id.toString();
		Database db = Database.getInstance();
		int idx = name.lastIndexOf('/');
		String colName = name.substring(0, idx);
		Collection col = db.getCollection(colName);
		String docName = name.substring(idx + 1);

		Transaction tx = new Transaction();
		try {
			Container c = col.getContainer(tx, docName);

			if ( c != null ) {
				ContentProxy dp = new ContentProxy(col, docName);
				return new ObjectInstance(dp);
			}
			else
				throw new DBException(FaultCodes.COL_CANNOT_RETRIEVE, "Container '"+docName+"' not found");
		}
		catch ( DBException e ) {
			tx.cancel();
			throw e;
		}
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }
}

