Home » Archived » BIRT » Trying (and struggling) to make a BIRT viewer JSF component
Trying (and struggling) to make a BIRT viewer JSF component [message #97380] |
Thu, 08 December 2005 09:52  |
Eclipse User |
|
|
|
Originally posted by: maspeli.deloitte.co.uk
Hi,
We're trying to make a BIRT viewer that is a JavaServerFaces control. If all
goes well and this clears the right hurdles, we'll hopefully be able to
release this back into the community. However, I'm struggling a bit with
both the philosophy behind the API and with exceptions I don't know the
cause of.
Basically, I strated with the BIRT viewer example. My first problem is that
I can't seem to check this out from CVS (dev.eclipse.org won't let me
connect as pserver anonymous on /cvsroot/birt). I found the source with
ViewCVS, however, and I'm now trying to adapt this code to fit a JSF type
framework. I've pasted the relevant code below. Basically, I can now get the
report to open (I think), but I get the following exception, no matter what
I do:
javax.faces.FacesException: javax.servlet.jsp.JspException: The output
format html is not supported.
org.apache.myfaces.context.servlet.ServletExternalContextImp l.dispatch(Servl
etExternalContextImpl.java:421)
org.apache.myfaces.application.jsp.JspViewHandlerImpl.render View(JspViewHand
lerImpl.java:234)
org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleI mpl.java:352)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:10 7)
org.apache.myfaces.component.html.util.ExtensionsFilter.doFi lter(ExtensionsF
ilter.java:122)
This happens as soon as I run the IRunAndRenderTask, no matter what I do. If
I do renderOption.setOutputFormat("foobar") I get "The output format foobar
is not supported", so it's clearly picking up the format. Also, even if I
try to set the output stream in renderOption to e.g. a
ByteArrayOutputStream, I still get the error.
The documentation for ExternalContext reads:
public abstract void dispatch(java.lang.String path)
throws java.io.IOExceptionDispatch a request to the
specified resource to create output for this response.
Servlet: This must be accomplished by calling the
javax.servlet.ServletContext method getRequestDispatcher(path), and calling
the forward() method on the resulting object.
Portlet: This must be accomplished by calling the
javax.portlet.PortletContext method getRequestDispatcher(), and calling the
include() method on the resulting object.
Parameters:
path - Context relative path to the specified resource, which must start
with a slash ("/") character
Throws:
FacesException - thrown if a ServletException or PortletException occurs
java.lang.IllegalArgumentException - if no request dispatcher can be
created for the specified path
java.lang.IllegalStateException - if this method is called in a portlet
environment, and the current request is an ActionRequest instead of a
RenderRequest
java.io.IOException - if an input/output error occurs
java.lang.NullPointerException - if path is null
A few points:
- my WEB-INF/lib contains everything the M3 runtime Web Viewer Example's
WEB-INF/lib contains
- I haven't set BIRT_HOME, I'm not sure if this is required for this
scenaro.
- I've re-implemented the ReportEngineService, PlatformServletContext and
ParameterAccessor from the example to work with JSF. The code is below.
Any help or background would be greatly appreciated!
---> The handler for the component that actually renders the report <---
package uk.gov.tfl.lez.view.components.birtviewer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.faces.application.Application;
import javax.faces.component.UIComponentBase;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTa sk;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
public class BIRTViewer extends UIComponentBase implements IBIRTViewer {
public static final String COMPONENT_TYPE = "uk.gov.tfl.lez.BIRTViewer";
public static final String COMPONENT_FAMILY = "uk.gov.tfl.lez.BIRTFamily";
public String getFamily() {
return COMPONENT_FAMILY;
}
public void encodeBegin(FacesContext context) throws IOException {
if (!isRendered())
return;
Application application = context.getApplication();
ExternalContext externalContext = context.getExternalContext();
String contextPath = externalContext.getRequestContextPath();
// XXX: We'd rather not do this briding. We could probably write a new
// implementation of IPlatformContext that operates on an ExternalContext
ServletContext servletContext = (ServletContext)
externalContext.getContext();
HttpServletRequest request = (HttpServletRequest)
externalContext.getRequest();
Map attributes = getAttributes();
String design = (String) attributes.get("design");
HashMap params;
try {
params = (HashMap) attributes.get("params");
} catch (ClassCastException e) {
params = new HashMap();
}
// Get the report engine via the ReportEngineService singleton wrapper
// XXX: This API is dumb. Fix it.
ReportEngineService.initEngineInstance(externalContext);
ReportEngineService engineService = ReportEngineService.getInstance();
// XXX: Need to initialise engine context and params context globally, not
per request like this!
ParameterAccessor.initParameters(servletContext);
engineService.setEngineContext(externalContext, request);
// Open the report from the filename provided
IReportRunnable report = engineService.openReportDesign(design);
// Parameters
// XXX: Need to parse parameters
// IGetParameterDefinitionTask parameterTask =
engineService.createGetParameterDefinitionTask(report);
// HashMap parameterMap = parseParameters(request, parameterTask,
report.getTestConfig());
// Collection parameterMap = parameterTask.getParameterDefns(true);
// Set render options - this tells BIRT where and how to render (in our
case, HTML to the response)
IRenderOption renderOption = new HTMLRenderOption();
renderOption.setOutputStream(context.getResponseStream());
renderOption.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_ HTML);
// Create the run-and-render task to allow us to execute the rendering
IRunAndRenderTask runTask = engineService.createRunAndRenderTask(report);
runTask.setLocale(application.getDefaultLocale());
runTask.setParameterValues(params);
runTask.setRenderOption(renderOption);
// Create render context - the renderer needs to write some files to a
working directory
// and needs to know how to do so.
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setImageDirectory(engineService.getImageDirect ory());
renderContext.setBaseImageURL(contextPath +
engineService.getImageBaseUrl());
renderContext.setBaseURL(contextPath);
renderContext.setSupportedImageFormats("PNG;GIF;JPG;BMP");
HashMap contextMap = new HashMap();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T,
renderContext);
runTask.setAppContext(contextMap);
// Finally, run the report, then clean up
try {
runTask.run();
} catch (BirtException e) {
throw new IOException(e.getLocalizedMessage());
} finally {
runTask.close();
}
}
}
---> ReportEngineService.java <----
package uk.gov.tfl.lez.view.components.birtviewer;
/*********************************************************** ****************
**********
* Copyright (c) 2004 Actuate Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
************************************************************ ****************
********/
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Level;
import javax.faces.context.ExternalContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTa sk;
import org.eclipse.birt.report.engine.api.IRenderTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IRunTask;
import org.eclipse.birt.report.engine.api.ReportEngine;
import uk.gov.tfl.lez.view.components.birtviewer.PlatformFacesConte xt;
public class ReportEngineService {
private static ReportEngineService instance;
/**
* Report engine instance.
*/
private ReportEngine engine = null;
/**
* Static engine config instance.
*/
private EngineConfig config = null;
/**
* Image directory for report images and charts.
*/
private String imageDirectory = null;
/**
* URL accesses images.
*/
private String imageBaseUrl = null;
/**
* Web app context path.
*/
private String contextPath = null;
/**
* Image handler instance.
*/
private HTMLServerImageHandler imageHandler = null;
protected ReportEngineService() {
}
/**
* Get engine instance.
*
* @return
*/
synchronized public static ReportEngineService getInstance() {
if(instance == null)
throw new IllegalStateException("You must call initEngineInstance()
before using getInstance()!");
return instance;
}
/**
* Initialise engine instance.
*
* @param context The external context of the JSF
* @return engine instance
*/
synchronized public static void initEngineInstance(ExternalContext context)
{
instance = new ReportEngineService();
instance.configureInstance(context);
}
synchronized private void configureInstance(ExternalContext context) {
config = new EngineConfig();
// XXX: Would rather not have to do this, but getRealPath() means we must
ServletContext servletContext = (ServletContext) context.getContext();
// Register new image handler
HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig();
emitterConfig.setActionHandler(new HTMLActionHandler());
imageHandler = new HTMLServerImageHandler();
emitterConfig.setImageHandler(imageHandler);
config.setEmitterConfiguration(HTMLRenderOption.OUTPUT_FORMA T_HTML,
emitterConfig);
// Prepare image directory.
imageDirectory =
context.getInitParameter(ParameterAccessor.INIT_PARAM_IMAGE_ DIR);
if (imageDirectory == null || imageDirectory.trim().length() <= 0
|| ParameterAccessor.isRelativePath(imageDirectory)) {
imageDirectory = servletContext.getRealPath("/report/images");
}
// Prepare image base url.
imageBaseUrl = "/run?__imageID=";
// Prepare log directory.
String logDirectory =
context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_DI R);
if (logDirectory == null || logDirectory.trim().length() <= 0 ||
ParameterAccessor.isRelativePath(logDirectory)) {
logDirectory = servletContext.getRealPath("/logs");
}
// Prepare log level.
String logLevel =
servletContext.getInitParameter(ParameterAccessor.INIT_PARAM _LOG_LEVEL);
Level level = Level.OFF;
if ("SEVERE".equalsIgnoreCase(logLevel)) {
level = Level.SEVERE;
} else if ("WARNING".equalsIgnoreCase(logLevel)) {
level = Level.WARNING;
} else if ("INFO".equalsIgnoreCase(logLevel)) {
level = Level.INFO;
} else if ("CONFIG".equalsIgnoreCase(logLevel)) {
level = Level.CONFIG;
} else if ("FINE".equalsIgnoreCase(logLevel)) {
level = Level.FINE;
} else if ("FINER".equalsIgnoreCase(logLevel)) {
level = Level.FINER;
} else if ("FINEST".equalsIgnoreCase(logLevel)) {
level = Level.FINEST;
} else if ("OFF".equalsIgnoreCase(logLevel)) {
level = Level.OFF;
}
config.setLogConfig(logDirectory, level);
}
/**
* Set Engine context.
*
* @param servletContext
* @param request
*/
synchronized public void setEngineContext(ExternalContext externalContext,
HttpServletRequest request) {
// XXX: Would rather not have to depend on HttpServletRequest here
if (engine == null) {
String url = request.getRequestURL().toString();
this.contextPath = request.getContextPath();
url = url.substring(0, url.indexOf(contextPath, url.indexOf("/"))) +
contextPath;
config.setEngineHome("");
IPlatformContext context = new PlatformFacesContext(externalContext,
url);
config.setEngineContext(context);
engine = new ReportEngine(config);
}
}
/**
* Open report design.
*
* @param report
* @return
*/
synchronized public IReportRunnable openReportDesign(String report) {
IReportRunnable runnable = null;
try {
runnable = engine.openReportDesign(report);
} catch (Exception e) {
throw new IllegalStateException("Could not open report design " + report
+ ".", e);
}
return runnable;
}
/**
* Open report design.
*
* @param report
* @return
*/
synchronized public IReportRunnable openReportDesign(InputStream stream) {
IReportRunnable runnable = null;
try {
runnable = engine.openReportDesign(stream);
} catch (Exception e) {
}
return runnable;
}
/**
* createGetParameterDefinitionTask.
*
* @param runnable
* @return
*/
synchronized public IGetParameterDefinitionTask
createGetParameterDefinitionTask(IReportRunnable runnable) {
IGetParameterDefinitionTask task = null;
try {
task = engine.createGetParameterDefinitionTask(runnable);
} catch (Exception e) {
}
return task;
}
/**
* createRunAndRenderTask.
*
* @param runnable
* @return
*/
synchronized public IRunAndRenderTask
createRunAndRenderTask(IReportRunnable runnable) {
IRunAndRenderTask task = null;
assert runnable != null;
try {
task = engine.createRunAndRenderTask(runnable);
} catch (Exception e) {
throw new IllegalStateException("Cannot create run-and-render task", e);
}
return task;
}
/**
* Open report document from archive,
*
* @param docName - the name of the report document
* @return
*//*
synchronized public IReportDocument openReportDocument(String docName) {
IReportDocument document = null;
try {
document = engine.openReportDocument(docName);
} catch (Exception e) {
}
return document;
}*/
/**
* Run report.
*
* @param runnable
* @param archive
* @param documentName
* @param locale
* @param parameters
* @throws RemoteException
*/
synchronized public void runReport(IReportRunnable runnable, String
documentName,
Locale locale, HashMap parameters) throws RemoteException {
assert runnable != null;
// Preapre the run report task.
IRunTask runTask = engine.createRunTask(runnable);
runTask.setLocale(locale);
runTask.setParameterValues(parameters);
// Run report.
try {
runTask.run(documentName);
} catch (BirtException e) {
throw new RemoteException("BIRT Report Engine", e);
} finally {
runTask.close();
}
}
/**
* Render report page.
*
* @param reportDocument
* @param pageNumber
* @param svgFlag
* @return report page content
* @throws RemoteException
*/
synchronized public ByteArrayOutputStream renderReport(IReportDocument
reportDocument, long pageNumber, boolean svgFlag)
throws RemoteException {
assert reportDocument != null;
assert pageNumber >= 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Create render task.
IRenderTask renderTask = engine.createRenderTask(reportDocument);
// Render context
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setImageDirectory(imageDirectory);
renderContext.setBaseImageURL(contextPath + imageBaseUrl);
renderContext.setSupportedImageFormats(svgFlag ? "PNG;GIF;JPG;BMP;SVG" :
"PNG;GIF;JPG;BMP"); //$NON-NLS-2$
renderContext.setBaseURL(this.contextPath + "/frameset");
HashMap contextMap = new HashMap();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T,
renderContext);
renderTask.setAppContext(contextMap);
// Render option
HTMLRenderOption setting = new HTMLRenderOption();
setting.setOutputStream(out);
setting.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML) ;
setting.setEmbeddable(true);
renderTask.setRenderOption(setting);
// Render designated page.
try {
renderTask.render(pageNumber);
} catch (BirtException e) {
throw new RemoteException("BIRT Report Engine", e);
} catch (Exception e) {
throw new RemoteException("BIRT Report Engine", e);
} finally {
renderTask.close();
}
return out;
}
/**
* @return Returns the imageBaseUrl.
*/
public String getImageBaseUrl() {
return imageBaseUrl;
}
/**
* @return Returns the imageDirectory.
*/
public String getImageDirectory() {
return imageDirectory;
}
/**
* @return Returns the imageHandler.
*/
public HTMLServerImageHandler getImageHandler() {
return imageHandler;
}
/**
* @return Returns the contextPath.
*/
public String getContextPath() {
return contextPath;
}
}
---> ParameterAccessor.java <---
package uk.gov.tfl.lez.view.components.birtviewer;
/*********************************************************** ****************
**********
* Copyright (c) 2004 Actuate Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
* Deloitte MCS - Modifications for use with BIRTViewer JSF component
************************************************************ ****************
********/
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
/**
* Utilities for URI-related operations
*/
public class ParameterAccessor {
/**
* URL parameter names.
*/
public static final String PARAM_REPORT = "__report";
public static final String PARAM_REPORT_DOCUMENT = "__document";
public static final String PARAM_FORMAT = "__format";
public static final String PARAM_FORMAT_HTML = "html";
public static final String PARAM_FORMAT_PDF = "pdf";
public static final String PARAM_LOCALE = "__locale";
public static final String PARAM_SVG = "__svg";
public static final String PARAM_PAGE = "__page";
public static final String PARAM_ISNULL = "__isnull";
public static final String PARAM_USETESTCONFIG = "__usetestconfig";
public static final String PARAM_IMAGEID = "__imageID";
/**
* Servlet configuration parameter names.
*/
public static final String INIT_PARAM_LOCALE = "BIRT_VIEWER_LOCALE";
public static final String INIT_PARAM_REPORT_DIR =
"BIRT_VIEWER_WORKING_FOLDER";
public static final String INIT_PARAM_IMAGE_DIR = "BIRT_VIEWER_IMAGE_DIR";
public static final String INIT_PARAM_LOG_DIR = "BIRT_VIEWER_LOG_DIR";
public static final String INIT_PARAM_LOG_LEVEL = "BIRT_VIEWER_LOG_LEVEL";
/**
* Report working folder.
*/
private static String workingFolder = null;
/**
* Current web application locale.
*/
private static Locale webAppLocale = null;
/**
* Initial the parameters class. Web.xml is in UTF-8 format. No need to do
* encoding convertion.
*
* @param config
* Servlet configuration
*/
public synchronized static void initParameters(ServletContext context) {
// Report root.in the web.xml has higher priority.
workingFolder = context.getInitParameter(INIT_PARAM_REPORT_DIR);
if (workingFolder == null || workingFolder.trim().length() <= 0) {
// Use birt dir as default report root.
workingFolder = context.getRealPath("/");
}
// Report root could be empty .WAR
// Clear out report location.
if (workingFolder != null &&
workingFolder.trim().endsWith(File.separator)) {
workingFolder = workingFolder.trim().substring(0,
workingFolder.trim().length() - 1);
}
webAppLocale =
getLocaleFromString(context.getInitParameter(INIT_PARAM_LOCA LE));
}
/**
* Get report file name.
*
* @param request
* http request
* @return report file name
*/
public static String getReport(HttpServletRequest request) {
String fileName = getParameter(request, PARAM_REPORT);
if (fileName == null) {
fileName = "";
} else {
fileName = fileName.trim();
}
// Get absolute report location.
if (isRelativePath(fileName)) {
if (fileName.startsWith(File.separator)) {
fileName = workingFolder + fileName;
} else {
fileName = workingFolder + File.separator + fileName;
}
}
return fileName;
}
/**
* Get report document name.
*
* @param request
* http request
* @return report file name
*/
public static String getReportDocument(HttpServletRequest request) {
String fileName = getParameter(request, PARAM_REPORT_DOCUMENT);
if (fileName == null) {
fileName = "";
} else {
fileName = fileName.trim();
}
if (fileName != null && fileName.length() > 0) {
// Get absolute report location.
if (isRelativePath(fileName)) {
if (fileName.startsWith(File.separator)) {
fileName = workingFolder + fileName;
} else {
fileName = workingFolder + File.separator + fileName;
}
}
}
return fileName;
}
/**
* Checks if a given file name contains relative path.
*
* @param fileName
* The file name.
* @return A <code>boolean</code> value indicating if the file name
* contains relative path or not.
*/
public static boolean isRelativePath(String fileName) {
if (File.separatorChar == '\\') {
// Win32
return fileName != null && fileName.indexOf(':') <= 0;
} else if (File.separatorChar == '/') {
// Unix
return fileName != null && !fileName.startsWith("/");
}
return false;
}
/**
* Get report format.
*
* @param request
* http request
* @return report format
*/
public static String getFormat(HttpServletRequest request) {
String format = getParameter(request, PARAM_FORMAT);
if (format != null && format.length() > 0) {
return format;
}
return PARAM_FORMAT_HTML; // The default format is html.
}
/**
* Get report locale from Http request.
*
* @param request
* http request
* @return report locale
*/
public static Locale getLocale(HttpServletRequest request) {
return getLocaleFromString(getParameter(request, PARAM_LOCALE));
}
/**
* Get report page from Http request.
*
* @param request
* http request
* @return report locale
*/
public static int getPage(HttpServletRequest request) {
int iPage = 1;
String page = getParameter(request, PARAM_PAGE);
if (page != null && page.length() > 0) {
try {
iPage = Integer.parseInt(page);
} catch (NumberFormatException ex) {
iPage = 1;
}
iPage = iPage < 0 ? 1 : iPage;
}
return iPage; // The default page value is 0.
}
/**
* Get web application locale.
*
* @return report locale
*/
public static Locale getWebAppLocale() {
return webAppLocale;
}
/**
* Check whether enable svg support or not.
*
* @param request
* http request
* @return whether or not render content toolbar
*/
public static boolean getSVGFlag(HttpServletRequest request) {
boolean svg = true;
if ("false".equalsIgnoreCase(getParameter(request, PARAM_SVG))) {
svg = false;
}
return svg;
}
/**
* Get report locale from a given string.
*
* @param locale
* locale string
* @return report locale
*/
public static Locale getLocaleFromString(String locale) {
if (locale == null || locale.length() <= 0) {
return Locale.getDefault();
}
int index = locale.indexOf('_');
if (index != -1) {
String language = locale.substring(0, index);
String country = locale.substring(index + 1);
return new Locale(language, country);
}
return new Locale(locale);
}
/**
* Get report locale in string.
*
* @param request
* http request
* @return report String
*/
public static String getLocaleString(HttpServletRequest request) {
return getParameter(request, PARAM_LOCALE);
}
/**
* Check whether viewer should take values from report's test config.
*
* @param request
* http request
* @return whether or not take values from report's test config.
*/
public static boolean isUseTestConfig(HttpServletRequest request) {
boolean isUseTestConfig = false;
if ("true".equalsIgnoreCase(getParameter(request, PARAM_USETESTCONFIG))) {
isUseTestConfig = true;
}
return isUseTestConfig;
}
/**
* Get report parameter by given name.
*
* @param request
* http request
* @param name
* parameter name
* @param defaultValue
* default parameter value
* @return parameter value
*/
public static String getReportParameter(HttpServletRequest request,
String name, String defaultValue) {
String value = getParameter(request, name);
if (value == null || ((String) value).trim().length() <= 0) {
value = "";
}
Map paramMap = request.getParameterMap();
String ISOName = toISOString(name);
if (paramMap == null || !paramMap.containsKey(ISOName)) {
value = defaultValue;
}
Set nullParams = getParameterValues(request, PARAM_ISNULL);
if (nullParams != null && nullParams.contains(name)) {
value = null;
}
return value;
}
/**
* Check whether report parameter exists in the url.
*
* @param request
* http request
* @param name
* parameter name
* @return whether report parameter exists in the url
*/
public static boolean isReportParameterExist(HttpServletRequest request,
String name) {
assert request != null && name != null;
boolean isExist = false;
Map paramMap = request.getParameterMap();
String ISOName = toISOString(name);
if (paramMap != null && paramMap.containsKey(ISOName)) {
isExist = true;
}
Set nullParams = getParameterValues(request, PARAM_ISNULL);
if (nullParams != null && nullParams.contains(name)) {
isExist = true;
}
return isExist;
}
/**
* Get query string with new parameter value.
*
* @param request
* http request
* @param name
* parameter name
* @param value
* default parameter value
* @return new query string with new parameter value
*/
public static String getEncodedQueryString(HttpServletRequest request,
String name, String value) {
String queryString = "";
Enumeration e = request.getParameterNames();
Set nullParams = getParameterValues(request, PARAM_ISNULL);
boolean isFirst = true;
while (e.hasMoreElements()) {
String paramName = (String) e.nextElement();
if (paramName != null && !paramName.equalsIgnoreCase(PARAM_ISNULL)) {
String paramValue = getParameter(request, paramName, false);
if (nullParams != null
&& nullParams.remove(toUTFString(paramName))
&& !paramName.equalsIgnoreCase(name)) // Parameter
// value is
// null.
{
paramName = urlEncode(paramName, "ISO-8859-1");
queryString += (isFirst ? "" : "&") + PARAM_ISNULL + "=" + paramName;
//$NON-NLS-2$ //$NON-NLS-3$
isFirst = false;
continue;
}
if (paramName.equalsIgnoreCase(name)) {
paramValue = value;
}
paramName = urlEncode(paramName, "ISO-8859-1");
paramValue = urlEncode(paramValue, "UTF-8");
queryString += (isFirst ? "" : "&") + paramName + "=" + paramValue;
//$NON-NLS-2$ //$NON-NLS-3$
isFirst = false;
}
}
if (nullParams != null && nullParams.size() > 0) {
Iterator i = nullParams.iterator();
while (i.hasNext()) {
String paramName = (String) i.next();
if (paramName != null && !paramName.equalsIgnoreCase(name)) {
paramName = urlEncode(paramName, "UTF-8");
queryString += (isFirst ? "" : "&") + PARAM_ISNULL + "=" + paramName;
//$NON-NLS-2$ //$NON-NLS-3$
isFirst = false;
}
}
}
if (getParameter(request, name) == null) {
String paramValue = value;
paramValue = urlEncode(paramValue, "UTF-8");
queryString += (isFirst ? "" : "&") + name + "=" + paramValue;
//$NON-NLS-2$ //$NON-NLS-3$
isFirst = false;
}
return queryString;
}
/**
* Get named parameter from http request. parameter names and values are
all
* in iso-8859-1 format in request.
*
* @param request
* incoming http request
* @param parameterName
* parameter name in UTF-8 format
* @return
*/
private static String getParameter(HttpServletRequest request,
String parameterName) {
return getParameter(request, parameterName, true);
}
/**
* Get named parameter from http request. parameter names and values are
all
* in iso-8859-1 format in request.
*
* @param request
* incoming http request
* @param parameterName
* parameter name
* @param isUTF
* is parameter in UTF-8 formator not
* @return
*/
private static String getParameter(HttpServletRequest request,
String parameterName, boolean isUTF) {
String ISOParameterName = (isUTF) ? toISOString(parameterName)
: parameterName;
return toUTFString(request.getParameter(ISOParameterName));
}
/**
* Get named parameters from http request. parameter names and values are
* all in iso-8859-1 format in request.
*
* @param request
* incoming http request
* @param parameterName
* parameter name in UTF-8 format
* @return
*/
private static Set getParameterValues(HttpServletRequest request,
String parameterName) {
return getParameterValues(request, parameterName, true);
}
/**
* Get named parameters from http request. parameter names and values are
* all in iso-8859-1 format in request.
*
* @param request
* incoming http request
* @param parameterName
* parameter name
* @param isUTF
* is parameter in UTF-8 formator not
* @return
*/
private static Set getParameterValues(HttpServletRequest request,
String parameterName, boolean isUTF) {
HashSet parameterValues = null;
String ISOParameterName = (isUTF) ? toISOString(parameterName)
: parameterName;
String[] ISOParameterValues = request
.getParameterValues(ISOParameterName);
if (ISOParameterValues != null) {
parameterValues = new HashSet();
for (int i = 0; i < ISOParameterValues.length; i++) {
parameterValues.add(toUTFString(ISOParameterValues[i]));
}
}
return parameterValues;
}
/**
* Convert UTF-8 string into ISO-8895-1
*
* @param s
* UTF-8 string
* @return
*/
private static String toISOString(String s) {
String ISOString = s;
if (s != null) {
try {
ISOString = new String(s.getBytes("UTF-8"), "ISO-8859-1"); //$NON-NLS-2$
} catch (UnsupportedEncodingException e) {
ISOString = s;
}
}
return ISOString;
}
/**
* Convert ISO-8895-1 string into UTF-8
*
* @param s
* ISO-8895-1 string
* @return
*/
private static String toUTFString(String s) {
String UTFString = s;
if (s != null) {
try {
UTFString = new String(s.getBytes("ISO-8859-1"), "UTF-8"); //$NON-NLS-2$
} catch (UnsupportedEncodingException e) {
UTFString = s;
}
}
return UTFString;
}
/**
* URL encoding based on incoming encoding format.
*
* @param s
* string to be encoded.
* @param format
* encoding format.
* @return
*/
private static String urlEncode(String s, String format) {
assert "ISO-8859-1".equalsIgnoreCase(format) ||
"UTF-8".equalsIgnoreCase(format); //$NON-NLS-2$
String encodedString = s;
if (s != null) {
try {
encodedString = URLEncoder.encode(s, format);
} catch (UnsupportedEncodingException e) {
encodedString = s;
}
}
return encodedString;
}
/**
* Is request parameter a report parameter.
*
* @param paraName
* @return boolean
*/
private static final boolean isReportParameter(String paraName) {
boolean isReportParameter = false;
if (paraName != null && paraName.trim().length() > 2
&& !paraName.substring(0, 2).equalsIgnoreCase("__")) {
isReportParameter = true;
}
return isReportParameter;
}
/**
* Check whether the request is to get image.
*
* @param request
* http request
* @return is get image or not
*/
public static boolean isGetImageOperator(HttpServletRequest request) {
String imageName = getParameter(request, PARAM_IMAGEID);
return imageName != null && imageName.length() > 0;
}
/**
* This function is used to encode an ordinary string that may contain
* characters or more than one consecutive spaces for appropriate HTML
* display.
*
* @param s
* @return String
*/
public static final String htmlEncode(String s) {
String sHtmlEncoded = "";
if (s == null) {
return null;
}
StringBuffer sbHtmlEncoded = new StringBuffer();
final char chrarry[] = s.toCharArray();
for (int i = 0; i < chrarry.length; i++) {
char c = chrarry[i];
switch (c) {
case '\t':
sbHtmlEncoded.append("	");
break;
case '\n':
sbHtmlEncoded.append("<br>");
break;
case '\r':
sbHtmlEncoded.append(" ");
break;
case ' ':
sbHtmlEncoded.append(" ");
break;
case '"':
sbHtmlEncoded.append(""");
break;
case '\'':
sbHtmlEncoded.append("'");
break;
case '<':
sbHtmlEncoded.append("<");
break;
case '>':
sbHtmlEncoded.append(">");
break;
case '`':
sbHtmlEncoded.append("`");
break;
case '&':
sbHtmlEncoded.append("&");
break;
default:
sbHtmlEncoded.append(c);
}
}
sHtmlEncoded = sbHtmlEncoded.toString();
return sHtmlEncoded;
}
/**
* Get current working folder.
*
* @return Returns the workingFolder.
*/
public static String getWorkingFolder() {
return workingFolder;
}
}
---> PlatformFacesContext.java <---
/*********************************************************** ****************
****
* Copyright (c) 2004 Actuate Corporation. All rights reserved. This program
and
* the accompanying materials are made available under the terms of the
Eclipse
* Public License v1.0 which accompanies this distribution, and is available
at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: Actuate Corporation - initial API and implementation
* Deloitte MCS - Derivative for JSF implementation
*
************************************************************ ****************
**/
package uk.gov.tfl.lez.view.components.birtviewer;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.PlatformServletContext;
import javax.faces.context.ExternalContext;
import javax.servlet.ServletContext;
/**
* A platform context is used by the BIRT engine to load resources.
* Since in web environment WAR deployment, absolute file paths are not
available,
* we must use resource operations instead of file operations.
*/
public class PlatformFacesContext implements IPlatformContext {
public ExternalContext context = null;
public String urlLeadingString = null; // The beginning of the path (e.g.
http://localhost:7001/birt).
private static final String directorySeparator = "/";
static protected Logger log =
Logger.getLogger(PlatformServletContext.class.getName());
public PlatformFacesContext(ExternalContext context, String
urlLeadingString) {
this.context = context;
this.urlLeadingString = urlLeadingString;
}
/* (non-Javadoc)
* @see org.eclipse.birt.core.framework.IPlatformContext#getFolderLi st(
String homeFolder, String subFolder )
*/
public List getFileList(String homeFolder, String subFolder, boolean
includingFiles, boolean relativeFileList) {
List folderList = new ArrayList();
String folderString = homeFolder;
if ((subFolder != null) && (subFolder.length() > 0) &&
!subFolder.equals("/")) {
folderString = concatFolderString(folderString, subFolder);
} else if (folderString.length() == 0 && subFolder.length() != 0) {
folderString = subFolder;
}
log.log(Level.WARNING, "Resouce paths with " + folderString + ", " +
homeFolder + ", " + subFolder);
Set files = context.getResourcePaths(folderString);
if ((files != null) && (files.size() > 0)) {
for (Iterator it = files.iterator(); it.hasNext();) {
Object obj = it.next();
if (!(obj instanceof String))
continue;
String pluginPath = (String) obj;
if (includingFiles || hasChildren(pluginPath)) // Simulate
File.isDirectory()
{
String pathString = pluginPath;
if (relativeFileList) {
// We assume the first part of pathString is homeFolder.
pathString = pathString.substring(homeFolder.length());
if (!pathString.startsWith(directorySeparator))
pathString = directorySeparator + pathString;
}
folderList.add(pathString);
}
}
}
return folderList;
}
/**
* Simulate File.isDirectory()
* @param path - the relative path to check
* @return whether the element specified by path has children or not.
*/
private boolean hasChildren(String path) {
Set children = context.getResourcePaths(path);
return ((children != null) && (children.size() > 0));
}
/* (non-Javadoc)
* @see org.eclipse.birt.core.framework.IPlatformContext#getInputStr eam(
String folder, String fileName )
*/
public InputStream getInputStream(String folder, String fileName) {
InputStream in = null;
String file = concatFolderString(folder, fileName);
in = context.getResourceAsStream(file);
return in;
}
/* (non-Javadoc)
* @see org.eclipse.birt.core.framework.IPlatformContext#getURL( String
folder, String fileName )
*/
public URL getURL(String folder, String fileName) {
URL url = null;
try {
String fullFileString = concatFolderString(folder, fileName);
// XXX: Would rather not have to do this!
ServletContext servletContext = (ServletContext) context.getContext();
String realPath = servletContext.getRealPath(fullFileString);
if (realPath == null) {
/* We can not use context.getResource, because,
* although ServletContext.getResource can return a URL, in WAR
deployment,
* the URL (e.g.
zip:D:/bea8.1/user_projects/domains/mydomain/myserver/upload /birt.war!/WEB-I
NF/plugins/org.eclipse.birt.report.engine.emitter.html/htmlE mitter.jar)
* can not be recognized by URLClassLoader. So we decided to use the
full URL path like
*
http://localhost:7001/birt/plugins/org.eclipse.birt.report.e ngine.emitter.html/htmlEmitter.jar
instead,
* which can be used by URLClassLoader can load the class.
* The first part (http://localhost:7001/birt) will be provided by
viewer and passed into the engine.
* The engine will append the second part to make it a full valid URL.
*/
url = new URL(urlLeadingString + fullFileString);
log.log(Level.FINE, "getResource({0}, {1}) returns {2}",
new Object[] { folder, fileName, realPath });
} else {
url = new File(realPath).toURL();
log.log(Level.FINE, "getRealPath({0}, {1}) returns {2}",
new Object[] { folder, fileName, realPath });
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
private String concatFolderString(String parentString, String childString)
{
if (parentString == null)
return childString;
else if (childString == null)
return parentString;
if (!parentString.endsWith(directorySeparator)) {
parentString += directorySeparator;
}
if (childString.startsWith(directorySeparator)) {
childString = childString.substring(1);
}
return parentString + childString;
}
}
|
|
|
Re: Trying (and struggling) to make a BIRT viewer JSF component [message #97508 is a reply to message #97380] |
Thu, 08 December 2005 12:17   |
Eclipse User |
|
|
|
Originally posted by: maspeli.deloitte.co.uk
Okay, this error had to do with the BIRT_HOME. I copied the 'plugins'
directory to my WebRoot and set the engine home accordingly. Reports now
render, but I see three problems:
- It renders the entire HTML page, including the DOCTYPE, <HTML> etc. Is
there some way around this in the API? I can always use regexps to clean it,
but it's a bit annoying.
- I have an embedded image in my test report. This gets rendered as an
empty <img> tag, no attributes, no nothing. This is using
HTMLServerImageHandler. I haven't really done anything to handle images, so
I'd expected they may be broken, but I would've thought the <img> tag output
with the report should point to *something*!
- If I try to run a report that accesses our MySQL database, I get an
exception. The mysql JDBC connector is in the WEB-INF/lib directory of the
deployment, and is working with Hibernate and works with the standalone
birt.war viewer (as do images, by the way). The exception is:
ERROR - Servlet.service() for servlet jsp threw exception
java.lang.NoClassDefFoundError:
org/eclipse/birt/data/oda/util/manifest/DtpManifestExplorer
at
org.eclipse.birt.report.model.extension.oda.ODAManifestUtil. getDataSourceExt
ension(ODAManifestUtil.java:40)
at
org.eclipse.birt.report.model.parser.OdaDataSourceState.pars eODADataSourceEx
tensionID(OdaDataSourceState.java:105)
at
org.eclipse.birt.report.model.parser.OdaDataSourceState.pars eAttrs(OdaDataSo
urceState.java:55)
at
org.eclipse.birt.report.model.parser.ModuleParserHandler.sta rtElement(Module
ParserHandler.java:159)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unk nown Source)
at
org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanSt artElement(Unkno
wn Source)
at
org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$Fragme ntContentDispatc
her.dispatch(Unknown Source)
at
org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDo cument(Unknown
Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:375)
at
org.eclipse.birt.report.model.parser.ModuleReader.readModule (ModuleReader.ja
va:89)
at
org.eclipse.birt.report.model.parser.ModuleReader.readModule (ModuleReader.ja
va:171)
at
org.eclipse.birt.report.model.parser.DesignReader.read(Desig nReader.java:135
)
at
org.eclipse.birt.report.model.core.DesignSession.openDesign( DesignSession.ja
va:175)
at
org.eclipse.birt.report.model.api.SessionHandle.openDesign(S essionHandle.jav
a:133)
at
org.eclipse.birt.report.engine.parser.ReportParser.getDesign Handle(ReportPar
ser.java:93)
at
org.eclipse.birt.report.engine.api.impl.ReportEngineHelper.o penReportDesign(
ReportEngineHelper.java:103)
at
org.eclipse.birt.report.engine.api.ReportEngine.openReportDe sign(ReportEngin
e.java:220)
at
uk.gov.tfl.lez.view.components.birtviewer.ReportEngineServic e.openReportDesi
gn(ReportEngineService.java:200)
at
uk.gov.tfl.lez.view.components.birtviewer.BIRTViewer.encodeB egin(BIRTViewer.
java:139)
at javax.faces.webapp.UIComponentTag.encodeBegin(UIComponentTag .java:337)
at javax.faces.webapp.UIComponentTag.doStartTag(UIComponentTag. java:224)
at
org.apache.jsp.testing.component_jsp._jspx_meth_hlez_report_ 0(org.apache.jsp
..testing.component_jsp:307)
at
org.apache.jsp.testing.component_jsp._jspx_meth_f_subview_0( org.apache.jsp.t
esting.component_jsp:282)
at
org.apache.jsp.testing.component_jsp._jspx_meth_tiles_put_4( org.apache.jsp.t
esting.component_jsp:246)
at
org.apache.jsp.testing.component_jsp._jspx_meth_tiles_insert _0(org.apache.js
p.testing.component_jsp:129)
at
org.apache.jsp.testing.component_jsp._jspService(org.apache. jsp.testing.comp
onent_jsp:78)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.ja va:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at
org.apache.jasper.servlet.JspServletWrapper.service(JspServl etWrapper.java:3
22)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServl et.java:314)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java :264)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:252)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(Applic ationDispatcher.
java:672)
at
org.apache.catalina.core.ApplicationDispatcher.processReques t(ApplicationDis
patcher.java:463)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(App licationDispatch
er.java:398)
at
org.apache.catalina.core.ApplicationDispatcher.forward(Appli cationDispatcher
..java:301)
at
org.apache.myfaces.context.servlet.ServletExternalContextImp l.dispatch(Servl
etExternalContextImpl.java:415)
at
org.apache.myfaces.application.jsp.JspViewHandlerImpl.render View(JspViewHand
lerImpl.java:234)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleI mpl.java:352)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:10 7)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:252)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.myfaces.component.html.util.ExtensionsFilter.doFi lter(ExtensionsF
ilter.java:122)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:202)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.catalina.core.StandardWrapperValve.invoke(Standar dWrapperValve.ja
va:213)
at
org.apache.catalina.core.StandardContextValve.invoke(Standar dContextValve.ja
va:178)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHo stValve.java:126
)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorRepo rtValve.java:105
)
at
org.apache.catalina.core.StandardEngineValve.invoke(Standard EngineValve.java
:107)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAd apter.java:148)
at
org.apache.coyote.http11.Http11Processor.process(Http11Proce ssor.java:868)
at
org.apache.coyote.http11.Http11BaseProtocol$Http11Connection Handler.processC
onnection(Http11BaseProtocol.java:663)
at
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(Poo lTcpEndpoint.jav
a:527)
at
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt( LeaderFollowerWo
rkerThread.java:80)
at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.ru n(ThreadPool.jav
a:684)
at java.lang.Thread.run(Thread.java:595)
ERROR - Servlet.service() for servlet Faces Servlet threw exception
javax.faces.FacesException:
org/eclipse/birt/data/oda/util/manifest/DtpManifestExplorer
at
org.apache.myfaces.context.servlet.ServletExternalContextImp l.dispatch(Servl
etExternalContextImpl.java:421)
at
org.apache.myfaces.application.jsp.JspViewHandlerImpl.render View(JspViewHand
lerImpl.java:234)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleI mpl.java:352)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:10 7)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:252)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.myfaces.component.html.util.ExtensionsFilter.doFi lter(ExtensionsF
ilter.java:122)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:202)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.catalina.core.StandardWrapperValve.invoke(Standar dWrapperValve.ja
va:213)
at
org.apache.catalina.core.StandardContextValve.invoke(Standar dContextValve.ja
va:178)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHo stValve.java:126
)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorRepo rtValve.java:105
)
at
org.apache.catalina.core.StandardEngineValve.invoke(Standard EngineValve.java
:107)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAd apter.java:148)
at
org.apache.coyote.http11.Http11Processor.process(Http11Proce ssor.java:868)
at
org.apache.coyote.http11.Http11BaseProtocol$Http11Connection Handler.processC
onnection(Http11BaseProtocol.java:663)
at
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(Poo lTcpEndpoint.jav
a:527)
at
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt( LeaderFollowerWo
rkerThread.java:80)
at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.ru n(ThreadPool.jav
a:684)
at java.lang.Thread.run(Thread.java:595)
Caused by: javax.servlet.ServletException:
org/eclipse/birt/data/oda/util/manifest/DtpManifestExplorer
at
org.apache.jasper.runtime.PageContextImpl.doHandlePageExcept ion(PageContextI
mpl.java:848)
at
org.apache.jasper.runtime.PageContextImpl.handlePageExceptio n(PageContextImp
l.java:781)
at
org.apache.jsp.testing.component_jsp._jspService(org.apache. jsp.testing.comp
onent_jsp:87)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.ja va:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at
org.apache.jasper.servlet.JspServletWrapper.service(JspServl etWrapper.java:3
22)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServl et.java:314)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java :264)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFi lter(Application
FilterChain.java:252)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(App licationFilterCh
ain.java:173)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(Applic ationDispatcher.
java:672)
at
org.apache.catalina.core.ApplicationDispatcher.processReques t(ApplicationDis
patcher.java:463)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(App licationDispatch
er.java:398)
at
org.apache.catalina.core.ApplicationDispatcher.forward(Appli cationDispatcher
..java:301)
at
org.apache.myfaces.context.servlet.ServletExternalContextImp l.dispatch(Servl
etExternalContextImpl.java:415)
.... 20 more
The current state of my code is below (ParameterAccessor.java is unchanged,
so I've left it out)
---> Code to render the report <---
public void encodeBegin(FacesContext context) throws IOException {
if (!isRendered())
return;
Application application = context.getApplication();
ExternalContext externalContext = context.getExternalContext();
String contextPath = externalContext.getRequestContextPath();
// XXX: We'd rather not do this briding. We could probably write a new
// implementation of IPlatformContext that operates on an
// ExternalContext
ServletContext servletContext = (ServletContext)
externalContext.getContext();
HttpServletRequest request = (HttpServletRequest)
externalContext.getRequest();
Map attributes = getAttributes();
String design = (String) attributes.get("design");
// XXX: Debug
design =
servletContext.getRealPath("/birt/EuroClassBoundaries.rptdesign ");
HashMap params;
try {
params = (HashMap) attributes.get("params");
} catch (ClassCastException e) {
params = new HashMap();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ResponseWriter writer = context.getResponseWriter();
// Get the report engine via the ReportEngineService singleton wrapper
ReportEngineService.initEngineInstance(externalContext, request);
ReportEngineService engineService = ReportEngineService.getInstance();
// XXX: Need to initialise engine context and params context globally,
// not per request like this!
ParameterAccessor.initParameters(servletContext);
// Open the report from the filename provided
IReportRunnable report = engineService.openReportDesign(design);
// Parameters
// XXX: Need to parse parameters
// IGetParameterDefinitionTask parameterTask =
// engineService.createGetParameterDefinitionTask(report);
// HashMap parameterMap = parseParameters(request, parameterTask,
// report.getTestConfig());
// Collection parameterMap = parameterTask.getParameterDefns(true);
// Set render options - this tells BIRT where and how to render (in our
// case, HTML to the response)
IRenderOption renderOption = new HTMLRenderOption();
renderOption.setOutputStream(out);
renderOption.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_ HTML);
// Create the run-and-render task to allow us to execute the rendering
IRunAndRenderTask runTask = engineService.createRunAndRenderTask(report);
// runTask.setLocale(application.getDefaultLocale());
runTask.setParameterValues(params);
runTask.setRenderOption(renderOption);
// Create render context - the renderer needs to write some files to a
// working directory and needs to know how to do so.
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setImageDirectory(engineService.getImageDirect ory());
renderContext.setBaseImageURL(contextPath +
engineService.getImageBaseUrl());
renderContext.setBaseURL(contextPath);
renderContext.setSupportedImageFormats("PNG;GIF;JPG;BMP");
HashMap contextMap = new HashMap();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T,
renderContext);
runTask.setAppContext(contextMap);
// Finally, run the report, then clean up
try {
runTask.run();
} catch (BirtException e) {
throw new IllegalStateException("Error whilst running report",
e.getCause());
} finally {
runTask.close();
}
out.flush();
writer.write(out.toString());
}
---> ReportEngineService.java <----
package uk.gov.tfl.lez.view.components.birtviewer;
/*********************************************************** ****************
**********
* Copyright (c) 2004 Actuate Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
************************************************************ ****************
********/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTa sk;
import org.eclipse.birt.report.engine.api.IRenderTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IRunTask;
import org.eclipse.birt.report.engine.api.ReportEngine;
import uk.gov.tfl.lez.view.components.birtviewer.PlatformFacesConte xt;
public class ReportEngineService {
private static ReportEngineService instance;
/**
* Report engine instance.
*/
private ReportEngine engine = null;
/**
* Static engine config instance.
*/
private EngineConfig config = null;
/**
* Image directory for report images and charts.
*/
private String imageDirectory = null;
/**
* URL accesses images.
*/
private String imageBaseUrl = null;
/**
* Web app context path.
*/
private String contextPath = null;
/**
* Image handler instance.
*/
private HTMLServerImageHandler imageHandler = null;
static protected Logger log =
Logger.getLogger(PlatformServletContext.class.getName());
protected ReportEngineService() {
}
/**
* Get engine instance.
*
* @return
*/
synchronized public static ReportEngineService getInstance() {
if(instance == null)
throw new IllegalStateException("You must call initEngineInstance()
before using getInstance()!");
return instance;
}
/**
* Initialise engine instance.
*
* @param context The external context of the JSF
* @return engine instance
*/
synchronized public static void initEngineInstance(ExternalContext context,
HttpServletRequest request) {
instance = new ReportEngineService();
instance.configureInstance(context, request);
}
synchronized private void configureInstance(ExternalContext context,
HttpServletRequest request) {
log.log(Level.INFO, "configuring reportengineservice instance");
// XXX: We'd rather not be dependent on servlet context and http request
ServletContext servletContext = (ServletContext) context.getContext();
config = new EngineConfig();
String url = request.getRequestURL().toString();
contextPath = request.getContextPath();
url = url.substring(0, url.indexOf(contextPath, url.indexOf("/"))) +
contextPath;
IPlatformContext platformContext = new PlatformFacesContext(context, url);
config.setEngineContext(platformContext);
log.log(Level.INFO, "created platform context on " + url);
// XXX: Is it necessary to set engine home? If so, externalise this to
web.xml
String engineHome = "/birt";
config.setEngineHome(engineHome);
log.log(Level.INFO, "set engine home to " + engineHome);
// Register new image handler
HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig();
emitterConfig.setActionHandler(new HTMLActionHandler());
imageHandler = new HTMLServerImageHandler();
emitterConfig.setImageHandler(imageHandler);
config.setEmitterConfiguration(HTMLRenderOption.OUTPUT_FORMA T_HTML,
emitterConfig);
log.log(Level.INFO, "set emitter configuration to emit HTML");
// Prepare image directory.
imageDirectory =
context.getInitParameter(ParameterAccessor.INIT_PARAM_IMAGE_ DIR);
if (imageDirectory == null || imageDirectory.trim().length() <= 0 ||
ParameterAccessor.isRelativePath(imageDirectory)) {
imageDirectory = servletContext.getRealPath("/report/images");
}
log.log(Level.INFO, "set image directoy to " + imageDirectory);
// Prepare image base url.
// XXX: Need to handle images properly!
imageBaseUrl = "/run?__imageID=";
// Prepare log directory.
String logDirectory =
context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_DI R);
if (logDirectory == null || logDirectory.trim().length() <= 0 ||
ParameterAccessor.isRelativePath(logDirectory)) {
logDirectory = servletContext.getRealPath("/logs");
}
log.log(Level.INFO, "set image directoy to " + logDirectory);
// Prepare log level.
String logLevel =
servletContext.getInitParameter(ParameterAccessor.INIT_PARAM _LOG_LEVEL);
Level level = Level.OFF;
if ("SEVERE".equalsIgnoreCase(logLevel)) {
level = Level.SEVERE;
} else if ("WARNING".equalsIgnoreCase(logLevel)) {
level = Level.WARNING;
} else if ("INFO".equalsIgnoreCase(logLevel)) {
level = Level.INFO;
} else if ("CONFIG".equalsIgnoreCase(logLevel)) {
level = Level.CONFIG;
} else if ("FINE".equalsIgnoreCase(logLevel)) {
level = Level.FINE;
} else if ("FINER".equalsIgnoreCase(logLevel)) {
level = Level.FINER;
} else if ("FINEST".equalsIgnoreCase(logLevel)) {
level = Level.FINEST;
} else if ("OFF".equalsIgnoreCase(logLevel)) {
level = Level.OFF;
}
config.setLogConfig(logDirectory, level);
log.log(Level.INFO, "set log level to " + level);
engine = new ReportEngine(config);
log.log(Level.INFO, "created engine");
}
/**
* Open report design.
*
* @param report
* @return
*/
synchronized public IReportRunnable openReportDesign(String report) {
IReportRunnable runnable = null;
try {
runnable = engine.openReportDesign(report);
} catch (Exception e) {
throw new IllegalStateException("Could not open report design " + report
+ ".", e);
}
return runnable;
}
/**
* Open report design.
*
* @param report
* @return
*/
synchronized public IReportRunnable openReportDesign(InputStream stream) {
IReportRunnable runnable = null;
try {
runnable = engine.openReportDesign(stream);
} catch (Exception e) {
}
return runnable;
}
/**
* createGetParameterDefinitionTask.
*
* @param runnable
* @return
*/
synchronized public IGetParameterDefinitionTask
createGetParameterDefinitionTask(IReportRunnable runnable) {
IGetParameterDefinitionTask task = null;
try {
task = engine.createGetParameterDefinitionTask(runnable);
} catch (Exception e) {
}
return task;
}
/**
* createRunAndRenderTask.
*
* @param runnable
* @return
*/
synchronized public IRunAndRenderTask
createRunAndRenderTask(IReportRunnable runnable) {
IRunAndRenderTask task = null;
assert runnable != null;
try {
task = engine.createRunAndRenderTask(runnable);
} catch (Exception e) {
throw new IllegalStateException("Cannot create run-and-render task", e);
}
return task;
}
/**
* Open report document from archive,
*
* @param docName - the name of the report document
* @return
*//*
synchronized public IReportDocument openReportDocument(String docName) {
IReportDocument document = null;
try {
document = engine.openReportDocument(docName);
} catch (Exception e) {
}
return document;
}*/
/**
* Run report.
*
* @param runnable
* @param archive
* @param documentName
* @param locale
* @param parameters
* @throws RemoteException
*/
synchronized public void runReport(IReportRunnable runnable, String
documentName,
Locale locale, HashMap parameters) throws RemoteException {
assert runnable != null;
// Preapre the run report task.
IRunTask runTask = engine.createRunTask(runnable);
runTask.setLocale(locale);
runTask.setParameterValues(parameters);
// Run report.
try {
runTask.run(documentName);
} catch (BirtException e) {
throw new RemoteException("BIRT Report Engine", e);
} finally {
runTask.close();
}
}
/**
* Render report page.
*
* @param reportDocument
* @param pageNumber
* @param svgFlag
* @return report page content
* @throws RemoteException
*/
synchronized public ByteArrayOutputStream renderReport(IReportDocument
reportDocument, long pageNumber, boolean svgFlag)
throws RemoteException {
assert reportDocument != null;
assert pageNumber >= 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Create render task.
IRenderTask renderTask = engine.createRenderTask(reportDocument);
// Render context
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setImageDirectory(imageDirectory);
renderContext.setBaseImageURL(contextPath + imageBaseUrl);
renderContext.setSupportedImageFormats(svgFlag ? "PNG;GIF;JPG;BMP;SVG" :
"PNG;GIF;JPG;BMP"); //$NON-NLS-2$
renderContext.setBaseURL(this.contextPath + "/frameset");
HashMap contextMap = new HashMap();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T,
renderContext);
renderTask.setAppContext(contextMap);
// Render option
HTMLRenderOption setting = new HTMLRenderOption();
setting.setOutputStream(out);
setting.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML) ;
setting.setEmbeddable(true);
renderTask.setRenderOption(setting);
// Render designated page.
try {
renderTask.render(pageNumber);
} catch (BirtException e) {
throw new RemoteException("BIRT Report Engine", e);
} catch (Exception e) {
throw new RemoteException("BIRT Report Engine", e);
} finally {
renderTask.close();
}
return out;
}
/**
* @return Returns the imageBaseUrl.
*/
public String getImageBaseUrl() {
return imageBaseUrl;
}
/**
* @return Returns the imageDirectory.
*/
public String getImageDirectory() {
return imageDirectory;
}
/**
* @return Returns the imageHandler.
*/
public HTMLServerImageHandler getImageHandler() {
return imageHandler;
}
/**
* @return Returns the contextPath.
*/
public String getContextPath() {
return contextPath;
}
}
Thanks again for any help!
Martin
|
|
|
Re: Trying (and struggling) to make a BIRT viewer JSF component [message #97628 is a reply to message #97508] |
Thu, 08 December 2005 13:58   |
Eclipse User |
|
|
|
Originally posted by: maspeli.deloitte.co.uk
I'm sorry for the monologue here, but hopefully this is useful to other
people as well (and will be if we manage to release this).
> - It renders the entire HTML page, including the DOCTYPE, <HTML> etc. Is
> there some way around this in the API? I can always use regexps to clean
it,
> but it's a bit annoying.
Still have this problem and would love a decent solution not involving
regexp replace.
> - I have an embedded image in my test report. This gets rendered as an
> empty <img> tag, no attributes, no nothing. This is using
> HTMLServerImageHandler. I haven't really done anything to handle images,
so
> I'd expected they may be broken, but I would've thought the <img> tag
output
> with the report should point to *something*!
Strangely, this stopped happening. I don't know what I did, but it works.
I've made a simple servlet that serves up images from the BIRT image
handler, and it seems to work fine.
One thing I am confused about - the BIRT runtime web app viewer gets my
images in its images/ directory and they seem to stay there. The images/
directory I've configured for my application is empty, even though images
are bein served. I use the HTMLServerImageHandler and it's writing straight
to the request in my servlet, so I suppose this is to be expected, but I'd
like to know why the birt.war application gets them and I don't. :)
> - If I try to run a report that accesses our MySQL database, I get an
> exception. The mysql JDBC connector is in the WEB-INF/lib directory of the
> deployment, and is working with Hibernate and works with the standalone
> birt.war viewer (as do images, by the way). The exception is:
I found some documentation that told me to update my plugin.xml and now it
works. Great!
So - I have a working report viewer, albeit one that spits out rather too
much HTML. It doesn't do parameters yet, though - that's step two. :)
Martin
|
|
|
Re: Trying (and struggling) to make a BIRT viewer JSF component [message #101331 is a reply to message #97628] |
Wed, 21 December 2005 16:23  |
Eclipse User |
|
|
|
Martin,
Sorry I didnt see this earlier.
This may be to late, but there is a option in the HTMLRenderOption class to
set embeddable.
This turns off the <HTML> tag. Probably to late, but wanted to let you
know.
Jason Weathersby
BIRT PMC
"Martin Aspeli" <maspeli@deloitte.co.uk> wrote in message
news:dn9voq$odi$1@news.eclipse.org...
> I'm sorry for the monologue here, but hopefully this is useful to other
> people as well (and will be if we manage to release this).
>
>> - It renders the entire HTML page, including the DOCTYPE, <HTML> etc. Is
>> there some way around this in the API? I can always use regexps to clean
> it,
>> but it's a bit annoying.
>
> Still have this problem and would love a decent solution not involving
> regexp replace.
>
>> - I have an embedded image in my test report. This gets rendered as an
>> empty <img> tag, no attributes, no nothing. This is using
>> HTMLServerImageHandler. I haven't really done anything to handle images,
> so
>> I'd expected they may be broken, but I would've thought the <img> tag
> output
>> with the report should point to *something*!
>
> Strangely, this stopped happening. I don't know what I did, but it works.
> I've made a simple servlet that serves up images from the BIRT image
> handler, and it seems to work fine.
>
> One thing I am confused about - the BIRT runtime web app viewer gets my
> images in its images/ directory and they seem to stay there. The images/
> directory I've configured for my application is empty, even though images
> are bein served. I use the HTMLServerImageHandler and it's writing
> straight
> to the request in my servlet, so I suppose this is to be expected, but I'd
> like to know why the birt.war application gets them and I don't. :)
>
>> - If I try to run a report that accesses our MySQL database, I get an
>> exception. The mysql JDBC connector is in the WEB-INF/lib directory of
>> the
>> deployment, and is working with Hibernate and works with the standalone
>> birt.war viewer (as do images, by the way). The exception is:
>
> I found some documentation that told me to update my plugin.xml and now it
> works. Great!
>
> So - I have a working report viewer, albeit one that spits out rather too
> much HTML. It doesn't do parameters yet, though - that's step two. :)
>
> Martin
>
>
|
|
|
Goto Forum:
Current Time: Sun Jun 08 12:53:53 EDT 2025
Powered by FUDForum. Page generated in 0.21147 seconds
|