<commit_before>package org.pentaho.reporting.platform.plugin;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.actionsequence.dom.ActionSequenceDocument;
import org.pentaho.actionsequence.dom.IActionDefinition;
import org.pentaho.actionsequence.dom.IActionSequenceInput;
import org.pentaho.actionsequence.dom.IActionSequenceOutput;
import org.pentaho.actionsequence.dom.actions.PojoAction;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.ISolutionFile;
import org.pentaho.platform.api.repository.ISchedule;
import org.pentaho.platform.api.repository.ISolutionRepository;
import org.pentaho.platform.api.repository.ISubscribeContent;
import org.pentaho.platform.api.repository.ISubscription;
import org.pentaho.platform.api.repository.ISubscriptionRepository;
import org.pentaho.platform.engine.core.audit.AuditHelper;
import org.pentaho.platform.engine.core.audit.MessageTypes;
import org.pentaho.platform.engine.core.solution.ActionInfo;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.WebServiceUtil;
import org.pentaho.platform.engine.services.solution.SimpleContentGenerator;
import org.pentaho.platform.engine.services.solution.SimpleParameterSetter;
import org.pentaho.platform.repository.messages.Messages;
import org.pentaho.platform.repository.subscription.Subscription;
import org.pentaho.platform.repository.subscription.SubscriptionHelper;
import org.pentaho.platform.util.UUIDUtil;
import org.pentaho.platform.util.web.MimeHelper;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfPageableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.csv.CSVTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.RTFTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.ExcelTableModule;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterContext;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterDefinition;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultReportParameterValidator;
import org.pentaho.reporting.engine.classic.core.parameters.ListParameter;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterAttributeNames;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterContext;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterDefinitionEntry;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterValues;
import org.pentaho.reporting.engine.classic.core.parameters.PlainParameter;
import org.pentaho.reporting.engine.classic.core.parameters.ValidationResult;
import org.pentaho.reporting.libraries.base.util.IOUtils;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.platform.plugin.gwt.client.ReportViewer.RENDER_TYPE;

public class ReportContentGenerator extends SimpleContentGenerator
{
  private static final Log log = LogFactory.getLog(ReportContentGenerator.class);

  private RENDER_TYPE renderMode = RENDER_TYPE.REPORT;
  private SimpleReportingComponent reportComponent;

  public void createContent(OutputStream outputStream) throws Exception
  {
    String id = UUIDUtil.getUUIDAsString();
    setInstanceId( id );
    final IParameterProvider requestParams = getRequestParameters();

    final String solution = URLDecoder.decode(requestParams.getStringParameter("solution", ""), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final String path = URLDecoder.decode(requestParams.getStringParameter("path", ""), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final String name = URLDecoder.decode(requestParams.getStringParameter("name", requestParams.getStringParameter("action", "")), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    final boolean subscribe = "true".equals(requestParams.getStringParameter("subscribe", "false")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    renderMode = RENDER_TYPE.valueOf(requestParams.getStringParameter("renderMode", RENDER_TYPE.REPORT.toString()).toUpperCase()); //$NON-NLS-1$

    final String reportDefinitionPath = ActionInfo.buildSolutionPath(solution, path, name);

    final long start = System.currentTimeMillis();
    AuditHelper.audit(userSession.getId(), userSession.getName(), reportDefinitionPath, getObjectName(), getClass().getName(), MessageTypes.INSTANCE_START,
        instanceId, "", 0, this); //$NON-NLS-1$

    try
    {

      // create inputs from request parameters
      final Map<String, Object> inputs = createInputs(requestParams);

      if (renderMode.equals(RENDER_TYPE.DOWNLOAD))
      {
        final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
        final ISolutionFile file = repository.getSolutionFile(reportDefinitionPath, ISolutionRepository.ACTION_CREATE);

        final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse"); //$NON-NLS-1$ //$NON-NLS-2$
        response.setHeader("Content-Disposition", "attach; filename=\"" + file.getFileName() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        response.setHeader("Content-Description", file.getFileName()); //$NON-NLS-1$
        response.setDateHeader("Last-Modified", file.getLastModified()); //$NON-NLS-1$

        // if the user has PERM_CREATE, we'll allow them to pull it for now, this is as relaxed
        // as I am comfortable with but I can imagine a PERM_READ or PERM_EXECUTE being used
        // in the future
        if (repository.hasAccess(file, ISolutionRepository.ACTION_CREATE) || repository.hasAccess(file, ISolutionRepository.ACTION_UPDATE))
        {
          IOUtils.getInstance().copyStreams(new ByteArrayInputStream(file.getData()), outputStream);
        }
      }
      else if (renderMode.equals(RENDER_TYPE.REPORT))
      {
        final ByteArrayOutputStream reportOutput = new ByteArrayOutputStream();
        // produce rendered report
        if (reportComponent == null)
        {
          reportComponent = new SimpleReportingComponent();
        }
        reportComponent.setSession(userSession);
        reportComponent.setOutputStream(reportOutput);
        reportComponent.setReportDefinitionPath(reportDefinitionPath);

        // the requested mime type can be null, in that case the report-component will resolve the desired
        // type from the output-target.
        final String mimeType = getMimeType(requestParams);
        reportComponent.setOutputType(mimeType);

        final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
        final ISolutionFile file = repository.getSolutionFile(reportDefinitionPath, ISolutionRepository.ACTION_EXECUTE);

        if (parameterProviders.get("path") != null && parameterProviders.get("path").getParameter("httpresponse") != null) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        {
          final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse"); //$NON-NLS-1$ //$NON-NLS-2$
          final String extension = MimeHelper.getExtension(mimeType);
          String filename = file.getFileName();
          if (filename.indexOf(".") != -1) { //$NON-NLS-1$
            filename = filename.substring(0, filename.indexOf(".")); //$NON-NLS-1$
          }
          response.setHeader("Content-Disposition", "inline; filename=\"" + filename + extension + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          response.setHeader("Content-Description", file.getFileName()); //$NON-NLS-1$
          response.setDateHeader("Last-Modified", file.getLastModified()); //$NON-NLS-1$
        }


        // add all inputs (request parameters) to report component
        reportComponent.setInputs(inputs);

        // 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.
        if (reportComponent.isPaginateOutput() && reportComponent.getAcceptedPage() < 0)
        {
          reportComponent.setAcceptedPage(0);
        }

        if (reportComponent.validate())
        {
          if (reportComponent.execute())
          {
            IOUtils.getInstance().copyStreams(new ByteArrayInputStream(reportOutput.toByteArray()), outputStream);
            outputStream.flush();
          }
        }
        else
        {
          outputStream.write(org.pentaho.reporting.platform.plugin.messages.Messages.getString("ReportPlugin.ReportValidationFailed").getBytes()); //$NON-NLS-1$
          outputStream.flush();<commit_msg>[BISERVER-3678] When including an html rendered prpt in dashboard designer, the client caches the results Now it does...  added headers for no caching.<commit_after>package org.pentaho.reporting.platform.plugin;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.actionsequence.dom.ActionSequenceDocument;
import org.pentaho.actionsequence.dom.IActionDefinition;
import org.pentaho.actionsequence.dom.IActionSequenceInput;
import org.pentaho.actionsequence.dom.IActionSequenceOutput;
import org.pentaho.actionsequence.dom.actions.PojoAction;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.ISolutionFile;
import org.pentaho.platform.api.repository.ISchedule;
import org.pentaho.platform.api.repository.ISolutionRepository;
import org.pentaho.platform.api.repository.ISubscribeContent;
import org.pentaho.platform.api.repository.ISubscription;
import org.pentaho.platform.api.repository.ISubscriptionRepository;
import org.pentaho.platform.engine.core.audit.AuditHelper;
import org.pentaho.platform.engine.core.audit.MessageTypes;
import org.pentaho.platform.engine.core.solution.ActionInfo;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.WebServiceUtil;
import org.pentaho.platform.engine.services.solution.SimpleContentGenerator;
import org.pentaho.platform.engine.services.solution.SimpleParameterSetter;
import org.pentaho.platform.repository.messages.Messages;
import org.pentaho.platform.repository.subscription.Subscription;
import org.pentaho.platform.repository.subscription.SubscriptionHelper;
import org.pentaho.platform.util.UUIDUtil;
import org.pentaho.platform.util.web.MimeHelper;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfPageableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.csv.CSVTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.RTFTableModule;
import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.ExcelTableModule;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterContext;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultParameterDefinition;
import org.pentaho.reporting.engine.classic.core.parameters.DefaultReportParameterValidator;
import org.pentaho.reporting.engine.classic.core.parameters.ListParameter;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterAttributeNames;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterContext;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterDefinitionEntry;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterValues;
import org.pentaho.reporting.engine.classic.core.parameters.PlainParameter;
import org.pentaho.reporting.engine.classic.core.parameters.ValidationResult;
import org.pentaho.reporting.libraries.base.util.IOUtils;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.platform.plugin.gwt.client.ReportViewer.RENDER_TYPE;

public class ReportContentGenerator extends SimpleContentGenerator
{
  private static final Log log = LogFactory.getLog(ReportContentGenerator.class);

  private RENDER_TYPE renderMode = RENDER_TYPE.REPORT;
  private SimpleReportingComponent reportComponent;

  public void createContent(OutputStream outputStream) throws Exception
  {
    String id = UUIDUtil.getUUIDAsString();
    setInstanceId( id );
    final IParameterProvider requestParams = getRequestParameters();

    final String solution = URLDecoder.decode(requestParams.getStringParameter("solution", ""), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final String path = URLDecoder.decode(requestParams.getStringParameter("path", ""), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final String name = URLDecoder.decode(requestParams.getStringParameter("name", requestParams.getStringParameter("action", "")), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    final boolean subscribe = "true".equals(requestParams.getStringParameter("subscribe", "false")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    renderMode = RENDER_TYPE.valueOf(requestParams.getStringParameter("renderMode", RENDER_TYPE.REPORT.toString()).toUpperCase()); //$NON-NLS-1$

    final String reportDefinitionPath = ActionInfo.buildSolutionPath(solution, path, name);

    final long start = System.currentTimeMillis();
    AuditHelper.audit(userSession.getId(), userSession.getName(), reportDefinitionPath, getObjectName(), getClass().getName(), MessageTypes.INSTANCE_START,
        instanceId, "", 0, this); //$NON-NLS-1$

    try
    {

      // create inputs from request parameters
      final Map<String, Object> inputs = createInputs(requestParams);

      if (renderMode.equals(RENDER_TYPE.DOWNLOAD))
      {
        final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
        final ISolutionFile file = repository.getSolutionFile(reportDefinitionPath, ISolutionRepository.ACTION_CREATE);

        final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse"); //$NON-NLS-1$ //$NON-NLS-2$
        response.setHeader("Content-Disposition", "attach; filename=\"" + file.getFileName() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        response.setHeader("Content-Description", file.getFileName()); //$NON-NLS-1$
        response.setDateHeader("Last-Modified", file.getLastModified()); //$NON-NLS-1$

        // if the user has PERM_CREATE, we'll allow them to pull it for now, this is as relaxed
        // as I am comfortable with but I can imagine a PERM_READ or PERM_EXECUTE being used
        // in the future
        if (repository.hasAccess(file, ISolutionRepository.ACTION_CREATE) || repository.hasAccess(file, ISolutionRepository.ACTION_UPDATE))
        {
          IOUtils.getInstance().copyStreams(new ByteArrayInputStream(file.getData()), outputStream);
        }
      }
      else if (renderMode.equals(RENDER_TYPE.REPORT))
      {
        final ByteArrayOutputStream reportOutput = new ByteArrayOutputStream();
        // produce rendered report
        if (reportComponent == null)
        {
          reportComponent = new SimpleReportingComponent();
        }
        reportComponent.setSession(userSession);
        reportComponent.setOutputStream(reportOutput);
        reportComponent.setReportDefinitionPath(reportDefinitionPath);

        // the requested mime type can be null, in that case the report-component will resolve the desired
        // type from the output-target.
        final String mimeType = getMimeType(requestParams);
        reportComponent.setOutputType(mimeType);

        final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
        final ISolutionFile file = repository.getSolutionFile(reportDefinitionPath, ISolutionRepository.ACTION_EXECUTE);

        if (parameterProviders.get("path") != null && parameterProviders.get("path").getParameter("httpresponse") != null) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        {
          final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse"); //$NON-NLS-1$ //$NON-NLS-2$
          final String extension = MimeHelper.getExtension(mimeType);
          String filename = file.getFileName();
          if (filename.indexOf(".") != -1) { //$NON-NLS-1$
            filename = filename.substring(0, filename.indexOf(".")); //$NON-NLS-1$
          }
          response.setHeader("Content-Disposition", "inline; filename=\"" + filename + extension + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          response.setHeader("Content-Description", file.getFileName()); //$NON-NLS-1$
          response.setHeader( "Pragma", "no-cache" );
          response.setHeader( "Cache-Control", "no-cache" );
          response.setDateHeader( "Expires", 0 );
        }


        // add all inputs (request parameters) to report component
        reportComponent.setInputs(inputs);

        // 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.
        if (reportComponent.isPaginateOutput() && reportComponent.getAcceptedPage() < 0)
        {
          reportComponent.setAcceptedPage(0);
        }

        if (reportComponent.validate())
        {
          if (reportComponent.execute())
          {
            IOUtils.getInstance().copyStreams(new ByteArrayInputStream(reportOutput.toByteArray()), outputStream);
            outputStream.flush();
          }
        }
        else
        {
          outputStream.write(org.pentaho.reporting.platform.plugin.messages.Messages.getString("ReportPlugin.ReportValidationFailed").getBytes()); //$NON-NLS-1$
          outputStream.flush();
{'fraction_non_alphanumeric': 0.11875507717303006, 'fraction_numerical': 0.00487408610885459, 'mean_word_length': 4.231606905710492, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '17382', 'n_tokens_mistral': 5585, 'n_tokens_neox': 5508, 'n_words': 1019}