List of usage examples for javax.naming InitialContext InitialContext
public InitialContext() throws NamingException
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize * @param message - The email message// w w w . j a va 2 s . c o m * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message */ public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException { final String methodName = EmailUtils.CNAME + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException"; Session mailSession = null; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", mailConfig); DEBUGGER.debug("Value: {}", message); DEBUGGER.debug("Value: {}", isWeb); } SMTPAuthenticator smtpAuth = null; if (DEBUG) { DEBUGGER.debug("MailConfig: {}", mailConfig); } try { if (isWeb) { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT); if (DEBUG) { DEBUGGER.debug("InitialContext: {}", initContext); DEBUGGER.debug("Context: {}", envContext); } if (envContext != null) { mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName()); } } else { Properties mailProps = new Properties(); try { mailProps.load( EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile())); } catch (NullPointerException npx) { try { mailProps.load(new FileInputStream(mailConfig.getPropertyFile())); } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } if (DEBUG) { DEBUGGER.debug("Properties: {}", mailProps); } if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) { smtpAuth = new SMTPAuthenticator(); mailSession = Session.getDefaultInstance(mailProps, smtpAuth); } else { mailSession = Session.getDefaultInstance(mailProps); } } if (DEBUG) { DEBUGGER.debug("Session: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); MimeMessage mailMessage = new MimeMessage(mailSession); // Our emailList parameter should contain the following // items (in this order): // 0. Recipients // 1. From Address // 2. Generated-From (if blank, a default value is used) // 3. The message subject // 4. The message content // 5. The message id (optional) // We're only checking to ensure that the 'from' and 'to' // values aren't null - the rest is really optional.. if // the calling application sends a blank email, we aren't // handing it here. if (message.getMessageTo().size() != 0) { for (String to : message.getMessageTo()) { if (DEBUG) { DEBUGGER.debug(to); } mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); } mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0))); mailMessage.setSubject(message.getMessageSubject()); mailMessage.setContent(message.getMessageBody(), "text/html"); if (message.isAlert()) { mailMessage.setHeader("Importance", "High"); } Transport mailTransport = mailSession.getTransport("smtp"); if (DEBUG) { DEBUGGER.debug("Transport: {}", mailTransport); } mailTransport.connect(); if (mailTransport.isConnected()) { Transport.send(mailMessage); } } } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } catch (NamingException nx) { throw new MessagingException(nx.getMessage(), nx); } }
From source file:com.googlecode.psiprobe.beans.ResourceResolverBean.java
public void lookupResource(ApplicationResource resource, boolean contextBound, boolean global) { DataSourceInfo dataSourceInfo = null; if (contextBound) { try {// w w w. j ava 2 s.c om javax.naming.Context ctx = !global ? new InitialContext() : getGlobalNamingContext(); String jndiName = resolveJndiName(resource.getName(), global); Object o = ctx.lookup(jndiName); resource.setLookedUp(true); for (Iterator it = datasourceMappers.iterator(); it.hasNext();) { DatasourceAccessor accessor = (DatasourceAccessor) it.next(); dataSourceInfo = accessor.getInfo(o); if (dataSourceInfo != null) { break; } } } catch (Throwable e) { resource.setLookedUp(false); dataSourceInfo = null; logger.error("Failed to lookup: " + resource.getName(), e); // // make sure we always re-throw ThreadDeath // if (e instanceof ThreadDeath) { throw (ThreadDeath) e; } } } else { resource.setLookedUp(false); } // // Tomcat 5.0.x DBCP datasources would have URL set to null if they incorrectly configured // so we need to deal with this little feature // if (dataSourceInfo != null && dataSourceInfo.getJdbcURL() == null) { resource.setLookedUp(false); } if (resource.isLookedUp() && dataSourceInfo != null) { resource.setDataSourceInfo(dataSourceInfo); } }
From source file:Controllers.AppointmentController.java
/** * Return list of all departments from db. * * @return//from w w w . j a va2s. c o m */ public Department[] fetchDepartments() { Department[] dep = null; try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); Statement stmt = connection.createStatement(); String smtquery = "SELECT * FROM departments"; ResultSet resultSet; resultSet = stmt.executeQuery(smtquery); List<Department> departments = new ArrayList<Department>(); while (resultSet.next()) { Department department = new Department(); department.setDepartmentId(resultSet.getInt("departmentId")); department.setDepartmentName(resultSet.getString("departmentName")); departments.add(department); } dep = new Department[departments.size()]; dep = departments.toArray(dep); 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); } return dep; }
From source file:com.funambol.server.db.DataSourceFactoryTest.java
/** * Test of getObjectInstance method, of class DataSourceFactory. *//* w ww .j a v a2 s. c o m*/ public void testGetObjectInstance_fnblds() throws Exception { DataSourceFactory dataSourceFactory = new DataSourceFactory(); InitialContext context = new InitialContext(); Hashtable environment = new Hashtable(); Name name = new CompositeName("fnblds"); Reference ref = new Reference("javax.sql.DataSource"); RefAddr minIdle = new StringRefAddr("minIdle", "3"); ref.add(minIdle); // // At the end this should be overwritten by the value in the fnblds.xml file // RefAddr url = new StringRefAddr("url", "this-is-the-url"); ref.add(url); Object result = dataSourceFactory.getObjectInstance(ref, name, context, environment); assertTrue(result instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource); BasicDataSource bds = (BasicDataSource) result; assertEquals(3, bds.getMinIdle()); // // These are read from the db.xml // assertEquals("db", bds.getUsername()); assertEquals("org.hsqldb.jdbcDriver", bds.getDriverClassName()); // // These are read from the fnblds.xml // assertEquals("", bds.getPassword()); assertEquals("jdbc:hsqldb:hsql://localhost/funambol", bds.getUrl()); }
From source file:Controllers.ReportController.java
public int fetchDepartmentId(int accountId) { int departmentId = 0; try {/*from w ww .j av a 2s .c om*/ Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); PreparedStatement pstmt = connection .prepareStatement("SELECT * FROM doctors" + " WHERE accountId = ?;"); pstmt.setInt(1, accountId); ResultSet resultSet = pstmt.executeQuery(); List<Doctor> appointmentsList = new ArrayList<Doctor>(); while (resultSet.next()) { departmentId = resultSet.getInt("departmentId"); } pstmt.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); } return departmentId; }
From source file:jdao.JDAO.java
public static Context retrieveContext(String jndi_path) { InitialContext jndiContext = null; Context env = null;/* w w w . j av a 2 s. c o m*/ try { log("INFO: resolving " + jndi_path); env = jndiContext = new InitialContext(); env = (Context) jndiContext.lookup(jndi_path); } catch (Exception xe) { try { Name jname = jndiContext.getNameParser(jndi_path).parse(jndi_path); Enumeration<String> en = jname.getAll(); while (en.hasMoreElements()) { String name = en.nextElement(); Context tmp = null; try { tmp = (Context) env.lookup(name); env = (Context) env.lookup(name); } catch (NameNotFoundException nnf) { log("INFO: creating " + name); env = env.createSubcontext(name); } } } catch (Exception xe2) { log("ERROR: resolving " + jndi_path, xe2); } } return env; }
From source file:de.catma.repository.db.SourceDocumentHandler.java
public SourceDocumentHandler(DBRepository dbRepository, String repoFolderPath) throws NamingException { this.dbRepository = dbRepository; this.sourceDocsPath = repoFolderPath + "/" + SOURCEDOCS_FOLDER + "/"; File file = new File(sourceDocsPath); if (!file.exists()) { if (!file.mkdirs()) { throw new IllegalStateException("cannot access/create repository folder " + sourceDocsPath); }// w ww. j av a 2s . com } this.sourceDocumentsByID = new HashMap<String, SourceDocument>(); Context context = new InitialContext(); this.dataSource = (DataSource) context.lookup("catmads"); }
From source file:com.bjond.utilities.MiscUtils.java
/** * Given a JNDI path to the T resource this method will return * a reference to the session bean or null if none found. * * @param resource//from w ww .ja v a2s .co m * @return */ @SuppressWarnings("unchecked") public static <T> T obtainService(final String resource, Class<T> c) { try { return (T) new InitialContext().lookup(resource); } catch (final Exception e) { return null; } }
From source file:com.duroty.application.mail.ejb.SendBean.java
/** * An ejbCreate method as required by the EJB specification. * * The container calls the instance?s <code>ejbCreate</code> method whose * signature matches the signature of the <code>create</code> method invoked * by the client. The input parameters sent from the client are passed to * the <code>ejbCreate</code> method. Each session bean class must have at * least one <code>ejbCreate</code> method. The number and signatures * of a session bean?s <code>create</code> methods are specific to each * session bean class.//from ww w. ja v a 2s .c o m * * @throws CreateException Thrown if method fails due to system-level error. * * @ejb.create-method * @ejb.permission * role-name = "mail" * */ public void ejbCreate() throws CreateException { Map options = ApplicationConstants.options; try { ctx = new InitialContext(); HashMap mail = (HashMap) ctx.lookup((String) options.get(Constants.MAIL_CONFIG)); this.hibernateSessionFactory = (String) mail.get(Constants.HIBERNATE_SESSION_FACTORY); this.smtpSessionFactory = (String) mail.get(Constants.DUROTY_MAIL_FACTOTY); manager = new SendManager(mail); } catch (Exception e) { throw new CreateException(e.getMessage()); } }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override public void init(ServletConfig config) { /// List possible local address try {/*from w ww . j a va 2s . c o m*/ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface current = interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue; Enumeration<InetAddress> addresses = current.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress current_addr = addresses.nextElement(); if (current_addr instanceof Inet4Address) ourIPs.add(current_addr.getHostAddress()); } } } catch (Exception e) { } servContext = config.getServletContext(); backend = config.getServletContext().getInitParameter("backendserver"); server = config.getServletContext().getInitParameter("fileserver"); try { String dataProviderName = config.getInitParameter("dataProviderClass"); dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance(); InitialContext cxt = new InitialContext(); if (cxt == null) { throw new Exception("no context found!"); } /// Init this here, might fail depending on server hosting ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend"); if (ds == null) { throw new Exception("Data jdbc/portfolio-backend source not found!"); } } catch (Exception e) { e.printStackTrace(); } }