Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1.  
  2.  
  3. public class MyGuiceServletContextListener extends GuiceServletContextListener {
  4.  
  5. @Override
  6. protected Injector getInjector() {
  7. Injector injector = Guice.createInjector(
  8. new ServerModule(), new DispatchServletModule(), new DatabaseConnectorModule());// , new DatabaseConnectorServletModule()
  9.  
  10. // Initialize the connection pool. This should be first, before any requests begin.
  11.  
  12. DatabaseConnectorImpl DatabaseConnectionPool = injector.getInstance(Key.get(DatabaseConnectorImpl.class));
  13. try {
  14. DatabaseConnectionPool.init();// FIXME: Is this necessary?
  15. } catch (ServletException e) {
  16. e.printStackTrace();
  17. }
  18.  
  19. return injector;
  20. }
  21. }
  22.  
  23.  
  24.  
  25. public class DatabaseConnectorModule extends ServletModule {
  26.  
  27. @Override
  28. protected void configureServlets() {
  29. // need a context for jndi to use.
  30. bind(Context.class).to(InitialContext.class);
  31.  
  32. // actual jndi name is "jdbc/exist".
  33. bind(Database.class).toProvider(JndiIntegration.fromJndi(Database.class, "java:/comp/env/jdbc/exist")).asEagerSingleton();
  34. serve("/*").with(DatabaseConnectorImpl.class);
  35. }
  36. }
  37.  
  38.  
  39. @Singleton
  40. public class DatabaseConnectorImpl extends HttpServlet {
  41.  
  42. private final Database database;
  43.  
  44. @Inject
  45. public DatabaseConnectorImpl(Database database) {
  46. this.database = database;
  47. try {
  48. DatabaseManager.registerDatabase(database);
  49. } catch (XMLDBException e) {
  50. System.err.println("Error in DatabaseConnectorImpl: " + e.getMessage());
  51. e.printStackTrace();
  52. }
  53. }
  54.  
  55. /**
  56. * Dole out the collections here. Anyone calling this class should already be validated because the class extracts the database username and password as a property.
  57. * <br> This is a convenience class because
  58. * @throws XMLDBException
  59. * if username, password, or something else is incorrect.
  60. */
  61. public Collection getCollection(String URI) throws XMLDBException {
  62. if(this.database == null){
  63. System.err.println("Error in DatabaseConnectorImpl: database is null");
  64. throw new NullPointerException("database is null in DatabaseConnectorImpl.getCollection");
  65. }
  66. String username = database.getProperty("username");
  67. String password = database.getProperty("password");
  68. return DatabaseManager.getCollection(URI, username, password);
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement