private void mapClasses() throws ClassNotFoundException {
   // Register all models.Class
   Set<String> classes = new HashSet<String>();
   classes.addAll(Classpath.getTypesAnnotatedWith(application, "models", Entity.class));
   classes.addAll(Classpath.getTypesAnnotatedWith(application, "models", Embedded.class));
   for (String clazz : classes) {
     MorphiaLogger.debug("mapping class: %1$s", clazz);
     morphia.map(Class.forName(clazz, true, application.classloader()));
   }
   // @see http://code.google.com/p/morphia/wiki/Datastore#Ensure_Indexes_and_Caps
   ds.ensureCaps(); // creates capped collections from @Entity
   ds.ensureIndexes(); // creates indexes from @Index annotations in your entities
 }
Ejemplo n.º 2
0
  @Override
  public void onStart() {
    Logger.debug("Spring Plugin Starting");

    String contextPath = app.configuration().getString(SPRING_CONTEXT_PATH);
    String namespaceAware = app.configuration().getString(SPRING_NAMESPACE_AWARE);
    String addPlayProperties = app.configuration().getString(SPRING_ADD_PLAY_PROPERTIES);

    URL url = null;
    if (contextPath != null) {
      Logger.debug("Loading application context: " + contextPath);
      url = app.classloader().getResource(contextPath);
    }
    if (url == null) {
      Logger.debug("Loading default application context: application-context.ml");
      url = app.classloader().getResource("application-context.xml");
    }
    if (url != null) {
      InputStream is = null;
      try {
        Logger.debug("Starting Spring application context from " + url.toExternalForm());
        applicationContext = new GenericApplicationContext();
        applicationContext.setClassLoader(Play.application().classloader());
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        if (!"false".equalsIgnoreCase(namespaceAware)) {
          Logger.debug("Application context is namespace aware");
          xmlReader.setNamespaceAware(true);
        } else {
          Logger.debug("Application context is NOT namespace aware");
        }
        xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);

        // Load Play Configuration
        if (!"false".equalsIgnoreCase(addPlayProperties)) {
          Logger.debug("Adding PropertyPlaceholderConfigurer with Play properties");

          // Convert play's configuration to plain old java properties
          Properties properties = new Properties();
          Set<String> keys = app.configuration().keys();
          for (String key : keys) {
            try {
              String value = app.configuration().getString(key);
              properties.setProperty(key, value);
            } catch (Throwable t) {
              // Some config items are complex, so we'll just skip those for now.
            }
          }

          PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
          configurer.setProperties(properties);
          applicationContext.addBeanFactoryPostProcessor(configurer);
        } else {
          Logger.debug("PropertyPlaceholderConfigurer with Play properties NOT added");
        }

        is = url.openStream();
        xmlReader.loadBeanDefinitions(new InputSource(is));
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(app.classloader());
        try {
          applicationContext.refresh();
          // startDate = System.currentTimeMillis();
        } catch (BeanCreationException e) {
          Throwable ex = e.getCause();
          throw new RuntimeException("Unable to instantiate Spring application context", ex);
        } finally {
          Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
      } catch (IOException e) {
        Logger.error("Can't load spring config file", e);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            Logger.error("Can't close spring config file stream", e);
          }
        }
      }
    }
  }
Ejemplo n.º 3
0
  @Override
  public void beforeStart(final Application application) {
    final Reflections reflections =
        new Reflections(
            new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder.Exclude(FilterBuilder.prefix("com.google")))
                .addUrls(ClasspathHelper.forClassLoader(application.classloader()))
                .addScanners(new SubTypesScanner()));

    // automatic Guice module detection
    Set<Class<? extends AbstractModule>> guiceModules =
        reflections.getSubTypesOf(AbstractModule.class);
    for (Class<? extends Module> moduleClass : guiceModules) {
      try {
        if (!moduleClass.isAnonymousClass()) {
          modules.add(moduleClass.newInstance());
        }
      } catch (InstantiationException e) {
        throw Throwables.propagate(e);
      } catch (IllegalAccessException e) {
        throw Throwables.propagate(e);
      }
    }

    modules.add(
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(Application.class).toInstance(application);
            bind(Reflections.class).toInstance(reflections);

            Names.bindProperties(
                this.binder(),
                fromKeys(
                    application.configuration().keys(),
                    new Function<String, String>() {
                      @Override
                      public String apply(String key) {
                        // remove after https://play.lighthouseapp.com/projects/82401/tickets/372 is
                        // fixed
                        if (key.contains("akka")) return null;

                        return application.configuration().getString(key);
                      }
                    }));

            for (Class<? extends Controller> controllerClass :
                reflections.getSubTypesOf(Controller.class)) {
              requestStaticInjection(controllerClass);
            }

            // bind all services
            Multibinder<Service> serviceBinder = Multibinder.newSetBinder(binder(), Service.class);
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractIdleService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractExecutionThreadService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }

            // bind actor - todo use reflections for this

            // start/stop services after injection and on shutdown of the Play app
            bindListener(
                MoreMatchers.subclassesOf(Service.class),
                new TypeListener() {
                  @Override
                  public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
                    typeEncounter.register(
                        new InjectionListener<I>() {
                          @Override
                          public void afterInjection(final I i) {
                            onStartListeners.add(
                                new OnStartListener() {
                                  @Override
                                  public void onApplicationStart(
                                      Application application, Injector injector) {
                                    Logger.info(String.format("Starting %s", i.toString()));
                                    ((Service) i).start();

                                    onStopListeners.add(
                                        new OnStopListener() {
                                          @Override
                                          public void onApplicationStop(Application application) {
                                            Logger.info(String.format("Stopping %s", i.toString()));
                                            ((Service) i).stop();
                                          }
                                        });
                                  }
                                });
                          }
                        });
                  }
                });
          }
        });
  }