Example usage for javax.naming InitialContext list

List of usage examples for javax.naming InitialContext list

Introduction

In this page you can find the example usage for javax.naming InitialContext list.

Prototype

public NamingEnumeration<NameClassPair> list(Name name) throws NamingException 

Source Link

Usage

From source file:com.funambol.server.db.DataSourceContextHelperTest.java

/**
 * Usefull method for troubleshooting/*  ww  w .  j a va2s . c  o m*/
 * @throws java.lang.Exception
 */
private static void printContext(String contextName) throws Exception {
    System.out.println("---------- Listing '" + contextName + "' ------------");
    InitialContext initialContext = new InitialContext();

    NamingEnumeration<NameClassPair> nameEnum = initialContext.list(contextName);
    if (nameEnum != null) {
        while (nameEnum.hasMore()) {
            NameClassPair name = nameEnum.next();
            String nameInSpace = name.getName();
            String className = name.getClassName();
            System.out.println("NameInSpace: " + nameInSpace + ", class: " + className);
        }
    }
    System.out.println("--------------------------------------------");
}

From source file:info.bunji.jdbc.logger.JdbcLoggerFactory.java

/**
 ********************************************
 * get loggerName from jdbc url.//from  w w  w.  j  a v a  2 s.  co  m
 *
 * @param url connection url
 * @return loggerName(jdbc url or DataSourceName)
 ********************************************
 */
private static String getLoggerName(String url) {
    if (!dsNameMap.containsKey(url)) {
        dsNameMap.put(url, url);

        // datasource????
        InitialContext ctx = null;
        try {
            // JNDI??????
            ctx = new InitialContext();
            NamingEnumeration<NameClassPair> ne = ctx.list("java:comp/env/jdbc");
            while (ne.hasMoreElements()) {
                NameClassPair nc = ne.nextElement();
                DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + nc.getName());
                // ?DataSource????getUrl()
                Method method = ds.getClass().getMethod("getUrl");
                String dsUrl = (String) method.invoke(ds);
                if (dsUrl.startsWith(DriverEx.DRIVER_URL_PREFIX)) {
                    dsUrl = dsUrl.replace(DriverEx.DRIVER_URL_PREFIX, "jdbc:");
                    if (dsUrl.equals(url)) {
                        dsNameMap.put(url, nc.getName());
                        break;
                    }
                }
            }
        } catch (Throwable t) {
            printThrowable(t);
        } finally {
            try {
                if (ctx != null)
                    ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return dsNameMap.get(url);
}

From source file:net.chrisrichardson.foodToGo.ejb3.facadeWithSpringDI.PlaceOrderFacadeUsingIntegratedDependencyInjectImpl.java

private void listContext(InitialContext initialContext, String root) throws NamingException {
    Enumeration<NameClassPair> enumeration = initialContext.list(root);
    while (enumeration.hasMoreElements()) {
        NameClassPair nc = enumeration.nextElement();
        logger.debug("Name=" + root + "/" + nc.getName());
        if (nc.getClassName().endsWith("NamingContext"))
            listContext(initialContext, root + "/" + nc.getName());
    }/*from w w  w .  j av  a  2s . co  m*/
}

From source file:com.flexive.shared.EJBLookup.java

/**
 * Discover which lookup strategy works for the given class
 *
 * @param appName     EJB application name
 * @param environment properties passed to the initial context
 * @param type        the class//from w w w. j  a va2 s .  c o m
 * @return appName (may have changed)
 */
private static <T> String discoverStrategy(String appName, final Hashtable<String, String> environment,
        Class<T> type) {
    InitialContext ctx = null;
    for (STRATEGY strat : STRATEGY.values()) {
        if (strat == STRATEGY.UNKNOWN)
            continue;
        used_strategy = strat;
        try {
            final Hashtable<String, String> env = environment != null
                    ? new Hashtable<String, String>(environment)
                    : new Hashtable<String, String>();
            prepareEnvironment(strat, env);
            ctx = new InitialContext(env);
            ctx.lookup(buildName(appName, type));

            if (used_strategy == STRATEGY.EJB31_MODULE) {
                // we need to resolve all interfaces required by non-web components (stream server, scheduler),
                // since they run outside the module context

                resolveKnownInterfaces();
            }
            return appName;
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Strategy " + strat + " failed: " + e.getMessage(), e);
            }
            //ignore and try next
        }
    }
    //houston, we have a problem - try locale and remote with appname again iterating through all "root" ctx bindings
    //this can happen if the ear is not named flexive.ear
    try {
        if (ctx == null)
            ctx = new InitialContext(environment);
        NamingEnumeration<NameClassPair> ncpe = ctx.list("");
        while (ncpe.hasMore()) {
            NameClassPair ncp = ncpe.next();
            if (ncp.getClassName().endsWith("NamingContext")) {
                appName = ncp.getName();
                try {
                    used_strategy = STRATEGY.APP_SIMPLENAME_LOCAL;
                    ctx.lookup(buildName(ncp.getName(), type));
                    APPNAME = ncp.getName();
                    LOG.info("Using application name [" + appName + "] for lookups!");
                    return APPNAME;
                } catch (Exception e) {
                    //ignore and try remote
                }
                try {
                    used_strategy = STRATEGY.APP_SIMPLENAME_REMOTE;
                    ctx.lookup(buildName(ncp.getName(), type));
                    APPNAME = ncp.getName();
                    LOG.info("Using application name [" + appName + "] for lookups!");
                    return APPNAME;
                } catch (Exception e) {
                    //ignore and try remote
                }
            }
        }
    } catch (Exception e) {
        LOG.warn(e);
    }
    used_strategy = null;
    return appName;
}

From source file:org.nuxeo.ecm.platform.io.test.TestIORemoteCopy.java

@Before
public void setUp() throws Exception {

    System.setProperty("org.nuxeo.runtime.streaming.isServer", "false");
    System.setProperty("org.nuxeo.runtime.server.port", "62475");
    System.setProperty("org.nuxeo.runtime.server.host", "localhost");
    System.setProperty("org.nuxeo.runtime.streaming.serverLocator", STREAM_SERVER_URL);

    super.setUp();

    // the core bundle
    deployContrib("org.nuxeo.ecm.core", "OSGI-INF/CoreService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "TypeService.xml");
    deployContrib("org.nuxeo.ecm.core", "OSGI-INF/SecurityService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RepositoryService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "test-CoreExtensions.xml");

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "CoreEventListenerService.xml");

    // repo test case misc
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "DefaultPlatform.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RepositoryManager.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "LifeCycleCoreExtensions.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "LifeCycleService.xml");
    // specific files
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "io-test-framework.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "io-test-contrib.xml");

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RemotingService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "JBossLoginConfig.xml");
    // donnot : deployContrib("StreamingServer.xml");

    deployBundle("org.nuxeo.ecm.relations.api");
    deployBundle("org.nuxeo.ecm.relations");
    deployBundle("org.nuxeo.ecm.relations.jena");
    deployBundle("org.nuxeo.ecm.platform.comment.api");
    deployBundle("org.nuxeo.ecm.platform.comment");

    InitialContext ctx1 = new InitialContext();
    System.err.println(ctx1.lookup("java:/comment-relations"));
    NamingEnumeration<NameClassPair> en = ctx1.list("/");
    while (en.hasMore()) {
        Object o = en.nextElement();
        System.err.println(o);//from   w  ww.j  a  va2s.  c om
    }

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "commentService-config-bundle.xml");

    Map<String, Serializable> ctx = new HashMap<String, Serializable>();
    ctx.put("username", SecurityConstants.ADMINISTRATOR);
    coreSession = CoreInstance.getInstance().open(localRepositoryName, ctx);

    ioService = Framework.getService(IOManager.class);
}

From source file:org.pepstock.jem.annotations.SetFields.java

private static void checkIfIsRightObject(String name, boolean isDD) throws NamingException {
    InitialContext ic = ContextUtils.getContext();
    NamingEnumeration<NameClassPair> list = ic.list(name);
    boolean isDataDescription = false;
    while (list.hasMore()) {
        NameClassPair pair = list.next();
        // checks if is datastream
        // only datastreams are changed
        if (pair instanceof DataStreamNameClassPair) {
            isDataDescription = true;/*from ww  w  .ja  v  a  2s . com*/
        }
    }
    if (isDD && !isDataDescription) {
        throw new NamingException(name + " is not a data description");
    }
    if (!isDD && isDataDescription) {
        throw new NamingException(name + " is not a data source");
    }
}

From source file:org.pepstock.jem.jppf.ExecuteManager.java

/**
 * Create a JPPF job that can be submitted for execution.
 * //from  w ww.  ja va2s  . c  o  m
 * @param runnable Class name of Runnable or JPPFTask to execute
 * @param parallelTaskNumber Number of parallel task to submit
 * @param xmlContext InitialContext, serialized in XML string
 * @return an instance of the {@link org.jppf.client.JPPFJob JPPFJob} class.
 * @throws NamingException 
 * @throws IOException 
 * @throws JPPFException 
 * @throws JPFFException
 *             if an error occurs while creating the job or adding tasks.
 */
private static JPPFJob createJob(String xmlContext)
        throws JPPFMessageException, NamingException, IOException, JPPFException {
    XStream xstream = new XStream();
    // reads all properties
    String jobName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_JOB_NAME);
    String taskName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_TASK_NAME);
    String runnable = JPPFConfiguration.getProperties().getProperty(Keys.JEM_RUNNABLE);
    int parallelTaskNumber = JPPFConfiguration.getProperties().getInt(Keys.JEM_TASK_NUMBER);

    // creates a data provider to pass initial context and number of parallel task
    MemoryMapDataProvider provider = new MemoryMapDataProvider();
    provider.setValue(Keys.JEM_CONTEXT, xmlContext);
    provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber));

    // checks if CHUNK is set
    if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION)) {
        // gets data description
        String dataDescription = JPPFConfiguration.getProperties()
                .getProperty(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION);
        File file = null;
        InitialContext ic = ContextUtils.getContext();

        // lookup for JNDI reference
        // needs file name because chunk is based on RandomFileAccess
        // that wants a FILE and not inputstream
        // so gets data description implementation object
        // to get REAL FILE
        NamingEnumeration<NameClassPair> list = ic.list(dataDescription);
        while (list.hasMore()) {
            NameClassPair pair = list.next();
            // checks if is datastream
            // only datastreams are searched            
            if (pair.getName().equalsIgnoreCase(dataDescription) && pair instanceof DataStreamNameClassPair) {
                DataStreamNameClassPair dsPair = (DataStreamNameClassPair) pair;
                DataStreamReference prevReference = (DataStreamReference) dsPair.getObject();
                // gets data description XML definition
                StringRefAddr sra = (StringRefAddr) prevReference.get(StringRefAddrKeys.DATASTREAMS_KEY);
                // creates datadescription implementatio to get file 
                DataDescriptionImpl ddImpl = (DataDescriptionImpl) xstream.fromXML(sra.getContent().toString());
                file = ddImpl.getDatasets().iterator().next().getRealFile();
                // leaves while
                break;
            }
        }
        // if file is null
        // data description is not found
        if (file == null) {
            throw new JPPFMessageException(JPPFMessage.JEMJ019E, dataDescription);
        }
        // calculated buffersize
        long bufferSize = file.length() / parallelTaskNumber;

        // using delimiter, creates chunk list
        List<ChunkDefinition> chunks = null;
        String delimiter = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER);
        String delimiterString = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER_STRING);

        if (delimiter != null) {
            // delimiter default LF
            char splitter = CharUtils.LF;
            // if delimiter is defined in BYTE mode
            // calculate char
            if (delimiter.toLowerCase().startsWith("0x")) {
                delimiter = StringUtils.substringAfter(delimiter.toLowerCase(), "0x");
                splitter = (char) Integer.parseInt(delimiter, 16);
            } else {
                // if uses a escape java char
                splitter = StringEscapeUtils.unescapeJava(delimiter).charAt(0);
            }
            String displayDelimiter = Integer.toHexString((byte) splitter) + "(" + splitter + ")";
            LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, displayDelimiter);

            // calculates chunks
            chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, splitter);
            provider.setValue(Keys.JEM_DELIMITER, splitter);
        } else if (delimiterString != null) {
            LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, delimiterString);
            // calculates chunks
            chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, delimiterString);
            provider.setValue(Keys.JEM_DELIMITER, delimiterString);
        } else {
            // if delimiter and delimiterString are missing, uses default delimiter (System.getProperty("line.separator")
            chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize);
        }
        // changes parallel task
        // because chunk calculation tries to maintain the same 
        // number of task but usually there are less after
        // chunk list creation
        parallelTaskNumber = chunks.size();

        LogAppl.getInstance().emit(JPPFMessage.JEMJ021I, chunks);

        // serializes and saves on data provider all necessary data 
        provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber));
        provider.setValue(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION, dataDescription);
        provider.setValue(Keys.JEM_CHUNKS, xstream.toXML(chunks));
    }

    LogAppl.getInstance().emit(JPPFMessage.JEMJ023I, parallelTaskNumber);

    // checks if merged data decritpion is an argument
    if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_MERGED_DATA_DESCRIPTION)) {
        // loads a list with all temporary files for tasks
        // to use to write partial output
        for (int i = 0; i < parallelTaskNumber; i++) {
            File temp = File.createTempFile("task[" + i + "]-merge", ".jemjppf");
            temp.deleteOnExit();
            TEMPORARY_FILES.add(temp);
            LogAppl.getInstance().emit(JPPFMessage.JEMJ022I, temp.getAbsolutePath(), i);
        }
        // sets data provider
        provider.setValue(Keys.JEM_MERGED_DATA_DESCRIPTION,
                JPPFConfiguration.getProperties().getProperty(Keys.JEM_MERGED_DATA_DESCRIPTION));
        provider.setValue(Keys.JEM_TEMPORARY_FILES, xstream.toXML(TEMPORARY_FILES));
    }

    // create a JPPF job
    JPPFJob job = new JPPFJob(provider);

    // give this job a readable unique id that we can use to monitor and
    // manage it.
    job.setName(jobName + "." + taskName);

    // Checks what instance has been past to distribute on grid
    try {
        Object clazz = Class.forName(runnable).newInstance();
        if (clazz instanceof JPPFTask) {
            for (int i = 0; i < parallelTaskNumber; i++) {
                JPPFTask t = new WrapperJPPFTask((JPPFTask) clazz);
                // add a task to the job.
                job.addTask(t);
            }
        } else if (clazz instanceof Runnable) {
            for (int i = 0; i < parallelTaskNumber; i++) {
                JPPFTask t = new RunnableTask((Runnable) clazz);
                // add a task to the job.
                job.addTask(t);
            }
        } else {
            throw new JPPFMessageException(JPPFMessage.JEMJ002E, runnable, Runnable.class.getName(),
                    JPPFTask.class.getName());
        }
    } catch (InstantiationException e) {
        throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(),
                JPPFTask.class.getName());
    } catch (IllegalAccessException e) {
        throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(),
                JPPFTask.class.getName());
    } catch (ClassNotFoundException e) {
        throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(),
                JPPFTask.class.getName());
    }

    // there is no guarantee on the order of execution of the tasks,
    // however the results are guaranteed to be returned in the same order
    // as the tasks.
    return job;
}