001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     matic
016 */
017package org.nuxeo.runtime.jtajca;
018
019import javax.naming.Context;
020import javax.naming.InitialContext;
021import javax.naming.NamingException;
022
023/**
024 * Utility class used for testing JNDI space provider.
025 *
026 * @author Stephane Lacoin (aka matic)
027 * @since 5.5
028 */
029public class InitialContextAccessor extends InitialContext {
030
031    public static final String ENV_CTX_NAME = "java:comp/env";
032
033    protected InitialContextAccessor() throws NamingException {
034        super(false); // lazy mode is breaking jboss
035    }
036
037    protected Context _getInitCtx() {
038        try {
039            return getURLOrDefaultInitCtx("java:");
040        } catch (NamingException e) {
041            return null;
042        }
043    }
044
045    /**
046     * Check for JNDI space availability
047     *
048     * @return true if JNDI space exists
049     */
050    public static boolean isAvailable() {
051        try {
052            return new InitialContextAccessor().getDefaultInitCtx() != null;
053        } catch (NamingException e) {
054            return false;
055        }
056    }
057
058    /**
059     * Try writing in JNDI space
060     *
061     * @param ctx
062     * @return true if JNDI space is writable
063     */
064    public static boolean isWritable(Context ctx, String prefix) {
065        try {
066            final String name = prefix.concat("IsWritable");
067            ctx.bind(name, "is-writable");
068            ctx.unbind(name);
069        } catch (NamingException e) {
070            return false;
071        }
072        return true;
073    }
074
075    /**
076     * Get access to the default initial context implementation
077     *
078     * @return the initial context implementation
079     */
080    public static Context getInitialContext() {
081        try {
082            return new InitialContextAccessor()._getInitCtx();
083        } catch (NamingException e) {
084            return null;
085        }
086    }
087
088}