Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.flexive.core.Database.java

private static DataSource tryGetDefaultDataSource(Context c, String dataSourceName,
        DefaultDataSourceInitializer initializer) throws SQLException {
    // try to get and initialize the default datasource in JavaEE 6 containers,
    // as configured in the GlobalConfigurationEngineBean EJB
    Connection con = null;/*w  w  w  . j a  va 2s.com*/
    Statement stmt = null;
    try {
        DataSource ds = (DataSource) c.lookup(dataSourceName);
        if (ds != null && !isDefaultDataSourceInitialized(ds)) {
            // try to initialize schema
            con = getDefaultInitConnection(c);
            if (con != null) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Schema not initialized for default datasource " + dataSourceName
                            + ", initializing...");
                }
                stmt = con.createStatement();
                stmt.execute("CREATE SCHEMA " + initializer.getSchema());
                stmt.close();
                try {
                    initializer.initSchema(con, StorageManager.getStorageImpl("H2"));
                } catch (Exception ex) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Failed to initialize schema " + initializer.getSchema() + " for "
                                + dataSourceName + ": " + ex.getMessage(), ex);
                    }
                }
            } else {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Default configuration schema not initialized, but failed to retrieve"
                            + " data source " + GlobalConfigurationEngineBean.DEFAULT_DS_INIT);
                }
                // ignore for now, the caller will get an exception when calling getConnection()
                // on the data source anyway
            }
        }
        return ds;
    } catch (NamingException e) {
        // not bound
        return null;
    } finally {
        closeObjects(Database.class, con, stmt);
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.grid.service.globus.resource.BaseResource.java

public ResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//from w w w  .  j av  a 2s .com
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();

    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 = (ResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:it.infn.ct.security.utilities.LDAPCleaner.java

private void sendUserRemainder(UserRequest ur, int days) {
    javax.mail.Session session = null;//from ww  w  . j a v a  2s . co m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

        Message mailMsg = new MimeMessage(session);
        mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin")));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(getGoodMail(ur),
                ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) {

            String ccMail[] = rb.getString("mailCopy").split(";");
            InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
            for (int i = 0; i < ccMail.length; i++) {
                mailCCopy[i] = new InternetAddress(ccMail[i]);
            }

            mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);
        }

        if (days > 0) {
            mailMsg.setSubject(
                    rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailNotificationBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        } else {
            mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailDeleteBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        }
        Transport.send(mailMsg);

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
    }
}

From source file:org.cesecore.audit.impl.queued.QueuedAuditorSessionBean.java

@PostConstruct
public void postConstruct() throws NamingException {
    final Context context = new InitialContext();
    if (ds == null) {
        ds = (DataSource) context.lookup(CesecoreConfiguration.getDataSourceJndiName());
    }//from  w  w w .j  a  v  a 2s  . c  o m
    queuedAuditorSession = sessionContext.getBusinessObject(QueuedAuditorSessionLocal.class);
}

From source file:com.esri.geoportal.harvester.migration.MigrationBroker.java

private void initDataSource(InitContext context) throws NamingException {
    Context initContext = new InitialContext();
    Context webContext = (Context) initContext.lookup("java:/comp/env");
    dataSource = (DataSource) webContext.lookup(definition.getJndi());
}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {//from   ww  w  . j ava 2 s .co m
        Context env = (Context) new InitialContext().lookup("java:comp/env");
        ds = (DataSource) env.lookup("jdbc/jfileshare");
    } catch (NamingException e) {
        throw new ServletException(e);
    }
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *//*  ww w .  ja v a 2 s. co  m*/
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

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

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:org.apache.synapse.transport.jms.JMSOutTransportInfo.java

/**
 * Get the JMS destination specified by the given URL from the context
 *
 * @param context the Context to lookup/*from   ww w  .j ava  2  s .com*/
 * @param url     URL
 * @return the JMS destination, or null if it does not exist
 */
private Destination getDestination(Context context, String url) {
    String destinationName = JMSUtils.getDestination(url);
    try {
        return (Destination) context.lookup(destinationName);
    } catch (NameNotFoundException e) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot locate destination : " + destinationName + " using " + url);
        }
    } catch (NamingException e) {
        handleException("Cannot locate destination : " + destinationName + " using " + url, e);
    }
    return null;
}

From source file:Controllers.AppointmentController.java

/**
 *
 * @param appointment/*from   w w  w .  j  av a 2s .c o  m*/
 * @param result
 * @param modelMap
 * @return 
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public String AddApp(@ModelAttribute("appointment") Appointment appointment, BindingResult result,
        ModelMap modelMap) {

    int accountId = appointment.getAccountId();
    int departmentId = appointment.getDepartmentId();
    Date fulldate = appointment.getDate();
    java.sql.Date date = new java.sql.Date(fulldate.getTime());
    String message = appointment.getMessage();

    String content = "";

    if (departmentId == 0 || date == null) {
        content = "Sorry, you didn't fill some of fields. Please, try again.";
        modelMap.addAttribute("content", content);
        return "appointmentConfirmation";
    }
    Date m = null;
    int appointmentcounter = 0;
    Appointment[] appointments = fetchAppointments();
    for (int i = 0; i < appointments.length; i++) {
        if (appointments[i].getDate().compareTo(date) == 0 && appointments[i].getDepartmentId() == departmentId)
            appointmentcounter++;
    }
    if (appointmentcounter >= 2) {
        content = "Sorry, there is no any free spaces for your appointment on " + date + " to visit "
                + findDepartmentName(departmentId) + ". Please, select another day.<br>";
        modelMap.addAttribute("content", content);
        return "appointmentConfirmation";
    }

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        Statement stmt = connection.createStatement();
        PreparedStatement pstmt;

        pstmt = connection.prepareStatement(
                "INSERT INTO appointments (accountId, departmentId, date, message)\n" + "VALUES (?,?,?,?);");
        pstmt.setInt(1, accountId);
        pstmt.setInt(2, departmentId);
        pstmt.setDate(3, date);
        pstmt.setString(4, message);
        pstmt.execute();

        content = "<h4>Appontment have been setted.</h4><br><h5>Please, check information below.</h5><br>"
                + "<table>" + "<tr><td>Seleted department:</td><td>" + findDepartmentName(departmentId)
                + "</td></tr>" + "<tr><td>Seleted date:</td><td>"
                + new SimpleDateFormat("yyyy-MM-dd").format(date) + "</td></tr>"
                + "<tr><td>Attached message</td><td>" + message + "</td></tr>" + "</table>";

        stmt.close();
    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    modelMap.addAttribute("content", content);

    return "appointmentConfirmation";
}

From source file:hermes.ext.jbossmq.JBossMQAdmin.java

private RMIAdaptor getRMIAdapter() throws NamingException, JMSException {
    if (rmiAdaptor == null) {
        Context ctx = jndiCF.createContext();

        rmiAdaptor = (RMIAdaptor) ctx.lookup(factory.getRmiAdaptorBinding());
    }//w  ww . j  a  v a2 s  .c  o  m

    return rmiAdaptor;

}