public void showInitializationMessage(
     final boolean initOk, final String fullyQualifiedServerUrl) {
   if (PentahoSystem.getObjectFactory().objectDefined(IVersionHelper.class.getSimpleName())) {
     IVersionHelper helper = PentahoSystem.get(IVersionHelper.class, null); // No session yet
     if (initOk) {
       System.out.println(
           Messages.getInstance()
               .getString(
                   "SolutionContextListener.INFO_SYSTEM_READY",
                   "(" + helper.getVersionInformation(PentahoSystem.class) + ")",
                   fullyQualifiedServerUrl,
                   SolutionContextListener
                       .solutionPath)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     } else {
       System.err.println(
           Messages.getInstance()
               .getString(
                   "SolutionContextListener.INFO_SYSTEM_NOT_READY",
                   "(" + helper.getVersionInformation(PentahoSystem.class) + ")",
                   fullyQualifiedServerUrl,
                   SolutionContextListener
                       .solutionPath)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
   }
 }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static String executeXml(
      RepositoryFile file,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      IPentahoSession userSession)
      throws Exception {
    try {
      HttpSessionParameterProvider sessionParameters =
          new HttpSessionParameterProvider(userSession);
      HttpRequestParameterProvider requestParameters =
          new HttpRequestParameterProvider(httpServletRequest);
      Map parameterProviders = new HashMap();
      parameterProviders.put("request", requestParameters); // $NON-NLS-1$
      parameterProviders.put("session", sessionParameters); // $NON-NLS-1$
      List messages = new ArrayList();
      IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest);
      httpServletResponse.setContentType("text/xml"); // $NON-NLS-1$
      httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding());
      boolean forcePrompt =
          "true"
              .equalsIgnoreCase(
                  requestParams.getStringParameter(
                      "prompt", "false")); // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$

      OutputStream contentStream = new ByteArrayOutputStream();
      SimpleOutputHandler outputHandler = new SimpleOutputHandler(contentStream, false);
      IRuntimeContext runtime = null;
      try {
        runtime =
            executeInternal(
                file,
                requestParams,
                httpServletRequest,
                outputHandler,
                parameterProviders,
                userSession,
                forcePrompt,
                messages);
        Document responseDoc =
            SoapHelper.createSoapResponseDocument(runtime, outputHandler, contentStream, messages);
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setSuppressDeclaration(true);
        format.setEncoding("utf-8"); // $NON-NLS-1$
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.write(responseDoc);
        writer.flush();
        return outputStream.toString("utf-8"); // $NON-NLS-1$
      } finally {
        if (runtime != null) {
          runtime.dispose();
        }
      }
    } catch (Exception e) {
      logger.warn(
          Messages.getInstance().getString("XactionUtil.XML_OUTPUT_NOT_SUPPORTED")); // $NON-NLS-1$
      throw e;
    }
  }
  private void setObjectFactory(final ServletContext context) {

    final String SYSTEM_FOLDER = "/system"; // $NON-NLS-1$
    String pentahoObjectFactoryClassName =
        getServerParameter("pentahoObjectFactory"); // $NON-NLS-1$
    String pentahoObjectFactoryConfigFile =
        getServerParameter("pentahoObjectFactoryCfgFile"); // $NON-NLS-1$

    // if web.xml doesnt specify a config file, use the default path.
    if (StringUtils.isEmpty(pentahoObjectFactoryConfigFile)) {
      pentahoObjectFactoryConfigFile =
          solutionPath + SYSTEM_FOLDER + "/" + DEFAULT_SPRING_CONFIG_FILE_NAME; // $NON-NLS-1$
    } else if (-1 == pentahoObjectFactoryConfigFile.indexOf("/")) { // $NON-NLS-1$
      pentahoObjectFactoryConfigFile =
          solutionPath + SYSTEM_FOLDER + "/" + pentahoObjectFactoryConfigFile; // $NON-NLS-1$
    }
    // else objectFactoryCreatorCfgFile contains the full path.
    IPentahoObjectFactory pentahoObjectFactory;
    try {
      Class<?> classObject = Class.forName(pentahoObjectFactoryClassName);
      pentahoObjectFactory = (IPentahoObjectFactory) classObject.newInstance();
    } catch (Exception e) {
      String msg =
          Messages.getInstance()
              .getErrorString(
                  "SolutionContextListener.ERROR_0002_BAD_OBJECT_FACTORY",
                  pentahoObjectFactoryClassName); //$NON-NLS-1$
      // Cannot proceed without an object factory, so we'll put some context around what
      // we were trying to do throw a runtime exception
      throw new RuntimeException(msg, e);
    }
    pentahoObjectFactory.init(pentahoObjectFactoryConfigFile, context);
    PentahoSystem.registerPrimaryObjectFactory(pentahoObjectFactory);
  }
  public static String postExecute(
      IRuntimeContext runtime,
      boolean debugMessages,
      boolean doWrapper,
      IOutputHandler outputHandler,
      Map<String, IParameterProvider> parameterProviders,
      HttpServletRequest request,
      HttpServletResponse response,
      List<?> messages,
      boolean deleteGeneratedFiles)
      throws Exception {
    StringBuffer buffer = new StringBuffer();

    boolean hasResponse = outputHandler.isResponseExpected();
    IContentItem responseContentItem =
        outputHandler.getOutputContentItem(
            IOutputHandler.RESPONSE, IOutputHandler.CONTENT, null, null);

    boolean success =
        (runtime != null && runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS);
    boolean printSuccess = (runtime != null) && success && (!hasResponse || debugMessages);
    boolean printError = (runtime != null) && !success && !response.isCommitted();

    if (printSuccess || printError) {
      final String htmlMimeType = "text/html"; // $NON-NLS-1$
      responseContentItem.setMimeType(htmlMimeType);
      response.setContentType(htmlMimeType);
      IMessageFormatter formatter =
          PentahoSystem.get(IMessageFormatter.class, PentahoSessionHolder.getSession());

      if (printSuccess) {
        formatter.formatSuccessMessage(htmlMimeType, runtime, buffer, debugMessages, doWrapper);
      } else {
        response.resetBuffer();
        formatter.formatFailureMessage(htmlMimeType, runtime, buffer, messages);
      }
    }
    // clear files which was generated during action execution
    // http://jira.pentaho.com/browse/BISERVER-12639
    IUnifiedRepository unifiedRepository = PentahoSystem.get(IUnifiedRepository.class, null);
    if (unifiedRepository != null) {
      for (IContentItem contentItem : runtime.getOutputContentItems()) {
        if (contentItem != null) {
          try {
            contentItem.closeOutputStream();
            if (deleteGeneratedFiles) {
              deleteContentItem(contentItem, unifiedRepository);
            }
          } catch (Exception e) {
            logger.warn(
                Messages.getInstance()
                    .getString("XactionUtil.CANNOT_REMOVE_OUTPUT_FILE", contentItem.getPath()),
                e);
          }
        }
      }
    }
    return buffer.toString();
  }
  public void contextDestroyed(final ServletContextEvent event) {

    PentahoSystem.shutdown();
    if (LocaleHelper.getLocale() == null) {
      LocaleHelper.setLocale(Locale.getDefault());
    }
    // log everything that goes on here
    logger.info(
        Messages.getInstance()
            .getString("SolutionContextListener.INFO_SYSTEM_EXITING")); // $NON-NLS-1$
  }
 static void deleteContentItem(IContentItem contentItem, IUnifiedRepository unifiedRepository) {
   if (contentItem instanceof RepositoryFileContentItem) {
     String path = contentItem.getPath();
     RepositoryFile repositoryFile = unifiedRepository.getFile(path);
     // repositoryFile can be null if we have not access or file does not exist
     if (repositoryFile != null) {
       unifiedRepository.deleteFile(repositoryFile.getId(), true, null);
     }
   } else if (contentItem instanceof FileContentItem) {
     // Files in the file system must not be deleted here
     String path = ((FileContentItem) contentItem).getFile().getName();
     logger.warn(Messages.getInstance().getString("XactionUtil.SKIP_REMOVING_OUTPUT_FILE", path));
   }
 }
  public void afterPropertiesSet() throws Exception {
    Assert.notNull(
        this.authenticationManager,
        Messages.getInstance()
            .getErrorString(
                "RequestParameterAuthenticationFilter.ERROR_0001_AUTHMGR_REQUIRED")); //$NON-NLS-1$
    Assert.notNull(
        this.authenticationEntryPoint,
        Messages.getInstance()
            .getErrorString(
                "RequestParameterAuthenticationFilter.ERROR_0002_AUTHM_ENTRYPT_REQUIRED")); //$NON-NLS-1$

    Assert.hasText(
        this.userNameParameter,
        Messages.getInstance()
            .getString(
                "RequestParameterAuthenticationFilter.ERROR_0003_USER_NAME_PARAMETER_MISSING")); //$NON-NLS-1$
    Assert.hasText(
        this.passwordParameter,
        Messages.getInstance()
            .getString(
                "RequestParameterAuthenticationFilter.ERROR_0004_PASSWORD_PARAMETER_MISSING")); //$NON-NLS-1$
  }
 private String getServerParameter(String paramName, boolean suppressWarning) {
   String result = context.getInitParameter(paramName);
   if (result == null) {
     ISystemConfig config = PentahoSystem.get(ISystemConfig.class);
     result = config.getProperty("server." + paramName);
   } else {
     if (!suppressWarning) {
       logger.warn(
           Messages.getInstance()
               .getString(
                   "SolutionContextListener.WARN_WEB_XML_PARAM_DEPRECATED",
                   paramName,
                   result)); //$NON-NLS-1$
     }
   }
   return result;
 }
 private static String lookupParameterGroupLabel(final String group) {
   if ("system".equals(group)) {
     return Messages.getInstance().getString("HttpWebService.PARAMETER_GROUP_SYSTEM");
   }
   return Messages.getInstance().getString("HttpWebService.PARAMETER_GROUP_USER");
 }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static String doParameter(
      final RepositoryFile file,
      IParameterProvider parameterProvider,
      final IPentahoSession userSession)
      throws IOException {
    ActionSequenceJCRHelper helper = new ActionSequenceJCRHelper();
    final IActionSequence actionSequence =
        helper.getActionSequence(
            file.getPath(), PentahoSystem.loggingLevel, RepositoryFilePermission.READ);
    final Document document = DocumentHelper.createDocument();
    try {
      final Element parametersElement = document.addElement("parameters");

      // noinspection unchecked
      final Map<String, IActionParameter> params =
          actionSequence.getInputDefinitionsForParameterProvider(IParameterProvider.SCOPE_REQUEST);
      for (final Map.Entry<String, IActionParameter> entry : params.entrySet()) {
        final String paramName = entry.getKey();
        final IActionParameter paramDef = entry.getValue();
        final String value = paramDef.getStringValue();
        final Class type;
        // yes, the actual type-code uses equals-ignore-case and thus allows the user
        // to specify type information in a random case. sTrInG is equal to STRING is equal to the
        // value
        // defined as constant (string)
        if (IActionParameter.TYPE_LIST.equalsIgnoreCase(paramDef.getType())) {
          type = String[].class;
        } else {
          type = String.class;
        }
        final String label = paramDef.getSelectionDisplayName();

        final String[] values;
        if (StringUtils.isEmpty(value)) {
          values = new String[0];
        } else {
          values = new String[] {value};
        }

        createParameterElement(
            parametersElement, paramName, type, label, "user", "parameters", values);
      }

      createParameterElement(
          parametersElement,
          "path",
          String.class,
          null,
          "system",
          "system",
          new String[] {file.getPath()});
      createParameterElement(
          parametersElement,
          "prompt",
          String.class,
          null,
          "system",
          "system",
          new String[] {"yes", "no"});
      createParameterElement(
          parametersElement,
          "instance-id",
          String.class,
          null,
          "system",
          "system",
          new String[] {parameterProvider.getStringParameter("instance-id", null)});
      // no close, as far as I know tomcat does not like it that much ..
      OutputFormat format = OutputFormat.createCompactFormat();
      format.setSuppressDeclaration(true);
      format.setEncoding("utf-8"); // $NON-NLS-1$
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      XMLWriter writer = new XMLWriter(outputStream, format);
      writer.write(document);
      writer.flush();
      return outputStream.toString("utf-8");
    } catch (Exception e) {
      logger.warn(Messages.getInstance().getString("HttpWebService.ERROR_0003_UNEXPECTED"), e);
      return null;
    }
  }
  /**
   * This method executes an xaction with forcePrompt=true and outputPreference=PARAMETERS, allowing
   * for the xaction to render the secure filter appropriately when being executed in the background
   * or while being scheduled.
   *
   * @param file the location of the xaction
   * @param httpServletRequest the request object
   * @param httpServletResponse the response object
   * @param userSession the user session
   * @return potential response message
   * @throws Exception
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static String executeScheduleUi(
      RepositoryFile file,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      IPentahoSession userSession,
      IMimeTypeListener mimeTypeListener)
      throws Exception {
    IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest);
    IRuntimeContext runtime = null;
    try {
      HttpSessionParameterProvider sessionParameters =
          new HttpSessionParameterProvider(userSession);
      HttpRequestParameterProvider requestParameters =
          new HttpRequestParameterProvider(httpServletRequest);

      boolean doMessages =
          "true"
              .equalsIgnoreCase(
                  requestParams.getStringParameter(
                      "debug", "false")); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      boolean doWrapper =
          "true"
              .equalsIgnoreCase(
                  requestParams.getStringParameter(
                      "wrapper", "true")); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

      IOutputHandler outputHandler =
          createOutputHandler(
              httpServletResponse, getOutputStream(httpServletResponse, doMessages));
      if (mimeTypeListener == null) {
        mimeTypeListener = new HttpMimeTypeListener(httpServletRequest, httpServletResponse, null);
      }
      outputHandler.setMimeTypeListener(mimeTypeListener);
      outputHandler.setSession(userSession);

      Map parameterProviders = new HashMap();
      parameterProviders.put("request", requestParameters); // $NON-NLS-1$
      parameterProviders.put("session", sessionParameters); // $NON-NLS-1$
      createOutputFileName(file, outputHandler);
      int outputPreference = IOutputHandler.OUTPUT_TYPE_PARAMETERS;
      outputHandler.setOutputPreference(outputPreference);
      List messages = new ArrayList();

      // forcePrompt=true when displaying the scheduling UI
      runtime =
          executeInternal(
              file,
              requestParams,
              httpServletRequest,
              outputHandler,
              parameterProviders,
              userSession,
              true,
              messages);
      String str =
          postExecute(
              runtime,
              doMessages,
              doWrapper,
              outputHandler,
              parameterProviders,
              httpServletRequest,
              httpServletResponse,
              messages,
              false);
      return str;
    } catch (Exception e) {
      logger.error(
          Messages.getInstance()
              .getString("XactionUtil.ERROR_EXECUTING_ACTION_SEQUENCE", file.getName()),
          e); //$NON-NLS-1$
      throw e;
    } finally {
      if (runtime != null) {
        runtime.dispose();
      }
    }
  }
  public void doFilter(
      final ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
      throw new ServletException(
          Messages.getInstance()
              .getErrorString(
                  "RequestParameterAuthenticationFilter.ERROR_0005_HTTP_SERVLET_REQUEST_REQUIRED")); //$NON-NLS-1$
    }

    if (!(response instanceof HttpServletResponse)) {
      throw new ServletException(
          Messages.getInstance()
              .getErrorString(
                  "RequestParameterAuthenticationFilter.ERROR_0006_HTTP_SERVLET_RESPONSE_REQUIRED")); //$NON-NLS-1$
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    InputStream in = httpRequest.getInputStream();
    byte[] bytes = IOUtils.toByteArray(in);
    // Do something with Bytes.

    final BufferedInputStream newStream = new BufferedInputStream(new ByteArrayInputStream(bytes));
    final Map parameterMap = request.getParameterMap();

    HttpServletRequestWrapper wrapper =
        new HttpServletRequestWrapper(httpRequest) {

          @Override
          public Map getParameterMap() {
            return parameterMap;
          }

          @Override
          public ServletInputStream getInputStream() throws IOException {
            return new ServletInputStream() {
              @Override
              public int read() throws IOException {
                return newStream.read();
              }
            };
          }
        };

    String username = httpRequest.getParameter(this.userNameParameter);
    String password = httpRequest.getParameter(this.passwordParameter);

    if (RequestParameterAuthenticationFilter.logger.isDebugEnabled()) {
      RequestParameterAuthenticationFilter.logger.debug(
          Messages.getInstance()
              .getString(
                  "RequestParameterAuthenticationFilter.DEBUG_AUTH_USERID",
                  username)); //$NON-NLS-1$
    }

    if ((username != null) && (password != null)) {
      // Only reauthenticate if username doesn't match SecurityContextHolder and user isn't
      // authenticated (see SEC-53)
      Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

      if ((existingAuth == null)
          || !existingAuth.getName().equals(username)
          || !existingAuth.isAuthenticated()) {
        UsernamePasswordAuthenticationToken authRequest =
            new UsernamePasswordAuthenticationToken(username, password);
        authRequest.setDetails(new WebAuthenticationDetails(httpRequest));

        Authentication authResult;

        try {
          authResult = authenticationManager.authenticate(authRequest);
        } catch (AuthenticationException failed) {
          // Authentication failed
          if (RequestParameterAuthenticationFilter.logger.isDebugEnabled()) {
            RequestParameterAuthenticationFilter.logger.debug(
                Messages.getInstance()
                    .getString(
                        "RequestParameterAuthenticationFilter.DEBUG_AUTHENTICATION_REQUEST",
                        username,
                        failed.toString())); // $NON-NLS-1$
          }

          SecurityContextHolder.getContext().setAuthentication(null);

          if (ignoreFailure) {
            chain.doFilter(wrapper, response);
          } else {
            authenticationEntryPoint.commence(wrapper, response, failed);
          }

          return;
        }

        // Authentication success
        if (RequestParameterAuthenticationFilter.logger.isDebugEnabled()) {
          RequestParameterAuthenticationFilter.logger.debug(
              Messages.getInstance()
                  .getString(
                      "RequestParameterAuthenticationFilter.DEBUG_AUTH_SUCCESS",
                      authResult.toString())); // $NON-NLS-1$
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);
      }
    }

    chain.doFilter(wrapper, response);
  }
  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);
              }
            });
  }