Search in sources :

Example 16 with IPentahoRequestContext

use of org.pentaho.platform.api.engine.IPentahoRequestContext in project pentaho-platform by pentaho.

the class GenericServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    if (showDeprecationMessage) {
        String deprecationMessage = "GenericServlet is deprecated and should no longer be handling requests. More detail below..." + "\n | You have issued a {0} request to {1} from referer {2} " + "\n | Please consider using one of the following REST services instead:" + "\n | * GET /api/repos/<pluginId>/<path> to read files from a plugin public dir" + "\n | * POST|GET /api/repos/<pathId>/generatedContent to create content resulting from execution of a " + "repo file" + "\n | * POST|GET /api/repos/<pluginId>/<contentGeneratorId> to execute a content generator by name (RPC " + "compatibility service)" + "\n \\ To turn this message off, set init-param 'showDeprecationMessage' to false in the GenericServlet " + "declaration" + "";
        String referer = StringUtils.defaultString(request.getHeader("Referer"), "");
        logger.warn(MessageFormat.format(deprecationMessage, request.getMethod(), request.getRequestURL(), referer));
    }
    PentahoSystem.systemEntryPoint();
    IOutputHandler outputHandler = null;
    // BISERVER-2767 - grabbing the current class loader so we can replace it at the end
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    try {
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        // $NON-NLS-1$
        String contentGeneratorId = "";
        // $NON-NLS-1$
        String urlPath = "";
        SimpleParameterProvider pathParams = new SimpleParameterProvider();
        if (StringUtils.isEmpty(pathInfo)) {
            logger.error(// $NON-NLS-1$
            Messages.getInstance().getErrorString("GenericServlet.ERROR_0005_NO_RESOURCE_SPECIFIED"));
            response.sendError(403);
            return;
        }
        String path = pathInfo.substring(1);
        int slashPos = path.indexOf('/');
        if (slashPos != -1) {
            // $NON-NLS-1$
            pathParams.setParameter("path", pathInfo.substring(slashPos + 1));
            contentGeneratorId = path.substring(0, slashPos);
        } else {
            contentGeneratorId = path;
        }
        // $NON-NLS-1$
        urlPath = "content/" + contentGeneratorId;
        IParameterProvider requestParameters = new HttpRequestParameterProvider(request);
        // $NON-NLS-1$
        pathParams.setParameter("query", request.getQueryString());
        // $NON-NLS-1$
        pathParams.setParameter("contentType", request.getContentType());
        InputStream in = request.getInputStream();
        // $NON-NLS-1$
        pathParams.setParameter("inputstream", in);
        // $NON-NLS-1$
        pathParams.setParameter("httpresponse", response);
        // $NON-NLS-1$
        pathParams.setParameter("httprequest", request);
        // $NON-NLS-1$
        pathParams.setParameter("remoteaddr", request.getRemoteAddr());
        if (PentahoSystem.debug) {
            // $NON-NLS-1$
            debug("GenericServlet contentGeneratorId=" + contentGeneratorId);
            // $NON-NLS-1$
            debug("GenericServlet urlPath=" + urlPath);
        }
        IPentahoSession session = getPentahoSession(request);
        IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
        if (pluginManager == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0001_BAD_OBJECT", // $NON-NLS-1$
            IPluginManager.class.getSimpleName());
            error(message);
            out.write(message.getBytes());
            return;
        }
        // TODO make doing the HTTP headers configurable per content generator
        SimpleParameterProvider headerParams = new SimpleParameterProvider();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getHeader(name);
            headerParams.setParameter(name, value);
        }
        String pluginId = pluginManager.getServicePlugin(pathInfo);
        if (pluginId != null && pluginManager.isStaticResource(pathInfo)) {
            boolean cacheOn = "true".equals(pluginManager.getPluginSetting(pluginId, "settings/cache", // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
            "false"));
            // $NON-NLS-1$
            String maxAge = (String) pluginManager.getPluginSetting(pluginId, "settings/max-age", null);
            allowBrowserCache(maxAge, pathParams);
            String mimeType = MimeHelper.getMimeTypeFromFileName(pathInfo);
            if (mimeType != null) {
                response.setContentType(mimeType);
            }
            OutputStream out = response.getOutputStream();
            // do we have this resource cached?
            ByteArrayOutputStream byteStream = null;
            if (cacheOn) {
                byteStream = (ByteArrayOutputStream) cache.getFromRegionCache(CACHE_FILE, pathInfo);
            }
            if (byteStream != null) {
                IOUtils.write(byteStream.toByteArray(), out);
                return;
            }
            InputStream resourceStream = pluginManager.getStaticResource(pathInfo);
            if (resourceStream != null) {
                try {
                    byteStream = new ByteArrayOutputStream();
                    IOUtils.copy(resourceStream, byteStream);
                    // if cache is enabled, drop file in cache
                    if (cacheOn) {
                        cache.putInRegionCache(CACHE_FILE, pathInfo, byteStream);
                    }
                    // write it out
                    IOUtils.write(byteStream.toByteArray(), out);
                    return;
                } finally {
                    IOUtils.closeQuietly(resourceStream);
                }
            }
            logger.error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0004_RESOURCE_NOT_FOUND", pluginId, // $NON-NLS-1$
            pathInfo));
            response.sendError(404);
            return;
        }
        // content generators defined in plugin.xml are registered with 2 aliases, one is the id, the other is type
        // so, we can still retrieve a content generator by id, even though this is not the correct way to find
        // it. the correct way is to look up a content generator by pluginManager.getContentGenerator(type,
        // perspectiveName)
        IContentGenerator contentGenerator = (IContentGenerator) pluginManager.getBean(contentGeneratorId);
        if (contentGenerator == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", // $NON-NLS-1$
            Encode.forHtml(contentGeneratorId));
            error(message);
            out.write(message.getBytes());
            return;
        }
        // set the classloader of the current thread to the class loader of
        // the plugin so that it can load its libraries
        // Note: we cannot ask the contentGenerator class for it's classloader, since the cg may
        // actually be a proxy object loaded by main the WebAppClassloader
        Thread.currentThread().setContextClassLoader(pluginManager.getClassLoader(pluginId));
        // String proxyClass = PentahoSystem.getSystemSetting( module+"/plugin.xml" ,
        // "plugin/content-generators/"+contentGeneratorId,
        // "content generator not found");
        // see if this is an upload
        // File uploading is a service provided by UploadFileServlet where appropriate protections
        // are in place to prevent uploads that are too large.
        // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // if (isMultipart) {
        // requestParameters = new SimpleParameterProvider();
        // // Create a factory for disk-based file items
        // FileItemFactory factory = new DiskFileItemFactory();
        // 
        // // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        // 
        // // Parse the request
        // List<?> /* FileItem */items = upload.parseRequest(request);
        // Iterator<?> iter = items.iterator();
        // while (iter.hasNext()) {
        // FileItem item = (FileItem) iter.next();
        // 
        // if (item.isFormField()) {
        // ((SimpleParameterProvider) requestParameters).setParameter(item.getFieldName(), item.getString());
        // } else {
        // String name = item.getName();
        // ((SimpleParameterProvider) requestParameters).setParameter(name, item.getInputStream());
        // }
        // }
        // }
        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        IMimeTypeListener listener = new HttpMimeTypeListener(request, response);
        outputHandler = getOutputHandler(response, true);
        outputHandler.setMimeTypeListener(listener);
        IParameterProvider sessionParameters = new HttpSessionParameterProvider(session);
        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
        Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
        parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParameters);
        parameterProviders.put(IParameterProvider.SCOPE_SESSION, sessionParameters);
        // $NON-NLS-1$
        parameterProviders.put("headers", headerParams);
        // $NON-NLS-1$
        parameterProviders.put("path", pathParams);
        SimpleUrlFactory urlFactory = // $NON-NLS-1$ //$NON-NLS-2$
        new SimpleUrlFactory(requestContext.getContextPath() + urlPath + "?");
        List<String> messages = new ArrayList<String>();
        contentGenerator.setOutputHandler(outputHandler);
        contentGenerator.setMessagesList(messages);
        contentGenerator.setParameterProviders(parameterProviders);
        contentGenerator.setSession(session);
        contentGenerator.setUrlFactory(urlFactory);
        // String contentType = request.getContentType();
        // contentGenerator.setInput(input);
        contentGenerator.createContent();
        if (PentahoSystem.debug) {
            // $NON-NLS-1$
            debug("Generic Servlet content generate successfully");
        }
    } catch (Exception e) {
        StringBuffer buffer = new StringBuffer();
        error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", request.getQueryString()), // $NON-NLS-1$
        e);
        List errorList = new ArrayList();
        String msg = e.getMessage();
        errorList.add(msg);
        // $NON-NLS-1$
        MessageFormatUtils.formatFailureMessage("text/html", null, buffer, errorList);
        response.getOutputStream().write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));
    } finally {
        // reset the classloader of the current thread
        Thread.currentThread().setContextClassLoader(origContextClassloader);
        PentahoSystem.systemExitPoint();
    }
}
Also used : IMimeTypeListener(org.pentaho.platform.api.engine.IMimeTypeListener) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) HttpRequestParameterProvider(org.pentaho.platform.web.http.request.HttpRequestParameterProvider) IContentGenerator(org.pentaho.platform.api.engine.IContentGenerator) ArrayList(java.util.ArrayList) List(java.util.List) SimpleParameterProvider(org.pentaho.platform.engine.core.solution.SimpleParameterProvider) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) IOutputHandler(org.pentaho.platform.api.engine.IOutputHandler) HttpSessionParameterProvider(org.pentaho.platform.web.http.session.HttpSessionParameterProvider) IPluginManager(org.pentaho.platform.api.engine.IPluginManager) SimpleUrlFactory(org.pentaho.platform.util.web.SimpleUrlFactory)

Example 17 with IPentahoRequestContext

use of org.pentaho.platform.api.engine.IPentahoRequestContext in project pentaho-platform by pentaho.

the class XYZSeriesCollectionChartComponent method getXmlContent.

@Override
public Document getXmlContent() {
    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("baseUrl", requestContext.getContextPath());
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("fullyQualifiedServerUrl", PentahoSystem.getApplicationContext().getFullyQualifiedServerURL());
    // $NON-NLS-1$
    String mapName = "chart" + AbstractChartComponent.chartCount++;
    Document chartDefinition = jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);
    if (chartDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        error(message);
        return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);
    if (dataDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0002_CHART_DATA_MISSING", actionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        // 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
    // $NON-NLS-1$
    String chartTitle = "";
    try {
        if (width == -1) {
            // $NON-NLS-1$
            width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText());
        }
        if (height == -1) {
            // $NON-NLS-1$
            height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText());
        }
    } catch (Exception e) {
    // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) != null) {
        // $NON-NLS-1$
        urlTemplate = // $NON-NLS-1$
        chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME).getText();
    }
    if (chartDefinition.selectSingleNode("/chart/paramName") != null) {
        // $NON-NLS-1$
        // $NON-NLS-1$
        paramName = chartDefinition.selectSingleNode("/chart/paramName").getText();
    }
    // $NON-NLS-1$
    Element root = result.addElement("charts");
    XYZSeriesCollectionChartDefinition chartDataDefinition = (XYZSeriesCollectionChartDefinition) 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, // $NON-NLS-1$
        this);
        applyOuterURLTemplateParam();
        populateInfo(info);
        // $NON-NLS-1$
        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));
        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);
                Number columnKey = chartDataDefinition.getX(row, column);
                // $NON-NLS-1$
                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());
            }
        }
        String mapString = ImageMapUtilities.getImageMap(mapName, info);
        // $NON-NLS-1$
        chartElement.addElement("imageMap").setText(mapString);
        // $NON-NLS-1$
        chartElement.addElement("image").setText(fileName);
    }
    return result;
}
Also used : Element(org.dom4j.Element) Document(org.dom4j.Document) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) StandardEntityCollection(org.jfree.chart.entity.StandardEntityCollection) StringWriter(java.io.StringWriter) ChartRenderingInfo(org.jfree.chart.ChartRenderingInfo) PrintWriter(java.io.PrintWriter)

Example 18 with IPentahoRequestContext

use of org.pentaho.platform.api.engine.IPentahoRequestContext in project pentaho-platform by pentaho.

the class SystemSolutionAxisConfigurator method addServiceEndPoints.

@Override
protected void addServiceEndPoints(AxisService axisService) {
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    // $NON-NLS-1$
    String endPoint1 = requestContext.getContextPath() + "content/ws-run/" + axisService.getName();
    axisService.setEPRs(new String[] { endPoint1 });
}
Also used : IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext)

Example 19 with IPentahoRequestContext

use of org.pentaho.platform.api.engine.IPentahoRequestContext in project pentaho-platform by pentaho.

the class PentahoWebContextFilterTest method setup.

@Before
public void setup() throws IOException, ServletException {
    this.serverScheme = "https";
    String serverName = "di.pentaho.local";
    int port = 9055;
    this.serverAddress = this.serverScheme + "://" + serverName + ":" + port;
    this.contextRoot = "/the/context/root/";
    this.fullyQualifiedServerURL = this.serverAddress + this.contextRoot;
    this.mockRequest = mock(HttpServletRequest.class);
    ServletContext mockServletContext = mock(ServletContext.class);
    ServletRegistration mockServletRegistration = mock(ServletRegistration.class);
    Collection<String> mappings = new ArrayList<>(1);
    mappings.add(PentahoWebContextFilter.DEFAULT_OSGI_BRIDGE);
    when(mockServletRegistration.getMappings()).thenReturn(mappings);
    when(mockServletContext.getServletRegistration(PentahoWebContextFilter.PLATFORM_OSGI_BRIDGE_ID)).thenReturn(mockServletRegistration);
    when(this.mockRequest.getServletContext()).thenReturn(mockServletContext);
    when(this.mockRequest.getRequestURI()).thenReturn("/somewhere/" + PentahoWebContextFilter.WEB_CONTEXT_JS);
    when(this.mockRequest.getScheme()).thenReturn(this.serverScheme);
    when(this.mockRequest.getServerName()).thenReturn(serverName);
    when(this.mockRequest.getServerPort()).thenReturn(port);
    when(this.mockRequest.getHeader("referer")).thenReturn(this.serverAddress + "/some/app");
    this.mockResponse = mock(HttpServletResponse.class);
    this.mockResponseOutputStream = new java.io.ByteArrayOutputStream();
    when(this.mockResponse.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            PentahoWebContextFilterTest.this.mockResponseOutputStream.write(b);
        }
    });
    FilterConfig mockFilterConfig = mock(FilterConfig.class);
    this.pentahoWebContextFilter = spy(new PentahoWebContextFilter());
    IApplicationContext mockApplicationContext = mock(IApplicationContext.class);
    when(mockApplicationContext.getFullyQualifiedServerURL()).thenReturn(this.fullyQualifiedServerURL);
    doReturn(mockApplicationContext).when(this.pentahoWebContextFilter).getApplicationContext();
    IPentahoRequestContext mockRequestContext = mock(IPentahoRequestContext.class);
    when(mockRequestContext.getContextPath()).thenReturn(this.contextRoot);
    doReturn(mockRequestContext).when(this.pentahoWebContextFilter).getRequestContext();
    this.activeTheme = "xptoTheme";
    IUserSetting mockUserSetting = mock(IUserSetting.class);
    when(mockUserSetting.getSettingValue()).thenReturn(this.activeTheme);
    IUserSettingService mockUserSettingsService = mock(IUserSettingService.class);
    when(mockUserSettingsService.getUserSetting("pentaho-user-theme", null)).thenReturn(mockUserSetting);
    doReturn(mockUserSettingsService).when(this.pentahoWebContextFilter).getUserSettingsService();
    this.sessionName = "testSession";
    IPentahoSession mockSession = mock(IPentahoSession.class);
    when(mockSession.getName()).thenReturn(this.sessionName);
    doReturn(mockSession).when(this.pentahoWebContextFilter).getSession();
    this.reservedChars = new ArrayList<>(2);
    this.reservedChars.add('r');
    this.reservedChars.add('c');
    doReturn(this.reservedChars).when(this.pentahoWebContextFilter).getRepositoryReservedChars();
    IPluginManager mockPluginManager = mock(IPluginManager.class);
    doReturn(mockPluginManager).when(this.pentahoWebContextFilter).getPluginManager();
    doReturn(PentahoWebContextFilter.DEFAULT_SERVICES_ROOT).when(this.pentahoWebContextFilter).initializeServicesPath();
    this.pentahoWebContextFilter.init(mockFilterConfig);
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) IUserSetting(org.pentaho.platform.api.usersettings.pojo.IUserSetting) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRegistration(javax.servlet.ServletRegistration) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) IUserSettingService(org.pentaho.platform.api.usersettings.IUserSettingService) ServletContext(javax.servlet.ServletContext) IPluginManager(org.pentaho.platform.api.engine.IPluginManager) FilterConfig(javax.servlet.FilterConfig) Before(org.junit.Before)

Example 20 with IPentahoRequestContext

use of org.pentaho.platform.api.engine.IPentahoRequestContext in project pentaho-platform by pentaho.

the class TimeSeriesCollectionChartComponent method getXmlContent.

@Override
public Document getXmlContent() {
    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("baseUrl", requestContext.getContextPath());
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("fullyQualifiedServerUrl", PentahoSystem.getApplicationContext().getFullyQualifiedServerURL());
    // $NON-NLS-1$
    String mapName = "chart" + AbstractChartComponent.chartCount++;
    Document chartDefinition = jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);
    if (chartDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        error(message);
        return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);
    if (dataDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0002_CHART_DATA_MISSING", actionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        // 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
    // $NON-NLS-1$
    String chartTitle = "";
    try {
        if (width == -1) {
            // $NON-NLS-1$
            width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText());
        }
        if (height == -1) {
            // $NON-NLS-1$
            height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText());
        }
    } catch (Exception e) {
    // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) != null) {
        // $NON-NLS-1$
        urlTemplate = // $NON-NLS-1$
        chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME).getText();
    }
    if (chartDefinition.selectSingleNode("/chart/paramName") != null) {
        // $NON-NLS-1$
        // $NON-NLS-1$
        paramName = chartDefinition.selectSingleNode("/chart/paramName").getText();
    }
    // $NON-NLS-1$
    Element root = result.addElement("charts");
    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, // $NON-NLS-1$
        this);
        applyOuterURLTemplateParam();
        populateInfo(info);
        // $NON-NLS-1$
        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));
        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);
                // $NON-NLS-1$
                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());
            }
        }
        String mapString = ImageMapUtilities.getImageMap(mapName, info);
        // $NON-NLS-1$
        chartElement.addElement("imageMap").setText(mapString);
        // $NON-NLS-1$
        chartElement.addElement("image").setText(fileName);
    }
    return result;
}
Also used : Element(org.dom4j.Element) Document(org.dom4j.Document) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) StandardEntityCollection(org.jfree.chart.entity.StandardEntityCollection) StringWriter(java.io.StringWriter) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ChartRenderingInfo(org.jfree.chart.ChartRenderingInfo) RegularTimePeriod(org.jfree.data.time.RegularTimePeriod) PrintWriter(java.io.PrintWriter)

Aggregations

IPentahoRequestContext (org.pentaho.platform.api.engine.IPentahoRequestContext)32 SimpleUrlFactory (org.pentaho.platform.util.web.SimpleUrlFactory)11 ArrayList (java.util.ArrayList)9 Document (org.dom4j.Document)9 Element (org.dom4j.Element)9 IOException (java.io.IOException)8 PrintWriter (java.io.PrintWriter)8 StringWriter (java.io.StringWriter)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 ChartRenderingInfo (org.jfree.chart.ChartRenderingInfo)7 StandardEntityCollection (org.jfree.chart.entity.StandardEntityCollection)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 File (java.io.File)5 OutputStream (java.io.OutputStream)5 List (java.util.List)5 IParameterProvider (org.pentaho.platform.api.engine.IParameterProvider)5 SimpleParameterProvider (org.pentaho.platform.engine.core.solution.SimpleParameterProvider)5 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)4 IPentahoUrlFactory (org.pentaho.platform.api.engine.IPentahoUrlFactory)4