/**
   * @throws ParseException
   * @throws org.pentaho.platform.plugin.services.importexport.ExportException
   * @throws java.io.IOException
   */
  protected void performExportLegacy() throws ParseException, ExportException, IOException {

    // path is validated before executing
    String filepath =
        getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_FILEPATH_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_FILEPATH_NAME"),
            true,
            false);

    String logFile =
        getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_LOGFILE_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_LOGFILE_NAME"),
            false,
            true);

    if (!isValidExportPath(filepath, logFile)) {
      throw new ExportException("file-path:" + filepath);
    }

    final Exporter exportProcessor = getExportProcessor();
    exportProcessor.doExport();
    // throw new UnsupportedOperationException(); // TODO implement
  }
  public void testForcePrompt() {
    startTest();
    SimpleParameterProvider parameterProvider = new SimpleParameterProvider();
    OutputStream outputStream =
        getOutputStream("RuntimeTest.testForcePrompt", ".html"); // $NON-NLS-1$ //$NON-NLS-2$
    SimpleOutputHandler outputHandler = new SimpleOutputHandler(outputStream, true);
    outputHandler.setOutputPreference(IOutputHandler.OUTPUT_TYPE_PARAMETERS);
    StandaloneSession session =
        new StandaloneSession(Messages.getString("BaseTest.DEBUG_JUNIT_SESSION")); // $NON-NLS-1$

    ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class, session);
    solutionEngine.setLoggingLevel(getLoggingLevel());
    solutionEngine.init(session);
    solutionEngine.setForcePrompt(true);
    IRuntimeContext context =
        run(
            solutionEngine,
            "test",
            "reporting",
            "jfreereport-reports-test-param.xaction",
            null,
            false,
            parameterProvider,
            outputHandler); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_SUCCESS,
        context.getStatus()); // $NON-NLS-1$

    finishTest();
  }
  public void testScriptCompoundResult() {
    startTest();
    info(
        Messages.getInstance()
            .getString("RulesTest.USER_ERRORS_EXPECTED_SCRIPT_INVALID")); // $NON-NLS-1$
    IRuntimeContext context =
        run("/test/rules/script_rule3.xaction"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_SUCCESS,
        context.getStatus()); // $NON-NLS-1$

    assertNotNull(context.getOutputParameter("fruit")); // $NON-NLS-1$
    assertNotNull(context.getOutputParameter("veg")); // $NON-NLS-1$
    assertEquals(
        "bad",
        "apples",
        context
            .getOutputParameter("fruit")
            .getStringValue()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        "bad",
        "carrots",
        context
            .getOutputParameter("veg")
            .getStringValue()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
    finishTest();
  }
  public void testHelloWorld() {
    startTest();
    SimpleParameterProvider parameterProvider = new SimpleParameterProvider();
    parameterProvider.setParameter("type", "html"); // $NON-NLS-1$ //$NON-NLS-2$
    OutputStream outputStream =
        getOutputStream("RuntimeTest.testHelloWorld", ".html"); // $NON-NLS-1$ //$NON-NLS-2$
    SimpleOutputHandler outputHandler = new SimpleOutputHandler(outputStream, true);
    StandaloneSession session =
        new StandaloneSession(Messages.getString("BaseTest.DEBUG_JUNIT_SESSION")); // $NON-NLS-1$

    IRuntimeContext context =
        run(
            "test",
            "platform",
            "HelloWorld.xaction",
            null,
            false,
            parameterProvider,
            outputHandler,
            session); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_SUCCESS,
        context.getStatus()); // $NON-NLS-1$

    finishTest();
  }
  public void testScriptRule() {
    startTest();

    SimpleParameterProvider parameterProvider = new SimpleParameterProvider();
    parameterProvider.setParameter("customer", "Acme"); // $NON-NLS-1$ //$NON-NLS-2$

    IRuntimeContext context =
        run(
            "/test/rules/script_rule1.xaction",
            parameterProvider); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_SUCCESS,
        context.getStatus()); // $NON-NLS-1$

    assertNotNull(
        Messages.getInstance().getString("RulesTest.ERROR_0001_NULL_RESULT"),
        context.getOutputParameter("rule-result")); // $NON-NLS-1$ //$NON-NLS-2$
    assertEquals(
        Messages.getInstance().getString("RulesTest.ERROR_0002_WRONG_RESULT"),
        "Central",
        context
            .getOutputParameter("rule-result")
            .getStringValue()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    info(
        Messages.getInstance()
            .getString(
                "RulesTest.DEBUG_0003_SCRIPT_RULE_SUCCESS",
                context
                    .getOutputParameter("rule-result")
                    .getStringValue())); //$NON-NLS-1$ //$NON-NLS-2$
    finishTest();
  }
 protected static void printHelp() {
   HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp(
       Messages.getInstance().getString("CommandLineProcessor.INFO_PRINTHELP_CMDLINE"),
       Messages.getInstance().getString("CommandLineProcessor.INFO_PRINTHELP_HEADER"),
       options,
       Messages.getInstance().getString("CommandLineProcessor.INFO_PRINTHELP_FOOTER"));
 }
  /**
   * retrieve a domain from the repo. This does lazy loading of the repo, so it calls
   * reloadDomains() if not already loaded.
   *
   * @param domainId domain to get from the repository
   * @return domain object
   */
  @Override
  public Domain getDomain(final String domainId) {
    if (logger.isDebugEnabled()) {
      logger.debug("getDomain(" + domainId + ")");
    }

    if (StringUtils.isEmpty(domainId)) {
      throw new IllegalArgumentException(
          messages.getErrorString(
              "PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
    }
    Domain domain = null;
    try {
      // Load the domain file
      final RepositoryFile file = getMetadataRepositoryFile(domainId);
      if (file != null) {
        if (hasAccessFor(file)) {
          SimpleRepositoryFileData data =
              repository.getDataForRead(file.getId(), SimpleRepositoryFileData.class);
          if (data != null) {
            domain = xmiParser.parseXmi(data.getStream());
            domain.setId(domainId);
            logger.debug("loaded domain");
            // Load any I18N bundles
            loadLocaleStrings(domainId, domain);
            logger.debug("loaded I18N bundles");
          } else {
            throw new UnifiedRepositoryException(
                messages.getErrorString(
                    "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                    domainId,
                    "data not found"));
          }
        } else {
          throw new PentahoAccessControlException(
              messages.getErrorString(
                  "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                  domainId,
                  "access denied"));
        }
      }
    } catch (Exception e) {
      if (!(e instanceof UnifiedRepositoryException
          || e instanceof PentahoAccessControlException)) {
        throw new UnifiedRepositoryException(
            messages.getErrorString(
                "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                domainId,
                e.getLocalizedMessage()),
            e);
      }
    }

    // Return
    return domain;
  }
 /**
  * this process must run on the same box as the JCR repository does not use REST
  *
  * @throws Exception ;
  * @throws org.pentaho.platform.plugin.services.importexport.ImportException
  */
 protected void performImportLegacy() throws Exception, ImportException {
   final ImportProcessor importProcessor = getImportProcessor();
   importProcessor.setImportSource(createImportSource());
   addImportHandlers(importProcessor);
   String overwrite =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_OVERWRITE_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_OVERWRITE_NAME"),
           false,
           true);
   importProcessor.performImport(
       Boolean.valueOf(overwrite == null ? "true" : overwrite).booleanValue());
 }
 /**
  * Returns the option value from the command line
  *
  * @param option the option whose value should be returned (NOTE: {@code null} will be returned if
  *     the option was not provided)
  * @param required indicates if the option is required
  * @param emptyOk indicates if a blank value is acceptable
  * @return the value provided from the command line, or {@code null} if none was provided
  * @throws ParseException indicates the required or non-blank value was not provided
  */
 protected String getOptionValue(
     final String option, final boolean required, final boolean emptyOk) throws ParseException {
   final String value = StringUtils.trim(commandLine.getOptionValue(option));
   if (required && StringUtils.isEmpty(value)) {
     throw new ParseException(
         Messages.getInstance()
             .getErrorString("CommandLineProcessor.ERROR_0001_MISSING_ARG", option));
   }
   if (!emptyOk && StringUtils.isEmpty(value)) {
     throw new ParseException(
         Messages.getInstance()
             .getErrorString("CommandLineProcessor.ERROR_0001_MISSING_ARG", option));
   }
   return value;
 }
 /**
  * Determines the {@link org.pentaho.platform.plugin.services.importexport.ImportProcessor} to be
  * used by evaluating the command line
  *
  * @return the @{link ImportProcessor} to be used for importing - or the {@link
  *     org.pentaho.platform.plugin.services.importexport.SimpleImportProcessor} if one can not be
  *     determined
  */
 protected ImportProcessor getImportProcessor() throws ParseException {
   final String comment =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_COMMENT_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_COMMENT_NAME"),
           false,
           true);
   final String destinationPath =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PATH_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PATH_NAME"),
           true,
           false);
   return new SimpleImportProcessor(destinationPath, comment);
 }
  public void testIPreparedComponentXQueryShareConnection() {
    startTest();
    info("Expected: Successful execution with object available"); // $NON-NLS-1$
    IRuntimeContext context =
        run(
            "test",
            "ipreparedcomponents",
            "ipreparedcomponent_xquery_shareconn.xaction"); //$NON-NLS-1$ //$NON-NLS-2$
                                                            // //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_SUCCESS,
        context.getStatus()); // $NON-NLS-1$

    IActionParameter rtn1 = context.getOutputParameter("prepared_component"); // $NON-NLS-1$
    assertNotNull(rtn1);
    IPreparedComponent preparedComponent1 = (IPreparedComponent) rtn1.getValue();
    assertNotNull(preparedComponent1);
    IPentahoResultSet resultset1 = preparedComponent1.executePrepared(null);
    assertTrue(resultset1.getRowCount() >= 1);
    Object val1 = resultset1.getValueAt(0, 0);
    assertNotNull(val1);

    finishTest();
  }
 public void testHelloWorldComponent() {
   startTest();
   String testName = HW_TEST_NAME + System.currentTimeMillis();
   SimpleParameterProvider parameterProvider = new SimpleParameterProvider();
   IRuntimeContext context =
       run(
           "/test/platform/HelloWorld.xaction",
           parameterProvider,
           testName,
           HW_TEST_EXTN); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
   assertEquals(
       Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
       IRuntimeContext.RUNTIME_STATUS_SUCCESS,
       context.getStatus()); // $NON-NLS-1$
   if (context != null) {
     // do nothing...
   }
   InputStream is = this.getInputStreamFromOutput(testName, HW_TEST_EXTN);
   assertNotNull(is); // Did the test execute properly...
   String lookingFor =
       "\nHello World. (2B || !2B) That is the question\n"; //$NON-NLS-1$ //$NON-NLS-2$
   String wasRead = FileHelper.getStringFromInputStream(is);
   assertEquals(wasRead, lookingFor);
   finishTest();
 }
 private Exporter getExportProcessor() throws ParseException {
   final IUnifiedRepository repository = getRepository();
   String path =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PATH_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PATH_NAME"),
           true,
           false);
   String filepath =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_FILEPATH_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_FILEPATH_NAME"),
           true,
           false);
   final Exporter exportProcess = new Exporter(repository, path, filepath);
   return exportProcess;
 }
  public void testScriptRuleError4() {
    startTest();

    info(
        "This should generate errors because the input to the script has a minus sign in the input name."); //$NON-NLS-1$
    IRuntimeContext context =
        run("/test/rules/script_rule_error4.xaction"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_FAILURE,
        context.getStatus()); // $NON-NLS-1$
    assertEquals(
        Messages.getInstance().getString("RulesTest.ERROR_0005_RESULT_WHEN_NULL_EXPECTED"),
        null,
        context.getOutputParameter("rule-result").getStringValue()); // $NON-NLS-1$//$NON-NLS-2$
    finishTest();
  }
  @Override
  public void addLocalizationFile(
      final String domainId,
      final String locale,
      final InputStream inputStream,
      final boolean overwrite)
      throws DomainStorageException {
    if (logger.isDebugEnabled()) {
      logger.debug("addLocalizationFile(" + domainId + ", " + locale + ", inputStream)");
    }
    if (null != inputStream) {
      if (StringUtils.isEmpty(domainId) || StringUtils.isEmpty(locale)) {
        throw new IllegalArgumentException(
            messages.getErrorString(
                "PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
      }

      lock.writeLock().lock();
      try {
        // Check for duplicates
        final RepositoryFile localeFile = metadataMapping.getLocaleFile(domainId, locale);
        if (!overwrite && localeFile != null) {
          throw new DomainStorageException(
              messages.getErrorString(
                  "PentahoMetadataDomainRepository.ERROR_0009_LOCALE_ALREADY_EXISTS",
                  domainId,
                  locale),
              null);
        }

        final SimpleRepositoryFileData data =
            new SimpleRepositoryFileData(inputStream, DEFAULT_ENCODING, LOCALE_MIME_TYPE);
        if (localeFile == null) {
          final RepositoryFile newLocaleFile = createUniqueFile(domainId, locale, data);
          metadataMapping.addLocale(domainId, locale, newLocaleFile);
        } else {
          repository.updateFile(localeFile, data, null);
        }
        // This invalidates any cached information
        flushDomains();
      } finally {
        lock.writeLock().unlock();
      }
    }
  }
  /**
   * Parses the command line and handles the situation where it isn't a valid import or export or
   * rest request
   *
   * @param args the command line arguments
   * @throws ParseException indicates that neither (or both) an import and/or export have been
   *     request
   */
  protected CommandLineProcessor(String[] args) throws ParseException {
    // parse the command line arguments
    commandLine = new PosixParser().parse(options, args);
    if (commandLine.hasOption(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_HELP_NAME"))
        || commandLine.hasOption(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_HELP_KEY"))) {
      requestType = RequestType.HELP;
    } else {
      if (commandLine.hasOption(
              Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_REST_NAME"))
          || commandLine.hasOption(
              Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_REST_KEY"))) {
        requestType = RequestType.REST;
      } else {
        final boolean importRequest =
            commandLine.hasOption(
                Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_IMPORT_KEY"));
        final boolean exportRequest =
            commandLine.hasOption(
                Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_EXPORT_KEY"));

        if (importRequest == exportRequest) {
          throw new ParseException(
              Messages.getInstance()
                  .getErrorString("CommandLineProcessor.ERROR_0003_PARSE_EXCEPTION"));
        }
        requestType = (importRequest ? RequestType.IMPORT : RequestType.EXPORT);
      }
    }
  }
  public void testScriptRuleError2() {
    startTest();
    info(
        Messages.getInstance()
            .getString("RulesTest.USER_ERRORS_EXPECTED_OUTPUT_NOT_DEFINED")); // $NON-NLS-1$
    IRuntimeContext context =
        run("/test/rules/script_rule_error2.xaction"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_CONTEXT_VALIDATE_FAIL,
        context.getStatus()); // $NON-NLS-1$

    assertEquals(
        Messages.getInstance().getString("RulesTest.ERROR_0006_RESULT_WHEN_ERROR_EXPECTED"),
        false,
        context.getOutputNames().contains("rule-result")); // $NON-NLS-1$//$NON-NLS-2$
    finishTest();
  }
  public void testScriptRuleError3() {
    startTest();
    info(
        Messages.getInstance()
            .getString("RulesTest.USER_ERRORS_EXPECTED_SCRIPT_INVALID")); // $NON-NLS-1$
    IRuntimeContext context =
        run("/test/rules/script_rule_error3.xaction"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_STATUS_FAILURE,
        context.getStatus()); // $NON-NLS-1$

    assertEquals(
        Messages.getInstance().getString("RulesTest.ERROR_0005_RESULT_WHEN_NULL_EXPECTED"),
        null,
        context.getOutputParameter("rule-result").getStringValue()); // $NON-NLS-1$//$NON-NLS-2$
    finishTest();
  }
  /**
   * How this class is executed from the command line. It will create an instance of an {@link
   * org.pentaho.platform.plugin.services.importexport.ImportProcessor} and initialize it base on
   * the options provided on the command line.
   *
   * @param args
   */
  public static void main(String[] args) throws Exception {

    try {
      // reset the exception information
      exception = null;

      final CommandLineProcessor commandLineProcessor = new CommandLineProcessor(args);
      String legacy =
          commandLineProcessor.getOptionValue(
              Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_LEGACY_KEY"),
              Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_LEGACY_NAME"),
              false,
              true);

      useRestService =
          "false".equals(legacy) ? false : true; // default to new REST version if not provided
      // new service only
      switch (commandLineProcessor.getRequestType()) {
        case HELP:
          printHelp();
          break;

        case IMPORT:
          commandLineProcessor.performImport();
          break;

        case EXPORT:
          commandLineProcessor.performExport();
          break;
        case REST:
          commandLineProcessor.performREST();
          break;
      }
    } catch (ParseException parseException) {
      exception = parseException;
      System.err.println(parseException.getLocalizedMessage());
      printHelp();
    } catch (Exception e) {
      exception = e;
      e.printStackTrace();
      log.error(e.getMessage(), e);
    }
  }
 /**
  * Used only for REST Jersey calls
  *
  * @throws ParseException
  */
 private void initRestService() throws ParseException {
   // get information about the remote connection
   String username =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_USERNAME_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_USERNAME_NAME"),
           true,
           false);
   String password =
       getOptionValue(
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PASSWORD_KEY"),
           Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PASSWORD_NAME"),
           true,
           false);
   ClientConfig clientConfig = new DefaultClientConfig();
   clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
   client = Client.create(clientConfig);
   client.addFilter(new HTTPBasicAuthFilter(username, password));
 }
Example #21
0
 public void testLooping() {
   startTest();
   IRuntimeContext context =
       run("test", "platform", "LoopingTest.xaction"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
   assertEquals(
       Messages.getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
       IRuntimeContext.RUNTIME_STATUS_SUCCESS,
       context.getStatus()); // $NON-NLS-1$
   finishTest();
 }
  /**
   * remove a model from a domain which is stored either on a disk or memory.
   *
   * @param domainId
   * @param modelId
   */
  @Override
  public void removeModel(final String domainId, final String modelId)
      throws DomainIdNullException, DomainStorageException {
    if (logger.isDebugEnabled()) {
      logger.debug("removeModel(" + domainId + ", " + modelId + ")");
    }

    if (StringUtils.isEmpty(domainId)) {
      throw new IllegalArgumentException(
          messages.getErrorString(
              "PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
    }
    if (StringUtils.isEmpty(modelId)) {
      throw new IllegalArgumentException(
          messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0006_MODEL_ID_INVALID"));
    }

    // Get the domain and remove the model
    final Domain domain = getDomain(domainId);
    if (null != domain) {
      boolean found = false;
      final Iterator<LogicalModel> iter = domain.getLogicalModels().iterator();
      while (iter.hasNext()) {
        LogicalModel model = iter.next();
        if (modelId.equals(model.getId())) {
          iter.remove();
          found = true;
          break;
        }
      }

      // Update the domain if we change it
      if (found) {
        try {
          storeDomain(domain, true);
          flushDomains();
        } catch (DomainAlreadyExistsException ignored) {
          // This can't happen since we have setup overwrite to true
        }
      }
    }
  }
 private static boolean getBooleanValue(final Document doc, final String xpath) {
   try {
     final Element element = (Element) doc.selectSingleNode(xpath);
     return element != null && Boolean.parseBoolean(element.getText());
   } catch (Exception e) {
     logger.error(
         messages.getErrorString(
             "EmailConfigurationXml.ERROR_0001_ERROR_PARSING_DATA", e.getLocalizedMessage()));
   }
   return false;
 }
  /**
   * Creates and adds the set of {@link
   * org.pentaho.platform.plugin.services.importexport.ImportHandler}s to be used with this import
   * process
   *
   * @param importProcessor the import processor in which the import handlers should be created
   */
  protected void addImportHandlers(final ImportProcessor importProcessor) throws ParseException {
    // TODO - Need a way to either (a) have all ImportProcessors use the
    // same set or (b) use spring to initialize this
    final IUnifiedRepository repository = getRepository();

    String username =
        getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_USERNAME_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_USERNAME_NAME"),
            true,
            false);
    String password =
        getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PASSWORD_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_PASSWORD_NAME"),
            true,
            false);
    String url =
        getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_URL_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_URL_NAME"),
            true,
            false);

    importProcessor.addImportHandler(new MondrianImportHandler(username, password, url));
    importProcessor.addImportHandler(new MetadataImportHandler(username, password, url));
    importProcessor.addImportHandler(new DefaultImportHandler(repository));
  }
  /** Performs the process of reloading the domain information from the repository */
  private void internalReloadDomains() {
    lock.writeLock().lock();
    try {
      metadataMapping.reset();

      // Reload the metadata about the metadata (that was fun to say)
      final List<RepositoryFile> children = repository.getChildren(getMetadataDir().getId(), "*");
      if (logger.isTraceEnabled()) {
        logger.trace("\tFound " + children.size() + " files in the repository");
      }
      for (final RepositoryFile child : children) {
        if (getAclHelper().canAccess(child, READ)) {
          // Get the metadata for this file
          final Map<String, Serializable> fileMetadata = repository.getFileMetadata(child.getId());
          if (fileMetadata == null
              || StringUtils.isEmpty((String) fileMetadata.get(PROPERTY_NAME_DOMAIN_ID))) {
            if (logger.isWarnEnabled()) {
              logger.warn(
                  messages.getString(
                      "PentahoMetadataDomainRepository.WARN_0001_FILE_WITHOUT_METADATA",
                      child.getName()));
            }
            continue;
          }
          final String domainId = (String) fileMetadata.get(PROPERTY_NAME_DOMAIN_ID);
          final String type = (String) fileMetadata.get(PROPERTY_NAME_TYPE);
          final String locale = (String) fileMetadata.get(PROPERTY_NAME_LOCALE);
          if (logger.isTraceEnabled()) {
            logger.trace(
                "\tprocessing file [type="
                    + type
                    + " : domainId="
                    + domainId
                    + " : locale="
                    + locale
                    + "]");
          }

          // Save the data in the map
          if (StringUtils.equals(type, TYPE_DOMAIN)) {
            metadataMapping.addDomain(domainId, child);
          } else if (StringUtils.equals(type, TYPE_LOCALE)) {
            metadataMapping.addLocale(domainId, locale, child);
          }
        }
      }

      needToReload = false;
    } finally {
      lock.writeLock().unlock();
    }
  }
  /**
   * Store a domain to the repository. The domain should persist between JVM restarts.
   *
   * @param domain domain object to store
   * @param overwrite if true, overwrite existing domain
   * @throws DomainIdNullException if domain id is null or empty
   * @throws DomainAlreadyExistsException if a domain with the same Domain ID already exists in the
   *     repository and {@code overwrite == false}
   * @throws DomainStorageException if there is a problem storing the domain
   */
  @Override
  public void storeDomain(final Domain domain, final boolean overwrite)
      throws DomainIdNullException, DomainAlreadyExistsException, DomainStorageException {
    if (logger.isDebugEnabled()) {
      logger.debug(
          "storeDomain(domain(id="
              + (domain != null ? domain.getId() : "")
              + ", "
              + overwrite
              + ")");
    }
    if (null == domain || StringUtils.isEmpty(domain.getId())) {
      throw new DomainIdNullException(
          messages.getErrorString("PentahoMetadataDomainRepository.ERROR_0001_DOMAIN_ID_NULL"));
    }

    String xmi = "";
    try {
      // NOTE - a ByteArrayInputStream doesn't need to be closed ...
      // ... so this is safe AS LONG AS we use a ByteArrayInputStream
      xmi = xmiParser.generateXmi(domain);
      // final InputStream inputStream = new ByteArrayInputStream( xmi.getBytes( DEFAULT_ENCODING )
      // );
      final InputStream inputStream = new ByteArrayInputStream(xmi.getBytes("UTF8"));
      storeDomain(inputStream, domain.getId(), overwrite);
    } catch (DomainStorageException dse) {
      throw dse;
    } catch (DomainAlreadyExistsException dae) {
      throw dae;
    } catch (Exception e) {
      final String errorMessage =
          messages.getErrorString(
              "PentahoMetadataDomainRepository.ERROR_0003_ERROR_STORING_DOMAIN",
              domain.getId(),
              e.getLocalizedMessage());
      logger.error(errorMessage, e);
      throw new DomainStorageException(xmi + errorMessage, e);
    }
  }
  protected XulMenubar getXulMenubar(String id, String documentPath, IPentahoSession session) {
    XulDomContainer container = getXulContainer(documentPath, session);
    if (container == null) {
      return null;
    }
    List<XulComponent> components =
        container.getDocumentRoot().getElementsByTagName("menubar"); // $NON-NLS-1$
    for (XulComponent component : components) {
      if (component instanceof XulMenubar && component.getId().equals(id)) {
        XulMenubar menubar = (XulMenubar) component;
        // now get customizations to it
        IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
        List<?> menuCustomizations = pluginManager.getMenuCustomizations();
        for (Object custom : menuCustomizations) {
          if (custom instanceof IMenuCustomization) {
            IMenuCustomization item = (IMenuCustomization) custom;
            try {
              // apply each customization and log any failures
              MenuUtil.customizeMenu(menubar, item, getXulLoader());
            } catch (Exception e) {
              session.error(
                  Messages.getString(
                      "BaseMenuProvider.ERROR_0004_COULD_NOT_CUSTOMIZE_MENU",
                      item.getId(),
                      item.getLabel()),
                  e); //$NON-NLS-1$
            }
          }
        }

        return menubar;
      }
    }
    Logger.error(
        getClass().getName(),
        Messages.getErrorString(
            "BaseMenuProvider.ERROR_0002_COULD_NOT_GET_MENUBAR")); //$NON-NLS-1$
    return null;
  }
 private static Short getShortValue(final Document doc, final String xpath) {
   try {
     final Element element = (Element) doc.selectSingleNode(xpath);
     Short value = Short.MIN_VALUE;
     if (element != null && !StringUtils.isEmpty(element.getText())) {
       value = Short.parseShort(element.getText());
     }
     return value;
   } catch (Exception e) {
     logger.error(
         messages.getErrorString(
             "EmailConfigurationXml.ERROR_0001_ERROR_PARSING_DATA", e.getLocalizedMessage()));
   }
   return Short.MIN_VALUE;
 }
 /**
  * Returns the option value from the command line
  *
  * @param shortOption the single character option whose value should be returned (NOTE: {@code
  *     null} will be returned if the option was not provided)
  * @param longOption the string option whose value should be returned (NOTE: {@code null} will be
  *     returned if the option was not provided)
  * @param required indicates if the option is required
  * @param emptyOk indicates if a blank value is acceptable
  * @return the value provided from the command line, or {@code null} if none was provided
  * @throws ParseException indicates the required or non-blank value was not provided
  */
 protected String getOptionValue(
     final String shortOption,
     final String longOption,
     final boolean required,
     final boolean emptyOk)
     throws ParseException {
   // first try the short option parameter
   String value = StringUtils.trim(commandLine.getOptionValue(shortOption));
   if (StringUtils.isEmpty(value)) {
     // if its empty, try the long option
     value = StringUtils.trim(commandLine.getOptionValue(longOption));
   }
   if (required && StringUtils.isEmpty(value)) {
     throw new ParseException(
         Messages.getInstance()
             .getErrorString("CommandLineProcessor.ERROR_0001_MISSING_ARG", longOption));
   }
   if (!emptyOk && StringUtils.isEmpty(value)) {
     throw new ParseException(
         Messages.getInstance()
             .getErrorString("CommandLineProcessor.ERROR_0001_MISSING_ARG", longOption));
   }
   return value;
 }
  public void testIPreparedComponentXQueryAvailableErrorNoPrepareComponent() {
    startTest();
    info("Expected: Successful execution with object available"); // $NON-NLS-1$
    IRuntimeContext context =
        run(
            "test",
            "ipreparedcomponents",
            "ipreparedcomponent_xquery_available_error_nopreparedcomponent.xaction"); //$NON-NLS-1$
                                                                                      // //$NON-NLS-2$ //$NON-NLS-3$
    assertEquals(
        Messages.getInstance().getString("BaseTest.USER_RUNNING_ACTION_SEQUENCE"),
        IRuntimeContext.RUNTIME_CONTEXT_VALIDATE_FAIL,
        context.getStatus()); // $NON-NLS-1$

    finishTest();
  }