List of usage examples for javax.naming Context lookup
public Object lookup(String name) throws NamingException;
From source file:opa.filter.LoadInitiativeSetup.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException { Connection conn = null;// w w w . ja v a2 s . c o m try { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; /* * select the fields from initiative_setup and translate them to the * InitiativeSetup model. * * TODO: use a real object-relational-mapper like hibernate. */ Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jdbcJndi); conn = ds.getConnection(); ResultSet rs = conn.createStatement() .executeQuery("select I.*, L.language from initiative_setup I, languages L " + "where I.default_lang = L.lang_id"); if (rs.next() == false) { log.fatal("Could not get info from initiative_setup table."); response.sendError(500); } InitiativeSetup setup = new InitiativeSetup(); Map<String, Object> map = Utils.resultSetToMap(rs); try { BeanUtils.populate(setup, map); } catch (Exception e) { log.fatal("could not build InitiativeSetup from table initiative_setup"); log.fatal(e, e); response.sendError(500); } request.getSession().setAttribute("initiativeSetup", setup); } catch (NamingException e) { log.fatal(e, e); } catch (SQLException e) { log.fatal(e, e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { // bleh } } } fc.doFilter(req, res); }
From source file:com.sun.socialsite.business.MailProvider.java
public MailProvider() throws StartupException { String connectionTypeString = Config.getProperty("mail.configurationType"); if ("properties".equals(connectionTypeString)) { type = ConfigurationType.MAIL_PROPERTIES; }/*from w ww . j a va 2 s .c o m*/ jndiName = Config.getProperty("mail.jndi.name"); mailHostname = Config.getProperty("mail.hostname"); mailUsername = Config.getProperty("mail.username"); mailPassword = Config.getProperty("mail.password"); try { String portString = Config.getProperty("mail.port"); if (portString != null) { mailPort = Integer.parseInt(portString); } } catch (Throwable t) { log.warn("mail server port not a valid integer, ignoring"); } // init and connect now so we fail early if (type == ConfigurationType.JNDI_NAME) { String name = "java:comp/env/" + jndiName; try { Context ctx = (Context) new InitialContext(); session = (Session) ctx.lookup(name); } catch (NamingException ex) { throw new StartupException("ERROR looking up mail-session with JNDI name: " + name); } } else { Properties props = new Properties(); props.put("mail.smtp.host", mailHostname); if (mailUsername != null && mailPassword != null) { props.put("mail.smtp.auth", "true"); } if (mailPort != -1) { props.put("mail.smtp.port", "" + mailPort); } session = Session.getDefaultInstance(props, null); } try { Transport transport = getTransport(); transport.close(); } catch (Throwable t) { throw new StartupException("ERROR connecting to mail server", t); } }
From source file:nl.trivento.albero.repositories.DatabaseRepository.java
private DataSource createJndiDataSource(Map<String, String> parameters) throws ConfigurationException { try {// w w w . ja v a 2s . c o m Context context = (Context) new InitialContext().lookup("java:/comp/env"); return (DataSource) context.lookup(parameters.get(JNDI_NAME)); } catch (NamingException exception) { throw new ConfigurationException(exception, "can't obtain data source from JNDI"); } }
From source file:org.gss_project.gss.server.webdav.milton.GssSecurityManager.java
private ExternalAPI getService() throws RpcException { try {//from w w w .j a v a 2 s.com final Context ctx = new InitialContext(); final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath")); return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class); } catch (final NamingException e) { log.error("Unable to retrieve the ExternalAPI EJB", e); throw new RpcException("An error occurred while contacting the naming service"); } }
From source file:org.dhatim.db.JndiDataSource.java
private Object lookup(String jndi) { Context context = null; try {//from w ww. jav a 2 s.co m context = new InitialContext(); return context.lookup(jndi); } catch (NamingException e) { throw new SmooksConfigurationException("JNDI Context lookup failed for '" + jndi + "'.", e); } finally { if (context != null) { try { context.close(); } catch (NamingException e) { throw new SmooksConfigurationException( "Error closing Naming Context after looking up DataSource JNDI '" + datasourceJndi + "'.", e); } } } }
From source file:org.ualerts.chat.database.EmbeddedHsqlDatabaseServer.java
private boolean wantEmbeddedDatabase() { boolean useEmbedded = false; try {//from ww w .ja v a 2 s . c o m Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(dataSourceName); Class<?> dataSourceClass = ds.getClass(); Method urlMethod = dataSourceClass.getMethod("getUrl"); String url = (String) urlMethod.invoke(ds); useEmbedded = url.endsWith("/" + DEFAULT_DATABASE_NAME); } catch (NoSuchMethodException ex) { logger.warn("data source has no accessor for the URL"); } catch (IllegalAccessException ex) { logger.warn("cannot access the data source URL"); } catch (InvocationTargetException ex) { logger.warn("error accessing the data source URL"); } catch (NamingException ex) { logger.warn("JNDI lookup failed: " + ex); } return useEmbedded; }
From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up the JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("topic.TOPIC", "BasicTopic"); hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1"); hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2"); hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up the topic Destination topic = (Destination) context.lookup("TOPIC"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side seperately with minimal clutter {/* w w w .j a v a 2 s.co m*/ // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(topic); // Send messaGES for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } // Look up the subscription (pretending it's a queue) receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3"); System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:it.infn.ct.security.actions.ExtendAccount.java
private void sendMail() throws MailException { javax.mail.Session session = null;/* w ww.j a va 2 s. c om*/ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom)); InternetAddress mailTos[] = new InternetAddress[1]; mailTos[0] = new InternetAddress(mailTo); mailMsg.setRecipients(Message.RecipientType.TO, mailTos); mailMsg.setSubject(mailSubject); LDAPUser user = LDAPUtils.getUser(username); mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " " + user.getSurname() + " (" + user.getUsername() + ")"); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { _log.error(ex); throw new MailException("Mail address format not valid"); } catch (MessagingException ex) { _log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:it.infn.ct.security.actions.ReactivateUser.java
private void sendMail(LDAPUser user) throws MailException { javax.mail.Session session = null;/*from ww w . j ava2 s .c o m*/ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom)); InternetAddress mailTos[] = new InternetAddress[1]; mailTos[0] = new InternetAddress(mailTo); mailMsg.setRecipients(Message.RecipientType.TO, mailTos); mailMsg.setSubject(mailSubject); mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " " + user.getSurname() + " (" + user.getUsername() + ")"); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { _log.error(ex); throw new MailException("Mail address format not valid"); } catch (MessagingException ex) { _log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:DatabaseInfo.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;//from www . j a va 2s. com Connection connection = null; Statement statement; ResultSet rs; outResponse.setContentType("text/html"); out = outResponse.getWriter(); try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); DatabaseMetaData md = connection.getMetaData(); statement = connection.createStatement(); out.println("<HTML><HEAD><TITLE>Database Server Information</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>General Source Information</H1>"); out.println("getURL() - " + md.getURL() + "<BR>"); out.println("getUserName() - " + md.getUserName() + "<BR>"); out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion() + "<BR>"); out.println("getDriverMajorVersion - " + md.getDriverMajorVersion() + "<BR>"); out.println("getDriverMinorVersion - " + md.getDriverMinorVersion() + "<BR>"); out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh() + "<BR>"); out.println("<H1>Feature Support</H1>"); out.println("supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>"); out.println("supportsBatchUpdates - " + md.supportsBatchUpdates() + "<BR>"); out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames() + "<BR>"); out.println("supportsPositionedDelete - " + md.supportsPositionedDelete() + "<BR>"); out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins() + "<BR>"); out.println("supportsStoredProcedures - " + md.supportsStoredProcedures() + "<BR>"); out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers() + "<BR>"); out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("<H1>Data Source Limits</H1>"); out.println("getMaxRowSize - " + md.getMaxRowSize() + "<BR>"); out.println("getMaxStatementLength - " + md.getMaxStatementLength() + "<BR>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxConnections - " + md.getMaxConnections() + "<BR>"); out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength() + "<BR>"); out.println("<H1>SQL Object Available</H1>"); out.println("getTableTypes()<BR><UL>"); rs = md.getTableTypes(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("getTables()<BR><UL>"); rs = md.getTables("accounts", "", "%", new String[0]); while (rs.next()) { out.println("<LI>" + rs.getString("TABLE_NAME")); } out.println("</UL>"); out.println("<H1>Transaction Support</H1>"); out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation() + "<BR>"); out.println( "dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions() + "<BR>"); out.println("<H1>General Source Information</H1>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable() + "<BR>"); out.println("getTimeDateFunctions - " + md.getTimeDateFunctions() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("getTypeInfo()<BR><UL>"); rs = md.getTypeInfo(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }