static {
   if (ApiProxy.getCurrentEnvironment() != null) {
     Logger.forceJuli = true;
     Logger.setUp("DEBUG");
     Logger.info("Play! is running in Google App Engine");
     Play.readOnlyTmp = true;
     Play.usePrecompiled = true;
   } else {
     Logger.redirectJuli = true;
   }
 }
  public static void main(String[] args) throws SQLException {

    /** Check that evolutions are enabled * */
    if (!evolutionsDirectory.exists()) {
      System.out.println(
          "~ Evolutions are not enabled. Create a db/evolutions directory to create your first 1.sql evolution script.");
      System.out.println("~");
      return;
    }

    /** Start the DB plugin * */
    Play.id = System.getProperty("play.id");
    Play.applicationPath = new File(System.getProperty("application.path"));
    Play.guessFrameworkPath();
    Play.readConfiguration();
    Play.javaPath = new ArrayList<VirtualFile>();
    Play.classes = new ApplicationClasses();
    Play.classloader = new ApplicationClassloader();
    Logger.init();
    Logger.setUp("ERROR");
    new DBPlugin().onApplicationStart();

    /** Connected * */
    System.out.println("~ Connected to " + DB.datasource.getConnection().getMetaData().getURL());

    /** Sumary * */
    Evolution database = listDatabaseEvolutions().peek();
    Evolution application = listApplicationEvolutions().peek();

    if ("resolve".equals(System.getProperty("mode"))) {
      try {
        checkEvolutionsState();
        System.out.println("~");
        System.out.println("~ Nothing to resolve...");
        System.out.println("~");
        return;
      } catch (InconsistentDatabase e) {
        resolve(e.revision);
        System.out.println("~");
        System.out.println("~ Revision " + e.revision + " has been resolved;");
        System.out.println("~");
      } catch (InvalidDatabaseRevision e) {
        // see later
      }
    }

    /** Check inconsistency * */
    try {
      checkEvolutionsState();
    } catch (InconsistentDatabase e) {
      System.out.println("~");
      System.out.println("~ Your database is an inconsistent state!");
      System.out.println("~");
      System.out.println("~ While applying this script part:");
      System.out.println("");
      System.out.println(e.evolutionScript);
      System.out.println("");
      System.out.println("~ The following error occured:");
      System.out.println("");
      System.out.println(e.error);
      System.out.println("");
      System.out.println(
          "~ Please correct it manually, and mark it resolved by running `play evolutions:resolve`");
      System.out.println("~");
      return;
    } catch (InvalidDatabaseRevision e) {
      // see later
    }

    System.out.print(
        "~ Application revision is "
            + application.revision
            + " ["
            + application.hash.substring(0, 7)
            + "]");
    System.out.println(
        " and Database revision is "
            + database.revision
            + " ["
            + database.hash.substring(0, 7)
            + "]");
    System.out.println("~");

    /** Evolution script * */
    List<Evolution> evolutions = getEvolutionScript();
    if (evolutions.isEmpty()) {
      System.out.println("~ Your database is up to date");
      System.out.println("~");
    } else {

      if ("apply".equals(System.getProperty("mode"))) {

        System.out.println("~ Applying evolutions:");
        System.out.println("");
        System.out.println(
            "# ------------------------------------------------------------------------------");
        System.out.println("");
        System.out.println(toHumanReadableScript(evolutions));
        System.out.println("");
        System.out.println(
            "# ------------------------------------------------------------------------------");
        System.out.println("");
        if (applyScript(true)) {
          System.out.println("~");
          System.out.println("~ Evolutions script successfully applied!");
          System.out.println("~");
        } else {
          System.out.println("~");
          System.out.println("~ Can't apply evolutions...");
          System.out.println("~");
          System.exit(-1);
        }

      } else if ("markApplied".equals(System.getProperty("mode"))) {

        if (applyScript(false)) {
          System.out.println("~ Evolutions script marked as applied!");
          System.out.println("~");
        } else {
          System.out.println("~ Can't apply evolutions...");
          System.out.println("~");
          System.exit(-1);
        }

      } else {

        System.out.println("~ Your database needs evolutions!");
        System.out.println("");
        System.out.println(
            "# ------------------------------------------------------------------------------");
        System.out.println("");
        System.out.println(toHumanReadableScript(evolutions));
        System.out.println("");
        System.out.println(
            "# ------------------------------------------------------------------------------");
        System.out.println("");
        System.out.println(
            "~ Run `play evolutions:apply` to automatically apply this script to the database");
        System.out.println(
            "~ or apply it yourself and mark it done using `play evolutions:markApplied`");
        System.out.println("~");
      }
    }
  }
Exemple #3
0
  /** Start the application. Recall to restart ! */
  public static synchronized void start() {
    try {

      if (started) {
        stop();
      }

      if (standalonePlayServer) {
        // Can only register shutdown-hook if running as standalone server
        if (!shutdownHookEnabled) {
          // registers shutdown hook - Now there's a good chance that we can notify
          // our plugins that we're going down when some calls ctrl+c or just kills our process..
          shutdownHookEnabled = true;
          Runtime.getRuntime()
              .addShutdownHook(
                  new Thread() {
                    public void run() {
                      Play.stop();
                    }
                  });
        }
      }

      if (mode == Mode.DEV) {
        // Need a new classloader
        classloader = new ApplicationClassloader();
        // Put it in the current context for any code that relies on having it there
        Thread.currentThread().setContextClassLoader(classloader);
        // Reload plugins
        pluginCollection.reloadApplicationPlugins();
      }

      // Reload configuration
      readConfiguration();

      // Configure logs
      String logLevel = configuration.getProperty("application.log", "INFO");
      // only override log-level if Logger was not configured manually
      if (!Logger.configuredManually) {
        Logger.setUp(logLevel);
      }
      Logger.recordCaller =
          Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

      // Locales
      langs =
          new ArrayList<String>(
              Arrays.asList(configuration.getProperty("application.langs", "").split(",")));
      if (langs.size() == 1 && langs.get(0).trim().length() == 0) {
        langs = new ArrayList<String>(16);
      }

      // Clean templates
      TemplateLoader.cleanCompiledCache();

      // SecretKey
      secretKey = configuration.getProperty("application.secret", "").trim();
      if (secretKey.length() == 0) {
        Logger.warn("No secret key defined. Sessions will not be encrypted");
      }

      // Default web encoding
      String _defaultWebEncoding = configuration.getProperty("application.web_encoding");
      if (_defaultWebEncoding != null) {
        Logger.info("Using custom default web encoding: " + _defaultWebEncoding);
        defaultWebEncoding = _defaultWebEncoding;
        // Must update current response also, since the request/response triggering
        // this configuration-loading in dev-mode have already been
        // set up with the previous encoding
        if (Http.Response.current() != null) {
          Http.Response.current().encoding = _defaultWebEncoding;
        }
      }

      // Try to load all classes
      Play.classloader.getAllClasses();

      // Routes
      Router.detectChanges(ctxPath);

      // Cache
      Cache.init();

      // Plugins
      try {
        pluginCollection.onApplicationStart();
      } catch (Exception e) {
        if (Play.mode.isProd()) {
          Logger.error(e, "Can't start in PROD mode with errors");
        }
        if (e instanceof RuntimeException) {
          throw (RuntimeException) e;
        }
        throw new UnexpectedException(e);
      }

      if (firstStart) {
        Logger.info(
            "Application '%s' is now started !", configuration.getProperty("application.name", ""));
        firstStart = false;
      }

      // We made it
      started = true;
      startedAt = System.currentTimeMillis();

      // Plugins
      pluginCollection.afterApplicationStart();

    } catch (PlayException e) {
      started = false;
      try {
        Cache.stop();
      } catch (Exception ignored) {
      }
      throw e;
    } catch (Exception e) {
      started = false;
      try {
        Cache.stop();
      } catch (Exception ignored) {
      }
      throw new UnexpectedException(e);
    }
  }
Exemple #4
0
  public static void main(String[] args) throws SQLException {

    /** Start the DB plugin * */
    Play.id = System.getProperty("play.id");
    Play.applicationPath = new File(System.getProperty("application.path"));
    Play.guessFrameworkPath();
    Play.readConfiguration();
    Play.javaPath = new ArrayList<VirtualFile>();
    Play.classes = new ApplicationClasses();
    Play.classloader = new ApplicationClassloader();

    Play.templatesPath = new ArrayList<VirtualFile>();
    Play.modulesRoutes = new HashMap<String, VirtualFile>();
    Play.loadModules();

    if (System.getProperty("modules") != null) {
      populateModulesWithSpecificModules();
    } else {
      populateModulesWithEvolutions();
    }

    if (modulesWithEvolutions.isEmpty()) {
      System.out.println("~ Nothing has evolutions, go away and think again.");
      return;
    }

    Logger.init();
    Logger.setUp("ERROR");
    new DBPlugin().onApplicationStart();

    /** Connected * */
    System.out.println(
        "~ Connected to " + EvolutionQuery.getDatasource().getConnection().getMetaData().getURL());

    for (Entry<String, VirtualFile> moduleRoot : modulesWithEvolutions.entrySet()) {

      /** Sumary * */
      Evolution database = listDatabaseEvolutions(moduleRoot.getKey()).peek();
      Evolution application =
          listApplicationEvolutions(moduleRoot.getKey(), moduleRoot.getValue()).peek();

      if ("resolve".equals(System.getProperty("mode"))) {
        try {
          checkEvolutionsState();
          System.out.println("~");
          System.out.println("~ Nothing to resolve for " + moduleRoot.getKey() + "...");
          System.out.println("~");
          return;
        } catch (InconsistentDatabase e) {
          resolve(moduleRoot.getKey(), e.getRevision());
          System.out.println("~");
          System.out.println(
              "~ Revision "
                  + e.getRevision()
                  + " for "
                  + moduleRoot.getKey()
                  + " has been resolved;");
          System.out.println("~");
        } catch (InvalidDatabaseRevision e) {
          // see later
        }
      }

      /** Check inconsistency * */
      try {
        checkEvolutionsState();
      } catch (InconsistentDatabase e) {
        System.out.println("~");
        System.out.println("~ Your database is in an inconsistent state!");
        System.out.println("~");
        System.out.println("~ While applying this script part:");
        System.out.println("");
        System.out.println(e.getEvolutionScript());
        System.out.println("");
        System.out.println("~ The following error occured:");
        System.out.println("");
        System.out.println(e.getError());
        System.out.println("");
        System.out.println(
            "~ Please correct it manually, and mark it resolved by running `play evolutions:resolve`");
        System.out.println("~");
        return;
      } catch (InvalidDatabaseRevision e) {
        // see later
      }

      System.out.print(
          "~ '"
              + moduleRoot.getKey()
              + "' Application revision is "
              + application.revision
              + " ["
              + application.hash.substring(0, 7)
              + "]");
      System.out.println(
          " and '"
              + moduleRoot.getKey()
              + "' Database revision is "
              + database.revision
              + " ["
              + database.hash.substring(0, 7)
              + "]");
      System.out.println("~");

      /** Evolution script * */
      List<Evolution> evolutions = getEvolutionScript(moduleRoot.getKey(), moduleRoot.getValue());
      if (evolutions.isEmpty()) {
        System.out.println("~ Your database is up to date for " + moduleRoot.getKey());
        System.out.println("~");
      } else {
        if ("apply".equals(System.getProperty("mode"))) {
          System.out.println("~ Applying evolutions for " + moduleRoot.getKey() + ":");
          System.out.println("");
          System.out.println(
              "# ------------------------------------------------------------------------------");
          System.out.println("");
          System.out.println(toHumanReadableScript(evolutions));
          System.out.println("");
          System.out.println(
              "# ------------------------------------------------------------------------------");
          System.out.println("");
          if (applyScript(true, moduleRoot.getKey(), moduleRoot.getValue())) {
            System.out.println("~");
            System.out.println(
                "~ Evolutions script successfully applied for " + moduleRoot.getKey() + "!");
            System.out.println("~");
          } else {
            System.out.println("~");
            System.out.println("~ Can't apply evolutions for " + moduleRoot.getKey() + "...");
            System.out.println("~");
          }

        } else if ("markApplied".equals(System.getProperty("mode"))) {

          if (applyScript(false, moduleRoot.getKey(), moduleRoot.getValue())) {
            System.out.println(
                "~ Evolutions script marked as applied for " + moduleRoot.getKey() + "!");
            System.out.println("~");
          } else {
            System.out.println("~ Can't apply evolutions for " + moduleRoot.getKey() + "...");
            System.out.println("~");
          }

        } else {

          System.out.println("~ Your database needs evolutions for " + moduleRoot.getKey() + "!");
          System.out.println("");
          System.out.println(
              "# ------------------------------------------------------------------------------");
          System.out.println("");
          System.out.println(toHumanReadableScript(evolutions));
          System.out.println("");
          System.out.println(
              "# ------------------------------------------------------------------------------");
          System.out.println("");
          System.out.println(
              "~ Run `play evolutions:apply` to automatically apply this script to the database");
          System.out.println(
              "~ or apply it yourself and mark it done using `play evolutions:markApplied`");
          System.out.println("~");
          System.exit(-1);
        }
      }
    }
  }
Exemple #5
0
  /**
   * Init the framework
   *
   * @param root The application path
   * @param id The framework id to use
   */
  public static void init(File root, String id) {
    // Simple things
    Play.id = id;
    Play.started = false;
    Play.applicationPath = root;

    // load all play.static of exists
    initStaticStuff();

    guessFrameworkPath();

    // Read the configuration file
    readConfiguration();

    Play.classes = new ApplicationClasses();

    // Configure logs
    Logger.init();
    String logLevel = configuration.getProperty("application.log", "INFO");

    // only override log-level if Logger was not configured manually
    if (!Logger.configuredManually) {
      Logger.setUp(logLevel);
    }
    Logger.recordCaller =
        Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

    Logger.info("Starting %s", root.getAbsolutePath());

    if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
      tmpDir = null;
      Logger.debug("No tmp folder will be used (play.tmp is set to none)");
    } else {
      tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
      if (!tmpDir.isAbsolute()) {
        tmpDir = new File(applicationPath, tmpDir.getPath());
      }

      if (Logger.isTraceEnabled()) {
        Logger.trace("Using %s as tmp dir", Play.tmpDir);
      }

      if (!tmpDir.exists()) {
        try {
          if (readOnlyTmp) {
            throw new Exception("ReadOnly tmp");
          }
          tmpDir.mkdirs();
        } catch (Throwable e) {
          tmpDir = null;
          Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
        }
      }
    }

    // Mode
    try {
      mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
    } catch (IllegalArgumentException e) {
      Logger.error(
          "Illegal mode '%s', use either prod or dev",
          configuration.getProperty("application.mode"));
      fatalServerErrorOccurred();
    }

    // Force the Production mode if forceProd or precompile is activate
    // Set to the Prod mode must be done before loadModules call
    // as some modules (e.g. DocViewver) is only available in DEV
    if (usePrecompiled || forceProd || System.getProperty("precompile") != null) {
      mode = Mode.PROD;
    }

    // Context path
    ctxPath = configuration.getProperty("http.path", ctxPath);

    // Build basic java source path
    VirtualFile appRoot = VirtualFile.open(applicationPath);
    roots.add(appRoot);
    javaPath = new CopyOnWriteArrayList<VirtualFile>();
    javaPath.add(appRoot.child("app"));
    javaPath.add(appRoot.child("conf"));

    // Build basic templates path
    if (appRoot.child("app/views").exists()) {
      templatesPath = new ArrayList<VirtualFile>(2);
      templatesPath.add(appRoot.child("app/views"));
    } else {
      templatesPath = new ArrayList<VirtualFile>(1);
    }

    // Main route file
    routes = appRoot.child("conf/routes");

    // Plugin route files
    modulesRoutes = new HashMap<String, VirtualFile>(16);

    // Load modules
    loadModules();

    // Load the templates from the framework after the one from the modules
    templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));

    // Enable a first classloader
    classloader = new ApplicationClassloader();

    // Fix ctxPath
    if ("/".equals(Play.ctxPath)) {
      Play.ctxPath = "";
    }

    // Default cookie domain
    Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
    if (Http.Cookie.defaultDomain != null) {
      Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
    }

    // Plugins
    pluginCollection.loadPlugins();

    // Done !
    if (mode == Mode.PROD) {
      if (preCompile() && System.getProperty("precompile") == null) {
        start();
      } else {
        return;
      }
    } else {
      Logger.warn("You're running Play! in DEV mode");
    }

    // Plugins
    pluginCollection.onApplicationReady();

    Play.initialized = true;
  }