Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java

@Before
public void setup() throws Exception {
    File folder = new File("/tmp");
    File[] files = folder.listFiles(new FilenameFilter() {
        @Override/*  w w w  . j ava2  s  .  c o  m*/
        public boolean accept(final File dir, final String name) {
            return name.startsWith("test.db");
        }
    });
    for (final File file : files) {
        if (!file.delete()) {
            System.out.println("Failed to remove " + file.getAbsolutePath());
        }
    }

    mongo.dropDatabase(DB_NAME);
    mongo.dropDatabase("local");
    mongo.dropDatabase("admin");
    mongo.dropDatabase("mongo");
    mongo.getDB(DB_NAME).dropDatabase();
    mongo.getDB("local").dropDatabase();
    mongo.getDB("admin").dropDatabase();
    mongo.getDB("mongo").dropDatabase();

    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).remove(new BasicDBObject());
    mongo.getDB("mongo").getCollection("metadata").remove(new BasicDBObject());

    db.createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null);
    BasicDBObject index = new BasicDBObject("name", 1);
    index.put("version.value", 1);
    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).ensureIndex(index, "name", true);

    if (notRegistered) {
        notRegistered = false;
        try {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            JdbcConnectionPool ds = JdbcConnectionPool.create(
                    "jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa");

            ic.bind("java:/mydatasource", ds);
        } catch (NamingException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        Context initCtx = new InitialContext();
        DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource");
        Connection conn = ds.getConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("DROP ALL OBJECTS ");
        stmt.close();
    }
}

From source file:be.fedict.trust.service.bean.TrustServiceTrustLinker.java

private void logAudit(String message) {

    try {/*w  w  w. java2 s .  c  o m*/
        InitialContext initialContext = new InitialContext();
        AuditDAO auditDAO = (AuditDAO) initialContext.lookup(AuditDAO.JNDI_BINDING);
        auditDAO.logAudit(message);
    } catch (NamingException e) {
        LOG.error("Failed to log audit message: " + message, e);
    }

}

From source file:com.googlecode.psiprobe.beans.ResourceResolverBean.java

public synchronized DataSource lookupDataSource(final Context context, String resourceName,
        ContainerWrapperBean containerWrapper) throws NamingException {
    if (context != null) {
        ((AbstractTomcatContainer) containerWrapper.getTomcatContainer()).bindToContext(context);
    }//from   w  w w  .  j av  a2 s.com
    try {
        javax.naming.Context ctx = (context != null) ? new InitialContext() : getGlobalNamingContext();
        String jndiName = resolveJndiName(resourceName, (context == null));
        Object o = ctx.lookup(jndiName);

        if (o instanceof DataSource) {
            return (DataSource) o;
        } else {
            return null;
        }
    } finally {
        if (context != null) {
            ((AbstractTomcatContainer) containerWrapper.getTomcatContainer()).unbindFromContext(context);
        }
    }
}

From source file:Util.java

/**
 * Create a link/*from   ww  w .java  2s. co  m*/
 * 
 * @param fromName
 *          the from name
 * @param toName
 *          the to name
 * @throws NamingException
 *           for any error
 */
public static void createLinkRef(String fromName, String toName) throws NamingException {
    InitialContext ctx = new InitialContext();
    createLinkRef(ctx, fromName, toName);
}

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

/**
 * Usefull method for troubleshooting//from  ww w.  j  av a 2  s.co 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:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Gets an MQ message off a specified queue and returns it as an
 * <code>Object</code> to the requestor for further processing.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param responseQueue - The request queue name to put the message on
 * @param timeout - How long to wait for a connection or response
 * @param messageId - The JMS correlation ID of the message the response is associated with
 * @return <code>Object</code> - The serializable data returned by the MQ request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */// ww  w .j  a  v a2  s.  c o  m
public static final synchronized Object getMqMessage(final String connName, final List<String> authData,
        final String responseQueue, final long timeout, final String messageId) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", responseQueue);
        DEBUGGER.debug("Value: {}", timeout);
        DEBUGGER.debug("Value: {}", messageId);
    }

    Connection conn = null;
    Session session = null;
    Object response = null;
    Context envContext = null;
    MessageConsumer consumer = null;
    ConnectionFactory connFactory = null;

    try {
        try {
            InitialContext initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

        // Create a Session
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        if (envContext != null) {
            try {
                consumer = session.createConsumer((Destination) envContext.lookup(responseQueue),
                        "JMSCorrelationID='" + messageId + "'");
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createQueue(responseQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'");
        }

        if (DEBUG) {
            DEBUGGER.debug("MessageConsumer: {}", consumer);
        }

        ObjectMessage message = (ObjectMessage) consumer.receive(timeout);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        if (message == null) {
            throw new UtilityException("Failed to retrieve message within the timeout specified.");
        }

        response = message.getObject();
        message.acknowledge();

        if (DEBUG) {
            DEBUGGER.debug("Object: {}", response);
        }
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return response;
}

From source file:de.zib.gndms.dspace.slice.service.globus.resource.SliceResourceBase.java

public SliceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//from  w  ww  .j av a2  s  .c  o  m
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/Slice";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (SliceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncherFactory.java

/**
 * Used to configure the migration launcher with properties from a servlet
 * context.  You do not need migration.properties to use this method.
 *
 * @param launcher the launcher to configure
 * @param sce      the event to get the context and associated parameters from
 * @throws MigrationException if a problem with the look up in JNDI occurs
 *//*  ww  w  .  j a va2s .  co  m*/
private void configureFromServletContext(JdbcMigrationLauncher launcher, ServletContextEvent sce)
        throws MigrationException {
    String readOnly = sce.getServletContext().getInitParameter("migration.readonly");
    launcher.setReadOnly(false);
    if ("true".equals(readOnly)) {
        launcher.setReadOnly(true);
    }

    // See if they want to override the lock after a certain amount of time
    String lockPollRetries = sce.getServletContext().getInitParameter("migration.lockPollRetries");
    if (lockPollRetries != null) {
        launcher.setLockPollRetries(Integer.parseInt(lockPollRetries));
    }

    String patchPath = ConfigurationUtil.getRequiredParam("migration.patchpath", sce, this);
    launcher.setPatchPath(patchPath);

    String postPatchPath = sce.getServletContext().getInitParameter("migration.postpatchpath");
    launcher.setPostPatchPath(postPatchPath);

    String databases = sce.getServletContext().getInitParameter("migration.jdbc.systems");
    String[] databaseNames;
    if ((databases == null) || "".equals(databases)) {
        databaseNames = new String[1];
        databaseNames[0] = "";
        log.debug("jdbc.systems was null or empty, not multi-node");
    } else {
        databaseNames = databases.split(",");
        log.debug("jdbc.systems was set to " + databases + ", configuring multi-node");
    }

    for (int i = 0; i < databaseNames.length; i++) {
        String databaseName = databaseNames[i];
        if (databaseName != "") {
            databaseName = databaseName + ".";
        }
        String databaseType = ConfigurationUtil.getRequiredParam("migration." + databaseName + "databasetype",
                sce, this);
        String systemName = ConfigurationUtil.getRequiredParam("migration.systemname", sce, this);
        String dataSource = ConfigurationUtil.getRequiredParam("migration." + databaseName + "datasource", sce,
                this);

        DataSourceMigrationContext context = getDataSourceMigrationContext();
        context.setSystemName(systemName);
        context.setDatabaseType(new DatabaseType(databaseType));

        try {
            Context ctx = new InitialContext();
            if (ctx == null) {
                throw new IllegalArgumentException(
                        "A jndi context must be " + "present to use this configuration.");
            }
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + dataSource);
            context.setDataSource(ds);
            log.debug("adding context with datasource " + dataSource + " of type " + databaseType);
            launcher.addContext(context);
        } catch (NamingException e) {
            throw new MigrationException("Problem with JNDI look up of " + dataSource, e);
        }
    }
}

From source file:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);//w ww  . j  a v a 2s  .  c om
    connection.start();
}

From source file:com.erbjuder.logger.server.entity.impl.LogMessage.java

public List<com.erbjuder.logger.server.entity.interfaces.LogMessageData> getLogMessageData(
        Set<Class> classSelectionList) {
    try {//w  w  w. j  av a  2  s .  c o  m

        LogMessageDataFacadeImpl logMessageDataFacade = (LogMessageDataFacadeImpl) new InitialContext()
                .lookup("java:module/LogMessageDataFacadeImpl");
        return logMessageDataFacade.getLogMessageData(this, classSelectionList);

    } catch (Exception e) {
        System.err.println(e.getMessage());
        return null;
    }
}