protected void makeAuditRecord(
     final float time, final String messageType, final JobExecutionContext jobExecutionContext) {
   if (jobExecutionContext != null && jobExecutionContext.getJobDetail() != null) {
     final JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
     AuditHelper.audit(
         PentahoSessionHolder.getSession() != null
             ? PentahoSessionHolder.getSession().getId()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER).toString()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER).toString()
             : null,
         jobExecutionContext.getJobDetail().getJobClass() != null
             ? jobExecutionContext.getJobDetail().getJobClass().getName()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID).toString()
             : null,
         messageType,
         jobDataMap.get("lineage-id") != null ? jobDataMap.get("lineage-id").toString() : null,
         null,
         time,
         null); //$NON-NLS-1$
   }
 }
  /**
   * Encapsulates the logic of registering import handlers, generating the manifest, and performing
   * the export
   */
  public ZipExportProcessor(String path, IUnifiedRepository repository, boolean withManifest) {
    this.withManifest = withManifest;

    // set a default path at root if missing
    if (StringUtils.isEmpty(path)) {
      this.path = "/";
    } else {
      this.path = path;
    }

    this.unifiedRepository = repository;

    this.exportHandlerList = new ArrayList<ExportHandler>();

    this.exportManifest = new ExportManifest();

    // set created by and create date in manifest information
    IPentahoSession session = PentahoSessionHolder.getSession();

    Date todaysDate = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(EXPORT_INFO_DATE_FORMAT);
    SimpleDateFormat timeFormat = new SimpleDateFormat(EXPORT_INFO_TIME_FORMAT);

    exportManifest.getManifestInformation().setExportBy(session.getName());
    exportManifest
        .getManifestInformation()
        .setExportDate(dateFormat.format(todaysDate) + " " + timeFormat.format(todaysDate));
  }
 protected String assembleRole(String catalog) {
   try {
     final IConnectionUserRoleMapper mondrianUserRoleMapper =
         PentahoSystem.get(IConnectionUserRoleMapper.class, "Mondrian-UserRoleMapper", null);
     if (mondrianUserRoleMapper != null) {}
     final String[] validMondrianRolesForUser =
         mondrianUserRoleMapper.mapConnectionRoles(
             PentahoSessionHolder.getSession(), "solution:" + catalog.replaceAll("solution/", ""));
     if ((validMondrianRolesForUser != null) && (validMondrianRolesForUser.length > 0)) {
       final StringBuffer buff = new StringBuffer();
       for (int i = 0; i < validMondrianRolesForUser.length; i++) {
         final String aRole = validMondrianRolesForUser[i];
         // According to http://mondrian.pentaho.org/documentation/configuration.php
         // double-comma escapes a comma
         if (i > 0) {
           buff.append(",");
         }
         buff.append(aRole.replaceAll(",", ",,"));
       }
       return buff.toString();
     } else {
       return "";
     }
   } catch (Exception e) {
     return "";
   }
 }
  public static MasterReport createReport(final Serializable fileId)
      throws ResourceException, IOException {
    final ResourceManager resourceManager = new ResourceManager();
    resourceManager.registerDefaults();
    final HashMap helperObjects = new HashMap();
    // add the runtime context so that PentahoResourceData class can get access
    // to the solution repo

    ResourceKey key = null;

    IUnifiedRepository unifiedRepository =
        PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession());
    RepositoryFile repositoryFile = unifiedRepository.getFileById(fileId);
    if (repositoryFile != null) {
      key =
          resourceManager.createKey(
              RepositoryResourceLoader.SOLUTION_SCHEMA_NAME
                  + RepositoryResourceLoader.SCHEMA_SEPARATOR
                  + repositoryFile.getPath(),
              helperObjects);
    } else {
      key =
          resourceManager.createKey(
              RepositoryResourceLoader.SOLUTION_SCHEMA_NAME
                  + RepositoryResourceLoader.SCHEMA_SEPARATOR
                  + fileId,
              helperObjects);
    }

    final Resource resource = resourceManager.create(key, null, MasterReport.class);
    return (MasterReport) resource.getResource();
  }
  public static void mapPlatformRolesToMondrianRolesHelper(Util.PropertyList properties)
      throws PentahoAccessControlException {
    if (properties.get(RolapConnectionProperties.Role.name(), null) == null) {
      // Only if the action sequence/requester hasn't already injected a role in here do this.

      if (PentahoSystem.getObjectFactory().objectDefined(MDXConnection.MDX_CONNECTION_MAPPER_KEY)) {
        IConnectionUserRoleMapper mondrianUserRoleMapper =
            PentahoSystem.get(
                IConnectionUserRoleMapper.class, MDXConnection.MDX_CONNECTION_MAPPER_KEY, null);
        if (mondrianUserRoleMapper != null) {
          // Do role mapping
          String[] validMondrianRolesForUser =
              mondrianUserRoleMapper.mapConnectionRoles(
                  PentahoSessionHolder.getSession(),
                  properties.get(RolapConnectionProperties.Catalog.name()));
          if ((validMondrianRolesForUser != null) && (validMondrianRolesForUser.length > 0)) {
            StringBuffer buff = new StringBuffer();
            String aRole = null;
            for (int i = 0; i < validMondrianRolesForUser.length; i++) {
              aRole = validMondrianRolesForUser[i];
              // According to http://mondrian.pentaho.org/documentation/configuration.php
              // double-comma escapes a comma
              if (i > 0) {
                buff.append(","); // $NON-NLS-1$
              }
              buff.append(aRole.replaceAll(",", ",,")); // $NON-NLS-1$//$NON-NLS-2$
            }
            properties.put(RolapConnectionProperties.Role.name(), buff.toString());
          }
        }
      }
    }
  }
Esempio n. 6
0
  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();
  }
  private static String callPlugin(
      final String pluginName, final String method, final Map<String, Object> parameters)
      throws ReportDataFactoryException {

    final IPentahoSession userSession = PentahoSessionHolder.getSession();
    final IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, userSession);

    try {
      Object cdaBean = pluginManager.getBean("cda.api");
      Class cdaBeanClass = cdaBean.getClass();

      Class[] paramTypes;
      Object[] paramValues;
      Method m;
      final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      if ("listParameters".equals(method)) {
        IParameterProvider params = new SimpleParameterProvider(parameters);

        paramTypes =
            new Class[] {
              String.class,
              String.class,
              String.class,
              String.class,
              String.class,
              HttpServletResponse.class,
              HttpServletRequest.class
            };
        m = cdaBeanClass.getMethod("listParameters", paramTypes);
        paramValues = new Object[7];
        paramValues[0] = params.getStringParameter("path", null);
        paramValues[1] = params.getStringParameter("solution", "");
        paramValues[2] = params.getStringParameter("file", "");
        paramValues[3] = params.getStringParameter("outputType", "json");
        paramValues[4] = params.getStringParameter("dataAccessId", "<blank>");
        paramValues[5] = getResponse(outputStream);
        paramValues[6] = getRequest(parameters);

        m.invoke(cdaBean, paramValues);

        return outputStream.toString();

      } else {
        paramTypes = new Class[] {HttpServletRequest.class};
        m = cdaBeanClass.getMethod("doQueryInterPlugin", paramTypes);

        paramValues = new Object[1];
        paramValues[0] = getRequest(parameters);

        return (String) m.invoke(cdaBean, paramValues);
      }

    } catch (Exception e) {
      throw new ReportDataFactoryException("Failed to acquire " + pluginName + " plugin: ", e);
    }
  }
 /**
  * Creates and/or returns an internal folder called {@code .trash} located just below the user's
  * home folder.
  */
 private Node getOrCreateTrashInternalFolderNode(
     final Session session, final PentahoJcrConstants pentahoJcrConstants)
     throws RepositoryException {
   IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
   String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY);
   Node userHomeFolderNode =
       (Node)
           session.getItem(
               ServerRepositoryPaths.getUserHomeFolderPath(
                   new Tenant(tenantId, true),
                   JcrStringHelper.fileNameEncode(PentahoSessionHolder.getSession().getName())));
   if (userHomeFolderNode.hasNode(FOLDER_NAME_TRASH)) {
     return userHomeFolderNode.getNode(FOLDER_NAME_TRASH);
   } else {
     return userHomeFolderNode.addNode(
         FOLDER_NAME_TRASH, pentahoJcrConstants.getPHO_NT_INTERNALFOLDER());
   }
 }
 @Override
 public void createContent() throws Exception {
   this.session = PentahoSessionHolder.getSession();
   this.repository = PentahoSystem.get(IUnifiedRepository.class, session);
   final RepositoryFile BIRTfile =
       (RepositoryFile) parameterProviders.get("path").getParameter("file");
   final String ExecBIRTFilePath = "../webapps/birt/" + BIRTfile.getId() + ".rptdocument";
   /*
    * Get BIRT report design from repository
    */
   final File ExecBIRTFile = new File(ExecBIRTFilePath);
   if (!ExecBIRTFile.exists()) {
     final FileOutputStream fos = new FileOutputStream(ExecBIRTFilePath);
     try {
       final SimpleRepositoryFileData data =
           repository.getDataForRead(BIRTfile.getId(), SimpleRepositoryFileData.class);
       final InputStream inputStream = data.getInputStream();
       final byte[] buffer = new byte[0x1000];
       int bytesRead = inputStream.read(buffer);
       while (bytesRead >= 0) {
         fos.write(buffer, 0, bytesRead);
         bytesRead = inputStream.read(buffer);
       }
     } catch (final Exception e) {
       Logger.error(getClass().getName(), e.getMessage());
     } finally {
       fos.close();
     }
   }
   /*
    * Redirect to BIRT Viewer
    */
   try {
     // Get informations about user context
     final IUserRoleListService service = PentahoSystem.get(IUserRoleListService.class);
     String roles = "";
     final ListIterator<String> li =
         service.getRolesForUser(null, session.getName()).listIterator();
     while (li.hasNext()) {
       roles = roles + li.next().toString() + ",";
     }
     // Redirect
     final HttpServletResponse response =
         (HttpServletResponse) this.parameterProviders.get("path").getParameter("httpresponse");
     response.sendRedirect(
         "/birt/frameset?__document="
             + BIRTfile.getId()
             + ".rptdocument&__showtitle=false&username="******"&userroles="
             + roles
             + "&reportname="
             + BIRTfile.getTitle());
   } catch (final Exception e) {
     Logger.error(getClass().getName(), e.getMessage());
   }
 }
 public static MasterReport createReportByName(final String fullFilePathAndName)
     throws ResourceException, IOException {
   IUnifiedRepository unifiedRepository =
       PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession());
   RepositoryFile repositoryFile = unifiedRepository.getFile(fullFilePathAndName);
   if (repositoryFile == null) {
     throw new IOException("File " + fullFilePathAndName + " not found in repository");
   } else {
     return createReport(repositoryFile.getId());
   }
 }
 /**
  * @return the {@link IBackingRepositoryLifecycleManager} that this instance will use. If none has
  *     been specified, it will default to getting the information from {@link PentahoSystem.get()}
  */
 public ITenantManager getTenantManager() {
   // Check ... if we haven't been injected with a lifecycle manager, get one from PentahoSystem
   try {
     IPentahoObjectFactory objectFactory = PentahoSystem.getObjectFactory();
     IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
     return (null != tenantManager
         ? tenantManager
         : objectFactory.get(ITenantManager.class, "tenantMgrProxy", pentahoSession));
   } catch (ObjectFactoryException e) {
     return null;
   }
 }
  @Override
  public Set<String> getDomainIds() {
    final IPentahoSession session = PentahoSessionHolder.getSession();

    final String domainKey = generateDomainIdCacheKeyForSession(session);
    Set<String> domainIds = (Set<String>) cacheManager.getFromRegionCache(CACHE_REGION, domainKey);
    if (domainIds != null) {
      // We've previously cached domainIds available for this session
      return domainIds;
    }
    // Domains are accessible by anyone. What they contain may be different so rely on the lookup to
    // be
    // session-specific.
    domainIds = delegate.getDomainIds();
    cacheManager.putInRegionCache(CACHE_REGION, domainKey, new HashSet<String>(domainIds));
    return domainIds;
  }
Esempio n. 13
0
  public MobileDashboard(
      IParameterProvider pathParams, DashboardDesignerContentGenerator generator) {
    super(pathParams, generator);
    IPentahoSession userSession = PentahoSessionHolder.getSession();
    final ISolutionRepository solutionRepository =
        PentahoSystem.get(ISolutionRepository.class, userSession);

    final String absRoot =
        pathParams.hasParameter("root")
            ? !pathParams.getParameter("root").toString().isEmpty()
                ? "http://" + pathParams.getParameter("root").toString()
                : ""
            : "";
    final boolean absolute =
        (!absRoot.isEmpty())
            || pathParams.hasParameter("absolute")
                && pathParams.getParameter("absolute").equals("true");

    final RenderMobileLayout layoutRenderer = new RenderMobileLayout();
    final RenderComponents componentsRenderer = new RenderComponents();

    try {
      final JSONObject json =
          (JSONObject)
              JsonUtils.readJsonFromInputStream(
                  solutionRepository.getResourceInputStream(dashboardLocation, true));

      json.put("settings", getWcdf().toJSON());
      final JXPathContext doc = JXPathContext.newContext(json);

      final StringBuilder dashboardBody = new StringBuilder();

      dashboardBody.append(layoutRenderer.render(doc));
      dashboardBody.append(componentsRenderer.render(doc));

      // set all dashboard members
      this.content = replaceTokens(dashboardBody.toString(), absolute, absRoot);

      this.header = renderHeaders(pathParams, this.content.toString());
      this.loaded = new Date();
    } catch (Exception e) {
      logger.error(e);
    }
  }
Esempio n. 14
0
  @SuppressWarnings("rawtypes")
  public static void createOutputFileName(RepositoryFile file, IOutputHandler outputHandler) {
    IPentahoSession userSession = PentahoSessionHolder.getSession();
    ActionSequenceJCRHelper actionHelper = new ActionSequenceJCRHelper(userSession);
    IActionSequence actionSequence =
        actionHelper.getActionSequence(
            file.getPath(), PentahoSystem.loggingLevel, RepositoryFilePermission.READ);

    String fileName = "content"; // $NON-NLS-1$
    if (actionSequence != null) {
      String title = actionSequence.getTitle();
      if ((title != null) && (title.length() > 0)) {
        fileName = title;
      } else {
        String sequenceName = actionSequence.getSequenceName();

        if ((sequenceName != null) && (sequenceName.length() > 0)) {
          fileName = sequenceName;
        } else {
          List actionDefinitionsList = actionSequence.getActionDefinitionsAndSequences();
          int i = 0;
          boolean done = false;

          while ((actionDefinitionsList.size() > i) && (!done)) {
            IActionDefinition actionDefinition = (IActionDefinition) actionDefinitionsList.get(i);
            String componentName = actionDefinition.getComponentName();
            if ((componentName != null) && (componentName.length() > 0)) {
              fileName = componentName;
              done = true;
            } else {
              ++i;
            }
          }
        }
      }
    }
    IMimeTypeListener mimeTypeListener = outputHandler.getMimeTypeListener();
    if (mimeTypeListener != null) {
      mimeTypeListener.setName(fileName);
    }
  }
Esempio n. 15
0
  public static String postExecute(
      IRuntimeContext runtime,
      boolean debugMessages,
      boolean doWrapper,
      IOutputHandler outputHandler,
      Map<String, IParameterProvider> parameterProviders,
      HttpServletRequest request,
      HttpServletResponse response,
      List<?> messages)
      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);
      }
    }
    return buffer.toString();
  }
 @Override
 public Domain getDomain(final String id) {
   final IPentahoSession session = PentahoSessionHolder.getSession();
   final CacheKey key = new CacheKey(session.getId(), id);
   Domain domain = (Domain) cacheManager.getFromRegionCache(CACHE_REGION, key);
   if (domain != null) {
     if (logger.isDebugEnabled()) {
       logger.debug("Found domain in cache: " + key); // $NON-NLS-1$
     }
     return domain;
   }
   domain = delegate.getDomain(id);
   if (domain != null) {
     SecurityHelper helper = new SecurityHelper();
     domain = helper.createSecureDomain(this, domain);
     // cache domain with the key we used to look it up, not whatever new id it might have now
     if (logger.isDebugEnabled()) {
       logger.debug("Caching domain by session: " + key); // $NON-NLS-1$
     }
     cacheManager.putInRegionCache(CACHE_REGION, key, domain);
   }
   return domain;
 }
Esempio n. 17
0
 private String getUserName() {
   return PentahoSessionHolder.getSession().getName();
 }
Esempio n. 18
0
 protected IPentahoSession getPentahoSession(final HttpServletRequest request) {
   return PentahoSessionHolder.getSession();
 }
 private IPentahoSession getPentahoSession() {
   return PentahoSessionHolder.getSession();
 }
  /** {@inheritDoc} */
  public void permanentlyDeleteFile(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId)
      throws RepositoryException {
    Assert.notNull(fileId);
    Node fileNode = session.getNodeByIdentifier(fileId.toString());
    // guard against using a file retrieved from a more lenient session inside a more strict session
    Assert.notNull(fileNode);

    // see if anything is referencing this node; if yes, then we cannot delete it as a
    // ReferentialIntegrityException
    // will result
    Set<RepositoryFile> referrers = new HashSet<RepositoryFile>();
    PropertyIterator refIter = fileNode.getReferences();
    if (refIter.hasNext()) {
      while (refIter.hasNext()) {
        // for each referrer property, march up the tree until we find the file node to which the
        // property belongs
        RepositoryFile referrer =
            getReferrerFile(session, pentahoJcrConstants, refIter.nextProperty());
        if (referrer != null) {
          referrers.add(referrer);
        }
      }
      if (!referrers.isEmpty()) {
        RepositoryFile referee =
            JcrRepositoryFileUtils.nodeToFile(
                session, pentahoJcrConstants, pathConversionHelper, lockHelper, fileNode);
        throw new RepositoryFileDaoReferentialIntegrityException(referee, referrers);
      }
    }

    // technically, the node can be deleted while it is locked; however, we want to avoid an
    // orphaned lock token;
    // delete
    // it first
    if (fileNode.isLocked()) {
      Lock lock = session.getWorkspace().getLockManager().getLock(fileNode.getPath());
      // don't need lock token anymore
      lockHelper.removeLockToken(session, pentahoJcrConstants, lock);
    }

    // if this file was non-permanently deleted, delete its containing folder too
    IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
    String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY);
    String trashFolder =
        ServerRepositoryPaths.getUserHomeFolderPath(
                new Tenant(tenantId, true), PentahoSessionHolder.getSession().getName())
            + RepositoryFile.SEPARATOR
            + FOLDER_NAME_TRASH;
    Node parent = fileNode.getParent();

    purgeHistory(fileNode, session, pentahoJcrConstants);

    if (fileNode.getPath().startsWith(trashFolder)) {
      // Remove the file and then the wrapper foler
      fileNode.remove();
      parent.remove();
    } else {
      fileNode.remove();
    }
  }
Esempio n. 21
0
  public Dashboard loadDashboard(
      String wcdfPath,
      boolean debug,
      boolean absolute,
      String scheme,
      String absRoot,
      boolean bypassCache,
      String alias)
      throws FileNotFoundException {

    String dashboardPath = getDashboardPath(wcdfPath);
    IPentahoSession userSession = PentahoSessionHolder.getSession();
    XmlStructure structure = new XmlStructure(userSession);
    Dashboard dashboard = null;
    WcdfDescriptor wcdf = null;
    DashboardCacheKey key;
    /*
     * First we must figure out what dashboard we should
     * be handling. We do this by loading up its wcdf
     * descriptor.
     */
    try {
      if (!wcdfPath.isEmpty() && wcdfPath.endsWith(".wcdf")) {
        wcdf = structure.loadWcdfDescriptor(wcdfPath);
      } else {
        /* We didn't receive a valid path. We're in preview mode.
         * TODO: Support mobile preview mode (must remove dependency on setStyle())
         */
        wcdf = new WcdfDescriptor();
        if (wcdfPath != null && wcdfPath.endsWith(".cdfde")) {
          wcdf.setWcdfPath(wcdfPath);
        }
        wcdf.setStyle(CdfStyles.DEFAULTSTYLE);
        wcdf.setRendererType(Renderers.BLUEPRINT.toString());
        bypassCache = true; // no cache for preview
      }
    } catch (IOException ioe) {
      logger.error(ioe);
      return null;
    }

    /* Next, if we're using the cache, we try to find
     * the dashboard in there.
     */
    key =
        new DashboardCacheKey(
            dashboardPath, CdfStyles.getInstance().getResourceLocation(wcdf.getStyle()), debug);
    key.setAbs(absolute);
    key.setRoot(scheme, absRoot);
    if (!bypassCache) {
      dashboard = getDashboardFromCache(key);
    }

    /* If it's not there, or we're bypassing the cache,
     * we load it up, and cache the newly loaded dashboard.
     */
    if (dashboard == null) {
      Cache cache = getCache();
      try {
        switch (Renderers.valueOf(wcdf.getRendererType().toUpperCase())) {
          case MOBILE:
            dashboard = new MobileDashboard(wcdf, absolute, absRoot, debug, scheme);
            break;

            /* Until we consider it safe to assume that all dashboards have
             * their renderer type correctly identified, we'll have to default
             * to assuming they're blueprint-style dashboards.
             */
          case BLUEPRINT:
          default:
            if (wcdf.isWidget()) {
              dashboard = new BlueprintWidget(wcdf, absolute, absRoot, debug, scheme, alias);
            } else {
              dashboard = new BlueprintDashboard(wcdf, absolute, absRoot, debug, scheme);
            }
            break;
        }
      } catch (IllegalArgumentException e) {
        logger.error("Bad renderer type: " + wcdf.getRendererType());
        return null;
      }
      cache.put(new Element(key, dashboard));
    }
    return dashboard;
  }
 Map<String, String> getTranslationMap() {
   return PentahoSystem.get(
       Map.class, "jdbcDriverTranslationMap", PentahoSessionHolder.getSession());
 }
 private ITenant getDefaultTenant() {
   IPentahoSession session = PentahoSessionHolder.getSession();
   String tenantId = (String) session.getAttribute(IPentahoSession.TENANT_ID_KEY);
   return new Tenant(tenantId, true);
 }
/** @author Rowell Belen */
public class SchedulerOutputPathResolver {

  final String DEFAULT_SETTING_KEY = "default-scheduler-output-path";

  private static final Log logger = LogFactory.getLog(SchedulerOutputPathResolver.class);

  private IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class);
  private IPentahoSession pentahoSession = PentahoSessionHolder.getSession();

  private IUserSettingService getSettingsService() {
    if (settingsService == null) {
      settingsService = PentahoSystem.get(IUserSettingService.class, pentahoSession);
    }
    return settingsService;
  }

  private IUserSettingService settingsService;
  private JobScheduleRequest scheduleRequest;

  public SchedulerOutputPathResolver(JobScheduleRequest scheduleRequest) {
    this.scheduleRequest = scheduleRequest;
  }

  public String resolveOutputFilePath() {

    String fileName =
        RepositoryFilenameUtils.getBaseName(scheduleRequest.getInputFile()); // default file name
    if (!StringUtils.isEmpty(scheduleRequest.getJobName())) {
      fileName = scheduleRequest.getJobName(); // use job name as file name if exists
    }
    String fileNamePattern = "/" + fileName + ".*";

    String outputFilePath = scheduleRequest.getOutputFile();
    if (StringUtils.isNotBlank(outputFilePath) && isValidOutputPath(outputFilePath)) {
      return outputFilePath + fileNamePattern; // return if valid
    }

    // evaluate fallback output paths
    String[] fallBackPaths =
        new String[] {
          getUserSettingOutputPath(), // user setting
          getSystemSettingOutputPath(), // system setting
          getUserHomeDirectoryPath() // home directory
        };

    for (String path : fallBackPaths) {
      if (StringUtils.isNotBlank(path) && isValidOutputPath(path)) {
        return path + fileNamePattern; // return the first valid path
      }
    }

    return null; // it should never reach here
  }

  private boolean isValidOutputPath(String path) {
    try {
      RepositoryFile repoFile = repository.getFile(path);
      if (repoFile != null && repoFile.isFolder()) {
        return true;
      }
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    }
    return false;
  }

  private String getUserSettingOutputPath() {
    try {
      IUserSetting userSetting = getSettingsService().getUserSetting(DEFAULT_SETTING_KEY, null);
      if (userSetting != null && StringUtils.isNotBlank(userSetting.getSettingValue())) {
        return userSetting.getSettingValue();
      }
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    }
    return null;
  }

  private String getSystemSettingOutputPath() {
    try {
      return PentahoSystem.getSystemSettings().getSystemSetting(DEFAULT_SETTING_KEY, null);
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    }
    return null;
  }

  private String getUserHomeDirectoryPath() {
    try {
      return ClientRepositoryPaths.getUserHomeFolderPath(pentahoSession.getName());
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    }
    return null;
  }
}
 static {
   IPentahoSession session = PentahoSessionHolder.getSession();
   datasourceMgmtSvc = PentahoSystem.get(IDatasourceMgmtService.class, session);
 }