Example #1
0
    public static void insert(Application app) {

      final String adminGroupTitle = app.configuration().getString("htwplus.admin.group");
      final String adminMail = app.configuration().getString("htwplus.admin.mail");
      final String adminPassword = app.configuration().getString("htwplus.admin.pw");

      // Do some inital db stuff
      JPA.withTransaction(
          new play.libs.F.Callback0() {

            @Override
            public void invoke() throws Throwable {

              // create Admin account if none exists
              Account admin = Account.findByEmail(adminMail);
              if (admin == null) {
                admin = new Account();
                admin.email = adminMail;
                admin.firstname = "Admin";
                admin.lastname = "@HTWplus";
                admin.role = AccountRole.ADMIN;
                admin.avatar = "a1";
                admin.password = Component.md5(adminPassword);
                admin.create();
              }

              // create Admin group if none exists
              Group group = Group.findByTitle(adminGroupTitle);
              if (group == null && admin != null) {
                group = new Group();
                group.title = adminGroupTitle;
                group.groupType = GroupType.close;
                group.description = "for HTWplus Admins only";
                group.createWithGroupAccount(admin);
              }

              // create Feedback group if none exists
              Group feedbackGroup = Group.findByTitle("HTWplus Feedback");
              if (feedbackGroup == null && admin != null) {
                group = new Group();
                group.title = "HTWplus Feedback";
                group.groupType = GroupType.open;
                group.description =
                    "Du hast Wünsche, Ideen, Anregungen, Kritik oder Probleme mit der Seite? Hier kannst du es loswerden!";
                group.createWithGroupAccount(admin);
              }

              // Generate indexes
              FullTextEntityManager fullTextEntityManager =
                  Search.getFullTextEntityManager(JPA.em());
              try {
                fullTextEntityManager.createIndexer(Group.class, Account.class).startAndWait();

              } catch (InterruptedException e) {

                Logger.error(e.getMessage());
              }
            }
          });
    }
Example #2
0
  @Override
  public void onStart(Application app) {
    if (app.isDev()) {
      Logger.info("using development database: " + PlayJongo.getDatabase().getName());
    }

    if (app.isTest()) {
      Logger.info("using test database: " + PlayJongo.getDatabase().getName());
      Logger.info("playjongo.test-uri: " + app.configuration().getString("playjongo.test-uri", ""));
    }
  }
Example #3
0
  @Override
  public void onStart() {
    String accessKey = application.configuration().getString(AWS_ACCESS_KEY);
    String secretKey = application.configuration().getString(AWS_SECRET_KEY);
    s3Bucket = application.configuration().getString(AWS_S3_BUCKET);

    if ((accessKey != null) && (secretKey != null)) {
      AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
      amazonS3 = new AmazonS3Client(awsCredentials);
      amazonS3.createBucket(s3Bucket);
      Logger.info("Using S3 Bucket: " + s3Bucket);
    }
  }
Example #4
0
 public static Result route(Application app, FakeRequest fakeRequest, byte[] body, long timeout) {
   return wrapScalaResult(
       Scala.orNull(
           play.api.test.Helpers.jRoute(
               app.getWrappedApplication(), fakeRequest.getWrappedRequest(), body)),
       timeout);
 }
 @Override
 public boolean enabled() {
   isEnabled =
       !"disabled".equals(application.configuration().getString(Constants.MORPHIA_PLUGIN_ENABLED));
   MorphiaLogger.warn(String.format("MorphiaPlugin is %s", isEnabled ? "enabled" : "disabled"));
   return isEnabled;
 }
Example #6
0
 @SuppressWarnings("unchecked")
 public static Result route(Application app, RequestBuilder requestBuilder, long timeout) {
   final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt =
       play.api.test.Helpers.jRoute(
           app.getWrappedApplication(),
           requestBuilder.build()._underlyingRequest(),
           requestBuilder.body());
   return wrapScalaResult(Scala.orNull(opt), timeout);
 }
Example #7
0
 @Provides
 Mongo create(final Application application) {
   try {
     return new Mongo(new MongoURI(application.configuration().getString("mongodb.uri")));
   } catch (UnknownHostException e) {
     addError(e);
     return null;
   }
 }
Example #8
0
  @Provides
  Datastore createDatastore(Mongo mongo, Morphia morphia, final Application application) {
    Datastore datastore =
        morphia.createDatastore(
            mongo,
            application.configuration().getString("mongodb.db"),
            application.configuration().getString("mongodb.username"),
            application.configuration().getString("mongodb.password").toCharArray());

    datastore.ensureIndexes();

    Logger.info(
        "Connected to MongoDB ["
            + mongo.debugString()
            + "] database ["
            + datastore.getDB().getName()
            + "]");
    return datastore;
  }
Example #9
0
 @Before
 static void setConnectedUser() {
   if (Security.isConnected()) {
     User user = User.find("byUsername", Security.connected()).first();
     if (!user.isAdmin) {
       flash.error(Messages.get("UserIsNotAuthorized"));
       Application.index();
     }
   }
 }
Example #10
0
 public void onStart(Application app) {
   JedisPool p = app.plugin(RedisPlugin.class).jedisPool();
   // uncomment to test sentinel setup
   // JedisSentinelPool p = app.plugin(RedisPlugin.class).jedisSentinelPool();
   Jedis j = p.getResource();
   j.set("foo", "yay");
   p.returnResource(j);
   Cache.set("foo2", 5);
   Map<String, String> m = new HashMap<String, String>();
   m.put("test", "value");
   Cache.set("foo3", m);
 }
 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
 }
Example #12
0
  private static void startStream(List<String> terms) throws TwitterException {
    if (twitter != null) {
      twitter.cleanUp();
    }
    if (esClient != null) {
      esClient.close();
      esClient = null;
    }

    play.Configuration pconf = Play.application().configuration();
    String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name");
    if (elasticSearchCluster != null) {
      Logger.info("Configuring ElasticSearch...");
      Settings settings =
          ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build();

      esClient =
          new TransportClient(settings)
              .addTransportAddress(
                  new InetSocketTransportAddress(
                      pconf.getString("tweet.elasticsearch.transport.host"),
                      pconf.getInt("tweet.elasticsearch.transport.port")));
    } else {
      esClient = null;
    }

    twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration();
    TwitterStreamFactory tf = new TwitterStreamFactory(tconf);
    twitter = tf.getInstance();
    StatusListener l =
        new TweetListener(
            terms,
            esClient,
            pconf.getString("tweet.elasticsearch.index"),
            pconf.getString("tweet.elasticsearch.type"));
    twitter.addListener(l);

    String[] tracks = new String[terms.size()];
    StringBuffer termsString = new StringBuffer();
    for (int i = 0; i < terms.size(); i++) {
      tracks[i] = terms.get(i);
      if (i != 0) termsString.append(",");
      termsString.append(terms.get(i));
    }
    FilterQuery q = new FilterQuery().track(tracks);
    twitter.filter(q);
    Logger.info("Starting listening for tweets using terms " + termsString.toString() + "...");
  }
Example #13
0
 public static void at(String location, String name, String address) {
   if (location != null
       && name != null
       && address != null
       && !location.equals("")
       && !name.equals("")
       && !address.equals("")) {
     new Post(
             user(),
             new Date().toString(),
             HTML.htmlEscape("Checked in at: " + name + "\n" + address))
         .save();
     Application.news(null);
   } else {
     redirect("/checkin");
   }
 }
 @Inject
 public ExecutionContextProvider(final Configuration config, final Application application) {
   boolean customEcEnabled =
       config.getBoolean(ConfigKeys.CUSTOM_EC_DEFAULT._1, ConfigKeys.CUSTOM_EC_DEFAULT._2);
   DeadboltExecutionContextProvider defaultProvider =
       new DefaultDeadboltExecutionContextProvider();
   DeadboltExecutionContextProvider ecp = defaultProvider;
   if (customEcEnabled) {
     try {
       ecp = application.injector().instanceOf(DeadboltExecutionContextProvider.class);
       LOGGER.debug("Custom execution context provider found");
     } catch (Exception e) {
       LOGGER.debug("No custom execution context found.");
     }
     this.ecProvider = ecp;
   } else {
     ecProvider = defaultProvider;
   }
 }
Example #15
0
 @Override
 public boolean enabled() {
   return (application.configuration().keys().contains(AWS_ACCESS_KEY)
       && application.configuration().keys().contains(AWS_SECRET_KEY)
       && application.configuration().keys().contains(AWS_S3_BUCKET));
 }
Example #16
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();
                                          }
                                        });
                                  }
                                });
                          }
                        });
                  }
                });
          }
        });
  }
Example #17
0
 /** Stops an application. */
 public static void stop(Application application) {
   play.api.Play.stop(application.getWrappedApplication());
 }
Example #18
0
 public static Result route(Application app, FakeRequest fakeRequest, long timeout) {
   final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt =
       play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.fake);
   return wrapScalaResult(Scala.orNull(opt), timeout);
 }
Example #19
0
 @Override
 public void onStart(Application app) {
   Util.configure(app.configuration());
   SitemapJob.startSitemapGenerator();
 }
Example #20
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);
          }
        }
      }
    }
  }
Example #21
0
 public void onStop(Application app) {
   Logger.info("Application shutdown...");
   Logger.info(app.toString());
 }
  @Override
  public void onStart() {
    if (!isEnabled) {
      return;
    }
    // Register SLF4JLogrImplFactory as Logger
    // @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error
    MorphiaLoggerFactory.reset();
    MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);

    try {
      Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX);
      if (morphiaConf == null) {
        throw Configuration.root()
            .reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null);
      }

      MorphiaLogger.debug(morphiaConf);

      String dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey());
      if (StringUtils.isBlank(dbName)) {
        throw morphiaConf.reportError(
            ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null);
      }

      // Connect to MongoDB
      String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey());

      if (StringUtils.isNotBlank(seeds)) {
        mongo = connect(seeds);
      } else {
        mongo =
            connect(
                morphiaConf.getString(ConfigKey.DB_HOST.getKey()),
                morphiaConf.getString(ConfigKey.DB_PORT.getKey()));
      }

      morphia = new Morphia();
      // To prevent problem during hot-reload
      if (application.isDev()) {
        morphia.getMapper().getOptions().objectFactory = new PlayCreator();
      }
      // Configure validator
      new ValidationExtension(morphia);

      // Check if credentials parameters are present
      String username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey());
      String password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey());

      if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) {
        throw morphiaConf.reportError(
            ConfigKey.DB_NAME.getKey(), "Missing username or password", null);
      }

      // Create datastore
      if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray());
      } else {
        ds = morphia.createDatastore(mongo, dbName);
      }

      MorphiaLogger.debug("Datastore [%s] created", dbName);
      // Create GridFS
      String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey());
      if (StringUtils.isBlank(dbName)) {
        uploadCollection = "uploads";
        MorphiaLogger.warn(
            "Missing Morphia configuration key [%s]. Use default value instead [%s]",
            ConfigKey.COLLECTION_UPLOADS, "uploads");
      }
      gridfs = new GridFS(ds.getDB(), uploadCollection);
      MorphiaLogger.debug("GridFS created", "");
      MorphiaLogger.debug("Add Interceptor...", "");
      morphia
          .getMapper()
          .addInterceptor(
              new AbstractEntityInterceptor() {

                @Override
                public void postLoad(final Object ent, final DBObject dbObj, final Mapper mapr) {
                  if (ent instanceof Model) {
                    Model m = (Model) ent;
                    m._post_Load();
                  }
                }
              });
      MorphiaLogger.debug("Classes mapping...", "");
      mapClasses();
      MorphiaLogger.debug("End of initializing Morphia", "");
    } catch (MongoException e) {
      MorphiaLogger.error(e, "Problem connecting MongoDB");
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      MorphiaLogger.error(e, "Problem mapping class");
      throw new RuntimeException(e);
    }
  }