コード例 #1
0
ファイル: MobileDashboard.java プロジェクト: mileidysg/cde
  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);
    }
  }
コード例 #2
0
ファイル: DashboardContext.java プロジェクト: kolinus/cdf
  public String getContext(IParameterProvider requestParams) {
    try {
      String solution = requestParams.getStringParameter("solution", ""),
          path = requestParams.getStringParameter("path", ""),
          // Fix #29. Because there is no file parameter in CDF, but action parameter
          // file parameter is used in CDE
          file =
              requestParams.getStringParameter(
                  "file", requestParams.getStringParameter("action", "")),
          fullPath = ("/" + solution + "/" + path + "/" + file).replaceAll("/+", "/");
      final JSONObject context = new JSONObject();
      Calendar cal = Calendar.getInstance();

      Document config = getConfigFile();

      context.put("queryData", processAutoIncludes(fullPath, config));
      context.put("sessionAttributes", processSessionAttributes(config));

      context.put("serverLocalDate", cal.getTimeInMillis());
      context.put("serverUTCDate", cal.getTimeInMillis() + cal.getTimeZone().getRawOffset());
      context.put("user", userSession.getName());
      context.put("locale", userSession.getLocale());
      context.put("solution", solution);
      context.put("path", path);
      context.put("file", file);
      context.put("fullPath", fullPath);

      SecurityParameterProvider securityParams = new SecurityParameterProvider(userSession);
      context.put("roles", securityParams.getParameter("principalRoles"));

      JSONObject params = new JSONObject();

      Iterator it = requestParams.getParameterNames();
      while (it.hasNext()) {
        String p = (String) it.next();
        if (p.indexOf("param") == 0) {
          params.put(p.substring(5), requestParams.getParameter(p));
        }
      }
      context.put("params", params);

      final StringBuilder s = new StringBuilder();
      s.append("\n<script language=\"javascript\" type=\"text/javascript\">\n");
      s.append("  Dashboards.context = ");
      s.append(context.toString(2) + "\n");
      s.append("</script>\n");
      // setResponseHeaders(MIME_PLAIN,0,null);
      logger.info(
          "[Timing] Finished building context: "
              + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));

      return s.toString();
    } catch (JSONException e) {
      return "";
    }
  }
コード例 #3
0
ファイル: DashboardFactory.java プロジェクト: eliassouza/cde
  public Dashboard loadDashboard(Map<String, IParameterProvider> params)
      throws FileNotFoundException {
    IParameterProvider pathParams = params.get("path"), requestParams = params.get("request");
    String scheme =
        requestParams.hasParameter("inferScheme")
                && requestParams.getParameter("inferScheme").equals("false")
            ? ""
            : DashboardDesignerContentGenerator.getScheme(pathParams);
    String root = requestParams.getStringParameter("root", "");
    boolean
        absolute =
            (!root.equals(""))
                || requestParams.hasParameter("absolute")
                    && requestParams.getParameter("absolute").equals("true"),
        bypassCache =
            requestParams.hasParameter("bypassCache")
                && requestParams.getParameter("bypassCache").equals("true");
    final boolean debug =
        requestParams.hasParameter("debug") && requestParams.getParameter("debug").equals("true");

    String wcdfPath = getWcdfPath(requestParams);
    return loadDashboard(wcdfPath, debug, absolute, scheme, root, bypassCache, "");
  }
  public void createReportContent(
      final OutputStream outputStream,
      final Serializable fileId,
      final String path,
      final boolean forceDefaultOutputTarget)
      throws Exception {
    final long start = System.currentTimeMillis();
    final Map<String, Object> inputs = contentGenerator.createInputs();

    AuditHelper.audit(
        userSession.getId(),
        userSession.getName(),
        path,
        contentGenerator.getObjectName(),
        getClass().getName(),
        MessageTypes.INSTANCE_START,
        contentGenerator.getInstanceId(),
        "",
        0,
        contentGenerator); //$NON-NLS-1$

    String result = MessageTypes.INSTANCE_END;
    StagingHandler reportStagingHandler = null;
    try {
      final Object rawSessionId = inputs.get(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID);
      if ((rawSessionId instanceof String) == false || "".equals(rawSessionId)) {
        inputs.put(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID, UUIDUtil.getUUIDAsString());
      }

      // produce rendered report
      final SimpleReportingComponent reportComponent = new SimpleReportingComponent();
      reportComponent.setReportFileId(fileId);
      reportComponent.setPaginateOutput(true);
      reportComponent.setForceDefaultOutputTarget(forceDefaultOutputTarget);
      reportComponent.setDefaultOutputTarget(HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE);
      if (path.endsWith(".prpti")) {
        reportComponent.setForceUnlockPreferredOutput(true);
      }
      reportComponent.setInputs(inputs);

      final MasterReport report = reportComponent.getReport();
      final StagingMode stagingMode = getStagingMode(inputs, report);
      reportStagingHandler = new StagingHandler(outputStream, stagingMode, this.userSession);

      if (reportStagingHandler.isFullyBuffered()) {
        // it is safe to disable the buffered writing for the report now that we have a
        // extra buffering in place.
        report.getReportConfiguration().setConfigProperty(FORCED_BUFFERED_WRITING, "false");
      }

      reportComponent.setOutputStream(reportStagingHandler.getStagingOutputStream());

      // the requested mime type can be null, in that case the report-component will resolve the
      // desired
      // type from the output-target.
      // Hoever, the report-component will inspect the inputs independently from the mimetype here.

      final IUnifiedRepository repository =
          PentahoSystem.get(IUnifiedRepository.class, userSession);
      final RepositoryFile file = repository.getFileById(fileId);

      // add all inputs (request parameters) to report component
      final String mimeType = reportComponent.getMimeType();

      // If we haven't set an accepted page, -1 will be the default, which will give us a report
      // with no pages. This default is used so that when we do our parameter interaction with the
      // engine we can spend as little time as possible rendering unused pages, making it no pages.
      // We are going to intentionally reset the accepted page to the first page, 0, at this point,
      // if the accepted page is -1.
      final String outputTarget = reportComponent.getComputedOutputTarget();
      if (HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE.equals(outputTarget)
          && reportComponent.getAcceptedPage() < 0) {
        reportComponent.setAcceptedPage(0);
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            Messages.getInstance()
                .getString(
                    "ReportPlugin.logStartGenerateContent",
                    mimeType, //$NON-NLS-1$
                    outputTarget,
                    String.valueOf(reportComponent.getAcceptedPage())));
      }

      HttpServletResponse response = null;
      boolean streamToBrowser = false;
      final IParameterProvider pathProviders = contentGenerator.getParameterProviders().get("path");
      if (pathProviders != null) {
        final Object httpResponse = pathProviders.getParameter("httpresponse");
        if (httpResponse
            instanceof HttpServletResponse) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          response = (HttpServletResponse) httpResponse; // $NON-NLS-1$ //$NON-NLS-2$
          if (reportStagingHandler.getStagingMode() == StagingMode.THRU) {
            // Direct back - check output stream...
            final OutputStream respOutputStream = response.getOutputStream();
            if (respOutputStream == outputStream) {
              //
              // Massive assumption here -
              // Assume the container returns the same object on successive calls to
              // response.getOutputStream()
              streamToBrowser = true;
            }
          }
        }
      }

      final String extension = MimeHelper.getExtension(mimeType);
      String filename = file.getName();
      if (filename.lastIndexOf(".") != -1) { // $NON-NLS-1$
        filename = filename.substring(0, filename.lastIndexOf(".")); // $NON-NLS-1$
      }
      String disposition =
          "inline; filename*=UTF-8''"
              + RepositoryPathEncoder.encode(
                  RepositoryPathEncoder.encodeRepositoryPath(filename + extension));

      final boolean validates = reportComponent.validate();
      if (!validates) {
        sendErrorResponse(response, outputStream, reportStagingHandler);
      } else {
        if (response != null) {
          // Send headers before we begin execution
          response.setHeader("Content-Disposition", disposition);
          response.setHeader("Content-Description", file.getName()); // $NON-NLS-1$
          response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
        }
        if (reportComponent.execute()) {
          if (response != null) {
            if (reportStagingHandler.canSendHeaders()) {
              response.setHeader("Content-Disposition", disposition);
              response.setHeader("Content-Description", file.getName()); // $NON-NLS-1$
              response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
              response.setContentLength(reportStagingHandler.getWrittenByteCount());
            }
          }
          if (logger.isDebugEnabled()) {
            logger.debug(
                Messages.getInstance()
                    .getString(
                        "ReportPlugin.logEndGenerateContent",
                        String.valueOf(reportStagingHandler.getWrittenByteCount()))); // $NON-NLS-1$
          }
          reportStagingHandler.complete(); // will copy bytes to final destination...

        } else { // failed execution
          sendErrorResponse(response, outputStream, reportStagingHandler);
        }
      }
    } catch (Exception ex) {
      result = MessageTypes.INSTANCE_FAILED;
      throw ex;
    } finally {
      if (reportStagingHandler != null) {
        reportStagingHandler.close();
      }
      final long end = System.currentTimeMillis();
      AuditHelper.audit(
          userSession.getId(),
          userSession.getName(),
          path,
          contentGenerator.getObjectName(),
          getClass().getName(),
          result,
          contentGenerator.getInstanceId(),
          "",
          ((float) (end - start) / 1000),
          contentGenerator); //$NON-NLS-1$
    }
  }
コード例 #5
0
  public void test1() throws ObjectFactoryException {

    StandaloneSession session = new StandaloneSession("test");

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

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

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

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

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

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

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

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

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

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

    param.setValue("testvalue2");

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

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

    engine.errorMsg = "test exception";
    resultMsg = globals.publish(session);
    assertEquals(
        Messages.getInstance().getString("GlobalListsPublisher.USER_ERROR_PUBLISH_FAILED")
            + "test exception",
        resultMsg);
    assertEquals(3, engine.executeCount);
  }