@Before
  public void init0() {
    microPlatform = new MicroPlatform("test-src/solution");
    microPlatform.define(ISolutionEngine.class, SolutionEngine.class);
    microPlatform.define(
        IUnifiedRepository.class, FileSystemBackedUnifiedRepository.class, Scope.GLOBAL);
    microPlatform.define(IMondrianCatalogService.class, MondrianCatalogHelper.class, Scope.GLOBAL);
    microPlatform.define("connection-SQL", SQLConnection.class);
    microPlatform.define("connection-MDX", MDXConnection.class);
    microPlatform.define(IDBDatasourceService.class, JndiDatasourceService.class, Scope.GLOBAL);
    microPlatform.define(IUserRoleListService.class, TestUserRoleListService.class, Scope.GLOBAL);
    microPlatform.define(UserDetailsService.class, TestUserDetailsService.class, Scope.GLOBAL);
    FileSystemBackedUnifiedRepository repo =
        (FileSystemBackedUnifiedRepository) PentahoSystem.get(IUnifiedRepository.class);
    repo.setRootDir(new File("test-src/solution"));
    try {
      microPlatform.start();
    } catch (PlatformInitializationException ex) {
      Assert.fail();
    }

    MondrianCatalogHelper catalogService =
        (MondrianCatalogHelper) PentahoSystem.get(IMondrianCatalogService.class);
    catalogService.setDataSourcesConfig(
        "file:"
            + PentahoSystem.getApplicationContext()
                .getSolutionPath("test/analysis/test-datasources.xml"));

    // JNDI
    System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory");
    System.setProperty("org.osjava.sj.root", "test-src/solution/system/simple-jndi");
    System.setProperty("org.osjava.sj.delimiter", "/");
  }
  /** @return String that represents the file path to a temporary file */
  protected String[] createTempFile() {
    // create temporary file names
    String solutionDir = "system/tmp/"; // $NON-NLS-1$
    String fileNamePrefix = "tmp_chart_"; // $NON-NLS-1$
    String extension = ".png"; // $NON-NLS-1$
    String fileName = null;
    String filePathWithoutExtension = null;
    try {
      File file =
          PentahoSystem.getApplicationContext()
              .createTempFile(getSession(), fileNamePrefix, extension, true);
      fileName = file.getName();
      filePathWithoutExtension = solutionDir + fileName.substring(0, fileName.indexOf('.'));
    } catch (IOException e) {
      getLogger()
          .error(
              Messages.getInstance()
                  .getErrorString("AbstractChartComponent.ERROR_0001_CANT_CREATE_TEMP_CHART"),
              e); //$NON-NLS-1$
    }
    String[] value = new String[2];
    value[AbstractChartComponent.FILENAME_INDEX] = fileName;
    value[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX] = filePathWithoutExtension;

    return value;
  }
  protected OutputStream getOutputStream(String testName, String extension) {
    OutputStream outputStream = null;
    try {
      String tmpDir =
          PentahoSystem.getApplicationContext().getFileOutputPath("test/tmp"); // $NON-NLS-1$
      File file = new File(tmpDir);
      file.mkdirs();
      String path =
          PentahoSystem.getApplicationContext()
              .getFileOutputPath("test/tmp/" + testName + extension); // $NON-NLS-1$
      outputStream = new FileOutputStream(path);
    } catch (FileNotFoundException e) {

    }
    return outputStream;
  }
 public String getDescription() {
   return Messages.getInstance()
       .getString(
           "SettingsPublisher.USER_DESCRIPTION",
           PentahoSystem.getApplicationContext()
               .getSolutionPath("system")
               .replace('\\', '/')); // $NON-NLS-1$ //$NON-NLS-2$
 }
 protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/javascript");
   OutputStream out = response.getOutputStream();
   // split out a base url, guaranteed to have a trailing slash
   String baseURL = PentahoSystem.getApplicationContext().getBaseUrl();
   if (!baseURL.endsWith("/")) {
     baseURL += "/";
   }
   String webContext = "var WEB_CONTEXT_BASE = '" + baseURL + "';";
   out.write(webContext.getBytes());
   out.close();
 }
 protected InputStream getInputStreamFromOutput(String testName, String extension) {
   String path =
       PentahoSystem.getApplicationContext()
           .getFileOutputPath("test/tmp/" + testName + extension); // $NON-NLS-1$
   File f = new File(path);
   if (f.exists()) {
     try {
       FileInputStream fis = new FileInputStream(f);
       return fis;
     } catch (Exception ignored) {
       return null;
     }
   } else {
     return null;
   }
 }
Example #7
0
  private static synchronized Cache getCache() throws CacheException {
    if (cacheManager
        == null) { // 'new CacheManager' used instead of 'CacheManager.create' to avoid overriding
      // default cache
      String cacheConfigFile = CACHE_CFG_FILE;

      String cfgFile =
          PentahoSystem.getApplicationContext()
              .getSolutionPath(DashboardDesignerContentGenerator.PLUGIN_PATH + cacheConfigFile);
      cacheManager = new CacheManager(cfgFile); // CacheManager.create(cfgFile);
    }

    enableCacheProperShutdown(true);

    if (!cacheManager.cacheExists(CACHE_NAME)) {
      cacheManager.addCache(CACHE_NAME);
    }

    return cacheManager.getCache(CACHE_NAME);
  }
  protected void reinitOutputTarget() throws ReportProcessingException, ContentIOException {
    final IApplicationContext ctx = PentahoSystem.getApplicationContext();

    final ContentLocation dataLocation;
    final PentahoNameGenerator dataNameGenerator;
    if (ctx != null) {
      File dataDirectory = new File(ctx.getFileOutputPath("system/tmp/")); // $NON-NLS-1$
      if (dataDirectory.exists() && (dataDirectory.isDirectory() == false)) {
        dataDirectory = dataDirectory.getParentFile();
        if (dataDirectory.isDirectory() == false) {
          throw new ReportProcessingException("Dead " + dataDirectory.getPath()); // $NON-NLS-1$
        }
      } else if (dataDirectory.exists() == false) {
        dataDirectory.mkdirs();
      }

      final FileRepository dataRepository = new FileRepository(dataDirectory);
      dataLocation = dataRepository.getRoot();
      dataNameGenerator = PentahoSystem.get(PentahoNameGenerator.class);
      if (dataNameGenerator == null) {
        throw new IllegalStateException(
            Messages.getInstance()
                .getString("ReportPlugin.errorNameGeneratorMissingConfiguration"));
      }
      dataNameGenerator.initialize(dataLocation, true);
    } else {
      dataLocation = null;
      dataNameGenerator = null;
    }

    final StreamRepository targetRepository =
        new StreamRepository(null, proxyOutputStream, "report"); // $NON-NLS-1$
    final ContentLocation targetRoot = targetRepository.getRoot();

    printer.setContentWriter(
        targetRoot,
        new DefaultNameGenerator(targetRoot, "index", "html")); // $NON-NLS-1$ //$NON-NLS-2$
    printer.setDataWriter(dataLocation, dataNameGenerator);
  }
  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();
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Retrieving the file upload defaults from pentaho.xml
      String relativePath =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/relative-path",
              String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); // $NON-NLS-1$
      String maxFileLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-file-limit", String.valueOf(MAX_FILE_SIZE)); // $NON-NLS-1$
      String maxFolderLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-folder-limit",
              String.valueOf(MAX_FOLDER_SIZE)); // $NON-NLS-1$

      response.setContentType("text/plain");
      FileItem uploadItem = getFileItem(request);
      if (uploadItem == null) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0001_NO_FILE_TO_UPLOAD"));
        return;
      }
      if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
        response
            .getWriter()
            .write(
                Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0003_FILE_TOO_BIG"));
        return;
      }

      String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);

      File pathDir = new File(path);
      // create the path if it doesn't exist yet
      if (!pathDir.exists()) {
        pathDir.mkdirs();
      }

      if (uploadItem.getSize() + getFolderSize(pathDir) > Long.parseLong(maxFolderLimit)) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"));
        return;
      }
      byte[] fileContents = uploadItem.get();
      UUID id = UUIDUtil.getUUID();
      String filename = id.toString() + CSV_EXT;

      if (doesFileExists(new File(path + filename))) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0002_FILE_ALREADY_EXIST"));
        return;
      }
      FileOutputStream outputStream = new FileOutputStream(path + filename);
      outputStream.write(fileContents);
      outputStream.flush();
      outputStream.close();
      response.getWriter().write(new String(filename));
    } catch (Exception e) {
      response
          .getWriter()
          .write(
              Messages.getInstance()
                  .getErrorString(
                      "UploadFileServlet.ERROR_0005_UNKNOWN_ERROR", e.getLocalizedMessage()));
    }
  }
  /**
   * Create a dial image.
   *
   * <ul>
   *   <li>Load the specified XML document describing the dial definition
   *   <li>Create a dial definition object from the XML definition
   *   <li>Use the JFreeChartEngine to create a dial image
   *   <li>Create an XML document describing the dial
   *   <li>Return the XML document
   * </ul>
   *
   * @return The XML document describing this dial
   */
  @Override
  public Document getXmlContent() {

    WidgetDefinition widget = null;
    if (type == DashboardWidgetComponent.TYPE_DIAL) {

      // load the XML document that defines the dial
      IActionSequenceResource resource =
          new ActionSequenceResource(
              title,
              IActionSequenceResource.SOLUTION_FILE_RESOURCE,
              "text/xml", //$NON-NLS-1$
              definitionPath);
      Document dialDefinition = null;
      try {
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        reader.setEntityResolver(new SolutionURIResolver());
        dialDefinition =
            reader.read(
                resource.getInputStream(RepositoryFilePermission.READ, LocaleHelper.getLocale()));
      } catch (Throwable t) {
        // XML document can't be read. We'll just return a null document.
      }

      if (dialDefinition == null) {
        error(
            Messages.getInstance()
                .getErrorString(
                    "Widget.ERROR_0002_INVALID_RESOURCE", definitionPath)); // $NON-NLS-1$
        return null;
      }
      // create a dial definition from the XML definition
      widget = new DialWidgetDefinition(dialDefinition, 0, width, height, getSession());

      if (widget != null) {
        // set the value to be displayed on the dial
        widget.setValue(new Double(value));
      }
    }
    /*
     * else if( type == TYPE_THERMOMETER ) { // load the XML document that
     * defines the thermometer
     *
     * ActionResource resource = new ActionResource( title,
     * IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$
     * PentahoSystem.getApplicationContext().getSolutionPath( definitionPath ) );
     * //$NON-NLS-1$ Document thermometerDefinition = null; try {
     * thermometerDefinition = PentahoSystem.getResourceAsDocument( resource ); }
     * catch (IOException e) {} // create a dial definition from the XML
     * definition widget = createThermometer( thermometerDefinition );
     *
     * if( widget != null ) { // set the value to be displayed on the dial
     * widget.setValue( new Double(value) ); // Set the XSL file to be used
     * to generate the HTML setXsl( "text/html", "DialWidget.xsl" );
     * //$NON-NLS-1$ //$NON-NLS-2$ } else { error(
     * Messages.getInstance().getString("Widget.ERROR_0001_COULD_NOT_CREATE") );
     * //$NON-NLS-1$ return null; } }
     */
    if (widget == null) {
      error(Messages.getInstance().getString("Widget.ERROR_0001_COULD_NOT_CREATE")); // $NON-NLS-1$
      return null;
    }
    // create an image for the dial using the JFreeChart engine
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    // create temporary file names
    String solutionDir = "system/tmp/"; // $NON-NLS-1$
    String fileNamePrefix = "tmp_pie_"; // $NON-NLS-1$
    String extension = ".png"; // $NON-NLS-1$
    String fileName = null;
    String filePathWithoutExtension = null;
    try {
      File file =
          PentahoSystem.getApplicationContext()
              .createTempFile(getSession(), fileNamePrefix, extension, true);
      fileName = file.getName();
      filePathWithoutExtension = solutionDir + fileName.substring(0, fileName.indexOf('.'));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    String dialTitle = ""; // $NON-NLS-1$
    JFreeChartEngine.saveChart(
        widget,
        dialTitle,
        units,
        filePathWithoutExtension,
        width,
        height,
        JFreeChartEngine.OUTPUT_PNG,
        printWriter,
        this);

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    Element root = result.addElement("widget"); // $NON-NLS-1$
    root.addElement("title").setText(title); // $NON-NLS-1$
    root.addElement("units").setText(units); // $NON-NLS-1$
    root.addElement("width").setText(Integer.toString(width)); // $NON-NLS-1$
    root.addElement("height").setText(Integer.toString(height)); // $NON-NLS-1$
    Element valueNode = root.addElement("value"); // $NON-NLS-1$
    valueNode.setText(Double.toString(value));
    valueNode.addAttribute(
        "in-image", Boolean.toString(widget.getValueFont() != null)); // $NON-NLS-1$
    root.addElement("image").setText(fileName); // $NON-NLS-1$
    return result;
  }
  @VisibleForTesting
  protected boolean isPortUsedByServer(IDatabaseConnection databaseConnection) {
    // get connection IP address
    String connectionHostName = databaseConnection.getHostname();
    InetAddress connectionAddress = null;
    try {
      connectionAddress = getAdressFromString(connectionHostName);
    } catch (UnknownHostException e) {
      Logger.warn(
          this,
          Messages.getInstance()
              .getErrorString(
                  "DatasourceSystemListener.WARN_0001_UNABLE_TO_GET_CONNECTION_ADDRESS"),
          e); //$NON-NLS-1$
      return false;
    }
    // get connection port
    String stringConnectionPort = databaseConnection.getDatabasePort();

    // get server URL
    String fullyQualifiedServerURL =
        PentahoSystem.getApplicationContext().getFullyQualifiedServerURL();
    URL url = null;
    try {
      url = new URL(fullyQualifiedServerURL);
    } catch (MalformedURLException e) {
      Logger.warn(
          this,
          Messages.getInstance()
              .getErrorString("DatasourceSystemListener.WARN_0002_UNABLE_TO_PARSE_SERVER_URL"),
          e); //$NON-NLS-1$
      return false;
    }
    // get server IP address
    String hostNameUsedByServer = url.getHost();
    InetAddress serverAddress = null;
    try {
      serverAddress = getAdressFromString(hostNameUsedByServer);
    } catch (UnknownHostException e) {
      Logger.warn(
          this,
          Messages.getInstance()
              .getErrorString("DatasourceSystemListener.WARN_0003_UNABLE_TO_GET_SERVER_ADDRESS"),
          e); //$NON-NLS-1$
      return false;
    }
    // get server port
    int portUsedByServer = url.getPort();

    boolean isAddressesEquals = connectionAddress.equals(serverAddress);

    boolean isPortsEquals = false;
    try {
      Integer connectionPort = Integer.valueOf(stringConnectionPort);
      isPortsEquals = connectionPort.equals(portUsedByServer);
    } catch (NumberFormatException e) {
      Logger.warn(
          this,
          Messages.getInstance()
              .getErrorString("DatasourceSystemListener.WARN_0004_UNABLE_TO_GET_PORT_NUMBER"),
          e); //$NON-NLS-1$
      return false;
    }

    return isAddressesEquals && isPortsEquals;
  }
  public static int saveAnalysis(
      final IPentahoSession session,
      final HashMap props,
      final String path,
      String fileName,
      final boolean overwrite) {

    if ("true"
        .equals(
            PentahoSystem.getSystemSetting(
                "kiosk-mode", "false"))) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      throw new RuntimeException(
          Messages.getInstance()
              .getErrorString("ANALYSISSAVER.ERROR_0006_SAVE_IS_DISABLED")); // $NON-NLS-1$
    }

    int result = 0;
    try {
      AnalysisSaver.logger = LogFactory.getLog(AnalysisSaver.class);
      String baseUrl = PentahoSystem.getApplicationContext().getSolutionPath(""); // $NON-NLS-1$
      ISolutionRepository solutionRepository =
          PentahoSystem.get(ISolutionRepository.class, session);

      // We will (at this point in time) always have an original action sequence to start from...
      String originalActionReference = (String) props.get("actionreference"); // $NON-NLS-1$

      if (originalActionReference == null) {
        throw new MissingParameterException(
            Messages.getInstance()
                .getErrorString(
                    "ANALYSISSAVER.ERROR_0001_MISSING_ACTION_REFERENCE")); //$NON-NLS-1$
      }

      Document document = null;
      try {
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        reader.setEntityResolver(new SolutionURIResolver());
        document =
            reader.read(
                ActionSequenceResource.getInputStream(
                    originalActionReference, LocaleHelper.getLocale()));
      } catch (Throwable t) {
        // XML document can't be read. We'll just return a null document.
      }

      // Update the document with the stuff we passed in on the props
      document = AnalysisSaver.updateDocument(document, props);
      fileName =
          fileName.endsWith(AnalysisSaver.SUFFIX) ? fileName : fileName + AnalysisSaver.SUFFIX;
      result =
          solutionRepository.publish(
              baseUrl,
              path,
              fileName,
              document.asXML().getBytes(document.getXMLEncoding()),
              overwrite);

      // Now save the resource files
      ActionInfo actionInfo = ActionInfo.parseActionString(originalActionReference);
      String originalPath =
          actionInfo.getSolutionName() + "/" + actionInfo.getPath(); // $NON-NLS-1$
      String originalFileName = actionInfo.getActionName();
      originalFileName =
          originalFileName.substring(0, originalFileName.lastIndexOf(AnalysisSaver.SUFFIX));
      ISolutionFile[] parentFiles =
          solutionRepository
              .getSolutionFile(originalPath, ISolutionRepository.ACTION_EXECUTE)
              .listFiles();
      String baseFileName = fileName.substring(0, fileName.lastIndexOf(AnalysisSaver.SUFFIX));
      for (ISolutionFile aSolutionFile : parentFiles) {
        if (!aSolutionFile.isDirectory()
            && aSolutionFile.getFileName().startsWith(originalFileName)
            && aSolutionFile
                .getFileName()
                .toLowerCase()
                .endsWith(AnalysisSaver.PROPERTIES_SUFFIX)) {
          String newFileName =
              aSolutionFile.getFileName().replaceFirst(originalFileName, baseFileName);
          result =
              result
                  & solutionRepository.publish(
                      baseUrl, path, newFileName, aSolutionFile.getData(), overwrite);
        }
      }

      solutionRepository.resetRepository();
    } catch (Exception e) {
      AnalysisSaver.logger.error(
          Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0000_UNKNOWN"),
          e); //$NON-NLS-1$
      result = ISolutionRepository.FILE_ADD_FAILED;
    }

    return result;
  }
  public boolean compare(String testName, String extension) {

    InputStream goldenStream = null;
    InputStream tmpFileStream = null;

    String filePath =
        PentahoSystem.getApplicationContext()
            .getFileOutputPath("test/tmp/" + testName + extension); // $NON-NLS-1$
    try {
      File file = new File(filePath);
      tmpFileStream = new FileInputStream(file);
    } catch (Throwable e) {
      // this gets caught in the assert below
    }
    assertNotNull(
        Messages.getString("GenericTest.USER_TEST_FILE_INVALID", filePath),
        tmpFileStream); //$NON-NLS-1$

    filePath =
        PentahoSystem.getApplicationContext()
            .getFileOutputPath("test/golden/" + testName + extension); // $NON-NLS-1$
    try {
      File file = new File(filePath);
      goldenStream = new FileInputStream(file);
    } catch (Throwable e) {
      // this gets caught in the assert below
    }
    assertNotNull(
        Messages.getString("GenericTest.USER_TEST_FILE_INVALID", filePath),
        goldenStream); //$NON-NLS-1$

    // compare the two files

    int goldPos = 0;
    int tmpPos = 0;
    byte goldBuffer[] = new byte[2048];
    byte tmpBuffer[] = new byte[2048];
    int filePosition = 0;
    try {
      // read the start of both files
      goldPos = goldenStream.read(goldBuffer);
      tmpPos = tmpFileStream.read(tmpBuffer);
      // assume lock-step
      if (goldPos != tmpPos) {
        System.out.println(
            Messages.getString("GenericTest.USER_FILE_POINTERS_NOT_IN_STEP")); // $NON-NLS-1$
        return false;
      }
      while (goldPos > 0 && tmpPos > 0) {
        for (int index = 0; index < goldPos; index++) {
          assertEquals(
              Messages.getString(
                  "GenericTest.USER_FILES_DIFFER", Integer.toString(filePosition + index)),
              goldBuffer[index],
              tmpBuffer[index]); // $NON-NLS-1$
        }
        filePosition += goldPos;
        goldPos = goldenStream.read(goldBuffer);
        tmpPos = tmpFileStream.read(tmpBuffer);
      }
    } catch (Exception e) {
      return false;
    }
    return true;
  }
 public EmailConfigurationXml() throws Exception {
   this(
       new File(PentahoSystem.getApplicationContext().getSolutionPath(DEFAULT_EMAIL_CONFIG_PATH)));
 }
Example #16
0
  @Override
  public boolean startup(IPentahoSession session) {

    logger.info("Starting OSGI Environment");
    String solutionRootPath = PentahoSystem.getApplicationContext().getSolutionRootPath();

    final String sep = File.separator;
    Properties osgiProps = new Properties();
    File propsFile =
        new File(solutionRootPath + sep + "system" + sep + "osgi" + sep + "config.properties");
    if (propsFile.exists()) {
      try {
        osgiProps.load(new FileInputStream(propsFile));
      } catch (IOException e) {
        logger.error("Error reading OSGI Host config", e);
      }
    }

    Map<String, String> configProps = new HashMap<String, String>();

    for (Map.Entry<Object, Object> entry : osgiProps.entrySet()) {
      configProps.put(entry.getKey().toString(), entry.getValue().toString());
    }

    // configProps.put( FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, Collections.singletonList(new
    // org.pentaho.platform.osgi.PentahoOSGIActivator()) );
    configProps.put(Constants.FRAMEWORK_STORAGE, solutionRootPath + "/system/osgi/cache");
    System.setProperty("felix.fileinstall.dir", solutionRootPath + "/system/osgi/bundles");

    configProps.put("felix.fileinstall.debug", "4");
    configProps.put("felix.fileinstall.bundles.new.start", "true");
    configProps.put("felix.fileinstall.bundles.startActivationPolicy", "false");

    configProps.put("org.eclipse.virgo.kernel.home", solutionRootPath + "/osgi/virgo");
    configProps.put(
        "org.eclipse.virgo.kernel.config", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put(
        "osgi.sharedConfiguration.area", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put("osgi.configuration.area", solutionRootPath + "/osgi/virgo/configuration");
    configProps.put("osgi.install.area", solutionRootPath + "/osgi/virgo");
    configProps.put("eclipse.ignoreApp", "true");

    try {
      logger.debug("Attempting to load OSGI FrameworkFactory.");
      FrameworkFactory factory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
      logger.debug("FrameworkFactory found");
      framework = factory.newFramework(configProps);
      logger.debug("Initializing FrameworkFactory");
      framework.init();

      logger.debug("Starting FrameworkFactory");
      framework.start();

      Runtime.getRuntime()
          .addShutdownHook(
              new Thread("Felix Shutdown Hook") {
                public void run() {
                  shutdownFramework();
                }
              });

      List<Bundle> bundleList = new ArrayList<Bundle>();

      File[] bundleDirectories =
          new File[] {
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "core_bundles"),
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "fragment_bundles"),
            new File(
                solutionRootPath
                    + File.separator
                    + "system"
                    + File.separator
                    + "osgi"
                    + File.separator
                    + "bundles")
          };

      logger.debug("Installing bundles");
      for (File bundleDirectory : bundleDirectories) {
        if (bundleDirectory.exists() == false) {
          logger.warn("Bundle directory: " + bundleDirectory.getName() + " does not exist");
          continue;
        }
        for (File f : bundleDirectory.listFiles()) {
          if (f.isFile() && f.getName().endsWith(".jar")) {
            try {
              Bundle b = framework.getBundleContext().installBundle(f.toURI().toString());
              bundleList.add(b);
            } catch (Exception e) {
              logger.error("Error installing Bundle", e);
            }
          }
        }
      }

      logger.debug("Starting bundles");
      for (Bundle bundle : bundleList) {
        try {
          // detect if a fragment bundle and skip. They cannot be started..
          if (bundle.getHeaders().get("Fragment-Host") != null) {
            continue;
          }
          bundle.start();
        } catch (Exception e) {
          logger.error("Error installing Bundle", e);
        }
      }

      new PentahoOSGIActivator().setBundleContext(framework.getBundleContext());

      return true;
    } catch (Exception ex) {
      logger.error("Error starting OSGI environment", ex);
      return false;
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {

      String relativePath =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/relative-path",
              String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); // $NON-NLS-1$
      String maxFileLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-file-limit",
              String.valueOf(MAX_FILE_SIZE)); // $NON-NLS-1$
      String maxFolderLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-folder-limit",
              String.valueOf(MAX_FOLDER_SIZE)); // $NON-NLS-1$
      IPentahoSession session = PentahoHttpSessionHelper.getPentahoSession(request);

      response.setContentType("text/plain"); // $NON-NLS-1$

      FileItem uploadItem = getFileItem(request);
      if (uploadItem == null) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0001_NO_FILE_TO_UPLOAD"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }
      if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0003_FILE_TOO_BIG"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }

      String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);
      File pathDir = new File(path);
      // create the path if it doesn't exist yet
      if (!pathDir.exists()) {
        pathDir.mkdirs();
      }

      if (uploadItem.getSize() + getFolderSize(new File(path)) > Long.parseLong(maxFolderLimit)) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }

      String filename = request.getParameter("file_name"); // $NON-NLS-1$
      if (StringUtils.isEmpty(filename)) {
        filename = UUIDUtil.getUUID().toString();
      }

      String temporary = request.getParameter("mark_temporary"); // $NON-NLS-1$
      boolean isTemporary = false;
      if (temporary != null) {
        isTemporary = Boolean.valueOf(temporary);
      }

      File file;
      if (isTemporary) {
        file =
            PentahoSystem.getApplicationContext()
                .createTempFile(session, "", ".tmp", true); // $NON-NLS-1$
      } else {
        file = new File(path + File.separatorChar + filename);
      }

      FileOutputStream outputStream = new FileOutputStream(file);
      byte[] fileContents = uploadItem.get();
      outputStream.write(fileContents);
      outputStream.flush();
      outputStream.close();

      response.getWriter().write(file.getName());
    } catch (Exception e) {
      String error =
          Messages.getErrorString(
              "UploadFileDebugServlet.ERROR_0005_UNKNOWN_ERROR",
              e.getLocalizedMessage()); // $NON-NLS-1$
      response.getWriter().write(error);
    }
  }
  @Override
  public Document getXmlContent() {

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    String mapName = "chart" + AbstractChartComponent.chartCount++; // $NON-NLS-1$
    Document chartDefinition =
        jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);

    if (chartDefinition == null) {
      Element errorElement = result.addElement("error"); // $NON-NLS-1$
      errorElement
          .addElement("title")
          .setText(
              Messages.getInstance()
                  .getString(
                      "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
                                                                                     // //$NON-NLS-2$
      String message =
          Messages.getInstance()
              .getString(
                  "CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath); // $NON-NLS-1$
      errorElement.addElement("message").setText(message); // $NON-NLS-1$
      error(message);
      return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);

    if (dataDefinition == null) {
      Element errorElement = result.addElement("error"); // $NON-NLS-1$
      errorElement
          .addElement("title")
          .setText(
              Messages.getInstance()
                  .getString(
                      "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
                                                                                     // //$NON-NLS-2$
      String message =
          Messages.getInstance()
              .getString(
                  "CHARTS.ERROR_0002_CHART_DATA_MISSING",
                  actionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      errorElement.addElement("message").setText(message); // $NON-NLS-1$
      // System .out.println( result.asXML() );
      return result;
    }

    // create an image for the dial using the JFreeChart engine
    PrintWriter printWriter = new PrintWriter(new StringWriter());
    // we'll dispay the title in HTML so that the dial image does not have
    // to
    // accommodate it
    String chartTitle = ""; // $NON-NLS-1$
    try {
      if (width == -1) {
        width =
            Integer.parseInt(
                chartDefinition.selectSingleNode("/chart/width").getText()); // $NON-NLS-1$
      }
      if (height == -1) {
        height =
            Integer.parseInt(
                chartDefinition.selectSingleNode("/chart/height").getText()); // $NON-NLS-1$
      }
    } catch (Exception e) {
      // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME)
        != null) { //$NON-NLS-1$
      urlTemplate =
          chartDefinition
              .selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME)
              .getText(); //$NON-NLS-1$
    }

    if (chartDefinition.selectSingleNode("/chart/paramName") != null) { // $NON-NLS-1$
      paramName = chartDefinition.selectSingleNode("/chart/paramName").getText(); // $NON-NLS-1$
    }

    Element root = result.addElement("charts"); // $NON-NLS-1$
    TimeSeriesCollection chartDataDefinition = (TimeSeriesCollection) dataDefinition;
    if (chartDataDefinition.getSeriesCount() > 0) {
      // create temporary file names
      String[] tempFileInfo = createTempFile();
      String fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
      String filePathWithoutExtension =
          tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];

      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      JFreeChartEngine.saveChart(
          chartDataDefinition,
          chartTitle,
          "",
          filePathWithoutExtension,
          width,
          height,
          JFreeChartEngine.OUTPUT_PNG,
          printWriter,
          info,
          this); //$NON-NLS-1$
      applyOuterURLTemplateParam();
      populateInfo(info);
      Element chartElement = root.addElement("chart"); // $NON-NLS-1$
      chartElement.addElement("mapName").setText(mapName); // $NON-NLS-1$
      chartElement.addElement("width").setText(Integer.toString(width)); // $NON-NLS-1$
      chartElement.addElement("height").setText(Integer.toString(height)); // $NON-NLS-1$
      for (int row = 0; row < chartDataDefinition.getSeriesCount(); row++) {
        for (int column = 0; column < chartDataDefinition.getItemCount(row); column++) {
          Number value = chartDataDefinition.getY(row, column);
          Comparable rowKey = chartDataDefinition.getSeriesKey(row);
          RegularTimePeriod columnKey = chartDataDefinition.getSeries(row).getTimePeriod(column);
          Element valueElement = chartElement.addElement("value2D"); // $NON-NLS-1$
          valueElement.addElement("value").setText(value.toString()); // $NON-NLS-1$
          valueElement.addElement("row-key").setText(rowKey.toString()); // $NON-NLS-1$
          valueElement.addElement("column-key").setText(columnKey.toString()); // $NON-NLS-1$
        }
      }
      String mapString = ImageMapUtilities.getImageMap(mapName, info);
      chartElement.addElement("imageMap").setText(mapString); // $NON-NLS-1$
      chartElement.addElement("image").setText(fileName); // $NON-NLS-1$
    }
    return result;
  }
  protected Document createDials(
      final IPentahoResultSet resultSet, final WidgetDefinition widgetDefinition) {

    if (resultSet == null) {
      error(
          Messages.getInstance()
              .getErrorString("WidgetGrid.ERROR_0001_NO_RESULTS_FROM_ACTION")); // $NON-NLS-1$
      return null;
    }

    if (valueItem == null) {
      error(
          Messages.getInstance()
              .getErrorString("WidgetGrid.ERROR_0002_NO_VALUE_ITEM")); // $NON-NLS-1$
    }

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    Element root = result.addElement("widgets"); // $NON-NLS-1$

    IPentahoMetaData metaData = resultSet.getMetaData();
    // TODO support multiple column headers / row headers
    // TODO support an iteration across columns for a given row

    // find the column that we have been told to you
    Object[][] columnHeaders = metaData.getColumnHeaders();
    int nameColumnNo = -1;
    int valueColumnNo = -1;
    for (int idx = 0; idx < columnHeaders[0].length; idx++) {
      if (columnHeaders[0][idx].toString().equalsIgnoreCase(nameItem)) {
        nameColumnNo = idx;
      }
      if (columnHeaders[0][idx].toString().equalsIgnoreCase(valueItem)) {
        valueColumnNo = idx;
      }
    }

    if (nameColumnNo == -1) {
      // we did not find the specified name column
      error(
          Messages.getInstance()
              .getErrorString(
                  "WidgetGrid.ERROR_0004_NAME_COLUMN_MISSING", nameItem)); // $NON-NLS-1$
      return null;
    }

    if (valueColumnNo == -1) {
      // we did not find the specified name column
      error(
          Messages.getInstance()
              .getErrorString(
                  "WidgetGrid.ERROR_0005_VALUE_COLUMN_MISSING", valueItem)); // $NON-NLS-1$
      return null;
    }

    double value;
    String name;
    Object[] row = resultSet.next();
    while (row != null) {
      name = row[nameColumnNo].toString();
      try {
        value = Double.parseDouble(row[valueColumnNo].toString());
        createDial(value, name, root, widgetDefinition);
      } catch (Exception e) {
      }

      row = resultSet.next();
    }
    setXslProperty("urlTarget", "pentaho_popup"); // $NON-NLS-1$ //$NON-NLS-2$
    setXslProperty("columns", Integer.toString(columns)); // $NON-NLS-1$
    if (style != null) {
      setXslProperty("style", style); // $NON-NLS-1$
    }
    return result;
  }
  protected void createDial(
      final double value,
      final String name,
      final Element root,
      final WidgetDefinition widgetDefinition) {

    widgetDefinition.setValue(new Double(value));

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    // TODO get units from somewhere
    String units = ""; // $NON-NLS-1$
    String dialName = ""; // $NON-NLS-1$
    // create temporary file names
    String solutionDir = "system/tmp/"; // $NON-NLS-1$
    String fileNamePrefix = "tmp_pie_"; // $NON-NLS-1$
    String extension = ".png"; // $NON-NLS-1$
    String fileName = null;
    String filePathWithoutExtension = null;
    try {
      File file =
          PentahoSystem.getApplicationContext()
              .createTempFile(getSession(), fileNamePrefix, extension, true);
      fileName = file.getName();
      filePathWithoutExtension = solutionDir + fileName.substring(0, fileName.indexOf('.'));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    JFreeChartEngine.saveChart(
        widgetDefinition,
        dialName,
        units,
        filePathWithoutExtension,
        widgetWidth,
        widgetHeight,
        JFreeChartEngine.OUTPUT_PNG,
        printWriter,
        this);

    Element widgetNode = root.addElement("widget"); // $NON-NLS-1$

    widgetNode.addElement("title").setText(name); // $NON-NLS-1$
    widgetNode.addElement("units").setText(units); // $NON-NLS-1$
    widgetNode.addElement("width").setText(Integer.toString(widgetWidth)); // $NON-NLS-1$
    widgetNode.addElement("height").setText(Integer.toString(widgetHeight)); // $NON-NLS-1$
    Element valueNode = widgetNode.addElement("value"); // $NON-NLS-1$
    valueNode.setText(Double.toString(value));
    valueNode.addAttribute(
        "in-image", Boolean.toString(widgetDefinition.getValueFont() != null)); // $NON-NLS-1$
    root.addElement("image").setText(fileName); // $NON-NLS-1$
    widgetNode.addElement("image").setText(fileName); // $NON-NLS-1$

    // apply the current data item name to the URL template
    String drillUrl = TemplateUtil.applyTemplate(urlTemplate, nameItem, name);

    // now apply any parameters to the URL template
    drillUrl = TemplateUtil.applyTemplate(drillUrl, context);

    widgetNode.addElement("urlDrill").setText(drillUrl); // $NON-NLS-1$
  }
  @SuppressWarnings("deprecation")
  @Override
  protected boolean performExport(final MasterReport report, final OutputStream outputStream) {
    try {
      IContentRepository contentRepository = null;
      try {
        contentRepository = PentahoSystem.get(IContentRepository.class, getSession());
      } catch (Throwable t) {
        debug(
            Messages.getInstance()
                .getString("JFreeReportHtmlComponent.DEBUG_0044_PROCESSING_WITHOUT_CONTENT_REPOS"),
            t); //$NON-NLS-1$
      }

      String contentHandlerPattern =
          getInputStringValue(AbstractJFreeReportComponent.REPORTHTML_CONTENTHANDLER);
      if (contentHandlerPattern == null) {
        final Configuration globalConfig = ClassicEngineBoot.getInstance().getGlobalConfig();
        contentHandlerPattern =
            globalConfig.getConfigProperty("org.pentaho.web.ContentHandler"); // $NON-NLS-1$
      }

      final IApplicationContext ctx = PentahoSystem.getApplicationContext();

      final URLRewriter rewriter;
      final ContentLocation dataLocation;
      final NameGenerator dataNameGenerator;
      if ((contentRepository == null)
          || JFreeReportHtmlComponent.DO_NOT_USE_THE_CONTENT_REPOSITORY) {
        debug(
            Messages.getInstance()
                .getString(
                    "JFreeReportHtmlComponent.DEBUG_0044_PROCESSING_WITHOUT_CONTENT_REPOS")); //$NON-NLS-1$
        if (ctx != null) {
          File dataDirectory = new File(ctx.getFileOutputPath("system/tmp/")); // $NON-NLS-1$
          if (dataDirectory.exists() && (dataDirectory.isDirectory() == false)) {
            dataDirectory = dataDirectory.getParentFile();
            if (dataDirectory.isDirectory() == false) {
              throw new ReportProcessingException(
                  Messages.getInstance()
                      .getErrorString(
                          "JFreeReportDirectoryComponent.ERROR_0001_INVALID_DIR",
                          dataDirectory.getPath())); // $NON-NLS-1$
            }
          } else if (dataDirectory.exists() == false) {
            dataDirectory.mkdirs();
          }

          final FileRepository dataRepository = new FileRepository(dataDirectory);
          dataLocation = dataRepository.getRoot();
          dataNameGenerator = new DefaultNameGenerator(dataLocation);
          rewriter = new PentahoURLRewriter(contentHandlerPattern);
        } else {
          dataLocation = null;
          dataNameGenerator = null;
          rewriter = new PentahoURLRewriter(contentHandlerPattern);
        }
      } else {
        debug(
            Messages.getInstance()
                .getString(
                    "JFreeReportHtmlComponent.DEBUG_045_PROCESSING_WITH_CONTENT_REPOS")); //$NON-NLS-1$
        final String thePath =
            getSolutionName()
                + "/"
                + getSolutionPath()
                + "/"
                + getSession().getId(); // $NON-NLS-1$//$NON-NLS-2$
        final IContentLocation pentahoContentLocation =
            contentRepository.newContentLocation(
                thePath, getActionName(), getActionTitle(), getSolutionPath(), true);
        // todo
        final ReportContentRepository repository =
            new ReportContentRepository(pentahoContentLocation, getActionName());
        dataLocation = repository.getRoot();
        dataNameGenerator = new DefaultNameGenerator(dataLocation);
        rewriter = new PentahoURLRewriter(contentHandlerPattern);
      }

      final StreamRepository targetRepository = new StreamRepository(null, outputStream);
      final ContentLocation targetRoot = targetRepository.getRoot();

      final HtmlOutputProcessor outputProcessor =
          new StreamHtmlOutputProcessor(report.getConfiguration());
      final HtmlPrinter printer = new AllItemsHtmlPrinter(report.getResourceManager());
      printer.setContentWriter(
          targetRoot,
          new DefaultNameGenerator(targetRoot, "index", "html")); // $NON-NLS-1$//$NON-NLS-2$
      printer.setDataWriter(dataLocation, dataNameGenerator);
      printer.setUrlRewriter(rewriter);
      outputProcessor.setPrinter(printer);

      final StreamReportProcessor sp = new StreamReportProcessor(report, outputProcessor);
      final int yieldRate = getYieldRate();
      if (yieldRate > 0) {
        sp.addReportProgressListener(new YieldReportListener(yieldRate));
      }
      sp.processReport();
      sp.close();

      outputStream.flush();
      close();
      return true;
    } catch (ReportProcessingException e) {
      error(
          Messages.getInstance()
              .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"),
          e); //$NON-NLS-1$
      return false;
    } catch (IOException e) {
      error(
          Messages.getInstance()
              .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"),
          e); //$NON-NLS-1$
      return false;
    } catch (ContentIOException e) {
      error(
          Messages.getInstance()
              .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"),
          e); //$NON-NLS-1$
      return false;
    }
  }