package org.xins.server.frontend;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.SourceLocator;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.BasicPropertyReader;
import org.xins.common.collections.ChainedMap;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.io.IOReader;
import org.xins.common.manageable.BootstrapException;
import org.xins.common.manageable.InitializationException;
import org.xins.common.spec.FunctionSpec;
import org.xins.common.text.ParseException;
import org.xins.common.text.TextUtils;
import org.xins.common.types.EnumItem;
import org.xins.common.types.standard.Date;
import org.xins.common.types.standard.Timestamp;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementBuilder;
import org.xins.common.xml.ElementParser;
import org.xins.common.xml.ElementSerializer;
import org.xins.server.API;
import org.xins.server.CustomCallingConvention;
import org.xins.server.Function;
import org.xins.server.FunctionNotSpecifiedException;
import org.xins.server.FunctionRequest;
import org.xins.server.FunctionResult;
import org.xins.server.InvalidRequestException;
import org.xins.server.Log;
import org.znerd.xmlenc.XMLOutputter;
public class FrontendCallingConvention extends CustomCallingConvention {
private static final String RESPONSE_ENCODING = "ISO-8859-1";
private static final String XML_CONTENT_TYPE = "text/xml;charset=" + RESPONSE_ENCODING;
private static final String HTML_CONTENT_TYPE = "text/html;charset=" + RESPONSE_ENCODING;
private static final String TEMPLATES_CACHE_PROPERTY = "templates.cache";
private static final Object[] NO_ARGS = {};
private static final Class[] NO_ARGS_CLASS = {};
private final API _api;
private SessionManager _session;
private String _baseXSLTDir;
private TransformerFactory _factory;
private String _defaultCommand;
private String _loginPage;
private String _errorPage;
private Map _redirectionMap = new ChainedMap();
private Map _conditionalRedirectionMap = new HashMap();
private boolean _cacheTemplates;
private Map _templateCache = new HashMap();
private Templates _templateControl;
private Templates _templateError;
private List _functionList = new ArrayList();
public FrontendCallingConvention(API api)
throws IllegalArgumentException {
MandatoryArgumentChecker.check("api", api);
_api = api;
try {
_session = (SessionManager) api.getClass().getMethod("getSessionManager", NO_ARGS_CLASS).invoke(api, NO_ARGS);
} catch (Exception ex) {
Log.log_3700(ex);
}
}
protected void bootstrapImpl(PropertyReader bootstrapProperties)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
BootstrapException {
_loginPage = bootstrapProperties.get("xinsff.login.page");
_errorPage = bootstrapProperties.get("xinsff.error.page");
_defaultCommand = bootstrapProperties.get("xinsff.default.command");
if (_defaultCommand == null) {
_defaultCommand = "DefaultCommand";
}
_factory = TransformerFactory.newInstance();
initRedirections(bootstrapProperties);
}
protected void initImpl(PropertyReader runtimeProperties)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException {
String templatesProperty = "templates." + _api.getName() + ".xinsff.source";
_baseXSLTDir = runtimeProperties.get(templatesProperty);
if (_baseXSLTDir == null) {
throw new MissingRequiredPropertyException(templatesProperty);
}
Properties systemProps = System.getProperties();
_baseXSLTDir = TextUtils.replace(_baseXSLTDir, systemProps, "${", "}");
_baseXSLTDir = _baseXSLTDir.replace('\\', '/');
String cacheEnabled = runtimeProperties.get(TEMPLATES_CACHE_PROPERTY);
initCacheEnabled(cacheEnabled);
Iterator itFunctions = _api.getFunctionList().iterator();
while (itFunctions.hasNext()) {
Function nextFunction = (Function) itFunctions.next();
_functionList.add(nextFunction.getName());
}
}
private void initCacheEnabled(String cacheEnabled)
throws InvalidPropertyValueException {
if (TextUtils.isEmpty(cacheEnabled)) {
_cacheTemplates = true;
} else {
cacheEnabled = cacheEnabled.trim();
if ("true".equals(cacheEnabled)) {
_cacheTemplates = true;
} else if ("false".equals(cacheEnabled)) {
_cacheTemplates = false;
} else {
throw new InvalidPropertyValueException(TEMPLATES_CACHE_PROPERTY,
cacheEnabled, "Expected either \"true\" or \"false\".");
}
}
}
protected boolean matches(HttpServletRequest httpRequest) throws Exception {
return (httpRequest.getMethod().equalsIgnoreCase("GET") && httpRequest.getParameterMap().size() == 0) ||
!TextUtils.isEmpty(httpRequest.getParameter("command"));
}
protected FunctionRequest convertRequestImpl(HttpServletRequest httpRequest)
throws InvalidRequestException,
FunctionNotSpecifiedException {
String functionName = httpRequest.getParameter("command");
if (functionName == null || functionName.equals("")) {
functionName = _defaultCommand;
}
_session.request(httpRequest);
if ("Control".equals(functionName)) {
String action = httpRequest.getParameter("action");
if ("ReadConfigFile".equals(action)) {
functionName = "_ReloadProperties";
}
return new FunctionRequest(functionName, null, null, true);
}
String actionName = httpRequest.getParameter("action");
if (actionName != null && !actionName.equals("") && !actionName.toLowerCase().equals("show")) {
functionName += TextUtils.firstCharUpper(actionName);
}
if (_session.shouldLogIn() ||
(_redirectionMap.get(functionName) != null && !_functionList.contains(functionName))) {
return new FunctionRequest(functionName, null, null, true);
}
BasicPropertyReader functionParams = new BasicPropertyReader();
Enumeration params = httpRequest.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
String realName = getRealParameter(name, functionName);
String value = httpRequest.getParameter(name);
functionParams.set(realName, value);
}
String dataSectionValue = httpRequest.getParameter("_data");
Element dataElement;
if (dataSectionValue != null && dataSectionValue.length() > 0) {
ElementParser parser = new ElementParser();
try {
dataElement = parser.parse(new StringReader(dataSectionValue));
} catch (IOException ex) {
throw new InvalidRequestException("Cannot parse the data section.", ex);
} catch (ParseException ex) {
throw new InvalidRequestException("Cannot parse the data section.", ex);
}
} else {
dataElement = null;
}
return new FunctionRequest(functionName, functionParams, dataElement);
}
protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
addSessionCookie(httpRequest, httpResponse);
String mode = httpRequest.getParameter("mode");
String command = httpRequest.getParameter("command");
if (command == null || command.equals("")) {
command = _defaultCommand;
}
String action = httpRequest.getParameter("action");
if (action == null || action.equals("show")) {
action = "";
}
String functionName = command + action;
_session.result(xinsResult.getErrorCode() == null);
if ("template".equalsIgnoreCase(mode)) {
String xsltSource = getCommandXSLT(command);
httpResponse.setContentType(XML_CONTENT_TYPE);
httpResponse.setStatus(HttpServletResponse.SC_OK);
Writer output = httpResponse.getWriter();
output.write(xsltSource);
output.close();
return;
}
if ("Control".equals(command)) {
xinsResult = control(action);
}
Element commandResult = null;
String commandResultXML = null;
if (_conditionalRedirectionMap.get(functionName) != null) {
commandResult = createXMLResult(httpRequest, xinsResult);
commandResultXML = serializeResult(commandResult);
}
String redirection = getRedirection(xinsResult, command, functionName, commandResultXML);
if (redirection != null) {
if ("source".equals(mode)) {
redirection += "&mode=source";
}
httpResponse.sendRedirect(redirection);
return;
}
if (commandResult == null) {
commandResult = createXMLResult(httpRequest, xinsResult);
commandResultXML = serializeResult(commandResult);
}
if ("source".equalsIgnoreCase(mode)) {
PrintWriter out = httpResponse.getWriter();
httpResponse.setContentType(XML_CONTENT_TYPE);
httpResponse.setStatus(HttpServletResponse.SC_OK);
out.print(commandResultXML);
out.close();
} else if (command != null) {
String xsltLocation = _baseXSLTDir + command + ".xslt";
try {
Templates template = null;
if ("Control".equals(command) && _templateControl == null) {
try {
StringReader controlXSLT = new StringReader(ControlResult.getControlTemplate());
_templateControl = _factory.newTemplates(new StreamSource(controlXSLT));
template = _templateControl;
} catch (TransformerConfigurationException tcex) {
Log.log_3701(tcex, "control");
}
} else if ("Control".equals(command)) {
template = _templateControl;
} else {
template = getTemplate(xsltLocation);
}
Log.log_3704(command);
String resultHTML = translate(commandResultXML, template);
String contentType = getContentType(template.getOutputProperties());
PrintWriter out = httpResponse.getWriter();
httpResponse.setContentType(contentType);
httpResponse.setStatus(HttpServletResponse.SC_OK);
out.print(resultHTML);
out.close();
} catch (TransformerConfigurationException tcex) {
showError(tcex, httpResponse, httpRequest);
} catch (TransformerException tex) {
showError(tex, httpResponse, httpRequest);
} catch (Exception ex) {
throw new IOException(ex.getMessage());
}
}
}
private void addSessionCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
Cookie cookie = new Cookie("SessionID", _session.getSessionId());
String host = httpRequest.getHeader("host");
if (TextUtils.isEmpty(host)) {
host = httpRequest.getRemoteHost();
}
String domain = host;
if (host.indexOf(".") != -1) {
domain = host.substring(host.indexOf("."));
}
if (domain.indexOf(":") != -1) {
domain = domain.substring(0, domain.indexOf(":"));
}
cookie.setDomain(domain);
cookie.setPath("/");
httpResponse.addCookie(cookie);
}
private Element createXMLResult(HttpServletRequest httpRequest, FunctionResult xinsResult) {
ElementBuilder builder = new ElementBuilder("commandresult");
builder.setAttribute("command", httpRequest.getParameter("command"));
ElementBuilder dataSection = new ElementBuilder("data");
Map sessionProperties = _session.getProperties();
if (sessionProperties != null) {
Iterator itSessionProperties = sessionProperties.entrySet().iterator();
while (itSessionProperties.hasNext()) {
Map.Entry nextEntry = (Map.Entry) itSessionProperties.next();
String nextProperty = (String) nextEntry.getKey();
Object propValue = nextEntry.getValue();
if (propValue instanceof Element && ((Element)propValue).getLocalName().equals("data")) {
propValue = ((Element)propValue).getChildElements();
}
if (nextProperty.startsWith("_") || propValue == null) {
} else if (propValue instanceof String || propValue instanceof Number || propValue instanceof Boolean ||
propValue instanceof EnumItem || propValue instanceof Date.Value || propValue instanceof Timestamp.Value) {
ElementBuilder builderParam = new ElementBuilder("parameter");
builderParam.setAttribute("name", "session." + nextProperty);
builderParam.setText(propValue.toString());
builder.addChild(builderParam.createElement());
} else if ("org.jdom.Element".equals(propValue.getClass().getName())) {
} else if (propValue instanceof Element) {
dataSection.addChild((Element) propValue);
} else if (propValue instanceof List) {
Iterator itPropValue = ((List) propValue).iterator();
while (itPropValue.hasNext()) {
Object nextPropertyInList = itPropValue.next();
if (nextPropertyInList == null) {
} else if ("org.jdom.Element".equals(nextPropertyInList.getClass().getName())) {
} else if (nextPropertyInList instanceof Element) {
dataSection.addChild((Element) nextPropertyInList);
}
}
}
}
}
Enumeration inputParameterNames = httpRequest.getParameterNames();
while (inputParameterNames.hasMoreElements()) {
String nextParameter = (String) inputParameterNames.nextElement();
ElementBuilder builderParam = new ElementBuilder("parameter");
builderParam.setAttribute("name", "input." + nextParameter);
builderParam.setText(httpRequest.getParameter(nextParameter));
builder.addChild(builderParam.createElement());
}
PropertyReader parameters = xinsResult.getParameters();
if (parameters != null) {
Iterator parameterNames = parameters.getNames();
while (parameterNames.hasNext()) {
String nextParameter = (String) parameterNames.next();
if (!"redirect".equals(nextParameter)) {
ElementBuilder builderParam = new ElementBuilder("parameter");
builderParam.setAttribute("name", nextParameter);
builderParam.setText(parameters.get(nextParameter));
builder.addChild(builderParam.createElement());
}
}
}
if (xinsResult.getErrorCode() != null) {
if (xinsResult.getErrorCode().equals("_InvalidRequest") ||
xinsResult.getErrorCode().equals("InvalidRequest")) {
addParameter(builder, "error.type", "FieldError");
ElementBuilder errorSection = new ElementBuilder("errorlist");
Iterator incorrectParams = xinsResult.getDataElement().getChildElements().iterator();
while (incorrectParams.hasNext()) {
Element incorrectParamElement = (Element) incorrectParams.next();
String elementName = incorrectParamElement.getLocalName();
if (elementName.equals("param-combo")) {
Iterator incorrectParamCombo = incorrectParamElement.getChildElements("param").iterator();
while (incorrectParamCombo.hasNext()) {
Element incorrectParamComboElement = (Element) incorrectParamCombo.next();
String paramName = incorrectParamComboElement.getAttribute("name");
Element fieldError = createFieldError(elementName, paramName);
errorSection.addChild(fieldError);
}
} else {
String paramName = incorrectParamElement.getAttribute("param");
Element fieldError = createFieldError(elementName, paramName);
errorSection.addChild(fieldError);
}
}
dataSection.addChild(errorSection.createElement());
builder.addChild(dataSection.createElement());
return builder.createElement();
} else {
addParameter(builder, "error.type", "FunctionError");
addParameter(builder, "error.code", xinsResult.getErrorCode());
}
}
Element resultElement = xinsResult.getDataElement();
if (resultElement != null) {
Iterator itChildren = resultElement.getChildElements().iterator();
while (itChildren.hasNext()) {
dataSection.addChild((Element) itChildren.next());
}
}
builder.addChild(dataSection.createElement());
return builder.createElement();
}
private Element createFieldError(String elementName, String paramName) {
paramName = getOriginalParameter(paramName);
ElementBuilder fieldError = new ElementBuilder("fielderror");
fieldError.setAttribute("field", paramName);
if (elementName.equals("missing-param")) {
fieldError.setAttribute("type", "mand");
} else if (elementName.equals("invalid-value-for-type")) {
fieldError.setAttribute("type", "format");
} else {
fieldError.setAttribute("type", elementName);
}
return fieldError.createElement();
}
private void addParameter(ElementBuilder builder, String name, String value) {
ElementBuilder builderParam = new ElementBuilder("parameter");
builderParam.setAttribute("name", name);
builderParam.setText(value);
builder.addChild(builderParam.createElement());
}
private String serializeResult(Element commandResult) {
Writer buffer = new StringWriter(2048);
try {
XMLOutputter xmlout = new XMLOutputter(buffer, RESPONSE_ENCODING);
ElementSerializer serializer = new ElementSerializer();
serializer.output(xmlout, commandResult);
return buffer.toString();
} catch (IOException ioe) {
Log.log_3702(ioe);
return null;
}
}
private String translate(String xmlInput, Templates template) throws Exception {
try {
Transformer xformer = template.newTransformer();
Source source = new StreamSource(new StringReader(xmlInput));
Writer buffer = new StringWriter(8192);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
return buffer.toString();
} catch (TransformerConfigurationException tcex) {
Log.log_3701(tcex, "<unknown>");
throw tcex;
} catch (TransformerException tex) {
SourceLocator locator = tex.getLocator();
if (locator != null) {
int line = locator.getLineNumber();
int col = locator.getColumnNumber();
String publicId = locator.getPublicId();
String systemId = locator.getSystemId();
Log.log_3703(tex, String.valueOf(line), String.valueOf(col), publicId, systemId);
} else {
Log.log_3703(tex, "<unknown>", "<unknown>", "<unknown>", "<unknown>");
}
throw tex;
}
}
private Templates getTemplate(String xsltUrl) throws Exception {
Templates template;
if (_cacheTemplates && _templateCache.containsKey(xsltUrl)) {
template = (Templates) _templateCache.get(xsltUrl);
} else {
try {
template = _factory.newTemplates(new StreamSource(xsltUrl));
if (_cacheTemplates) {
_templateCache.put(xsltUrl, template);
}
} catch (TransformerConfigurationException tcex) {
Log.log_3701(tcex, xsltUrl);
throw tcex;
}
}
return template;
}
private String getCommandXSLT(String command) throws IOException {
String xsltLocation = _baseXSLTDir + command + ".xslt";
InputStream inputXSLT = new URL(xsltLocation).openStream();
return IOReader.readFully(inputXSLT);
}
private String getContentType(Properties outputProperties) {
String mimeType = outputProperties.getProperty("media-type");
if (TextUtils.isEmpty(mimeType)) {
String method = outputProperties.getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = outputProperties.getProperty("encoding");
if (!TextUtils.isEmpty(mimeType) && !TextUtils.isEmpty(encoding)) {
mimeType += ";charset=" + encoding;
}
if (!TextUtils.isEmpty(mimeType)) {
return mimeType;
} else {
return HTML_CONTENT_TYPE;
}
}
private FunctionResult control(String action) {
if ("RemoveSessionProperties".equals(action)) {
_session.removeProperties();
} else if ("FlushCommandTemplateCache".equals(action)) {
_templateCache.clear();
} else if ("RefreshCommandTemplateCache".equals(action)) {
_templateCache.clear();
String xsltLocation;
Iterator itRealFunctions = _api.getFunctionList().iterator();
while (itRealFunctions.hasNext()) {
Function nextFunction = (Function) itRealFunctions.next();
String nextCommand = nextFunction.getName();
xsltLocation = _baseXSLTDir + nextCommand + ".xslt";
try {
Templates template = _factory.newTemplates(new StreamSource(xsltLocation));
_templateCache.put(xsltLocation, template);
} catch (TransformerConfigurationException tcex) {
}
}
Iterator itVirtualFunctions = _redirectionMap.entrySet().iterator();
while (itVirtualFunctions.hasNext()) {
Map.Entry nextFunction = (Map.Entry) itVirtualFunctions.next();
xsltLocation = _baseXSLTDir + nextFunction.getKey() + ".xslt";
if (nextFunction.getValue().equals("-")) {
try {
Templates template = _factory.newTemplates(new StreamSource(xsltLocation));
_templateCache.put(xsltLocation, template);
} catch (TransformerConfigurationException tcex) {
}
}
}
}
return new ControlResult(_api, _session, _redirectionMap);
}
private String getRedirection(FunctionResult xinsResult, String command,
String functionName, String xmlResult) {
String redirection = xinsResult.getParameter("redirect");
if (_session.shouldLogIn() || (redirection == null && "NotLoggedIn".equals(xinsResult.getErrorCode()))) {
redirection = _loginPage + "&targetcommand=" + command;
}
if (redirection == null && xinsResult.getErrorCode() == null && _conditionalRedirectionMap.get(functionName) != null) {
Templates conditionTemplate = (Templates) _conditionalRedirectionMap.get(functionName);
try {
redirection = translate(xmlResult, conditionTemplate);
} catch (Exception ex) {
}
}
if (redirection == null && xinsResult.getErrorCode() == null) {
redirection = (String) _redirectionMap.get(functionName);
}
if (redirection == null || redirection.equals("-") ||
(xinsResult.getErrorCode() != null && "NotLoggedIn".equals(xinsResult.getErrorCode()))) {
return null;
}
if (redirection.equals("/")) {
redirection = _defaultCommand;
} else if (!redirection.startsWith("http://") && !redirection.startsWith("https://")) {
redirection = "?command=" + redirection;
PropertyReader parameters = xinsResult.getParameters();
if (parameters != null) {
Iterator parameterNames = parameters.getNames();
while (parameterNames.hasNext()) {
String nextParameter = (String) parameterNames.next();
if (!"redirect".equals(nextParameter)) {
redirection += "&" + nextParameter + '=' + parameters.get(nextParameter);
}
}
}
}
return redirection;
}
private void initRedirections(PropertyReader bootstrapProperties) {
TreeMap conditionalRedirectionProperties = new TreeMap();
Iterator itProperties = bootstrapProperties.getNames();
while (itProperties.hasNext()) {
String nextProp = (String) itProperties.next();
if (nextProp.startsWith("xinsff.redirect.")) {
String command = nextProp.substring(16);
String redirectionPage = bootstrapProperties.get(nextProp);
int conditionalPos = command.indexOf('[');
if (conditionalPos != -1) {
conditionalRedirectionProperties.put(command, redirectionPage);
} else {
_redirectionMap.put(command, redirectionPage);
}
}
}
String startXSLT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" +
"<xsl:output omit-xml-declaration=\"yes\" />\n" +
"<xsl:template match=\"commandresult\">\n" +
"<xsl:choose>\n";
Iterator itConditions = conditionalRedirectionProperties.entrySet().iterator();
String currentCommand = null;
String xsltText = null;
while (itConditions.hasNext()) {
Map.Entry nextCondition = (Map.Entry) itConditions.next();
String nextKey = (String) nextCondition.getKey();
int conditionPos = nextKey.indexOf('[');
String command = nextKey.substring(0, conditionPos);
String condition = nextKey.substring(conditionPos + 1, nextKey.length() - 1);
String redirectionPage = (String) nextCondition.getValue();
if (currentCommand != null && !currentCommand.equals(command)) {
finishConditionalTemplate(command, xsltText);
currentCommand = null;
}
if (currentCommand == null) {
xsltText = startXSLT;
currentCommand = command;
}
xsltText += "<xsl:when test=\"" + condition + "\"><xsl:text>" + redirectionPage + "</xsl:text></xsl:when>\n";
if (!itConditions.hasNext()) {
finishConditionalTemplate(command, xsltText);
}
}
}
private void finishConditionalTemplate(String command, String currentXSLT) {
String defaultRedirection = (String) _redirectionMap.get(command);
if (defaultRedirection == null) {
defaultRedirection = "-";
}
String xsltText = currentXSLT;
xsltText += "<xsl:when test=\"not(param[@name='error.type'])\"><xsl:text>" + defaultRedirection + "</xsl:text></xsl:when>\n";
xsltText += "<xsl:otherwise><xsl:text>-</xsl:text></xsl:otherwise>\n";
xsltText += "</xsl:choose></xsl:template></xsl:stylesheet>";
try {
StringReader conditionXSLT = new StringReader(xsltText);
Templates conditionTemplate = _factory.newTemplates(new StreamSource(conditionXSLT));
_conditionalRedirectionMap.put(command, conditionTemplate);
} catch (TransformerConfigurationException tcex) {
Log.log_3701(tcex, "conditional redirection for " + command + " command");
}
}
private void showError(Exception transformException, HttpServletResponse httpResponse,
HttpServletRequest httpRequest) throws IOException {
try {
FunctionResult errorResult = new ErrorResult(transformException, httpRequest);
if (_templateError == null) {
if (_errorPage == null) {
try {
StringReader errorXSLT = new StringReader(ErrorResult.getDefaultErrorTemplate());
_templateError = _factory.newTemplates(new StreamSource(errorXSLT));
} catch (TransformerConfigurationException tcex) {
Log.log_3701(tcex, "error");
}
} else {
_templateError = getTemplate(_baseXSLTDir + _errorPage + ".xslt");
}
}
Element commandResult = createXMLResult(httpRequest, errorResult);
String commandResultXML = serializeResult(commandResult);
String resultHTML = translate(commandResultXML, _templateError);
String contentType = getContentType(_templateError.getOutputProperties());
PrintWriter out = httpResponse.getWriter();
httpResponse.setContentType(contentType);
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
out.print(resultHTML);
out.close();
} catch (Exception ex) {
if (ex instanceof IOException) {
throw (IOException)ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException)ex;
} else {
throw new IOException(ex.getMessage());
}
}
}
private String getRealParameter(String receivedParameter, String functionName) {
String flatParameter = receivedParameter;
if (receivedParameter.indexOf("_") != -1) {
flatParameter = TextUtils.removeCharacter('_', receivedParameter);
}
try {
FunctionSpec function = _api.getAPISpecification().getFunction(functionName);
Set parametersSet = function.getInputParameters().keySet();
if (parametersSet.contains(receivedParameter)) {
return receivedParameter;
}
Iterator itParameters = parametersSet.iterator();
while (itParameters.hasNext()) {
String nextParameterName = (String) itParameters.next();
if (nextParameterName.equalsIgnoreCase(flatParameter)) {
return nextParameterName;
}
}
} catch (Exception ex) {
}
return receivedParameter;
}
private String getOriginalParameter(String parameter) {
Map inputs = (Map) _session.getProperty("_inputs");
Iterator itParameterNames = inputs.keySet().iterator();
while (itParameterNames.hasNext()) {
String nextParam = (String) itParameterNames.next();
String flatParam = TextUtils.removeCharacter('_', nextParam);
if (parameter.equalsIgnoreCase(flatParam)) {
return nextParam;
}
}
return parameter;
}
}