/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s):
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.common;

import javax.naming.NamingEnumeration;
import javax.naming.NameClassPair;
import javax.naming.Context;
import javax.naming.NamingException;
import org.objectweb.util.monolog.api.Logger;

/**
 * Used to print out a Naming context content
 */
public class ContextDump {

    public static void print(String header, Context ctx, Logger logger, int logLevel) {
        logger.log(logLevel, header);
        logger.log(logLevel, "=================================");
        print(ctx, logger, logLevel, "");
        logger.log(logLevel, "=================================");
    }

    /**
     * @param ctx
     * @param logger
     * @param logLevel
     * @param string
     */
    private static void print(Context ctx, Logger logger, int logLevel, String indent) {
        String aName = null;
        try {
            for (NamingEnumeration pNames = ctx.list(""); pNames.hasMore();) {
                Object o = pNames.next();
                if (o instanceof NameClassPair) {
                    aName = ((NameClassPair) o).getName();
                    Object v = ctx.lookup(aName);
                    if (v != null) {
                        if (v instanceof Context) {
                            logger.log(logLevel, indent + aName);
                            print((Context) v, logger, logLevel, indent + "  ");
                        } else {
                            logger.log(logLevel, indent + aName + " = " + v);
                        }
                    }
                }
            }
        } catch (NamingException ne) {
            logger.log(logLevel, "Failed to dump contex: " + ne.toString());
        }
    }
}