List of usage examples for javax.naming Context lookup
public Object lookup(String name) throws NamingException;
From source file:com.acmeair.web.ServiceLocator.java
private ServiceLocator() { String type = null;/*from www . jav a2 s . co m*/ String lookup = REPOSITORY_LOOKUP_KEY.replace('.', '/'); javax.naming.Context context = null; javax.naming.Context envContext; try { context = new javax.naming.InitialContext(); envContext = (javax.naming.Context) context.lookup("java:comp/env"); if (envContext != null) type = (String) envContext.lookup(lookup); } catch (NamingException e) { // e.printStackTrace(); } if (type != null) { logger.info("Found repository in web.xml:" + type); } else if (context != null) { try { type = (String) context.lookup(lookup); if (type != null) logger.info("Found repository in server.xml:" + type); } catch (NamingException e) { // e.printStackTrace(); } } if (type == null) { type = System.getProperty(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in jvm property:" + type); else { type = System.getenv(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in environment property:" + type); } } // TODO: Later add back in other implementations type = "wxsdirect"; logger.info("Using default repository :" + type); ctx = new AnnotationConfigApplicationContext(WXSDirectAppConfig.class); }
From source file:com.flexive.core.Database.java
/** * Retrieve data source for global configuration table, regardless * of the current request's division id. * * @return a database connection//from w ww . j ava 2 s. c om * @throws SQLException if no connection could be retrieved */ public static synchronized DataSource getGlobalDataSource() throws SQLException { // Try to obtain a connection if (globalDataSource != null) { return globalDataSource; } try { final Context c = EJBLookup.getInitialContext(); for (String path : getPossibleJndiNames(DS_GLOBAL_CONFIG)) { try { if (LOG.isDebugEnabled()) { LOG.debug("Trying JNDI path " + path + "..."); } globalDataSource = (DataSource) c.lookup(path); if (LOG.isInfoEnabled()) { LOG.info("Found global datasource under JNDI path " + path); } break; } catch (NamingException e) { // try next path } } if (globalDataSource == null) { //try the weird geronimo logic as last resort Object o = null; try { o = EJBLookup.getInitialContext().lookup( "jca:/console.dbpool/flexiveConfiguration/JCAManagedConnectionFactory/flexiveConfiguration"); globalDataSource = (DataSource) o.getClass().getMethod("$getResource").invoke(o); } catch (NoSuchMethodException e) { if (o instanceof DataSource) return (DataSource) o; String sErr = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: JNDI resource is no DataSource and method $getResource not found!"; LOG.error(sErr); throw new SQLException(sErr); } catch (NamingException e) { // not bound, try next path } catch (Exception e) { final String msg = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: " + e.getMessage(); LOG.error(msg); throw new SQLException(msg); } } if (globalDataSource == null) { globalDataSource = tryGetDefaultDataSource(c, GlobalConfigurationEngineBean.DEFAULT_DS_CONFIG, new DefaultGlobalDataSourceInitializer()); } if (globalDataSource == null) { final String msg = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: no datasource found in JNDI"; LOG.error(msg); throw new SQLException(msg); } return globalDataSource; } catch (NamingException exc) { String msg = "Naming Exception, unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: " + exc.getMessage(); LOG.error(msg); throw new SQLException(msg); } }
From source file:org.easybatch.jms.JmsIntegrationTest.java
@Test public void testJmsSupport() throws Exception { Context jndiContext = getJndiContext(); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext .lookup("QueueConnectionFactory"); Queue queue = (Queue) jndiContext.lookup("q"); QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueSender queueSender = queueSession.createSender(queue); queueConnection.start();/*from ww w.j av a 2 s . c o m*/ //send a regular message to the queue TextMessage message = queueSession.createTextMessage(); message.setText(MESSAGE_TEXT); queueSender.send(message); //send a poison record to the queue queueSender.send(new JmsPoisonMessage()); Job job = aNewJob().reader(new JmsQueueRecordReader(queueConnectionFactory, queue)) .filter(new JmsPoisonRecordFilter()).processor(new RecordCollector()) .jobListener(new JmsQueueSessionListener(queueSession)) .jobListener(new JmsQueueConnectionListener(queueConnection)).build(); JobReport jobReport = JobExecutor.execute(job); assertThat(jobReport).isNotNull(); assertThat(jobReport.getParameters().getDataSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME); assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2); assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(1); assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(1); List<JmsRecord> records = (List<JmsRecord>) jobReport.getResult(); assertThat(records).isNotNull().isNotEmpty().hasSize(1); JmsRecord jmsRecord = records.get(0); Header header = jmsRecord.getHeader(); assertThat(header).isNotNull(); assertThat(header.getNumber()).isEqualTo(1); assertThat(header.getSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME); Message payload = jmsRecord.getPayload(); assertThat(payload).isNotNull().isInstanceOf(TextMessage.class); TextMessage textMessage = (TextMessage) payload; assertThat(textMessage.getText()).isNotNull().isEqualTo(MESSAGE_TEXT); }
From source file:net.kamhon.ieagle.dao.DynamicDataSource.java
public void afterPropertiesSet() throws Exception { if (StringUtils.isNotBlank(jndiName)) { Context initContext = null; try {//from www .j a v a 2 s . com initContext = new InitialContext(); dataSource = (DataSource) initContext.lookup(jndiName); log.info("Using DataSource " + jndiName); } catch (Exception e1) { try { dataSource = (DataSource) initContext.lookup("java:/comp/env/" + jndiName); log.info("Using DataSource " + "java:/comp/env/" + jndiName); } catch (Exception e2) { try { if (jndiName.startsWith("comp/env/")) { jndiName = jndiName.substring("comp/env/".length()); System.out.println("\n\n" + jndiName + "\n\n"); dataSource = (DataSource) initContext.lookup(jndiName); log.info("Using DataSource " + jndiName); } } catch (Exception e3) { initBasicDataSource(); } } } } if (dataSource == null) { initBasicDataSource(); } }
From source file:org.picketlink.idm.performance.TestBase.java
public void removeContext(Context mainCtx, String name) throws Exception { Context deleteCtx = (Context) mainCtx.lookup(name); NamingEnumeration subDirs = mainCtx.listBindings(name); while (subDirs.hasMoreElements()) { Binding binding = (Binding) subDirs.nextElement(); String subName = binding.getName(); removeContext(deleteCtx, subName); }//w w w . ja v a2 s . co m mainCtx.unbind(name); }
From source file:org.freeciv.servlet.NewPBEMUser.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = java.net.URLDecoder.decode(request.getParameter("username"), "UTF-8"); String password = java.net.URLDecoder.decode(request.getParameter("password"), "UTF-8"); String email = java.net.URLDecoder.decode(request.getParameter("email"), "UTF-8"); String captcha = java.net.URLDecoder.decode(request.getParameter("captcha"), "UTF-8"); if (password == null || password.length() <= 2) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid password. Please try again with another password."); return;//from w w w . j a v a2 s . c o m } if (username == null || username.length() <= 2) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid username. Please try again with another username."); return; } if (email == null || email.length() <= 4) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid e-mail address. Please try again with another username."); return; } HttpClient client = HttpClientBuilder.create().build(); String captcha_url = "https://www.google.com/recaptcha/api/siteverify"; HttpPost post = new HttpPost(captcha_url); List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("secret", captcha_secret)); urlParameters.add(new BasicNameValuePair("response", captcha)); post.setEntity(new UrlEncodedFormEntity(urlParameters)); if (!captcha_secret.contains("secret goes here")) { /* Validate captcha against google api. skip validation for localhost where captcha_secret still has default value. */ HttpResponse captcha_response = client.execute(post); InputStream in = captcha_response.getEntity().getContent(); String body = IOUtils.toString(in, "UTF-8"); if (!(body.contains("success") && body.contains("true"))) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Captcha failed!"); return; } } Connection conn = null; try { Thread.sleep(300); String ipAddress = request.getHeader("X-Real-IP"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } Context env = (Context) (new InitialContext().lookup("java:comp/env")); DataSource ds = (DataSource) env.lookup("jdbc/freeciv_mysql"); conn = ds.getConnection(); String insertTableSQL = "INSERT INTO auth (username, email, password, activated, ip) VALUES (?,?, MD5(?), ?, ?)"; PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL); preparedStatement.setString(1, username.toLowerCase()); preparedStatement.setString(2, email); preparedStatement.setString(3, password); preparedStatement.setInt(4, 1); preparedStatement.setString(5, ipAddress); preparedStatement.executeUpdate(); } catch (Exception err) { response.setHeader("result", "error"); err.printStackTrace(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to create user: " + err); } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:Controllers.AppointmentController.java
/** * Return list of all departments from db. * * @return/*from w ww. j a va2 s. 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:Controllers.AppointmentController.java
/** * return list on all appointments./*w ww. j a va 2 s .c o m*/ * * @return */ public Appointment[] fetchAppointments() { Appointment[] appointments = null; try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); Statement stmt = connection.createStatement(); String smtquery = "SELECT * FROM appointments"; ResultSet resultSet; resultSet = stmt.executeQuery(smtquery); List<Appointment> appointmentsList = new ArrayList<Appointment>(); while (resultSet.next()) { Appointment appointment = new Appointment(); appointment.setAccountId(resultSet.getInt("accountId")); appointment.setAppointmentId(resultSet.getInt("appointmentId")); appointment.setDate(resultSet.getDate("date")); appointment.setDepartmentId(resultSet.getInt("departmentId")); appointment.setMessage(resultSet.getString("message")); appointmentsList.add(appointment); } appointments = new Appointment[appointmentsList.size()]; appointments = appointmentsList.toArray(appointments); 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 appointments; }
From source file:com.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.teiid.impl.HiveTeiidConnectorImpl.java
public Object getConnectionFactory() throws Exception { if (translatorConfig == null) { translatorConfig = new TranslatorConfig(); translatorConfig.setProductName("hive"); translatorConfig.setTranslatorName("hive"); translatorConfig.setTranslatorFactoryClass("org.teiid.translator.hive.HiveExecutionFactory"); }//w w w . jav a2 s .com Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jndiName); translatorConfig.setupTranslator(); return ds; }