public ISolutionEngine getSolutionEngine(String path) {

    StandaloneApplicationContext applicationContext =
        new StandaloneApplicationContext(path, ""); // $NON-NLS-1$
    if (!PentahoSystem.getInitializedOK()) {
      PentahoSystem.init(applicationContext);
      assertTrue(
          "PentahoSystem did not initialize", PentahoSystem.getInitializedOK()); // $NON-NLS-1$
    }

    IPentahoSession session = new StandaloneSession("system"); // $NON-NLS-1$
    ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class, session);
    assertNotNull("SolutionEngine is null", solutionEngine); // $NON-NLS-1$
    solutionEngine.setLoggingLevel(ILogger.ERROR);
    solutionEngine.init(session);

    try {
      solutionEngine.setSession(session);
      return solutionEngine;
    } catch (Exception e) {
      // we should not get here
      e.printStackTrace();
      assertTrue(e.getMessage(), false);
    }
    return null;
  }
  public static synchronized void initializePentahoSystem(String solutionPath) throws Exception {

    // this setting is useful only for running the integration tests from within IntelliJ
    // this same property is set for integration tests via the pom when running with mvn
    String folderPaths = "target/spoon/plugins";
    File f = new File(folderPaths);
    System.setProperty("KETTLE_PLUGIN_BASE_FOLDERS", f.getAbsolutePath());

    StandaloneApplicationContext appContext = new StandaloneApplicationContext(solutionPath, "");
    PentahoSystem.setSystemSettingsService(new PathBasedSystemSettings());
    if (solutionPath == null) {
      throw new MetaverseException(
          Messages.getString("ERROR.MetaverseInit.BadConfigPath", solutionPath));
    }

    try {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();

      Thread.currentThread().setContextClassLoader(MetaverseUtil.class.getClassLoader());
      IPentahoObjectFactory pentahoObjectFactory = new StandaloneSpringPentahoObjectFactory();
      pentahoObjectFactory.init(solutionPath, PentahoSystem.getApplicationContext());
      PentahoSystem.registerObjectFactory(pentahoObjectFactory);

      // Restore context classloader
      Thread.currentThread().setContextClassLoader(cl);
    } catch (Exception e) {
      throw new MetaverseException(Messages.getString("ERROR.MetaverseInit.CouldNotInit"), e);
    }
    PentahoSystem.init(appContext);
    PentahoSessionHolder.setSession(new StandaloneSession());

    registerKettlePlugins();

    try {
      KettleEnvironment.init();
    } catch (KettleException e) {
      e.printStackTrace();
    }
  }
  public void test1() throws ObjectFactoryException {

    StandaloneSession session = new StandaloneSession("test");

    StandaloneApplicationContext appContext =
        new StandaloneApplicationContext("test-res/solution", "");

    StandaloneSpringPentahoObjectFactory factory = new StandaloneSpringPentahoObjectFactory();
    factory.init(
        "test-res/solution/system/pentahoObjects.GlobalListPublisherTest.spring.xml", null);

    PentahoSystem.setObjectFactory(factory);
    PentahoSystem.setSystemSettingsService(
        factory.get(ISystemSettings.class, "systemSettingsService", session));
    PentahoSystem.init(appContext);

    List<ISessionStartupAction> actions = new ArrayList<ISessionStartupAction>();

    SessionStartupAction startupAction1 = new SessionStartupAction();
    startupAction1.setSessionType(PentahoSystem.SCOPE_GLOBAL);
    startupAction1.setActionPath("testsolution/testpath/test.xaction");
    startupAction1.setActionOutputScope(PentahoSystem.SCOPE_GLOBAL);
    actions.add(startupAction1);

    TestRuntimeContext context = new TestRuntimeContext();
    context.status = IRuntimeContext.RUNTIME_STATUS_SUCCESS;
    TestSolutionEngine engine =
        PentahoSystem.get(TestSolutionEngine.class, "ISolutionEngine", session);
    engine.testRuntime = context;
    Map<String, IActionParameter> outputs = new HashMap<String, IActionParameter>();
    TestActionParameter param = new TestActionParameter();
    param.setValue("testvalue");
    outputs.put("testoutput", param);
    context.outputParameters = outputs;

    engine.executeCount = 0;
    GlobalListsPublisher globals = new GlobalListsPublisher();
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_SYSTEM_SETTINGS"),
        globals.getName());
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_DESCRIPTION"),
        globals.getDescription());
    assertTrue(!globals.getName().startsWith("!"));
    assertTrue(!globals.getDescription().startsWith("!"));
    assertNotNull(globals.getLogger());
    String resultMsg = globals.publish(session);
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_SYSTEM_SETTINGS_UPDATED"),
        resultMsg);

    assertEquals(0, engine.executeCount);
    PentahoSystem.setSessionStartupActions(actions);
    IParameterProvider globalParams = PentahoSystem.getGlobalParameters();

    resultMsg = globals.publish(session);
    assertEquals(1, engine.executeCount);
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_SYSTEM_SETTINGS_UPDATED"),
        resultMsg);

    // check that we made it all the way to executing the startup action
    assertEquals(session, engine.initSession);
    assertEquals(startupAction1.getActionPath(), engine.actionPath);
    assertEquals("testvalue", globalParams.getParameter("testoutput"));

    param.setValue("testvalue2");

    resultMsg = globals.publish(session);
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_SYSTEM_SETTINGS_UPDATED"),
        resultMsg);
    assertEquals(2, engine.executeCount);

    assertNotNull(globalParams);
    assertEquals("testvalue2", globalParams.getParameter("testoutput"));

    engine.errorMsg = "test exception";
    resultMsg = globals.publish(session);
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_ERROR_PUBLISH_FAILED")
            + "test exception",
        resultMsg);
    assertEquals(3, engine.executeCount);
  }
  public void contextInitialized(final ServletContextEvent event) {

    context = event.getServletContext();

    String encoding = getServerParameter("encoding"); // $NON-NLS-1$
    if (encoding != null) {
      LocaleHelper.setSystemEncoding(encoding);
    }

    String textDirection = getServerParameter("text-direction"); // $NON-NLS-1$
    if (textDirection != null) {
      LocaleHelper.setTextDirection(textDirection);
    }

    String localeLanguage = getServerParameter("locale-language"); // $NON-NLS-1$
    String localeCountry = getServerParameter("locale-country"); // $NON-NLS-1$
    boolean localeSet = false;
    if (!StringUtils.isEmpty(localeLanguage) && !StringUtils.isEmpty(localeCountry)) {
      Locale[] locales = Locale.getAvailableLocales();
      if (locales != null) {
        for (Locale element : locales) {
          if (element.getLanguage().equals(localeLanguage)
              && element.getCountry().equals(localeCountry)) {
            LocaleHelper.setLocale(element);
            localeSet = true;
            break;
          }
        }
      }
    }
    if (!localeSet) {
      // do this thread in the default locale
      LocaleHelper.setLocale(Locale.getDefault());
    }
    LocaleHelper.setDefaultLocale(LocaleHelper.getLocale());
    // log everything that goes on here
    logger.info(
        Messages.getInstance()
            .getString("SolutionContextListener.INFO_INITIALIZING")); // $NON-NLS-1$
    logger.info(
        Messages.getInstance()
            .getString("SolutionContextListener.INFO_SERVLET_CONTEXT", context)); // $NON-NLS-1$
    SolutionContextListener.contextPath = context.getRealPath(""); // $NON-NLS-1$
    logger.info(
        Messages.getInstance()
            .getString(
                "SolutionContextListener.INFO_CONTEXT_PATH",
                SolutionContextListener.contextPath)); // $NON-NLS-1$

    SolutionContextListener.solutionPath = PentahoHttpSessionHelper.getSolutionPath(context);
    if (StringUtils.isEmpty(SolutionContextListener.solutionPath)) {
      String errorMsg =
          Messages.getInstance()
              .getErrorString("SolutionContextListener.ERROR_0001_NO_ROOT_PATH"); // $NON-NLS-1$
      logger.error(errorMsg);
      /*
       * Since we couldn't find solution repository path there is no point in going forward and the user should know
       * that a major config setting was not found. So we are throwing in a RunTimeException with the requisite message.
       */
      throw new RuntimeException(errorMsg);
    }

    logger.info(
        Messages.getInstance()
            .getString(
                "SolutionContextListener.INFO_ROOT_PATH",
                SolutionContextListener.solutionPath)); // $NON-NLS-1$

    String fullyQualifiedServerUrl =
        getServerParameter("fully-qualified-server-url"); // $NON-NLS-1$
    if (fullyQualifiedServerUrl == null) {
      // assume this is a demo installation
      // TODO: Create a servlet that's loaded on startup to set this value
      fullyQualifiedServerUrl = "http://localhost:8080/pentaho/"; // $NON-NLS-1$
    }

    IApplicationContext applicationContext =
        new WebApplicationContext(
            SolutionContextListener.solutionPath,
            fullyQualifiedServerUrl,
            context.getRealPath(""),
            context); //$NON-NLS-1$

    /*
     * Copy out all the Server.properties from to the application context
     */
    Properties props = new Properties();
    ISystemConfig systemConfig = PentahoSystem.get(ISystemConfig.class);
    if (systemConfig != null) {
      IConfiguration config = systemConfig.getConfiguration("server");
      if (config != null) {
        try {
          props.putAll(config.getProperties());
        } catch (IOException e) {
          logger.error("Could not find/read the server.properties file.");
        }
      }
    }

    /*
     * Copy out all the initParameter values from the servlet context and put them in the application context.
     */
    Enumeration<?> initParmNames = context.getInitParameterNames();
    String initParmName;
    while (initParmNames.hasMoreElements()) {
      initParmName = (String) initParmNames.nextElement();
      props.setProperty(initParmName, getServerParameter(initParmName, true));
    }
    ((WebApplicationContext) applicationContext).setProperties(props);

    setSystemCfgFile(context);
    setObjectFactory(context);

    PentahoSystem.init(applicationContext, true);

    final String fullyQualifiedServerUrlOut = fullyQualifiedServerUrl;
    ServerStatusProvider.getInstance()
        .registerServerStatusChangeListener(
            new IServerStatusChangeListener() {
              @Override
              public void onStatusChange() {
                if (ServerStatusProvider.getInstance().getStatus()
                    != IServerStatusProvider.ServerStatus.STARTING) {
                  showInitializationMessage(
                      ServerStatusProvider.getInstance().getStatus()
                          == IServerStatusProvider.ServerStatus.STARTED,
                      fullyQualifiedServerUrlOut);
                }
                ServerStatusProvider.getInstance().removeServerStatusChangeListener(this);
              }
            });
  }
  @Test
  public void testSyncWebService() throws Exception {

    // first init kettle

    KettleEnvironment.init(false);
    BasePropertyHandler.getInstance().notify(new TestPropertyHandler());
    File f = new File(Const.getKettleDirectory());
    f.mkdirs();

    // second init platform
    PentahoSystem.registerObjectFactory(new SimpleObjectFactory());
    PentahoSystem.init(new TestAppContext(), null);
    PentahoSystem.setSystemSettingsService(
        new ISystemSettings() {
          public String getSystemCfgSourceName() {
            return null;
          }

          public String getSystemSetting(String arg0, String arg1) {
            if ("singleDiServerInstance".equals(arg0)) {
              return "false";
            }
            return arg1;
          }

          public String getSystemSetting(String arg0, String arg1, String arg2) {
            return null;
          }

          public List getSystemSettings(String arg0) {
            return null;
          }

          public List getSystemSettings(String arg0, String arg1) {
            return null;
          }

          public Document getSystemSettingsDocument(String arg0) {
            return null;
          }

          public Properties getSystemSettingsProperties(String arg0) {
            return null;
          }

          public void resetSettingsCache() {}
        });

    // now test the webservice
    IRepositorySyncWebService webservice = getRepositorySyncWebService();

    // first without the plugin available
    try {
      webservice.sync("test id", "http://localhost:8080/pentaho-di");
      Assert.fail();
    } catch (RepositorySyncException e) {
      Assert.assertTrue(
          e.getMessage().indexOf("unable to load the PentahoEnterpriseRepository plugin") >= 0);
    }

    // second with plugin but not registered
    RepositoryPluginType.getInstance()
        .registerCustom(
            TestRepositoryMeta.class,
            "PentahoEnterpriseRepository",
            "PentahoEnterpriseRepository",
            "PentahoEnterpriseRepository",
            "PentahoEnterpriseRepository",
            "");
    PluginRegistry.getInstance()
        .getPlugin(RepositoryPluginType.class, "PentahoEnterpriseRepository")
        .getClassMap()
        .put(
            RepositoryMeta.class,
            "com.pentaho.pdi.ws.RepositorySyncWebServiceTest$TestRepositoryMeta");

    RepositorySyncStatus status = webservice.sync("test id", "http://localhost:8080/pentaho-di");

    Assert.assertEquals(RepositorySyncStatus.REGISTERED, status);

    // third after already registered
    status = webservice.sync("test id", "http://localhost:8080/pentaho-di");

    Assert.assertEquals(RepositorySyncStatus.ALREADY_REGISTERED, status);

    // forth test with different url
    try {
      webservice.sync("test id", "http://localhost:9090/pentaho-di");
      Assert.fail();
    } catch (RepositorySyncException e) {
      Assert.assertTrue(e.getMessage().indexOf("with the URL:") >= 0);
    }

    // fifth test different base-url
    fullyQualifiedServerUrl = "http://localhost:9090/pentaho-di";
    try {
      webservice.sync("test id", "http://localhost:8080/pentaho-di");
      Assert.fail();
    } catch (RepositorySyncException e) {
      Assert.assertTrue(e.getMessage().indexOf("fully qualified server url") >= 0);
    }
  }