diff --git a/specialpurpose/pricat/build.gradle b/specialpurpose/pricat/build.gradle
new file mode 100644
index 0000000000..6a59b82fd1
--- /dev/null
+++ b/specialpurpose/pricat/build.gradle
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+dependencies {
+ pluginLibsCompile 'org.safehaus.jug:jug:2.0.0:asl'
+ pluginLibsCompile 'org.apache.poi:poi-ooxml:3.14'
+ pluginLibsCompile 'org.apache.poi:poi-ooxml-schemas:3.14'
+ pluginLibsCompile 'org.apache.poi:poi-excelant:3.14'
+ pluginLibsCompile 'org.apache.poi:poi-scratchpad:3.14'
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/config/PricatUiLabels.xml b/specialpurpose/pricat/config/PricatUiLabels.xml
new file mode 100644
index 0000000000..239509f5f6
--- /dev/null
+++ b/specialpurpose/pricat/config/PricatUiLabels.xml
@@ -0,0 +1,532 @@
+
+
+
+
+ OFBiz: PriCat Demo
+ OFBiz:价目表
+
+
+ PriCat
+ 价目表
+
+
+ OFBiz: PriCat Demo
+ OFBiz:价目表演示
+
+
+ PriCat Demo
+ 价目表演示
+
+
+ HTML Report Demo - Count Down
+ 页面输出演示 - 倒计数
+
+
+ HTML Report Demo - Count Up
+ 页面输出演示 - 正计数
+
+
+ PriCat Demo - Parse PriCat
+ 价目表演示 - 解析价目表
+
+
+ PriCat Demo Main Page
+ 价目表演示首页
+
+
+ PriCat Demo includes 2 HTML Report Demo and 1 Parse PriCat File Demo.
+ 价目表演示包含了2个页面输出演示和1个解析价目表文件的演示。
+
+
+ Parse Sample PriCat Demo
+ 演示解析样例价目表文件
+
+
+ Sample PriCat Template
+ 价目表样例模板
+
+
+ Download PriCat Template
+ 下载价目表模板
+
+
+ Upload PriCat
+ 上传价目表
+
+
+ Parse Sample PriCat
+ 解析样例价目表
+
+
+ Template Type
+ 模板类型
+
+
+ Sample PriCat
+ 样例价目表
+
+
+ OFBiz Type
+ OFBiz类型
+
+
+ Storing your upload file to server ...
+ 正在把上传文件存到服务器中 ...
+
+
+ no file uploaded!
+ 没有上传文件!
+
+
+ Start parsing the uploaded file ...
+ 开始解析上传的文件 ...
+
+
+ ... parsing completed
+ ... 完成解析
+
+
+ Cannot find any facility for current user(userLoginId: [{0}]).
+ 没有找到当前用户(userLoginId: [{0}])的任何一个仓库。
+
+
+ Getting facilities of current user ...
+ 正在获得当前用户的仓库 ...
+
+
+ ({0}) Facility found for current user: {1}[{2}].
+ ({0}) 找到当前用户的仓库:{1}[{2}]。
+
+
+ Facility {0}[{1}] does not belong to you. Please use a facility of yours.
+ 仓库{0}[{1}]不属于你,请改为你自己的仓库。
+
+
+ The selected Excel template type:
+ 选择的Excel模板类型:
+
+
+ The selected facility Id:
+ 选择的仓库编号:
+
+
+ Loading file {0} ...
+ 正在读入文件{0} ...
+
+
+ Please make sure your Excel file is in format of Microsoft Excel 2007 and later. And then try again.
+ 请确认你的Excel文件格式是微软Office 2007或更新版本的,然后重试一下。
+
+
+ Checking whether your file contains at least a sheet ...
+ 正在检查你的文件是否包含至少一个表单 ...
+
+
+ Pricat Version {0} is not supported.
+ 还不能支持这个价格分类的版本{0}。
+
+
+ Only the 1st sheet will be parsed.
+ 只解析第一张表。
+
+
+ There's no sheet in the PriCat file.
+ 价格分类文件中没有表。
+
+
+ Sheet [{2}] has {0} rows of header and {1} rows of data.
+ 表单[{2}]有{0}行表头和{1}行数据。
+
+
+ Sheet [{0}] has only 1 row of data.
+ 表单[{0}]只有一行数据。
+
+
+ There's no row in sheet [{0}].
+ 表单[{0}]中没有数据。
+
+
+ The sheet has {0} columns, it's not the same as sample sheet's {1}.
+ 表单有{0}列,与样例表单的{1}列不同。
+
+
+ The column {0} has a name {1}, it's not identical to {2}.
+ 列{0}的名字是{1},应是{2}。
+
+
+ ({0}) parsing {1} ...
+ ({0}) 正在解析 {1} ...
+
+
+ Check PriCat file's version ...
+ 检查价格分类文件的版本 ...
+
+
+ Checking currencyId ...
+ 正在检查币种 ...
+
+
+ CurrencyId is required. Please set it at row 3 column 2.
+ 必须设置货币。请设置在第三行、第二列。
+
+
+ CurrencyId is {0}
+ 货币是{0}
+
+
+ CurrencyId {0} cannot be found in this system.
+ 本系统中找不到货币{0}。
+
+
+ {0} is not a currency in this system.
+ {0}在这个系统里不是货币。
+
+
+ There are errors in PriCat header. Please correct it and upload it again.
+ 表头中有错误,请修改后重新上传。
+
+
+ There are no data in your PriCat file, no further operation is required.
+ 你的价格分类文件中没有数据,不再做数据解析了。
+
+
+ There are errors in data of your PriCat file. Please correct it and upload it again.
+ 价格分类文件的数据中有错误,请修改后重新上传。
+
+
+ The type of cell[{0}, {1}] is not String. The cell value will be changed to String type.
+ 单元格[{0}, {1}]不是字符类型。将把这个单元格的值转为字符类型。
+
+
+ The type of cell[{0}, {1}] is not numeric. The cell value will be changed to numeric type.
+ 单元格[{0}, {1}]不是数字类型。将把这个单元格的值转为数字类型。
+
+
+ Unable to parse the value to a numeric.
+ 无法把这个单元格的值转为数字。
+
+
+ Checking whether the number of header columns matches the template's of version {0} ...
+ 正在检查表头的列数是否与版本{0}的模板一致 ...
+
+
+ The number of columns of {0} template header columns, column number {1} and imported template columns are not consistent ...
+ 模板表头的列数{0}列,与导入的模板的列数{1}列不一致 ...
+
+
+ Checking whether the header labels match the template's of version {0} ...
+ 正在检查表头的文字是否与版本{0}的模板一致 ...
+
+
+ The lable of row {0} colum {1} is [{2}], it does not match [{3}] as expected.
+ 行{0}列{1}的文字是[{2}],与期望的[{3}]不一致。
+
+
+ Table header column number less than the required {0}
+ 表头列数小于要求的{0}列
+
+
+ the first {0} column labels will be checked
+ 将检查表头的前{0}列的标签
+
+
+ Writing errors as commonts to your Excel file ...
+ 正在把错误信息作为批注写到你的Excel文件里 ...
+
+
+ Start to clean log and commented excel files
+ 开始清理日志和批注过的Excel文件
+
+
+ history entries less than {0}
+ 历史记录少于{0}条
+
+
+ {0} entries to remove
+ 要删除{0}条记录
+
+
+ In the system, the name of facilityId[{0}] is [{1}], NOT [{2}]. Please correct it and import again.
+ 系统中,仓库标识[{0}]的名称是[{1}],不是[{2}]。请修改后重新导入。
+
+
+ empty row
+ 空行
+
+
+
+ Exception:
+ 意外错误:
+
+
+ OK
+ 确定
+
+
+ Cancel
+ 取消
+
+
+ Edit
+ 编辑
+
+
+ Discard
+ 放弃
+
+
+ Close
+ 关闭
+
+
+ Advance
+ 高级
+
+
+ Set
+ 设置
+
+
+ Back
+ 返回
+
+
+ Continue
+ 继续
+
+
+ Detail
+ 详细
+
+
+ Download
+ 下载
+
+
+ ({0}) This is default format.
+ ({0}) 这是缺省格式。
+
+
+ ({0}) This is warning format.
+ ({0}) 这是警告格式。
+
+
+ ({0}) This is headline format.
+ ({0}) 这是标题格式。
+
+
+ ({0}) This is note format.
+ ({0}) 这是记录格式。
+
+
+ ({0}) This is OK format.
+ ({0}) 这是正确时的格式。
+
+
+ ({0}) This is error format.
+ ({0}) 这是错误时的格式。
+
+
+ ({0}) This is throwable format.
+ ({0}) 这是抛出错误的格式。
+
+
+ Start counting down ...
+ 开始倒数 ...
+
+
+ ... counting completed.
+ ... 完成计数。
+
+
+ String counting up ...
+ 开始正计数 ...
+
+
+ Error:
+ 错误:
+
+
+ Details:
+ 详细:
+
+
+ Click here to see Import Excel demo
+ 点击这里看导入Excel演示
+
+
+ Start parsing a sample excel file ...
+ 开始解析一个Excel样例文件 ...
+
+
+ ... parsing completed
+ ... 完成解析
+
+
+ Only the 1st sheet will be parsed.
+ 只解析第一张表。
+
+
+ There's no sheet in the excel.
+ Excel中没有表。
+
+
+ Sheet {1} has {0} rows.
+ 表单{1}有{0}行数据。
+
+
+ Sheet {0} has only 1 row.
+ 表单{0}只有一行数据。
+
+
+ There's no row in sheet {0}.
+ 表单{0}中没有数据。
+
+
+ The sheet has {0} columns, it's not the same as sample sheet's {1}.
+ 表单有{0}列,与样例表单的{1}列不同。
+
+
+ The column {0} has a name {1}, it's not identical to {2}.
+ 列{0}的名字是{1},应是{2}。
+
+
+ ({0}) parsing {1} ...
+ ({0}) 正在解析 {1} ...
+
+
+ Using {0} to parsing the excel file.
+ 正在使用{0}解析Excel文件。
+
+
+ Using {0} to parsing the {1} format excel file...
+ 正在使用{0}解析{1}格式的Excel文件...
+
+
+ ok
+ 完成
+
+
+ error
+ 出错了
+
+
+ skipped
+ 跳过
+
+
+
+ Excel Import History
+ Excel导入操作历史记录
+
+
+ (Only current login user's history can be displayed)
+ (仅能显示当前用户的导入操作历史记录)
+
+
+ No.
+ 序号
+
+
+ Filename
+ 文件名
+
+
+ Start Time
+ 开始时间
+
+
+ End Time
+ 结束时间
+
+
+ End Reason
+ 结束原因
+
+
+ Import Status
+ 导入状态
+
+
+ Actions
+ 操作
+
+
+ No excel import history data.
+ 没有Excel导入历史记录
+
+
+ Importing
+ 正在导入
+
+
+ Imported
+ 已导入
+
+
+ Success
+ 成功
+
+
+ Stopped by user
+ 用户终止了导入
+
+
+ Stopped by error
+ 因出错而停止了导入
+
+
+ Data error found
+ 数据中有错误
+
+
+ View log content
+ 浏览日志内容
+
+
+ Download excel
+ 下载Excel
+
+
+ View Import History
+ 导入操作历史记录
+
+
+ View
+ 浏览
+
+
+ Download
+ 下载
+
+
+
+ OK
+
+
+ [S]
+
+
+ [E]
+
+
+ [W]
+
+
diff --git a/specialpurpose/pricat/config/pricat.properties b/specialpurpose/pricat/config/pricat.properties
new file mode 100644
index 0000000000..65c7b34ca5
--- /dev/null
+++ b/specialpurpose/pricat/config/pricat.properties
@@ -0,0 +1,24 @@
+###############################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+###############################################################################
+
+# the latest pricat version to parse and download
+pricat.latest.version=V1.1
+
+# the max number of pricat history files to keep
+pricat.history.max.filenumber=20
diff --git a/specialpurpose/pricat/data/PricatData.xml b/specialpurpose/pricat/data/PricatData.xml
new file mode 100644
index 0000000000..1fe9314263
--- /dev/null
+++ b/specialpurpose/pricat/data/PricatData.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/entitydef/entitymodel.xml b/specialpurpose/pricat/entitydef/entitymodel.xml
new file mode 100644
index 0000000000..b8611499f9
--- /dev/null
+++ b/specialpurpose/pricat/entitydef/entitymodel.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImport.groovy b/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImport.groovy
new file mode 100644
index 0000000000..ffa9297c50
--- /dev/null
+++ b/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImport.groovy
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import org.apache.ofbiz.base.util.*;
+
+module = "FindMyExcelImport.groovy";
+
+data = delegator.findByAnd("ExcelImportHistory", [userLoginId : userLogin.userLoginId], ["sequenceNum DESC"], false);
+context.data = data;
diff --git a/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImportLog.groovy b/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImportLog.groovy
new file mode 100644
index 0000000000..8eef0970ee
--- /dev/null
+++ b/specialpurpose/pricat/groovyScripts/pricat/FindMyExcelImportLog.groovy
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import org.apache.ofbiz.base.util.*;
+import java.io.FileInputStream;
+
+module = "FindMyExcelImport.groovy";
+
+context.borderStyle = "2px inset /*begin-color ThreeDHighlight*/#ffffff/*end-color*/";
+context.borderSimpleStyle = "2px solid /*begin-color ThreeDFace*/#f0f0f0/*end-color*/";
+
+sequenceNum = request.getParameter("sequenceNum");
+
+if (sequenceNum == null) {
+ context.logFileContent = "No sequenceNum parameter found.";
+ return;
+}
+
+historyEntry = delegator.findOne("ExcelImportHistory", [sequenceNum : Long.valueOf(sequenceNum), userLoginId : userLogin.userLoginId], false);
+if (historyEntry == null) {
+ context.logFileContent = "No import history found.";
+ return;
+}
+
+logFile = FileUtil.getFile("runtime/pricat/" + userLogin.userLoginId + "/" + sequenceNum + ".log");
+if (!logFile.exists()) {
+ context.logFileContent = "No log file found.";
+}
+
+FileInputStream fis = new FileInputStream(logFile);
+InputStreamReader isr = new InputStreamReader(fis);
+BufferedReader br = new BufferedReader(isr);
+logFileContent = "";
+while((s = br.readLine())!=null){
+ logFileContent += s;
+}
+context.logFileContent = logFileContent;
+
diff --git a/specialpurpose/pricat/ofbiz-component.xml b/specialpurpose/pricat/ofbiz-component.xml
new file mode 100644
index 0000000000..4fb0c2e492
--- /dev/null
+++ b/specialpurpose/pricat/ofbiz-component.xml
@@ -0,0 +1,46 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java
new file mode 100644
index 0000000000..52fc5f6cd4
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java
@@ -0,0 +1,144 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import java.io.IOException;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.jsp.JspException;
+
+import org.apache.ofbiz.htmlreport.util.ReportStringUtil;
+
+/**
+ * HTML report output to be used for database create tables / drop tables operations.
+ *
+ */
+public abstract class AbstractHtmlReport extends HtmlReport {
+
+ public static final String module = AbstractHtmlReport.class.getName();
+
+ public final static String THREAD_TYPE = "thread_type";
+
+ public final static String RUN_CREATETABLE_SCRIPT = "runcreatetablescript";
+
+ public final static String RUN_DROPTABLE_SCRIPT = "rundroptablescript";
+
+ public final static String FILE_REPORT_OUTPUT = "specialpurpose/pricat/webapp/pricat/ftl/report.ftl";
+
+ /**
+ * Constructs a new report using the provided locale for the output language.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ public AbstractHtmlReport(HttpServletRequest request, HttpServletResponse response) {
+ this(request, response, false, false);
+ }
+
+ /**
+ * Constructs a new report using the provided locale for the output language.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @param writeHtml if true, this report should generate HTML instead of JavaScript output
+ * @param isTransient If set to true nothing is kept in memory
+ */
+ public AbstractHtmlReport(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient) {
+ super(request, response, writeHtml, isTransient);
+ }
+
+ /**
+ * Prepare display an html report.
+ *
+ * @throws JspException if dialog actions fail
+ * @throws IOException
+ * @throws ServletException
+ * @throws TemplateException
+ * @throws IOException
+ */
+ public void prepareDisplayReport(HttpServletRequest request, HttpServletResponse response, String name, String dialogUri) throws IOException {
+
+ if (ReportStringUtil.isNotEmpty(dialogUri)) {
+ setDialogRealUri(request, dialogUri);
+ }
+
+ String action = getParamAction(request);
+ if (action == null) action = "";
+ if (action.equals("reportend") || action.equals("cancel")) {
+ setParamAction("reportend");
+ } else if (action.equals("reportupdate")) {
+ setParamAction("reportupdate");
+ } else {
+ InterfaceReportThread thread = initializeThread(request, response, name);
+ thread.start();
+ setParamAction("reportbegin");
+ setParamThread(thread.getUUID().toString());
+ }
+ }
+
+ /**
+ * Initializes the report thread to use for this report.
+ *
+ * @return the reported thread to use for this report.
+ */
+ public abstract InterfaceReportThread initializeThread(HttpServletRequest request, HttpServletResponse response, String name);
+
+ /**
+ * Set the report dialog uri.
+ *
+ * @param dialogUri
+ */
+ public void setDialogRealUri(HttpServletRequest request, String dialogUri) {
+ request.setAttribute(DIALOG_URI, dialogUri);
+ }
+
+ public static String checkButton(HttpServletRequest request, HttpServletResponse response) {
+ String action = request.getParameter("action");
+ if (ReportStringUtil.isNotEmpty(action)) {
+ if (action.equalsIgnoreCase("ok")) {
+ request.removeAttribute(SESSION_REPORT_CLASS);
+ request.removeAttribute(DIALOG_URI);
+ return "ok";
+ } else if (action.equalsIgnoreCase("cancel")) {
+ request.removeAttribute(SESSION_REPORT_CLASS);
+ request.removeAttribute(DIALOG_URI);
+ return "cancel";
+ }
+ }
+ action = request.getParameter("ok");
+ if (ReportStringUtil.isNotEmpty(action)) {
+ if (action.equalsIgnoreCase("ok")) {
+ request.removeAttribute(SESSION_REPORT_CLASS);
+ request.removeAttribute(DIALOG_URI);
+ return "ok";
+ }
+ }
+ action = request.getParameter("cancel");
+ if (ReportStringUtil.isNotEmpty(action)) {
+ if (action.equalsIgnoreCase("cancel")) {
+ request.removeAttribute(SESSION_REPORT_CLASS);
+ request.removeAttribute(DIALOG_URI);
+ return "cancel";
+ }
+ }
+
+ return "success";
+ }
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReport.java
new file mode 100644
index 0000000000..783dddc474
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReport.java
@@ -0,0 +1,187 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Base report class.
+ *
+ */
+public abstract class AbstractReport implements InterfaceReport {
+
+ /** Contains all error messages generated by the report. */
+ private List errors;
+
+ /** The locale this report is written in. */
+ private Locale locale;
+
+ /** Runtime of the report. */
+ private long startTime;
+
+ /** Contains all warning messages generated by the report. */
+ private List warnings = new ArrayList();
+
+ /** Day constant. */
+ private static final long DAYS = 1000 * 60 * 60 * 24;
+
+ /** Hour constant. */
+ private static final long HOURS = 1000 * 60 * 60;
+
+ /** Minute constant. */
+ private static final long MINUTES = 1000 * 60;
+
+ /** Second constant. */
+ private static final long SECONDS = 1000;
+
+ public static final String SESSION_REPORT_CLASS = "OFBIZ_HTML_REPORT";
+
+ public void addError(Object obj) {
+
+ errors.add(obj);
+ }
+
+ public void addWarning(Object obj) {
+
+ warnings.add(obj);
+ }
+
+ public String formatRuntime() {
+
+ long runtime = getRuntime();
+ long seconds = (runtime / SECONDS) % 60;
+ long minutes = (runtime / MINUTES) % 60;
+ long hours = (runtime / HOURS) % 24;
+ long days = runtime / DAYS;
+ StringBuffer strBuf = new StringBuffer();
+
+ if (days > 0) {
+ if (days < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(days);
+ strBuf.append(':');
+ }
+
+ if (hours < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(hours);
+ strBuf.append(':');
+
+ if (minutes < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(minutes);
+ strBuf.append(':');
+
+ if (seconds < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(seconds);
+
+ return strBuf.toString();
+ }
+
+ public List getErrors() {
+ return errors;
+ }
+
+ public Locale getLocale() {
+ return locale;
+ }
+
+ public long getRuntime() {
+ return System.currentTimeMillis() - startTime;
+ }
+
+ public List getWarnings() {
+ return warnings;
+ }
+
+ public boolean hasError() {
+ return (errors.size() > 0);
+ }
+
+ public boolean hasWarning() {
+ return (warnings.size() > 0);
+ }
+
+ public void resetRuntime() {
+ startTime = System.currentTimeMillis();
+ }
+
+ /**
+ * Initializes some member variables for this report.
+ *
+ * @param locale the locale for this report
+ */
+ protected void init(Locale locale) {
+ startTime = System.currentTimeMillis();
+ this.locale = locale;
+ errors = new ArrayList();
+ }
+
+ /**
+ * Prints a String to the report.
+ *
+ * @param value the String to add
+ */
+ public void print(String value) {
+ print(value, FORMAT_DEFAULT);
+ }
+
+ /**
+ * Prints a String to the report, using the indicated formatting.
+ *
+ * Use the contants starting with FORMAT from this interface
+ * to indicate which formatting to use.
+ *
+ * @param value the message container to add
+ * @param format the formatting to use for the output
+ */
+ public abstract void print(String value, int format);
+
+ /**
+ * Prints a String with line break to the report.
+ *
+ * @param value the message container to add
+ */
+ public void println(String value) {
+
+ println(value, FORMAT_DEFAULT);
+ }
+
+ /**
+ * Prints a String with line break to the report, using the indicated formatting.
+ *
+ * Use the contants starting with FORMAT from this interface
+ * to indicate which formatting to use.
+ *
+ * @param value the String to add
+ * @param format the formatting to use for the output
+ */
+ public void println(String value, int format) {
+ print(value, format);
+ println();
+ }
+
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java
new file mode 100644
index 0000000000..fca4b74c0b
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java
@@ -0,0 +1,217 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import java.util.List;
+import java.util.Locale;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.ofbiz.base.util.UtilHttp;
+import org.safehaus.uuid.EthernetAddress;
+import org.safehaus.uuid.UUID;
+import org.safehaus.uuid.UUIDGenerator;
+
+/**
+ * Provides a common Thread class for the reports.
+ *
+ */
+public abstract class AbstractReportThread extends Thread implements InterfaceReportThread {
+
+ /** Indicates if the thread was already checked by the grim reaper. */
+ private boolean doomed;
+
+ /** The report that belongs to the thread. */
+ private InterfaceReport report;
+
+ /** The time this report is running. */
+ private long startTime;
+
+ private UUID uuid;
+
+ private Locale locale;
+
+ /**
+ * Constructs a new report Thread with the given name.
+ *
+ * @param name the name of the Thread
+ */
+ protected AbstractReportThread(HttpServletRequest request, HttpServletResponse response, String name) {
+
+ super(Thread.currentThread().getThreadGroup(), name);
+ // report Threads are never daemon Threads
+ setDaemon(false);
+ // the session must not be updated when it is used in a report
+ EthernetAddress ethernetAddress = UUIDGenerator.getInstance().getDummyAddress();
+ uuid = UUIDGenerator.getInstance().generateTimeBasedUUID(ethernetAddress);
+
+ setName(name + " [" + uuid.toString() + "]");
+ // new Threads are not doomed
+ doomed = false;
+ // set start time
+ startTime = System.currentTimeMillis();
+ locale = UtilHttp.getLocale(request);
+ }
+
+
+ public UUID getUUID() {
+ return uuid;
+ }
+
+ /**
+ * Adds an error object to the list of errors that occured during the report.
+ *
+ * @param obj the error object
+ */
+ public void addError(Object obj) {
+
+ if (getReport() != null) {
+ getReport().addError(obj);
+ }
+ }
+
+ /**
+ * Returns the error exception in case there was an error during the execution of
+ * this Thread, null otherwise.
+ *
+ * @return the error exception in case there was an error, null otherwise
+ */
+ public Throwable getError() {
+
+ return null;
+ }
+
+ /**
+ * Returns a list of all errors that occured during the report.
+ *
+ * @return an error list that occured during the report
+ */
+ public List> getErrors() {
+
+ if (getReport() != null) {
+ return getReport().getErrors();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the part of the report that is ready for output.
+ *
+ * @return the part of the report that is ready for output
+ */
+ public abstract String getReportUpdate();
+
+ /**
+ * Returns the time this report has been running.
+ *
+ * @return the time this report has been running
+ */
+ public synchronized long getRuntime() {
+
+ if (doomed) {
+ return startTime;
+ } else {
+ return System.currentTimeMillis() - startTime;
+ }
+ }
+
+ /**
+ * Returns if the report generated an error output.
+ *
+ * @return true if the report generated an error, otherwise false
+ */
+ public boolean hasError() {
+
+ if (getReport() != null) {
+ return (getReport().getErrors().size() > 0);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true if this thread is already "doomed" to be deleted.
+ *
+ * A OFBiz deamon Thread (the "Grim Reaper") will collect all
+ * doomed Threads, i.e. threads that are not longer active for some
+ * time.
+ *
+ * @return true if this thread is already "doomed" to be deleted
+ */
+ public synchronized boolean isDoomed() {
+
+ if (isAlive()) {
+ // as long as the Thread is still active it is never doomed
+ return false;
+ }
+ if (doomed) {
+ // not longer active, and already doomed, so rest in peace...
+ return true;
+ }
+ // condemn the Thread to be collected by the grim reaper next time
+ startTime = getRuntime();
+ doomed = true;
+ return false;
+ }
+
+ /**
+ * Returns the report where the output of this Thread is written to.
+ *
+ * @return the report where the output of this Thread is written to
+ */
+ protected InterfaceReport getReport() {
+
+ return report;
+ }
+
+ /**
+ * Initialize a HTML report for this Thread.
+ *
+ * @param locale the locale for the report output messages
+ */
+ protected void initHtmlReport(HttpServletRequest request, HttpServletResponse response) {
+
+ report = HtmlReport.getInstance(request, response);
+ ((HtmlReport) report).setParamThread(getUUID().toString());
+ }
+
+ /**
+ * Initialize a HTML report for this Thread.
+ *
+ * @param locale the locale for the report output messages
+ */
+ protected void initHtmlReport(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient) {
+
+ report = HtmlReport.getInstance(request, response, writeHtml, isTransient);
+ ((HtmlReport) report).setParamThread(getUUID().toString());
+ }
+
+ protected void initHtmlReport(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient, String logFileName) {
+
+ report = HtmlReport.getInstance(request, response, writeHtml, isTransient, logFileName);
+ ((HtmlReport) report).setParamThread(getUUID().toString());
+ }
+
+ protected Locale getLocale() {
+ return locale;
+ }
+
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java
new file mode 100644
index 0000000000..708f4ab620
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java
@@ -0,0 +1,1347 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.FileUtil;
+import org.apache.ofbiz.base.util.StringUtil;
+import org.apache.ofbiz.base.util.UtilHttp;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.htmlreport.util.ReportEncoder;
+import org.apache.ofbiz.htmlreport.util.ReportStringUtil;
+
+/**
+ * HTML report output to be used in report.ftl.
+ *
+ */
+public class HtmlReport extends AbstractReport {
+
+ public static final String module = HtmlReport.class.getName();
+
+ /** The delimiter that is used in the resource list request parameter. */
+ public static final String DELIMITER_RESOURCES = "|";
+
+ /** Request parameter name for the resource list. */
+ public static final String PARAM_RESOURCELIST = "resourcelist";
+
+ /** Constant for a HTML linebreak with added "real" line break. */
+ protected static final String LINEBREAK = " ";
+
+ /**
+ * Constant for a HTML linebreak with added "real" line break-
+ * traditional style for report threads that still use XML templates for their output.
+ */
+ protected static final String LINEBREAK_TRADITIONAL = " \n";
+
+ /** The list of report objects e.g. String, Exception ... */
+ protected List content;
+
+ /** The list of report objects e.g. String, Exception ... */
+ protected List logContent;
+
+ /**
+ * Counter to remember what is already shown,
+ * indicates the next index of the content list that has to be reported.
+ */
+ protected int indexNext;
+
+ /** Flag to indicate if an exception should be displayed long or short. */
+ protected boolean showExceptionStackTrace;
+
+ /** If set to true nothing is kept in memory. */
+ protected boolean isTransient;
+
+ /** Boolean flag indicating whether this report should generate HTML or JavaScript output. */
+ protected boolean writeHtml;
+
+ /** Helper variable to deliver the html end part. */
+ public static final int HTML_END = 1;
+
+ /** Helper variable to deliver the html start part. */
+ public static final int HTML_START = 0;
+
+ /** The thread to display in this report. */
+ protected String paramThread;
+
+ /** The next thread to display after this report. */
+ protected String paramThreadHasNext;
+
+ protected String paramAction;
+
+ protected String paramTitle;
+
+ protected String paramResource;
+
+ /** Flag for refreching workplace .*/
+ protected String paramRefreshWorkplace;
+
+ /** Constant for the "OK" button in the build button methods. */
+ public static final int BUTTON_OK = 0;
+
+ /** Constant for the "Cancel" button in the build button methods. */
+ public static final int BUTTON_CANCEL = 1;
+
+ /** Constant for the "Close" button in the build button methods. */
+ public static final int BUTTON_CLOSE = 2;
+
+ /** Constant for the "Advanced" button in the build button methods. */
+ public static final int BUTTON_ADVANCED = 3;
+
+ /** Constant for the "Set" button in the build button methods. */
+ public static final int BUTTON_SET = 4;
+
+ /** Constant for the "Details" button in the build button methods. */
+ public static final int BUTTON_DETAILS = 5;
+
+ /** Constant for the "OK" button in the build button methods (without form submission). */
+ public static final int BUTTON_OK_NO_SUBMIT = 6;
+
+ /** Constant for the "Edit" button in the build button methods (same function as "Ok" button but different text on button. */
+ public static final int BUTTON_EDIT = 7;
+
+ /** Constant for the "Discard" button in the build button methods (same function as "Cancel" button but different text on button. */
+ public static final int BUTTON_DISCARD = 8;
+
+ /** Constant for the "Back" button in the build button methods. */
+ public static final int BUTTON_BACK = 9;
+
+ /** Constant for the "Continue" button in the build button methods. */
+ public static final int BUTTON_CONTINUE = 10;
+
+ /** Constant for the "Download" button in the build button methods. */
+ public static final int BUTTON_DOWNLOAD = 11;
+
+ /** Request parameter value for the action: back. */
+ public static final String DIALOG_BACK = "back";
+
+ /** Request parameter value for the action: cancel. */
+ public static final String DIALOG_CANCEL = "cancel";
+
+ /** Request parameter value for the action: continue. */
+ public static final String DIALOG_CONTINUE = "continue";
+
+ /** Request parameter value for the action: set. */
+ public static final String DIALOG_SET = "set";
+
+ /** The resource list parameter value. */
+ protected String paramResourcelist;
+
+ /** The list of resource names for the multi operation. */
+ protected List resourceList;
+
+ /** The key name which contains the localized message for the continue checkbox. */
+ protected String paramReportContinueKey;
+
+ public static final String DIALOG_URI = "dialoguri";
+
+ public static final String FORM_URI = "formuri";
+
+ public static final String resource = "PricatUiLabels";
+
+ /** Log file. */
+ protected File logFile;
+
+ /** Log file name. */
+ protected String logFileName;
+
+ /** Log file output stream. */
+ protected FileOutputStream logFileOutputStream;
+
+ protected long sequenceNum = -1;
+
+ /**
+ * Constructs a new report using the provided locale for the output language.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ public HtmlReport(HttpServletRequest request, HttpServletResponse response) {
+
+ this(request, response, false, false);
+ }
+
+ /**
+ * Constructs a new report using the provided locale for the output language.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @param writeHtml if true, this report should generate HTML instead of JavaScript output
+ * @param isTransient If set to true nothing is kept in memory
+ */
+ public HtmlReport(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient) {
+
+ init(UtilHttp.getLocale(request));
+ content = new ArrayList(256);
+ logContent = new ArrayList(256);
+ showExceptionStackTrace = true;
+ this.writeHtml = writeHtml;
+ this.isTransient = isTransient;
+ }
+
+ public static HtmlReport getInstance(HttpServletRequest request, HttpServletResponse response) {
+ HtmlReport wp = (HtmlReport) request.getSession().getAttribute(SESSION_REPORT_CLASS);
+ if (wp == null) {
+ wp = new HtmlReport(request, response, true, true);
+ request.getSession().setAttribute(SESSION_REPORT_CLASS, wp);
+ }
+ return wp;
+ }
+
+ public static HtmlReport getInstance(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient) {
+ HtmlReport wp = (HtmlReport) request.getSession().getAttribute(SESSION_REPORT_CLASS);
+ if (wp == null) {
+ wp = new HtmlReport(request, response, writeHtml, isTransient);
+ request.getSession().setAttribute(SESSION_REPORT_CLASS, wp);
+ }
+ return wp;
+ }
+
+ public static HtmlReport getInstance(HttpServletRequest request, HttpServletResponse response, boolean writeHtml, boolean isTransient, String logFileName) {
+ HtmlReport wp = (HtmlReport) request.getSession().getAttribute(SESSION_REPORT_CLASS);
+ if (wp == null || UtilValidate.isEmpty(wp.getLogFileName()) || !wp.getLogFileName().equals(logFileName)) {
+ wp = new HtmlReport(request, response, writeHtml, isTransient);
+ request.getSession().setAttribute(SESSION_REPORT_CLASS, wp);
+ }
+ return wp;
+ }
+
+ public String getParamAction(HttpServletRequest request) {
+ paramAction = request.getParameter("action");
+ return paramAction != null ? paramAction : "reportbegin";
+ }
+
+ public void setParamAction(String action) {
+ paramAction = action;
+ }
+
+ public void setParamThread(String name) {
+ paramThread = name;
+ }
+
+ public synchronized String getReportUpdate() {
+ StringBuffer result = new StringBuffer();
+ StringBuffer logResult = new StringBuffer();
+ int indexEnd = content.size();
+ for (int i = indexNext; i < indexEnd; i++) {
+ int pos = isTransient ? 0 : i;
+ Object obj = content.get(pos);
+ if ((obj instanceof String) || (obj instanceof StringBuffer)) {
+ result.append(obj);
+ } else if (obj instanceof Throwable) {
+ result.append(getExceptionElementJS((Throwable)obj));
+ }
+ if (isTransient) {
+ content.remove(indexNext);
+ }
+ if (UtilValidate.isNotEmpty(logContent)) {
+ Object logObj = logContent.get(pos);
+ if ((logObj instanceof String) || (logObj instanceof StringBuffer)) {
+ logResult.append(logObj);
+ } else if (logObj instanceof Throwable) {
+ result.append(getExceptionElementHtml((Throwable) logObj));
+ }
+ if (isTransient) {
+ logContent.remove(indexNext);
+ }
+ }
+ }
+
+ indexNext = isTransient ? 0 : indexEnd;
+
+ if (isTransient && logFileOutputStream != null && logResult.toString().length() > 0) {
+ try {
+ logFileOutputStream.write((logResult.toString() + "\n").getBytes());
+ logFileOutputStream.flush();
+ } catch (IOException e) {
+ Debug.logError(e.getMessage(), module);
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Returns if the report writes html or javascript code.
+ *
+ * @return true if the report writes html, and false if the report writes javascript code
+ */
+ public boolean isWriteHtml() {
+ return writeHtml;
+ }
+
+ public synchronized void print(String value, int format) {
+ StringBuffer buf = null;
+ value = ReportStringUtil.escapeJavaScript(value);
+ switch (format) {
+ case FORMAT_HEADLINE:
+ buf = new StringBuffer();
+ buf.append("aH('");
+ buf.append(value);
+ buf.append("'); ");
+ break;
+ case FORMAT_WARNING:
+ buf = new StringBuffer();
+ buf.append("aW('");
+ buf.append(value);
+ buf.append("'); ");
+ addWarning(value);
+ break;
+ case FORMAT_ERROR:
+ buf = new StringBuffer();
+ buf.append("aE('");
+ buf.append(value);
+ buf.append("'); ");
+ addError(value);
+ break;
+ case FORMAT_NOTE:
+ buf = new StringBuffer();
+ buf.append("aN('");
+ buf.append(value);
+ buf.append("'); ");
+ break;
+ case FORMAT_OK:
+ buf = new StringBuffer();
+ buf.append("aO('");
+ buf.append(value);
+ buf.append("'); ");
+ break;
+ case FORMAT_DEFAULT:
+ default:
+ buf = new StringBuffer();
+ buf.append("a('");
+ buf.append(value);
+ buf.append("'); ");
+ }
+ if (value.trim().endsWith(getLineBreak())) {
+ buf.append("aB(); ");
+ }
+ content.add(buf.toString());
+
+ switch (format) {
+ case FORMAT_HEADLINE:
+ buf = new StringBuffer();
+ buf.append("");
+ buf.append(value);
+ buf.append(" ");
+ break;
+ case FORMAT_WARNING:
+ buf = new StringBuffer();
+ buf.append("");
+ buf.append(value);
+ buf.append(" ");
+ addWarning(value);
+ break;
+ case FORMAT_ERROR:
+ buf = new StringBuffer();
+ buf.append("");
+ buf.append(value);
+ buf.append(" ");
+ addError(value);
+ break;
+ case FORMAT_NOTE:
+ buf = new StringBuffer();
+ buf.append("");
+ buf.append(value);
+ buf.append(" ");
+ break;
+ case FORMAT_OK:
+ buf = new StringBuffer();
+ buf.append("");
+ buf.append(value);
+ buf.append(" ");
+ break;
+ case FORMAT_DEFAULT:
+ default:
+ buf = new StringBuffer(value);
+ }
+ if (value.trim().endsWith(getLineBreak())) {
+ buf.append("\n");
+ }
+ logContent.add(buf.toString());
+ }
+
+ public void println() {
+ print(getLineBreak());
+ }
+
+ public synchronized void println(Throwable t) {
+ addError(t.getMessage());
+ content.add(getExceptionElementJS(t));
+ logContent.add(getExceptionElementHtml(t));
+ }
+
+ /**
+ * Returns the correct line break notation depending on the output style of this report.
+ *
+ * @return the correct line break notation
+ */
+ protected String getLineBreak() {
+ return writeHtml ? LINEBREAK_TRADITIONAL : LINEBREAK;
+ }
+
+ /**
+ * Output helper method to format a reported Throwable element.
+ *
+ * This method ensures that exception stack traces are properly escaped
+ * when they are added to the report.
+ *
+ * There is a member variable {@link #showExceptionStackTrace} in this
+ * class that controls if the stack track is shown or not.
+ * In a later version this might be configurable on a per-user basis.
+ *
+ * @param throwable the exception to format
+ * @return the formatted StringBuffer
+ */
+ private StringBuffer getExceptionElementJS(Throwable throwable) {
+ StringBuffer buf = new StringBuffer(256);
+ if (showExceptionStackTrace) {
+ buf.append("aT('");
+ buf.append(UtilProperties.getMessage(resource, "REPORT_EXCEPTION", getLocale()));
+ String exception = ReportEncoder.escapeXml(throwable.getLocalizedMessage());
+ if (UtilValidate.isEmpty(exception)) {
+ exception = ReportEncoder.escapeXml(throwable.getMessage());
+ }
+ if (UtilValidate.isNotEmpty(exception)) {
+ exception = exception.replaceAll("[\r\n]+", LINEBREAK);
+ buf.append(ReportStringUtil.escapeJavaScript(exception) + LINEBREAK);
+ } else {
+ buf.append(throwable.toString());
+ }
+ buf.append("'); ");
+ } else {
+ buf.append("aT('");
+ buf.append(UtilProperties.getMessage(resource, "REPORT_EXCEPTION", getLocale()));
+ buf.append(ReportStringUtil.escapeJavaScript(throwable.toString()));
+ buf.append("'); ");
+ }
+ return buf;
+ }
+
+ private StringBuffer getExceptionElementHtml(Throwable throwable) {
+ StringBuffer buf = new StringBuffer(256);
+ if (showExceptionStackTrace) {
+ buf.append("");
+ buf.append(UtilProperties.getMessage(resource, "REPORT_EXCEPTION", getLocale()));
+ String exception = ReportEncoder.escapeXml(throwable.getLocalizedMessage());
+ if (UtilValidate.isEmpty(exception)) {
+ exception = ReportEncoder.escapeXml(throwable.getMessage());
+ }
+ if (UtilValidate.isNotEmpty(exception)) {
+ exception = exception.replaceAll("[\r\n]+", LINEBREAK);
+ buf.append(exception);
+ } else {
+ buf.append(throwable.toString());
+ }
+ buf.append(" ");
+ } else {
+ buf.append("");
+ buf.append(UtilProperties.getMessage(resource, "REPORT_EXCEPTION", getLocale()));
+ buf.append(throwable.toString());
+ buf.append(" ");
+ buf.append(getLineBreak());
+ }
+ return buf;
+ }
+
+ public void printMessageWithParam(String uiLabel, Object param) {
+ print(uiLabel, InterfaceReport.FORMAT_NOTE);
+ }
+
+ public void printMessageWithParam(int m, int n, String uiLabel, Object param) {
+ print(uiLabel, InterfaceReport.FORMAT_NOTE);
+ }
+
+ /**
+ * Builds the start html of the page, including setting of DOCTYPE and
+ * inserting a header with the content-type.
+ *
+ * This overloads the default method of the parent class.
+ *
+ * @return the start html of the page
+ */
+ public String htmlStart() {
+
+ return pageHtml(HTML_START, true);
+ }
+
+ /**
+ * Builds the start html of the page, including setting of DOCTYPE and
+ * inserting a header with the content-type.
+ *
+ * This overloads the default method of the parent class.
+ *
+ * @param loadStyles if true, the defaul style sheet will be loaded
+ * @return the start html of the page
+ */
+ public String htmlStart(boolean loadStyles) {
+
+ return pageHtml(HTML_START, loadStyles);
+ }
+
+ /**
+ * Builds the start html of the page, including setting of DOCTYPE and
+ * inserting a header with the content-type.
+ *
+ * This overloads the default method of the parent class.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param loadStyles if true, the defaul style sheet will be loaded
+ * @return the start html of the page
+ */
+ public String pageHtml(int segment, boolean loadStyles) {
+ if (segment == HTML_START) {
+ StringBuffer result = new StringBuffer(512);
+ result.append("\n");
+ result.append("\n
\n");
+ result.append(" \n");
+ if (loadStyles) {
+ result.append(" \n");
+ result.append("\n");
+ }
+ return result.toString();
+ } else {
+ return "";
+ }
+ }
+
+ /**
+ * Builds the standard javascript for submitting the dialog.
+ *
+ * @return the standard javascript for submitting the dialog
+ */
+ public String dialogScriptSubmit() {
+ StringBuffer result = new StringBuffer(512);
+ result.append("function submitAction(actionValue, theForm, formName) {\n");
+ result.append("\tif (theForm == null) {\n");
+ result.append("\t\ttheForm = document.forms[formName];\n");
+ result.append("\t}\n");
+ result.append("\ttheForm.action.value = actionValue;\n");
+ result.append("\ttheForm.submit();\n");
+ result.append("\treturn false;\n");
+ result.append("}\n");
+ return result.toString();
+ }
+
+ /**
+ * Returns true if the report Thread is still alive (i.e. running), false otherwise.
+ *
+ * @return true if the report Thread is still alive
+ */
+ public boolean isAlive(HttpServletRequest request) {
+ ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
+ int i = threadGroup.activeCount();
+ Thread[] threads = new Thread[i];
+ threadGroup.enumerate(threads, true);
+ AbstractReportThread thread = null;
+ for (int j=0; j
+ *
+ * @return the thread parameter value
+ */
+ public String getParamThread(HttpServletRequest request) {
+ String thread = request.getParameter("thread");
+ return ReportStringUtil.isNotEmptyOrWhitespaceOnly(thread) ? thread : (paramThread == null? "" : paramThread);
+ }
+
+ /**
+ * Returns the threadhasnext parameter value.
+ *
+ * @return the threadhasnext parameter value
+ */
+ public String getParamThreadHasNext(HttpServletRequest request) {
+ String threadhasnext = request.getParameter("threadhasnext");
+ return ReportStringUtil.isNotEmptyOrWhitespaceOnly(threadhasnext) ? threadhasnext : "false";
+ }
+
+ /**
+ * Builds the start html of the body.
+ *
+ * @param className optional class attribute to add to the body tag
+ * @param parameters optional parameters to add to the body tag
+ * @return the start html of the body
+ */
+ public String bodyStart(String className, String parameters) {
+ return pageBody(HTML_START, className, parameters);
+ }
+
+ /**
+ * Builds the html of the body.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param className optional class attribute to add to the body tag
+ * @param parameters optional parameters to add to the body tag
+ * @return the html of the body
+ */
+ public String pageBody(int segment, String className, String parameters) {
+ if (segment == HTML_START) {
+ StringBuffer result = new StringBuffer(128);
+ result.append("\n
\n");
+ return result.toString();
+ } else {
+ return "";
+ }
+ }
+
+ /**
+ * Builds the end html of the body.
+ *
+ * @return the end html of the body
+ */
+ public String bodyEnd() {
+ return pageBody(HTML_END, null, null);
+ }
+
+ /**
+ * Builds the end html of the page.
+ *
+ * @return the end html of the page
+ */
+ public String htmlEnd() {
+ return pageHtml(HTML_END, null);
+ }
+
+ /**
+ * Returns the default html for a workplace page, including setting of DOCTYPE and
+ * inserting a header with the content-type.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param title the title of the page, if null no title tag is inserted
+ * @return the default html for a workplace page
+ */
+ public String pageHtml(int segment, String title) {
+ return pageHtmlStyle(segment, title, null);
+ }
+
+ /**
+ * Returns the default html for a workplace page, including setting of DOCTYPE and
+ * inserting a header with the content-type, allowing the selection of an individual style sheet.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param title the title of the page, if null no title tag is inserted
+ * @param stylesheet the used style sheet, if null the default stylesheet 'workplace.css' is inserted
+ * @return the default html for a workplace page
+ */
+ public String pageHtmlStyle(int segment, String title, String stylesheet) {
+ if (segment == HTML_START) {
+ StringBuffer result = new StringBuffer(512);
+// result.append("\n");
+// result.append("\n
\n");
+// if (title != null) {
+// result.append("");
+// result.append(title);
+// result.append(" \n");
+// }
+// result.append(" \n");
+ result.append(" \n");
+ return result.toString();
+ } else {
+ return "";
+// return "";
+ }
+ }
+
+ /**
+ * Returns the start html for the outer dialog window border.
+ *
+ * @return the start html for the outer dialog window border
+ */
+ public String dialogStart() {
+ return dialog(HTML_START, null);
+ }
+
+ /**
+ * Builds the outer dialog window border.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param attributes optional additional attributes for the opening dialog table
+ *
+ * @return a dialog window start / end segment
+ */
+ public String dialog(int segment, String attributes) {
+ if (segment == HTML_START) {
+ StringBuffer html = new StringBuffer(512);
+ html.append("\n\n");
+ html.append("\n");
+ return html.toString();
+ } else {
+ return "
\n
\n
\n";
+ }
+ }
+
+ /**
+ * Returns the start html for the content area of the dialog window.
+ *
+ * @param title the title for the dialog
+ *
+ * @return the start html for the content area of the dialog window
+ */
+ public String dialogContentStart(String title) {
+ return dialogContent(HTML_START, title);
+ }
+
+ /**
+ * Builds the content area of the dialog window.
+ *
+ * @param segment the HTML segment (START / END)
+ * @param title the title String for the dialog window
+ *
+ * @return a content area start / end segment
+ */
+ public String dialogContent(int segment, String title) {
+ if (segment == HTML_START) {
+ StringBuffer result = new StringBuffer(512);
+ // null title is ok, we always want the title headline
+ result.append(dialogHead(title));
+ result.append("
\n");
+ result.append("\n");
+ return result.toString();
+ } else {
+ return "\n
\n";
+ }
+ }
+
+ /**
+ * Builds the title of the dialog window.
+ *
+ * @param title the title String for the dialog window
+ *
+ * @return the HTML title String for the dialog window
+ */
+ public String dialogHead(String title) {
+ return "
" + (title == null ? "" : title) + "
";
+ }
+
+ /**
+ * Returns the value of the title parameter,
+ * or null if this parameter was not provided.
+ *
+ * This parameter is used to build the title
+ * of the dialog. It is a parameter so that the title
+ * can be passed to included elements.
+ *
+ * @return the value of the title parameter
+ */
+ public String getParamTitle(HttpServletRequest request) {
+ if (paramTitle == null) {
+ paramTitle = request.getParameter("title");
+ }
+ return paramTitle != null ? paramTitle : "";
+ }
+
+ /**
+ * Returns all initialized parameters of the current workplace class
+ * as hidden field tags that can be inserted in a form.
+ *
+ * @return all initialized parameters of the current workplace class
+ * as hidden field tags that can be inserted in a html form
+ */
+ public String paramsAsHidden(HttpServletRequest request) {
+ return paramsAsHidden(request, null);
+ }
+
+ /**
+ * Returns all initialized parameters of the current workplace class
+ * that are not in the given exclusion list as hidden field tags that can be inserted in a form.
+ *
+ * @param excludes the parameters to exclude
+ *
+ * @return all initialized parameters of the current workplace class
+ * that are not in the given exclusion list as hidden field tags that can be inserted in a form
+ */
+ public String paramsAsHidden(HttpServletRequest request, Collection> excludes) {
+ StringBuffer result = new StringBuffer(512);
+ Map params = paramValues(request);
+ Iterator> i = params.entrySet().iterator();
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry)i.next();
+ String param = (String)entry.getKey();
+ if ((excludes == null) || (!excludes.contains(param))) {
+ result.append(" \n");
+ }
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * Returns the values of all parameter methods of this workplace class instance.
+ *
+ * @return the values of all parameter methods of this workplace class instance
+ */
+ protected Map paramValues(HttpServletRequest request) {
+ List methods = paramGetMethods();
+ Map map = new HashMap(methods.size());
+ Iterator i = methods.iterator();
+ while (i.hasNext()) {
+ Method m = (Method)i.next();
+ Object o = null;
+ try {
+ o = m.invoke(this, new Object[0]);
+ } catch (InvocationTargetException ite) {
+ // can usually be ignored
+ } catch (IllegalAccessException eae) {
+ // can usually be ignored
+ }
+ if (o != null) {
+ map.put(m.getName().substring(8).toLowerCase(), o);
+ }
+ }
+ return map;
+ }
+
+ /**
+ * Returns a list of all methods of the current class instance that
+ * start with "getParam" and have no parameters.
+ *
+ * @return a list of all methods of the current class instance that
+ * start with "getParam" and have no parameters
+ */
+ private List paramGetMethods() {
+ List list = new ArrayList();
+ Method[] methods = this.getClass().getMethods();
+ int length = methods.length;
+ for (int i = 0; i < length; i++) {
+ Method method = methods[i];
+ if (method.getName().startsWith("getParam") && (method.getParameterTypes().length == 0)) {
+ // Debug.logInfo("getMethod: " + method.getName(), module);
+ list.add(method);
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Returns an optional introduction text to be displayed above the report output.
+ *
+ * @return an optional introduction text
+ */
+ public String reportIntroductionText() {
+ return "";
+ }
+
+ /**
+ * Returns an optional conclusion text to be displayed below the report output.
+ *
+ * @return an optional conclusion text
+ */
+ public String reportConclusionText() {
+ return "";
+ }
+
+ /**
+ * Returns the end html for the content area of the dialog window.
+ *
+ * @return the end html for the content area of the dialog window
+ */
+ public String dialogContentEnd() {
+ return dialogContent(HTML_END, null);
+ }
+
+ /**
+ * Builds a button row with an "Ok" and a "Cancel" button.
+ *
+ * This row is displayed when the first report is running.
+ *
+ * @param okAttrs optional attributes for the ok button
+ * @param cancelAttrs optional attributes for the cancel button
+ * @return the button row
+ */
+ public String dialogButtonsContinue(String okAttrs, String cancelAttrs) {
+ return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[] {
+ okAttrs,
+ cancelAttrs});
+ }
+
+ /**
+ * Builds a button row with an "OK" and a "Cancel" button.
+ *
+ * This row is used when a single report is running or after the first report has finished.
+ *
+ * @param okAttrs optional attributes for the ok button
+ * @param cancelAttrs optional attributes for the cancel button
+ * @return the button row
+ */
+ public String dialogButtonsOkCancel(HttpServletRequest request, String okAttrs, String cancelAttrs) {
+ if (Boolean.valueOf(getParamThreadHasNext(request)).booleanValue()
+ && ReportStringUtil.isNotEmpty(getParamReportContinueKey())) {
+ return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[] {
+ okAttrs,
+ cancelAttrs});
+ }
+ return dialogButtons(new int[] {BUTTON_OK}, new String[] {okAttrs});
+ }
+
+ /**
+ * Builds a button row with an "OK", a "Cancel" and a "Download" button.
+ *
+ * This row is used when a single report is running or after the first report has finished.
+ *
+ * @param okAttrs optional attributes for the ok button
+ * @param cancelAttrs optional attributes for the cancel button
+ * @param downloadAttrs optional attributes for the download button
+ * @return the button row
+ */
+ public String dialogButtonsOkCancelDownload(HttpServletRequest request, String okAttrs, String cancelAttrs, String downloadAttrs) {
+ if (ReportStringUtil.isEmptyOrWhitespaceOnly(downloadAttrs)) {
+ downloadAttrs = "";
+ } else {
+ downloadAttrs += " ";
+ }
+ if (Boolean.valueOf(getParamThreadHasNext(request)).booleanValue()
+ && ReportStringUtil.isNotEmpty(getParamReportContinueKey())) {
+ return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL, BUTTON_DOWNLOAD}, new String[] {
+ okAttrs,
+ cancelAttrs,
+ downloadAttrs + "onclick=\"downloadPricat(" + (sequenceNum > 0 ? sequenceNum : "") + ");\""});
+ }
+ return dialogButtons(new int[] {BUTTON_OK, BUTTON_DOWNLOAD}, new String[] {
+ okAttrs,
+ downloadAttrs + "onclick=\"downloadPricat(" + (sequenceNum > 0 ? sequenceNum : "") + ");\""});
+ }
+
+ /**
+ * Builds the html for the button row under the dialog content area, including buttons.
+ *
+ * @param buttons array of constants of which buttons to include in the row
+ * @param attributes array of Strings for additional button attributes
+ *
+ * @return the html for the button row under the dialog content area, including buttons
+ */
+ public String dialogButtons(int[] buttons, String[] attributes) {
+ StringBuffer result = new StringBuffer(256);
+ result.append(dialogButtonRow(HTML_START));
+ for (int i = 0; i < buttons.length; i++) {
+ dialogButtonsHtml(result, buttons[i], attributes[i]);
+ }
+ result.append(dialogButtonRow(HTML_END));
+ return result.toString();
+ }
+
+ /**
+ * Builds the button row under the dialog content area without the buttons.
+ *
+ * @param segment the HTML segment (START / END)
+ *
+ * @return the button row start / end segment
+ */
+ public String dialogButtonRow(int segment) {
+ if (segment == HTML_START) {
+ return "\n
\n";
+ } else {
+ return "
\n\n";
+ }
+ }
+
+ /**
+ * Renders the HTML for a single input button of a specified type.
+ *
+ * @param result a string buffer where the rendered HTML gets appended to
+ * @param button a integer key to identify the button
+ * @param attribute an optional string with possible tag attributes, or null
+ */
+ protected void dialogButtonsHtml(StringBuffer result, int button, String attribute) {
+ attribute = appendDelimiter(attribute);
+ switch (button) {
+ case BUTTON_OK:
+ result.append(" \n");
+ break;
+ case BUTTON_CANCEL:
+ result.append(" \n");
+ break;
+ case BUTTON_EDIT:
+ result.append(" \n");
+ break;
+ case BUTTON_DISCARD:
+ result.append(" \n");
+ break;
+ case BUTTON_CLOSE:
+ result.append(" \n");
+ break;
+ case BUTTON_ADVANCED:
+ result.append(" \n");
+ break;
+ case BUTTON_SET:
+ result.append(" \n");
+ break;
+ case BUTTON_BACK:
+ result.append(" \n");
+ break;
+ case BUTTON_CONTINUE:
+ result.append(" \n");
+ break;
+ case BUTTON_DETAILS:
+ result.append(" \n");
+ break;
+ case BUTTON_DOWNLOAD:
+ result.append(" \n");
+ break;
+ default:
+ // not a valid button code, just insert a warning in the HTML
+ result.append("\n");
+ }
+ }
+
+ /**
+ * Appends a space char. between tag attributes.
+ *
+ * @param attribute a tag attribute
+ *
+ * @return the tag attribute with a leading space char
+ */
+ protected String appendDelimiter(String attribute) {
+ if (ReportStringUtil.isNotEmpty(attribute)) {
+ if (!attribute.startsWith(" ")) {
+ // add a delimiter space between the beginning button HTML and the button tag attributes
+ return " " + attribute;
+ } else {
+ return attribute;
+ }
+ }
+ return "";
+ }
+
+ /**
+ * Returns true if the dialog operation has to be performed on multiple resources.
+ *
+ * @return true if the dialog operation has to be performed on multiple resources, otherwise false
+ */
+ public boolean isMultiOperation(HttpServletRequest request) {
+ return (getResourceList(request).size() > 1);
+ }
+
+ /**
+ * Returns the resources that are defined for the dialog operation.
+ *
+ * For single resource operations, the list contains one item: the resource name found
+ * in the request parameter value of the "resource" parameter.
+ *
+ * @return the resources that are defined for the dialog operation
+ */
+ public List getResourceList(HttpServletRequest request) {
+ if (resourceList == null) {
+ // use lazy initializing
+ if (getParamResourcelist(request) != null) {
+ // found the resourcelist parameter
+ resourceList = StringUtil.split(getParamResourcelist(request), DELIMITER_RESOURCES);
+ Collections.sort(resourceList);
+ } else {
+ // this is a single resource operation, create list containing the resource name
+ resourceList = new ArrayList(1);
+ String resource = getParamResource(request);
+ if (ReportStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {
+ resourceList.add(resource);
+ } else {
+ resourceList.add("");
+ }
+ }
+ }
+ return resourceList;
+ }
+
+ /**
+ * Returns the value of the resource list parameter, or null if the parameter is not provided.
+ *
+ * This parameter selects the resources to perform operations on.
+ *
+ * @return the value of the resource list parameter or null, if the parameter is not provided
+ */
+ public String getParamResourcelist(HttpServletRequest request) {
+ if (ReportStringUtil.isNotEmpty(paramResourcelist) && !"null".equals(paramResourcelist)) {
+ return paramResourcelist;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the value of the file parameter,
+ * or null if this parameter was not provided.
+ *
+ * The file parameter selects the file on which the dialog action
+ * is to be performed.
+ *
+ * @return the value of the file parameter
+ */
+ public String getParamResource(HttpServletRequest request) {
+ paramResource = request.getParameter("resource");
+ if ((paramResource != null) && !"null".equals(paramResource)) {
+ return paramResource;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns if the workplace must be refreshed.
+ *
+ * @return "true" if the workplace must be refreshed.
+ */
+ public String getParamRefreshWorkplace() {
+ return paramRefreshWorkplace;
+ }
+
+ /**
+ * Returns the key name which contains the localized message for the continue checkbox.
+ *
+ * @return the key name which contains the localized message for the continue checkbox
+ */
+ public String getParamReportContinueKey() {
+ if (paramReportContinueKey == null) {
+ paramReportContinueKey = "";
+ }
+ return paramReportContinueKey;
+ }
+
+ /**
+ * Returns the value of the resourcelist parameter in form of a String separated
+ * with {@link #DELIMITER_RESOURCES}, or the value of the resource parameter if the
+ * first parameter is not provided (no multiple choice has been done.
+ *
+ * This may be used for jsps as value for the parameter for resources {@link #PARAM_RESOURCELIST}.
+ *
+ * @return the value of the resourcelist parameter or null, if the parameter is not provided
+ */
+ public String getResourceListAsParam(HttpServletRequest request) {
+ String result = getParamResourcelist(request);
+ if (ReportStringUtil.isEmptyOrWhitespaceOnly(result)) {
+ result = getParamResource(request);
+ }
+ return result;
+ }
+
+ /**
+ * Returns the end html for the outer dialog window border.
+ *
+ * @return the end html for the outer dialog window border
+ */
+ public String dialogEnd() {
+ return dialog(HTML_END, null);
+ }
+
+ /**
+ * Returns the http URI of the current dialog, to be used
+ * as value for the "action" attribute of a html form.
+ *
+ * This URI is the real one.
+ *
+ * @return the http URI of the current dialog
+ */
+ public String getDialogRealUri(HttpServletRequest request) {
+ return String.valueOf(request.getAttribute(DIALOG_URI));
+ }
+
+ /**
+ * Set the report form uri.
+ *
+ * @param request
+ * @param formUri
+ */
+ public void setFormRealUri(HttpServletRequest request, String formUri) {
+ request.setAttribute(FORM_URI, formUri);
+ }
+
+ /**
+ * Get the report form uri.
+ *
+ * @param request
+ * @return
+ */
+ public String getFormRealUri(HttpServletRequest request) {
+ return (String) request.getAttribute(FORM_URI);
+ }
+
+ public void addLogFile(String logFileName) {
+ if (logFile == null || logFileOutputStream == null) {
+ this.logFileName = logFileName;
+ logFile = FileUtil.getFile(logFileName);
+ try {
+ logFileOutputStream = new FileOutputStream(logFile);
+ } catch (FileNotFoundException e) {
+ // do nothing
+ }
+ }
+ }
+
+ public String closeLogFile() {
+ if (logFileOutputStream != null) {
+ try {
+ logFileOutputStream.flush();
+ } catch (IOException e) {
+ // do nothing
+ } finally {
+ if (logFileOutputStream != null) {
+ try {
+ logFileOutputStream.close();
+ } catch (IOException e) {
+ // do nothing
+ Debug.logError(e, HtmlReport.module);
+ }
+ }
+ }
+ }
+ return logFileName;
+ }
+
+ public String getLogFileName() {
+ return logFileName;
+ }
+
+ public long getSequenceNum() {
+ return sequenceNum;
+ }
+
+ public void setSequenceNum(long sequenceNum) {
+ this.sequenceNum = sequenceNum;
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java
new file mode 100644
index 0000000000..1e7f3299ff
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java
@@ -0,0 +1,230 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * This is the interface for the report classes which are used for the output
+ * during operations that run on a separate Thread in OFBiz,
+ * like import, export etc.
+ *
+ */
+public interface InterfaceReport {
+
+ /** Indicates default formatting. */
+ int FORMAT_DEFAULT = 0;
+
+ /** Indicates error formatting. */
+ int FORMAT_ERROR = 5;
+
+ /** Indicates headline formatting. */
+ int FORMAT_HEADLINE = 2;
+
+ /** Indicates note formatting. */
+ int FORMAT_NOTE = 3;
+
+ /** Indicates OK formatting. */
+ int FORMAT_OK = 4;
+
+ /** Indicates warning formatting. */
+ int FORMAT_WARNING = 1;
+
+ /** Request parameter value that this report should create an "extended" output. */
+ String REPORT_TYPE_EXTENDED = "extended";
+
+ /** Request parameter value that this report should create a "simple" output. */
+ String REPORT_TYPE_SIMPLE = "simple";
+
+ /**
+ * Adds an error object to the list of errors that occured during the report.
+ *
+ * @param obj the error object
+ */
+ void addError(Object obj);
+
+ /**
+ * Adds a warning object to the list of warnings that occured during the report.
+ *
+ * @param obj the error object
+ */
+ void addWarning(Object obj);
+
+ /**
+ * Formats the runtime formatted as "hh:mm:ss".
+ *
+ * @return the runtime formatted as "hh:mm:ss"
+ */
+ String formatRuntime();
+
+ /**
+ * Returns a list of all errors that occured during the report.
+ *
+ * @return an error list that occured during the report
+ */
+ List getErrors();
+
+ /**
+ * Returns the locale this report was initialized with.
+ *
+ * @return the locale this report was initialized with
+ */
+ Locale getLocale();
+
+ /**
+ * Updates this report, this processes all new output added since
+ * the last call to this method.
+ *
+ * This is only required in case the output is written to a HTML page,
+ * if the shell output is used, this will just return an empty String.
+ *
+ * @return new elements that have been added to the report and not yet processed.
+ */
+ String getReportUpdate();
+
+ /**
+ * Returns the time this report has been running.
+ *
+ * @return the time this report has been running
+ */
+ long getRuntime();
+
+ /**
+ * Returns a list of all warnings that occured during the report.
+ *
+ * @return a warning list that occured during the report
+ */
+ List getWarnings();
+
+ /**
+ * Returns if the report generated an error output.
+ *
+ * @return true if the report generated an error, otherwise false
+ */
+ boolean hasError();
+
+ /**
+ * Returns if the report generated a warning output.
+ *
+ * @return true if the report generated a warning, otherwise false
+ */
+ boolean hasWarning();
+
+ /**
+ * Prints a localized message to the report.
+ *
+ * @param uiLabel the String to add
+ */
+ void print(String uiLabel);
+
+ /**
+ * Prints a localized message to the report, using the indicated formatting.
+ *
+ * Use the contants starting with FORMAT from this interface
+ * to indicate which formatting to use.
+ *
+ * @param uiLabel the String to add
+ * @param format the formatting to use for the output
+ */
+ void print(String uiLabel, int format);
+
+ /**
+ * Adds a line break to the report.
+ */
+ void println();
+
+ /**
+ * Prints a localized message to the report.
+ *
+ * @param uiLabel the message to add
+ */
+ void println(String uiLabel);
+
+ /**
+ * Prints a localized message to the report, using the indicated formatting.
+ *
+ * Use the contants starting with FORMAT from this interface
+ * to indicate which formatting to use.
+ *
+ * @param container the message container to add
+ * @param format the formatting to use for the output
+ */
+ void println(String uiLabel, int format);
+
+ /**
+ * Adds an Exception to the report, ensuring that the Exception content is
+ * processed to generate a valid output esp. for HTML pages.
+ *
+ * The exception will be stored and the output will later be processed
+ * in a special way.
+ *
+ * @param t the exception to add
+ *
+ */
+ void println(Throwable t);
+
+ /**
+ * Prints a localized message followed by a parameter and dots to the report.
+ *
+ * @param uiLabel the Message to add
+ * @param param the Parameter to add
+ */
+ void printMessageWithParam(String uiLabel, Object param);
+
+ /**
+ * Convenience method to print a localized message, followed by a parameter and dots to the report.
+ *
+ * The output follows the pattern: ( 3 / 8 ) Deleting filename.txt ...
+ *
+ * @param m the number of the report output
+ * @param n the total number of report outputs
+ * @param uiLabel the Message to add
+ * @param param the Parameter to add
+ *
+ */
+ void printMessageWithParam(int m, int n, String uiLabel, Object param);
+
+ /**
+ * Resets the runtime to 0 milliseconds.
+ */
+ void resetRuntime();
+
+ /**
+ * Add a log file to the report.
+ *
+ * @param logFileName
+ */
+ void addLogFile(String logFileName);
+
+ /**
+ * Close log file if necessary.
+ *
+ */
+ String closeLogFile();
+
+ /**
+ * Set log's sequence number.
+ * @param sequenceNum
+ */
+ void setSequenceNum(long sequenceNum);
+
+ long getSequenceNum();
+
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReportThread.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReportThread.java
new file mode 100644
index 0000000000..78e46dfe06
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReportThread.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport;
+
+import org.safehaus.uuid.UUID;
+
+/**
+ * Identifies a class that can be used as a report thread.
+ *
+ */
+public interface InterfaceReportThread {
+
+ /**
+ * Starts the report thread.
+ */
+ void start();
+
+ /**
+ * Returns the UUID of this report thread.
+ *
+ * @return the UUID of this report thread
+ */
+ UUID getUUID();
+
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlReport.java
new file mode 100644
index 0000000000..55dd49b10f
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlReport.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport.sample;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.ofbiz.htmlreport.AbstractHtmlReport;
+import org.apache.ofbiz.htmlreport.InterfaceReportThread;
+
+/**
+ * Provides a report for running sample html report.
+ *
+ */
+public class SampleHtmlReport extends AbstractHtmlReport {
+
+ /**
+ * Public constructor with report variables.
+ *
+ * @param req the HttpServletRequest request
+ * @param res the HttpServletResponse response
+ */
+ public SampleHtmlReport(HttpServletRequest request, HttpServletResponse response) {
+
+ super(request, response);
+ }
+
+ public static SampleHtmlReport getReport(HttpServletRequest request, HttpServletResponse response) {
+
+ SampleHtmlReport wp = (SampleHtmlReport) request.getAttribute(SESSION_REPORT_CLASS);
+ if (wp == null) {
+ wp = new SampleHtmlReport(request, response);
+ request.setAttribute(SESSION_REPORT_CLASS, wp);
+ }
+ return wp;
+ }
+
+ public InterfaceReportThread initializeThread(HttpServletRequest request, HttpServletResponse response, String name) {
+
+ if (name == null) {
+ name = "";
+ }
+ ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
+ int i = threadGroup.activeCount();
+ Thread[] threads = new Thread[i];
+ threadGroup.enumerate(threads, true);
+ InterfaceReportThread thread = null;
+ for (int j=0; j messages = Collections.unmodifiableList(Arrays.asList(messageLables));
+
+ private static final String resource = "PricatUiLabels";
+
+ /**
+ * Constructor, creates a new HtmlImportThreat.
+ *
+ */
+ public SampleHtmlThread(HttpServletRequest request, HttpServletResponse response, String name) {
+ super(request, response, name);
+ initHtmlReport(request, response);
+ }
+
+ public String getReportUpdate() {
+ return getReport().getReportUpdate();
+ }
+
+ /**
+ * @see java.lang.Runnable#run()
+ */
+ public void run() {
+ try {
+ if (getName().startsWith(COUNT_DOWN)) {
+ getReport().println(UtilProperties.getMessage(resource, "START_COUNT_DOWN", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ Random random = new Random();
+ int j = 0;
+ for (int i=1000; i>0; i--) {
+ sleep(20);
+ j = random.nextInt(7);
+ if (j == 6) {
+ getReport().println(new Throwable(UtilProperties.getMessage(resource, messages.get(j), new Object[] {i}, getLocale())));
+ } else {
+ getReport().println(UtilProperties.getMessage(resource, messages.get(j), new Object[] {i}, getLocale()), j);
+ }
+ }
+ getReport().println(UtilProperties.getMessage(resource, "COUNT_COMPLETED", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ } else if (getName().startsWith(COUNT_UP)) {
+ getReport().println(UtilProperties.getMessage(resource, "START_COUNT_UP", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ Random random = new Random();
+ int j = 0;
+ for (int i=1; i<=1000; i++) {
+ sleep(20);
+ j = random.nextInt(7);
+ if (j == 6) {
+ getReport().println(new Throwable(UtilProperties.getMessage(resource, messages.get(j), new Object[] {i}, getLocale())));
+ } else {
+ getReport().println(UtilProperties.getMessage(resource, messages.get(j), new Object[] {i}, getLocale()), j);
+ }
+ }
+ getReport().println(UtilProperties.getMessage(resource, "COUNT_COMPLETED", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ } else {
+ getReport().println(getName(), InterfaceReport.FORMAT_ERROR);
+ }
+ } catch (Exception e) {
+ getReport().println(e);
+ if (Debug.errorOn()) {
+ Debug.log(e);
+ }
+ }
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java
new file mode 100644
index 0000000000..e787742264
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java
@@ -0,0 +1,678 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport.util;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * The ReportEncoder class provides static methods to decode and encode data.
+ *
+ * The methods in this class are substitutes for java.net.URLEncoder.encode() and
+ * java.net.URLDecoder.decode().
+ *
+ * The de- and encoding uses the same coding mechanism as JavaScript, special characters are
+ * replaced with %hex where hex is a two digit hex number.
+ *
+ * Note: On the client side (browser) instead of using corresponding escape
+ * and unescape JavaScript functions, better use encodeURIComponent and
+ * decodeURIComponent functions which are work properly with unicode characters.
+ * These functions are supported in IE 5.5+ and NS 6+ only.
+ *
+ */
+public final class ReportEncoder {
+
+ /** Constant for the standard ISO-8859-1 encoding. */
+ public static final String ENCODING_ISO_8859_1 = "ISO-8859-1";
+
+ /** Constant for the standard US-ASCII encoding. */
+ public static final String ENCODING_US_ASCII = "US-ASCII";
+
+ /**
+ * Constant for the standard UTF-8 encoding.
+ *
+ * Default encoding for JavaScript decodeUriComponent methods is UTF-8 by w3c standard.
+ */
+ public static final String ENCODING_UTF_8 = "UTF-8";
+
+ /** The regex pattern to match HTML entities. */
+ private static final Pattern ENTITIY_PATTERN = Pattern.compile("\\\\d+;");
+
+ /** The prefix for HTML entities. */
+ private static final String ENTITY_PREFIX = "";
+
+ /** The replacement for HTML entity prefix in parameters. */
+ private static final String ENTITY_REPLACEMENT = "$$";
+
+ /** A cache for encoding name lookup. */
+ private static Map encodingCache = new HashMap(16);
+
+ /** The plus entity. */
+ private static final String PLUS_ENTITY = ENTITY_PREFIX + "043;";
+
+ /**
+ * Constructor.
+ */
+ private ReportEncoder() {
+ // empty
+ }
+
+ /**
+ * Adjusts the given String by making sure all characters that can be displayed
+ * in the given charset are contained as chars, whereas all other non-displayable
+ * characters are converted to HTML entities.
+ *
+ * Just calls {@link #decodeHtmlEntities(String, String)} first and feeds the result
+ * to {@link #encodeHtmlEntities(String, String)}.
+ *
+ * @param input the input to adjust the HTML encoding for
+ * @param encoding the charset to encode the result with\
+ *
+ * @return the input with the decoded/encoded HTML entities
+ */
+ public static String adjustHtmlEncoding(String input, String encoding) {
+
+ return encodeHtmlEntities(decodeHtmlEntities(input, encoding), encoding);
+ }
+
+ /**
+ * Changes the encoding of a byte array that represents a String.
+ *
+ * @param input the byte array to convert
+ * @param oldEncoding the current encoding of the byte array
+ * @param newEncoding the new encoding of the byte array
+ *
+ * @return the byte array encoded in the new encoding
+ */
+ public static byte[] changeEncoding(byte[] input, String oldEncoding, String newEncoding) {
+
+ if ((oldEncoding == null) || (newEncoding == null)) {
+ return input;
+ }
+ if (oldEncoding.trim().equalsIgnoreCase(newEncoding.trim())) {
+ return input;
+ }
+ byte[] result = input;
+ try {
+ result = (new String(input, oldEncoding)).getBytes(newEncoding);
+ } catch (UnsupportedEncodingException e) {
+ // return value will be input value
+ }
+ return result;
+ }
+
+ /**
+ * Creates a String out of a byte array with the specified encoding, falling back
+ * to the system default in case the encoding name is not valid.
+ *
+ * Use this method as a replacement for new String(byte[], encoding)
+ * to avoid possible encoding problems.
+ *
+ * @param bytes the bytes to decode
+ * @param encoding the encoding scheme to use for decoding the bytes
+ *
+ * @return the bytes decoded to a String
+ */
+ public static String createString(byte[] bytes, String encoding) {
+
+ String enc = encoding.intern();
+ if (enc != ENCODING_UTF_8) {
+ enc = lookupEncoding(enc, null);
+ }
+ if (enc != null) {
+ try {
+ return new String(bytes, enc);
+ } catch (UnsupportedEncodingException e) {
+ // this can _never_ happen since the charset was looked up first
+ }
+ } else {
+ enc = ENCODING_UTF_8;
+ try {
+ return new String(bytes, enc);
+ } catch (UnsupportedEncodingException e) {
+ // this can also _never_ happen since the default encoding is always valid
+ }
+ }
+ // this code is unreachable in practice
+ return null;
+ }
+
+ /**
+ * Decodes a String using UTF-8 encoding, which is the standard for http data transmission
+ * with GET ant POST requests.
+ *
+ * @param source the String to decode
+ *
+ * @return String the decoded source String
+ */
+ public static String decode(String source) {
+
+ return decode(source, ENCODING_UTF_8);
+ }
+
+ /**
+ * This method is a substitute for URLDecoder.decode().
+ *
+ * In case you don't know what encoding to use, set the value of
+ * the encoding parameter to null.
+ * This method will then default to UTF-8 encoding, which is probably the right one.
+ *
+ * @param source The string to decode
+ * @param encoding The encoding to use (if null, the system default is used)
+ *
+ * @return The decoded source String
+ */
+ public static String decode(String source, String encoding) {
+
+ if (source == null) {
+ return null;
+ }
+ if (encoding != null) {
+ try {
+ return URLDecoder.decode(source, encoding);
+ } catch (java.io.UnsupportedEncodingException e) {
+ // will fallback to default
+ }
+ }
+ // fallback to default decoding
+ try {
+ return URLDecoder.decode(source, ENCODING_UTF_8);
+ } catch (java.io.UnsupportedEncodingException e) {
+ // ignore
+ }
+ return source;
+ }
+
+ /**
+ * Decodes HTML entity references like € that are contained in the
+ * String to a regular character, but only if that character is contained in the given
+ * encodings charset.
+ *
+ * @param input the input to decode the HTML entities in
+ * @param encoding the charset to decode the input for
+ * @return the input with the decoded HTML entities
+ *
+ * @see #encodeHtmlEntities(String, String)
+ */
+ public static String decodeHtmlEntities(String input, String encoding) {
+
+ Matcher matcher = ENTITIY_PATTERN.matcher(input);
+ StringBuffer result = new StringBuffer(input.length());
+ Charset charset = Charset.forName(encoding);
+ CharsetEncoder encoder = charset.newEncoder();
+
+ while (matcher.find()) {
+ String entity = matcher.group();
+ String value = entity.substring(2, entity.length() - 1);
+ int c = Integer.valueOf(value).intValue();
+ if (c < 128) {
+ // first 128 chars are contained in almost every charset
+ entity = new String(new char[] {(char)c});
+ // this is intended as performance improvement since
+ // the canEncode() operation appears quite CPU heavy
+ } else if (encoder.canEncode((char)c)) {
+ // encoder can encode this char
+ entity = new String(new char[] {(char)c});
+ }
+ matcher.appendReplacement(result, entity);
+ }
+ matcher.appendTail(result);
+ return result.toString();
+ }
+
+ /**
+ * Decodes a string used as parameter in an uri in a way independent of other encodings/decodings applied before.
+ *
+ * @param input the encoded parameter string
+ *
+ * @return the decoded parameter string
+ *
+ * @see #encodeParameter(String)
+ */
+ public static String decodeParameter(String input) {
+
+ String result = ReportStringUtil.substitute(input, ENTITY_REPLACEMENT, ENTITY_PREFIX);
+ return ReportEncoder.decodeHtmlEntities(result, ENCODING_UTF_8);
+ }
+
+ /**
+ * Encodes a String using UTF-8 encoding, which is the standard for http data transmission
+ * with GET ant POST requests.
+ *
+ * @param source the String to encode
+ *
+ * @return String the encoded source String
+ */
+ public static String encode(String source) {
+
+ return encode(source, ENCODING_UTF_8);
+ }
+
+ /**
+ * This method is a substitute for URLEncoder.encode().
+ *
+ * In case you don't know what encoding to use, set the value of
+ * the encoding parameter to null.
+ * This method will then default to UTF-8 encoding, which is probably the right one.
+ *
+ * @param source the String to encode
+ * @param encoding the encoding to use (if null, the system default is used)
+ *
+ * @return the encoded source String
+ */
+ public static String encode(String source, String encoding) {
+
+ if (source == null) {
+ return null;
+ }
+ if (encoding != null) {
+ try {
+ return URLEncoder.encode(source, encoding);
+ } catch (java.io.UnsupportedEncodingException e) {
+ // will fallback to default
+ }
+ }
+ // fallback to default encoding
+ try {
+ return URLEncoder.encode(source, ENCODING_UTF_8);
+ } catch (java.io.UnsupportedEncodingException e) {
+ // ignore
+ }
+ return source;
+ }
+
+ /**
+ * Encodes all characters that are contained in the String which can not displayed
+ * in the given encodings charset with HTML entity references
+ * like €.
+ *
+ * This is required since a Java String is
+ * internally always stored as Unicode, meaning it can contain almost every character, but
+ * the HTML charset used might not support all such characters.
+ *
+ * @param input the input to encode for HTML
+ * @param encoding the charset to encode the result with
+ *
+ * @return the input with the encoded HTML entities
+ *
+ * @see #decodeHtmlEntities(String, String)
+ */
+ public static String encodeHtmlEntities(String input, String encoding) {
+
+ StringBuffer result = new StringBuffer(input.length() * 2);
+ CharBuffer buffer = CharBuffer.wrap(input.toCharArray());
+ Charset charset = Charset.forName(encoding);
+ CharsetEncoder encoder = charset.newEncoder();
+ for (int i = 0; i < buffer.length(); i++) {
+ int c = buffer.get(i);
+ if (c < 128) {
+ // first 128 chars are contained in almost every charset
+ result.append((char)c);
+ // this is intended as performance improvement since
+ // the canEncode() operation appears quite CPU heavy
+ } else if (encoder.canEncode((char)c)) {
+ // encoder can encode this char
+ result.append((char)c);
+ } else {
+ // append HTML entity reference
+ result.append(ENTITY_PREFIX);
+ result.append(c);
+ result.append(";");
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Encodes all characters that are contained in the String which can not displayed
+ * in the given encodings charset with Java escaping like \u20ac.
+ *
+ * This can be used to escape values used in Java property files.
+ *
+ * @param input the input to encode for Java
+ * @param encoding the charset to encode the result with
+ *
+ * @return the input with the encoded Java entities
+ */
+ public static String encodeJavaEntities(String input, String encoding) {
+
+ StringBuffer result = new StringBuffer(input.length() * 2);
+ CharBuffer buffer = CharBuffer.wrap(input.toCharArray());
+ Charset charset = Charset.forName(encoding);
+ CharsetEncoder encoder = charset.newEncoder();
+ for (int i = 0; i < buffer.length(); i++) {
+ int c = buffer.get(i);
+ if (c < 128) {
+ // first 128 chars are contained in almost every charset
+ result.append((char)c);
+ // this is intended as performance improvement since
+ // the canEncode() operation appears quite CPU heavy
+ } else if (encoder.canEncode((char)c)) {
+ // encoder can encode this char
+ result.append((char)c);
+ } else {
+ // append Java entity reference
+ result.append("\\u");
+ String hex = Integer.toHexString(c);
+ int pad = 4 - hex.length();
+ for (int p = 0; p < pad; p++) {
+ result.append('0');
+ }
+ result.append(hex);
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Encodes a string used as parameter in an uri in a way independent of other encodings/decodings applied later.
+ *
+ * Used to ensure that GET parameters are not wrecked by wrong or incompatible configuration settings.
+ * In order to ensure this, the String is first encoded with html entities for any character that cannot encoded
+ * in US-ASCII; additionally, the plus sign is also encoded to avoid problems with the white-space replacer.
+ * Finally, the entity prefix is replaced with characters not used as delimiters in urls.
+ *
+ * @param input the parameter string
+ *
+ * @return the encoded parameter string
+ */
+ public static String encodeParameter(String input) {
+
+ String result = ReportEncoder.encodeHtmlEntities(input, ReportEncoder.ENCODING_US_ASCII);
+ result = ReportStringUtil.substitute(result, "+", PLUS_ENTITY);
+ return ReportStringUtil.substitute(result, ENTITY_PREFIX, ENTITY_REPLACEMENT);
+ }
+
+ /**
+ * Encodes a String in a way that is compatible with the JavaScript escape function.
+ *
+ * @param source The text to be encoded
+ * @param encoding the encoding type
+ *
+ * @return The JavaScript escaped string
+ */
+ public static String escape(String source, String encoding) {
+
+ // the blank is encoded into "+" not "%20" when using standard encode call
+ return ReportStringUtil.substitute(encode(source, encoding), "+", "%20");
+ }
+
+ /**
+ * Escapes special characters in a HTML-String with their number-based
+ * entity representation, for example & becomes &.
+ *
+ * A character num is replaced if
+ * ((ch != 32) && ((ch > 122) || (ch < 48) || (ch == 60) || (ch == 62)))
+ *
+ * @param source the String to escape
+ *
+ * @return String the escaped String
+ *
+ * @see #escapeXml(String)
+ */
+ public static String escapeHtml(String source) {
+
+ int terminatorIndex;
+ if (source == null) {
+ return null;
+ }
+ StringBuffer result = new StringBuffer(source.length() * 2);
+ for (int i = 0; i < source.length(); i++) {
+ int ch = source.charAt(i);
+ // avoid escaping already escaped characters
+ if (ch == 38) {
+ terminatorIndex = source.indexOf(";", i);
+ if (terminatorIndex > 0) {
+ if (source.substring(i + 1, terminatorIndex).matches("#[0-9]+|lt|gt|amp|quote")) {
+ result.append(source.substring(i, terminatorIndex + 1));
+ // Skip remaining chars up to (and including) ";"
+ i = terminatorIndex;
+ continue;
+ }
+ }
+ }
+ if ((ch != 32) && ((ch > 122) || (ch < 48) || (ch == 60) || (ch == 62))) {
+ result.append(ENTITY_PREFIX);
+ result.append(ch);
+ result.append(";");
+ } else {
+ result.append((char)ch);
+ }
+ }
+ return new String(result);
+ }
+
+ /**
+ * Escapes non ASCII characters in a HTML-String with their number-based
+ * entity representation, for example & becomes &.
+ *
+ * A character num is replaced if
+ * (ch > 255)
+ *
+ * @param source the String to escape
+ *
+ * @return String the escaped String
+ *
+ * @see #escapeXml(String)
+ */
+ public static String escapeNonAscii(String source) {
+
+ if (source == null) {
+ return null;
+ }
+ StringBuffer result = new StringBuffer(source.length() * 2);
+ for (int i = 0; i < source.length(); i++) {
+ int ch = source.charAt(i);
+ if (ch > 255) {
+ result.append(ENTITY_PREFIX);
+ result.append(ch);
+ result.append(";");
+ } else {
+ result.append((char)ch);
+ }
+ }
+ return new String(result);
+ }
+
+ /**
+ * Encodes a String in a way that is compatible with the JavaScript escape function.
+ * Multiple blanks are encoded _multiply _with %20.
+ *
+ * @param source The text to be encoded
+ * @param encoding the encoding type
+ *
+ * @return The JavaScript escaped string
+ */
+ public static String escapeWBlanks(String source, String encoding) {
+
+ if (ReportStringUtil.isEmpty(source)) {
+ return source;
+ }
+ StringBuffer ret = new StringBuffer(source.length() * 2);
+
+ // URLEncode the text string
+ // this produces a very similar encoding to JavaSscript encoding,
+ // except the blank which is not encoded into "%20" instead of "+"
+
+ String enc = encode(source, encoding);
+ for (int z = 0; z < enc.length(); z++) {
+ char c = enc.charAt(z);
+ if (c == '+') {
+ ret.append("%20");
+ } else {
+ ret.append(c);
+ }
+ }
+ return ret.toString();
+ }
+
+ /**
+ * Escapes a String so it may be printed as text content or attribute
+ * value in a HTML page or an XML file.
+ *
+ * This method replaces the following characters in a String:
+ *
+ * < with <
+ * > with >
+ * & with &
+ * " with "
+ *
+ *
+ * @param source the string to escape
+ *
+ * @return the escaped string
+ *
+ * @see #escapeHtml(String)
+ */
+ public static String escapeXml(String source) {
+
+ return escapeXml(source, false);
+ }
+
+ /**
+ * Escapes a String so it may be printed as text content or attribute
+ * value in a HTML page or an XML file.
+ *
+ * This method replaces the following characters in a String:
+ *
+ * < with <
+ * > with >
+ * & with &
+ * " with "
+ *
+ *
+ * @param source the string to escape
+ * @param doubleEscape if false, all entities that already are escaped are left untouched
+ *
+ * @return the escaped string
+ *
+ * @see #escapeHtml(String)
+ */
+ public static String escapeXml(String source, boolean doubleEscape) {
+
+ if (source == null) {
+ return null;
+ }
+ StringBuffer result = new StringBuffer(source.length() * 2);
+
+ for (int i = 0; i < source.length(); ++i) {
+ char ch = source.charAt(i);
+ switch (ch) {
+ case '<':
+ result.append("<");
+ break;
+ case '>':
+ result.append(">");
+ break;
+ case '&':
+ // don't escape already escaped international and special characters
+ if (!doubleEscape) {
+ int terminatorIndex = source.indexOf(";", i);
+ if (terminatorIndex > 0) {
+ if (source.substring(i + 1, terminatorIndex).matches("#[0-9]+")) {
+ result.append(ch);
+ break;
+ }
+ }
+ }
+ // note that to other "break" in the above "if" block
+ result.append("&");
+ break;
+ case '"':
+ result.append(""");
+ break;
+ default:
+ result.append(ch);
+ }
+ }
+ return new String(result);
+ }
+
+ /**
+ * Checks if a given encoding name is actually supported, and if so
+ * resolves it to it's canonical name, if not it returns the given fallback
+ * value.
+ *
+ * Charsets have a set of aliases. For example, valid aliases for "UTF-8"
+ * are "UTF8", "utf-8" or "utf8". This method resolves any given valid charset name
+ * to it's "canonical" form, so that simple String comparison can be used
+ * when checking charset names internally later.
+ *
+ * Please see http://www.iana.org/assignments/character-sets
+ * for a list of valid charset alias names.
+ *
+ * @param encoding the encoding to check and resolve
+ * @param fallback the fallback encoding scheme
+ *
+ * @return the resolved encoding name, or the fallback value
+ */
+ public static String lookupEncoding(String encoding, String fallback) {
+
+ String result = (String) encodingCache.get(encoding);
+ if (result != null) {
+ return result;
+ }
+
+ try {
+ result = Charset.forName(encoding).name();
+ encodingCache.put(encoding, result);
+ return result;
+ } catch (Throwable t) {
+ // we will use the default value as fallback
+ }
+
+ return fallback;
+ }
+
+ /**
+ * Decodes a String in a way that is compatible with the JavaScript
+ * unescape function.
+ *
+ * @param source The String to be decoded
+ * @param encoding the encoding type
+ *
+ * @return The JavaScript unescaped String
+ */
+ public static String unescape(String source, String encoding) {
+
+ if (source == null) {
+ return null;
+ }
+ int len = source.length();
+ // to use standard decoder we need to replace '+' with "%20" (space)
+ StringBuffer preparedSource = new StringBuffer(len);
+ for (int i = 0; i < len; i++) {
+ char c = source.charAt(i);
+ if (c == '+') {
+ preparedSource.append("%20");
+ } else {
+ preparedSource.append(c);
+ }
+ }
+ return decode(preparedSource.toString(), encoding);
+ }
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportStringUtil.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportStringUtil.java
new file mode 100644
index 0000000000..f1baa0b6b2
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportStringUtil.java
@@ -0,0 +1,570 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.htmlreport.util;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * Provides String utility functions.
+ *
+ */
+public final class ReportStringUtil {
+
+ /** Constant for "false". */
+ public static final String FALSE = Boolean.toString(false);
+
+ /** a convenient shorthand to the line separator constant. */
+ public static final String LINE_SEPARATOR = System.getProperty("line.separator");
+
+ /** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */
+ public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'};
+
+ /** a convenient shorthand for tabulations. */
+ public static final String TABULATOR = " ";
+
+ /** Constant for "true". */
+ public static final String TRUE = Boolean.toString(true);
+
+ /** Day constant. */
+ private static final long DAYS = 1000 * 60 * 60 * 24;
+
+ /** Hour constant. */
+ private static final long HOURS = 1000 * 60 * 60;
+
+ /** Minute constant. */
+ private static final long MINUTES = 1000 * 60;
+
+ /** Second constant. */
+ private static final long SECONDS = 1000;
+
+ /**
+ * Default constructor (empty), private because this class has only
+ * static methods.
+ */
+ private ReportStringUtil() {
+ // empty
+ }
+
+ /**
+ * Changes the filename suffix.
+ *
+ * @param filename the filename to be changed
+ * @param suffix the new suffix of the file
+ *
+ * @return the filename with the replaced suffix
+ */
+ public static String changeFileNameSuffixTo(String filename, String suffix) {
+
+ int dotPos = filename.lastIndexOf('.');
+ if (dotPos != -1) {
+ return filename.substring(0, dotPos + 1) + suffix;
+ } else {
+ // the string has no suffix
+ return filename;
+ }
+ }
+
+ /**
+ * Returns a string representation for the given collection using the given separator.
+ *
+ * @param collection the collection to print
+ * @param separator the item separator
+ *
+ * @return the string representation for the given collection
+ */
+ public static String collectionAsString(Collection collection, String separator) {
+
+ StringBuffer string = new StringBuffer(128);
+ Iterator it = collection.iterator();
+ while (it.hasNext()) {
+ string.append(it.next());
+ if (it.hasNext()) {
+ string.append(separator);
+ }
+ }
+ return string.toString();
+ }
+
+ /**
+ * Replaces occurrences of special control characters in the given input with
+ * a HTML representation.
+ *
+ * This method currently replaces line breaks to <br/> and special HTML chars
+ * like < > & " with their HTML entity representation.
+ *
+ * @param source the String to escape
+ *
+ * @return the escaped String
+ */
+ public static String escapeHtml(String source) {
+
+ if (source == null) {
+ return null;
+ }
+ source = ReportEncoder.escapeXml(source);
+ source = substitute(source, "\r", "");
+ source = substitute(source, "\n", " \n");
+ return source;
+ }
+
+ /**
+ * Escapes a String so it may be used in JavaScript String definitions.
+ *
+ * This method replaces line breaks, quotation marks and \ characters.
+ *
+ * @param source the String to escape
+ *
+ * @return the escaped String
+ */
+ public static String escapeJavaScript(String source) {
+
+ source = substitute(source, "\\", "\\\\");
+ source = substitute(source, "\"", "\\\"");
+ source = substitute(source, "\'", "\\\'");
+ source = substitute(source, "\r\n", "\\n");
+ source = substitute(source, "\n", "\\n");
+ return source;
+ }
+
+ /**
+ * Escapes a String so it may be used as a Perl5 regular expression.
+ *
+ * This method replaces the following characters in a String:
+ * {}[]()\$^.*+/
+ *
+ * @param source the string to escape
+ *
+ * @return the escaped string
+ */
+ public static String escapePattern(String source) {
+
+ if (source == null) {
+ return null;
+ }
+ StringBuffer result = new StringBuffer(source.length() * 2);
+ for (int i = 0; i < source.length(); ++i) {
+ char ch = source.charAt(i);
+ switch (ch) {
+ case '\\':
+ result.append("\\\\");
+ break;
+ case '/':
+ result.append("\\/");
+ break;
+ case '$':
+ result.append("\\$");
+ break;
+ case '^':
+ result.append("\\^");
+ break;
+ case '.':
+ result.append("\\.");
+ break;
+ case '*':
+ result.append("\\*");
+ break;
+ case '+':
+ result.append("\\+");
+ break;
+ case '|':
+ result.append("\\|");
+ break;
+ case '?':
+ result.append("\\?");
+ break;
+ case '{':
+ result.append("\\{");
+ break;
+ case '}':
+ result.append("\\}");
+ break;
+ case '[':
+ result.append("\\[");
+ break;
+ case ']':
+ result.append("\\]");
+ break;
+ case '(':
+ result.append("\\(");
+ break;
+ case ')':
+ result.append("\\)");
+ break;
+ default:
+ result.append(ch);
+ }
+ }
+ return new String(result);
+ }
+
+ /**
+ * Formats a runtime in the format hh:mm:ss, to be used e.g. in reports.
+ *
+ * If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.
+ *
+ * @param runtime the time to format
+ *
+ * @return the formatted runtime
+ */
+ public static String formatRuntime(long runtime) {
+
+ long seconds = (runtime / SECONDS) % 60;
+ long minutes = (runtime / MINUTES) % 60;
+ long hours = (runtime / HOURS) % 24;
+ long days = runtime / DAYS;
+ StringBuffer strBuf = new StringBuffer();
+
+ if (days > 0) {
+ if (days < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(days);
+ strBuf.append(':');
+ }
+
+ if (hours < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(hours);
+ strBuf.append(':');
+
+ if (minutes < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(minutes);
+ strBuf.append(':');
+
+ if (seconds < 10) {
+ strBuf.append('0');
+ }
+ strBuf.append(seconds);
+
+ return strBuf.toString();
+ }
+
+ /**
+ * Returns true if the provided String is either null
+ * or the empty String "".
+ *
+ * @param value the value to check
+ *
+ * @return true, if the provided value is null or the empty String, false otherwise
+ */
+ public static boolean isEmpty(String value) {
+
+ return (value == null) || (value.length() == 0);
+ }
+
+ /**
+ * Returns true if the provided String is either null
+ * or contains only white spaces.
+ *
+ * @param value the value to check
+ *
+ * @return true, if the provided value is null or contains only white spaces, false otherwise
+ */
+ public static boolean isEmptyOrWhitespaceOnly(String value) {
+
+ return isEmpty(value) || (value.trim().length() == 0);
+ }
+
+ /**
+ * Returns true if the provided Objects are either both null
+ * or equal according to {@link Object#equals(Object)}.
+ *
+ * @param value1 the first object to compare
+ * @param value2 the second object to compare
+ *
+ * @return true if the provided Objects are either both null
+ * or equal according to {@link Object#equals(Object)}
+ */
+ public static boolean isEqual(Object value1, Object value2) {
+
+ if (value1 == null) {
+ return (value2 == null);
+ }
+ return value1.equals(value2);
+ }
+
+ /**
+ * Returns true if the provided String is neither null
+ * nor the empty String "".
+ *
+ * @param value the value to check
+ *
+ * @return true, if the provided value is not null and not the empty String, false otherwise
+ */
+ public static boolean isNotEmpty(String value) {
+
+ return (value != null) && (value.length() != 0);
+ }
+
+ /**
+ * Returns true if the provided String is neither null
+ * nor contains only white spaces.
+ *
+ * @param value the value to check
+ *
+ * @return true, if the provided value is null
+ * or contains only white spaces, false otherwise
+ */
+ public static boolean isNotEmptyOrWhitespaceOnly(String value) {
+
+ return (value != null) && (value.trim().length() > 0);
+ }
+
+ /**
+ * Returns the last index of any of the given chars in the given source.
+ *
+ * If no char is found, -1 is returned.
+ *
+ * @param source the source to check
+ * @param chars the chars to find
+ *
+ * @return the last index of any of the given chars in the given source, or -1
+ */
+ public static int lastIndexOf(String source, char[] chars) {
+
+ // now try to find an "sentence ending" char in the text in the "findPointArea"
+ int result = -1;
+ for (int i = 0; i < chars.length; i++) {
+ int pos = source.lastIndexOf(chars[i]);
+ if (pos > result) {
+ // found new last char
+ result = pos;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns the last index a whitespace char the given source.
+ *
+ * If no whitespace char is found, -1 is returned.
+ *
+ * @param source the source to check
+ *
+ * @return the last index a whitespace char the given source, or -1
+ */
+ public static int lastWhitespaceIn(String source) {
+
+ if (isEmpty(source)) {
+ return -1;
+ }
+ int pos = -1;
+ for (int i = source.length() - 1; i >= 0; i--) {
+ if (Character.isWhitespace(source.charAt(i))) {
+ pos = i;
+ break;
+ }
+ }
+ return pos;
+ }
+
+ /**
+ * Substitutes searchString in the given source String with replaceString.
+ *
+ * This is a high-performance implementation which should be used as a replacement for
+ * {@link String#replaceAll(java.lang.String, java.lang.String)} in case no
+ * regular expression evaluation is required.
+ *
+ * @param source the content which is scanned
+ * @param searchString the String which is searched in content
+ * @param replaceString the String which replaces searchString
+ *
+ * @return the substituted String
+ */
+ public static String substitute(String source, String searchString, String replaceString) {
+
+ if (source == null) {
+ return null;
+ }
+
+ if (isEmpty(searchString)) {
+ return source;
+ }
+
+ if (replaceString == null) {
+ replaceString = "";
+ }
+ int len = source.length();
+ int sl = searchString.length();
+ int rl = replaceString.length();
+ int length;
+ if (sl == rl) {
+ length = len;
+ } else {
+ int c = 0;
+ int s = 0;
+ int e;
+ while ((e = source.indexOf(searchString, s)) != -1) {
+ c++;
+ s = e + sl;
+ }
+ if (c == 0) {
+ return source;
+ }
+ length = len - (c * (sl - rl));
+ }
+
+ int s = 0;
+ int e = source.indexOf(searchString, s);
+ if (e == -1) {
+ return source;
+ }
+ StringBuffer sb = new StringBuffer(length);
+ while (e != -1) {
+ sb.append(source.substring(s, e));
+ sb.append(replaceString);
+ s = e + sl;
+ e = source.indexOf(searchString, s);
+ }
+ e = len;
+ sb.append(source.substring(s, e));
+ return sb.toString();
+ }
+
+ /**
+ * Returns the java String literal for the given String.
+ *
+ * This is the form of the String that had to be written into source code
+ * using the unicode escape sequence for special characters.
+ *
+ * Example: "�" would be transformed to "\\u00C4".
+ *
+ * @param s a string that may contain non-ascii characters
+ *
+ * @return the java unicode escaped string Literal of the given input string
+ */
+ public static String toUnicodeLiteral(String s) {
+
+ StringBuffer result = new StringBuffer();
+ char[] carr = s.toCharArray();
+
+ String unicode;
+ for (int i = 0; i < carr.length; i++) {
+ result.append("\\u");
+ // append leading zeros
+ unicode = Integer.toHexString(carr[i]).toUpperCase();
+ for (int j = 4 - unicode.length(); j > 0; j--) {
+ result.append("0");
+ }
+ result.append(unicode);
+ }
+ return result.toString();
+ }
+
+ /**
+ * Returns a substring of the source, which is at most length characters long.
+ *
+ * This is the same as calling {@link #trimToSize(String, int, String)} with the
+ * parameters (source, length, " ...").
+ *
+ * @param source the string to trim
+ * @param length the maximum length of the string to be returned
+ *
+ * @return a substring of the source, which is at most length characters long
+ */
+ public static String trimToSize(String source, int length) {
+
+ return trimToSize(source, length, length, " ...");
+ }
+
+ /**
+ * Returns a substring of the source, which is at most length characters long.
+ *
+ * If a char is cut, the given suffix is appended to the result.
+ *
+ * This is almost the same as calling {@link #trimToSize(String, int, int, String)} with the
+ * parameters (source, length, length*, suffix). If length
+ * if larger then 100, then length* = length / 2,
+ * otherwise length* = length.
+ *
+ * @param source the string to trim
+ * @param length the maximum length of the string to be returned
+ * @param suffix the suffix to append in case the String was trimmed
+ *
+ * @return a substring of the source, which is at most length characters long
+ */
+ public static String trimToSize(String source, int length, String suffix) {
+
+ int area = (length > 100) ? length / 2 : length;
+ return trimToSize(source, length, area, suffix);
+ }
+
+ /**
+ * Returns a substring of the source, which is at most length characters long, cut
+ * in the last area chars in the source at a sentence ending char or whitespace.
+ *
+ * If a char is cut, the given suffix is appended to the result.
+ *
+ * @param source the string to trim
+ * @param length the maximum length of the string to be returned
+ * @param area the area at the end of the string in which to find a sentence ender or whitespace
+ * @param suffix the suffix to append in case the String was trimmed
+ *
+ * @return a substring of the source, which is at most length characters long
+ */
+ public static String trimToSize(String source, int length, int area, String suffix) {
+
+ if ((source == null) || (source.length() <= length)) {
+ // no operation is required
+ return source;
+ }
+ if (isEmpty(suffix)) {
+ // we need an empty suffix
+ suffix = "";
+ }
+ // must remove the length from the after sequence chars since these are always added in the end
+ int modLength = length - suffix.length();
+ if (modLength <= 0) {
+ // we are to short, return beginning of the suffix
+ return suffix.substring(0, length);
+ }
+ int modArea = area + suffix.length();
+ if ((modArea > modLength) || (modArea < 0)) {
+ // area must not be longer then max length
+ modArea = modLength;
+ }
+
+ // first reduce the String to the maximum allowed length
+ String findPointSource = source.substring(modLength - modArea, modLength);
+
+ String result;
+ // try to find an "sentence ending" char in the text
+ int pos = lastIndexOf(findPointSource, SENTENCE_ENDING_CHARS);
+ if (pos >= 0) {
+ // found a sentence ender in the lookup area, keep the sentence ender
+ result = source.substring(0, modLength - modArea + pos + 1) + suffix;
+ } else {
+ // no sentence ender was found, try to find a whitespace
+ pos = lastWhitespaceIn(findPointSource);
+ if (pos >= 0) {
+ // found a whitespace, don't keep the whitespace
+ result = source.substring(0, modLength - modArea + pos) + suffix;
+ } else {
+ // not even a whitespace was found, just cut away what's to long
+ result = source.substring(0, modLength) + suffix;
+ }
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java
new file mode 100644
index 0000000000..2badc5c751
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java
@@ -0,0 +1,663 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
+import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
+import org.apache.poi.ss.util.CellAddress;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.ss.util.WorkbookUtil;
+import org.apache.poi.xssf.usermodel.OFBizPricatUtil;
+import org.apache.poi.xssf.usermodel.XSSFAnchor;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
+import org.apache.poi.xssf.usermodel.XSSFComment;
+import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
+import org.apache.poi.xssf.usermodel.XSSFDrawing;
+import org.apache.poi.xssf.usermodel.XSSFFont;
+import org.apache.poi.xssf.usermodel.XSSFPicture;
+import org.apache.poi.xssf.usermodel.XSSFPictureData;
+import org.apache.poi.xssf.usermodel.XSSFRichTextString;
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFShape;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.commons.fileupload.FileItem;
+
+import org.apache.ofbiz.htmlreport.InterfaceReport;
+import org.apache.ofbiz.order.finaccount.FinAccountHelper;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.FileUtil;
+import org.apache.ofbiz.base.util.UtilDateTime;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.condition.EntityCondition;
+import org.apache.ofbiz.entity.condition.EntityOperator;
+import org.apache.ofbiz.entity.util.EntityUtil;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ServiceUtil;
+
+/**
+ * Abstract class of pricat parser.
+ *
+ */
+public abstract class AbstractPricatParser implements InterfacePricatParser {
+
+ public static final String module = AbstractPricatParser.class.getName();
+
+ protected LocalDispatcher dispatcher;
+
+ protected Delegator delegator;
+
+ protected List fileItems;
+
+ protected File pricatFile;
+
+ protected String userLoginId;
+
+ protected GenericValue userLogin;
+
+ protected String pricatFileVersion;
+
+ protected String currencyId;
+
+ protected Map errorMessages = new HashMap();
+
+ protected HSSFDataFormatter formatter = new HSSFDataFormatter();
+
+ protected Map facilities = new HashMap();
+
+ protected HttpSession session;
+
+ protected List basicCategoryConds;
+
+ protected List basicBrandConds;
+
+ protected String selectedPricatType = DEFAULT_PRICAT_TYPE;
+
+ protected String selectedFacilityId;
+
+ protected InterfaceReport report;
+
+ protected Locale locale;
+
+ protected long sequenceNum = -1L;
+
+ public AbstractPricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, Map facilities, File pricatFile, GenericValue userLogin) {
+ this.dispatcher = dispatcher;
+ this.delegator = delegator;
+ this.locale = locale;
+ this.report = report;
+ this.userLogin = userLogin;
+ if (UtilValidate.isNotEmpty(userLogin)) {
+ this.userLoginId = userLogin.getString("userLoginId");
+ }
+ this.facilities = facilities;
+ this.pricatFile = pricatFile;
+ initBasicConds(UtilMisc.toList(userLogin.getString("partyId")));
+ }
+
+ public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet) {
+ report.println();
+ report.print(UtilProperties.getMessage(resource, "WriteCommentsBackToExcel", locale), InterfaceReport.FORMAT_NOTE);
+ FileOutputStream fos = null;
+ XSSFCreationHelper factory = workbook.getCreationHelper();
+ XSSFFont boldFont = workbook.createFont();
+ boldFont.setFontName("Arial");
+ boldFont.setBold(true);
+ boldFont.setCharSet(134);
+ boldFont.setFontHeightInPoints((short) 9);
+ XSSFFont plainFont = workbook.createFont();
+ plainFont.setFontName("Arial");
+ plainFont.setCharSet(134);
+ plainFont.setFontHeightInPoints((short) 9);
+
+ XSSFSheet errorSheet = null;
+ if (errorMessages.keySet().size() > 0) {
+ String errorSheetName = UtilDateTime.nowDateString("yyyy-MM-dd HHmm") + " Errors";
+ errorSheetName = WorkbookUtil.createSafeSheetName(errorSheetName);
+ errorSheet = workbook.createSheet(errorSheetName);
+ workbook.setSheetOrder(errorSheetName, 0);
+ workbook.setActiveSheet(workbook.getSheetIndex(errorSheetName));
+ XSSFDrawing drawingPatriarch = errorSheet.getDrawingPatriarch();
+ if (drawingPatriarch == null) {
+ drawingPatriarch = errorSheet.createDrawingPatriarch();
+ }
+ for (int i = 0; i <= getHeaderRowNo(); i++) {
+ XSSFRow newRow = errorSheet.createRow(i);
+ XSSFRow row = sheet.getRow(i);
+ newRow.setHeight(row.getHeight());
+ copyRow(row, newRow, factory, drawingPatriarch);
+ }
+
+ // copy merged regions
+ for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
+ CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
+ if (mergedRegion.getFirstRow() < getHeaderRowNo()) {
+ errorSheet.addMergedRegion(mergedRegion);
+ }
+ }
+
+ // copy images
+ List pics = workbook.getAllPictures();
+ List shapes = sheet.getDrawingPatriarch().getShapes();
+ for (int i = 0; i < shapes.size(); i++) {
+ XSSFShape shape = shapes.get(i);
+ XSSFAnchor anchor = shape.getAnchor();
+ if (shape instanceof XSSFPicture && anchor instanceof XSSFClientAnchor) {
+ XSSFPicture pic = (XSSFPicture) shape;
+ XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor;
+ if (clientAnchor.getRow1() < getHeaderRowNo()) {
+ for (int j = 0; j < pics.size(); j++) {
+ XSSFPictureData picture = pics.get(j);
+ if (picture.getPackagePart().getPartName().equals(pic.getPictureData().getPackagePart().getPartName())) {
+ drawingPatriarch.createPicture(clientAnchor, j);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ // set comments in the original sheet
+ XSSFDrawing patriarch = sheet.getDrawingPatriarch();
+ for (CellReference cell : errorMessages.keySet()) {
+ if (cell != null && errorMessages.get(cell) != null) {
+ XSSFComment comment = sheet.getCellComment(new CellAddress(cell.getRow(), cell.getCol()));
+ boolean isNewComment = false;
+ if (comment == null) {
+ XSSFClientAnchor anchor = factory.createClientAnchor();
+ anchor.setDx1(100);
+ anchor.setDx2(100);
+ anchor.setDy1(100);
+ anchor.setDy2(100);
+ anchor.setCol1(cell.getCol());
+ anchor.setCol2(cell.getCol() + 4);
+ anchor.setRow1(cell.getRow());
+ anchor.setRow2(cell.getRow() + 4);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ comment = patriarch.createCellComment(anchor);
+ isNewComment = true;
+ }
+ XSSFRichTextString rts = factory.createRichTextString("OFBiz PriCat:\n");
+ rts.applyFont(boldFont);
+ rts.append(errorMessages.get(cell), plainFont);
+ comment.setString(rts);
+ comment.setAuthor("Apache OFBiz PriCat");
+ if (isNewComment) {
+ sheet.getRow(cell.getRow()).getCell(cell.getCol()).setCellComment(comment);
+ OFBizPricatUtil.formatCommentShape(sheet, cell);
+ }
+ }
+ }
+
+ // set comments in the new error sheet
+ XSSFDrawing errorPatriarch = errorSheet.getDrawingPatriarch();
+ int newRowNum = getHeaderRowNo() + 1;
+ Map rowMapping = new HashMap();
+ for (CellReference cell : errorMessages.keySet()) {
+ if (cell != null && errorMessages.get(cell) != null) {
+ XSSFRow row = sheet.getRow(cell.getRow());
+ Integer rowNum = Integer.valueOf(row.getRowNum());
+ int errorRow = newRowNum;
+ if (rowMapping.containsKey(rowNum)) {
+ errorRow = rowMapping.get(rowNum).intValue();
+ } else {
+ XSSFRow newRow = errorSheet.getRow(errorRow);
+ if (newRow == null) {
+ newRow = errorSheet.createRow(errorRow);
+ }
+ rowMapping.put(rowNum, Integer.valueOf(errorRow));
+ newRow.setHeight(row.getHeight());
+ copyRow(row, newRow, factory, errorPatriarch);
+ newRowNum ++;
+ }
+ }
+ }
+
+ // write to file
+ if (sequenceNum > 0L) {
+ File commentedExcel = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx");
+ fos = new FileOutputStream(commentedExcel);
+ workbook.write(fos);
+ } else {
+ fos = new FileOutputStream(pricatFile);
+ workbook.write(fos);
+ }
+ fos.flush();
+ fos.close();
+ workbook.close();
+ } catch (FileNotFoundException e) {
+ report.println(e);
+ Debug.logError(e, module);
+ } catch (IOException e) {
+ report.println(e);
+ Debug.logError(e, module);
+ } finally {
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException e) {
+ Debug.logError(e, module);
+ }
+ }
+ if (workbook != null) {
+ try {
+ workbook.close();
+ } catch (IOException e) {
+ Debug.logError(e, module);
+ }
+ }
+ }
+ report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ report.println();
+ }
+
+ private void copyRow(XSSFRow sourceRow, XSSFRow targetRow, XSSFCreationHelper factory, XSSFDrawing patriarch) {
+ for (int j = 0; j < sourceRow.getPhysicalNumberOfCells(); j++) {
+ XSSFCell cell = sourceRow.getCell(j);
+ if (cell != null) {
+ XSSFCell newCell = targetRow.createCell(j);
+ int cellType = cell.getCellType();
+ newCell.setCellType(cellType);
+ switch (cellType) {
+ case XSSFCell.CELL_TYPE_BOOLEAN:
+ newCell.setCellValue(cell.getBooleanCellValue());
+ break;
+ case XSSFCell.CELL_TYPE_ERROR:
+ newCell.setCellErrorValue(cell.getErrorCellValue());
+ break;
+ case XSSFCell.CELL_TYPE_FORMULA:
+ newCell.setCellFormula(cell.getCellFormula());
+ break;
+ case XSSFCell.CELL_TYPE_NUMERIC:
+ newCell.setCellValue(cell.getNumericCellValue());
+ break;
+ case XSSFCell.CELL_TYPE_STRING:
+ newCell.setCellValue(cell.getRichStringCellValue());
+ break;
+ default:
+ newCell.setCellValue(formatter.formatCellValue(cell));
+ }
+ if (cell.getCellComment() != null) {
+ XSSFClientAnchor anchor = factory.createClientAnchor();
+ anchor.setDx1(100);
+ anchor.setDx2(100);
+ anchor.setDy1(100);
+ anchor.setDy2(100);
+ anchor.setCol1(newCell.getColumnIndex());
+ anchor.setCol2(newCell.getColumnIndex() + 4);
+ anchor.setRow1(newCell.getRowIndex());
+ anchor.setRow2(newCell.getRowIndex() + 4);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ XSSFComment comment = patriarch.createCellComment(anchor);
+ comment.setString(cell.getCellComment().getString());
+ newCell.setCellComment(comment);
+ }
+ newCell.setCellStyle(cell.getCellStyle());
+ newCell.getSheet().setColumnWidth(newCell.getColumnIndex(), cell.getSheet().getColumnWidth(cell.getColumnIndex()));
+ }
+ }
+ }
+
+ public void initBasicConds(List orgPartyIds) {
+ basicCategoryConds = new ArrayList();
+ basicCategoryConds.add(EntityCondition.makeCondition("isPublic", "N"));
+ //basicCategoryConds.add(EntityCondition.makeCondition("isDefault", "Y"));
+
+ basicBrandConds = new ArrayList();
+ basicBrandConds.add(EntityCondition.makeCondition("isPublic", "N"));
+ basicBrandConds.add(EntityCondition.makeCondition("productFeatureTypeId", "BRAND"));
+
+ List partyIdConds = new ArrayList();
+ for (String orgPartyId : orgPartyIds) {
+ partyIdConds.add(EntityCondition.makeCondition("ownerPartyId", orgPartyId));
+ }
+ if (UtilValidate.isNotEmpty(partyIdConds)) {
+ basicCategoryConds.add(EntityCondition.makeCondition(partyIdConds, EntityOperator.OR));
+ basicBrandConds.add(EntityCondition.makeCondition(partyIdConds, EntityOperator.OR));
+ }
+ }
+
+ public Map updateSkuPrice(String skuId, String ownerPartyId, BigDecimal memberPrice) {
+ return ServiceUtil.returnSuccess();
+ }
+
+ public Map updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension) {
+ Map results = ServiceUtil.returnSuccess();
+ results.put("colorId", "sampleColorId");
+ results.put("dimensionId", "sampleDimensionId");
+ return results;
+ }
+
+ public Map getDimensionIds(String productId, String ownerPartyId, String dimension) {
+ Map results = ServiceUtil.returnSuccess();
+ results.put("dimensionId", "sampleDimensionId");
+ return results;
+ }
+
+ public Map getColorIds(String productId, String ownerPartyId, String color) {
+ Map results = ServiceUtil.returnSuccess();
+ results.put("foundColor", Boolean.TRUE);
+ results.put("colorId", "sampleColorId");
+ return results;
+ }
+
+ public String getBrandId(String brandName, String ownerPartyId) {
+ return "sampleBrandId";
+ }
+
+ public boolean isNumOfSheetsOK(XSSFWorkbook workbook) {
+ report.print(UtilProperties.getMessage(resource, "CheckPricatHasSheet", locale), InterfaceReport.FORMAT_NOTE);
+ int sheets = workbook.getNumberOfSheets();
+ if (sheets < 1) {
+ report.println(UtilProperties.getMessage(resource, "PricatTableNoSheet", locale), InterfaceReport.FORMAT_ERROR);
+ return false;
+ } else if (sheets >= 1) {
+ report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ report.println(UtilProperties.getMessage(resource, "PricatTableOnlyParse1stSheet", locale), InterfaceReport.FORMAT_WARNING);
+ }
+ return true;
+ }
+
+ /**
+ * Get data by version definition.
+ *
+ * @param row
+ * @param colNames
+ * @param size
+ * @return
+ */
+ public List getCellContents(XSSFRow row, List colNames, int size) {
+ List results = new ArrayList();
+ boolean foundError = false;
+ if (isEmptyRow(row, size, true)) {
+ return null;
+ }
+ for (int i = 0; i < size; i++) {
+ XSSFCell cell = null;
+ if (row.getPhysicalNumberOfCells() > i) {
+ cell = row.getCell(i);
+ }
+ if (cell == null) {
+ if (((Boolean) colNames.get(i)[2]).booleanValue()) {
+ report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale));
+ foundError = true;
+ continue;
+ } else {
+ cell = row.createCell(i);
+ }
+ }
+ int cellType = cell.getCellType();
+ String cellValue = formatter.formatCellValue(cell);
+ if (UtilValidate.isNotEmpty(cellValue)) {
+ if (cellType == XSSFCell.CELL_TYPE_FORMULA) {
+ cellValue = BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding).toString();
+ report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE);
+ } else {
+ report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE);
+ }
+ } else {
+ report.print(((i == 0)?"":","), InterfaceReport.FORMAT_NOTE);
+ }
+ if (((Boolean) colNames.get(i)[2]).booleanValue() && UtilValidate.isEmpty(cellValue)) {
+ report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale));
+ foundError = true;
+ results.add(null);
+ continue;
+ }
+ if (((Boolean) colNames.get(i)[2]).booleanValue() && cellType != (int) colNames.get(i)[1]) {
+ // String warningMessage = "";
+ if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
+ results.add(cellValue);
+ } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
+ if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING) {
+ cell.setCellType(XSSFCell.CELL_TYPE_STRING);
+ }
+ try {
+ results.add(BigDecimal.valueOf(Double.parseDouble(cell.getStringCellValue())).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ }
+ } else {
+ if (UtilValidate.isEmpty(cellValue)) {
+ results.add(null);
+ continue;
+ }
+ if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
+ if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
+ results.add(cell.getStringCellValue());
+ } else {
+ results.add(cellValue);
+ }
+ } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
+ if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
+ try {
+ results.add(BigDecimal.valueOf(Double.valueOf(cell.getStringCellValue())));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
+ try {
+ results.add(BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ } else {
+ try {
+ results.add(BigDecimal.valueOf(Double.valueOf(cellValue)).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ }
+ }
+ }
+ }
+ if (foundError) {
+ return null;
+ }
+ return results;
+ }
+
+ public void setFacilityId(String selectedFacilityId) {
+ this.selectedFacilityId = selectedFacilityId;
+ }
+
+ protected boolean isEmptyRow(XSSFRow row, int size, boolean display) {
+ // check whether this row is empty
+ if (UtilValidate.isEmpty(row)) {
+ report.print(UtilProperties.getMessage(resource, "ExcelEmptyRow", locale), InterfaceReport.FORMAT_NOTE);
+ return true;
+ }
+ boolean isEmptyRow = true;
+ int physicalNumberOfCells = row.getPhysicalNumberOfCells();
+ int i = 0;
+ for (; i < size; i++) {
+ XSSFCell cell = null;
+ if (physicalNumberOfCells > i) {
+ cell = row.getCell(i);
+ }
+ if (cell != null && UtilValidate.isNotEmpty(formatter.formatCellValue(cell)) && UtilValidate.isNotEmpty(formatter.formatCellValue(cell).trim())) {
+ isEmptyRow = false;
+ break;
+ }
+ }
+ if (isEmptyRow) {
+ if (display) {
+ report.print(UtilProperties.getMessage(resource, "ExcelEmptyRow", locale), InterfaceReport.FORMAT_NOTE);
+ }
+ return true;
+ } else if (!isEmptyRow && i > size) {
+ if (display) {
+ report.print(UtilProperties.getMessage(resource, "IgnoreDataOutOfRange", locale), InterfaceReport.FORMAT_NOTE);
+ }
+ return true;
+ }
+ return isEmptyRow;
+ }
+
+ protected abstract int getHeaderRowNo();
+
+
+ public synchronized void endExcelImportHistory(String logFileName, String thruReasonId) {
+ Thread currentThread = Thread.currentThread();
+ String threadName = null;
+ if (currentThread instanceof PricatParseExcelHtmlThread) {
+ threadName = ((PricatParseExcelHtmlThread) currentThread).getUUID().toString();
+ }
+ if (UtilValidate.isEmpty(threadName)) {
+ return;
+ }
+ try {
+ GenericValue historyValue = null;
+ if (sequenceNum < 1L) {
+ historyValue = EntityUtil.getFirst(EntityUtil.filterByDate(delegator.findByAnd("ExcelImportHistory",
+ UtilMisc.toMap("userLoginId", userLoginId, "logFileName", logFileName), UtilMisc.toList("sequenceNum DESC"), false)));
+ } else {
+ historyValue = delegator.findOne("ExcelImportHistory", UtilMisc.toMap("userLoginId", userLoginId, "sequenceNum", (Long) sequenceNum), false);
+ }
+ Timestamp now = UtilDateTime.nowTimestamp();
+ if (UtilValidate.isEmpty(historyValue)) {
+ historyValue = delegator.makeValue("ExcelImportHistory", UtilMisc.toMap("sequenceNum", Long.valueOf(sequenceNum), "userLoginId", userLoginId,
+ "fileName", pricatFile.getName(), "statusId", "EXCEL_IMPORTED", "fromDate", now,
+ "thruDate", now, "threadName", threadName, "logFileName", logFileName));
+ } else {
+ historyValue.set("statusId", "EXCEL_IMPORTED");
+ historyValue.set("thruDate", now);
+ if (pricatFile != null && pricatFile.exists()) {
+ historyValue.set("fileName", pricatFile.getName());
+ }
+ historyValue.set("thruReasonId", thruReasonId);
+ }
+ delegator.createOrStore(historyValue);
+ } catch (GenericEntityException e) {
+ // do nothing
+ }
+ }
+
+ public boolean hasErrorMessages() {
+ return !errorMessages.keySet().isEmpty();
+ }
+
+ /**
+ * Check whether a commented file exists.
+ *
+ * @param request
+ * @param sequenceNum
+ * @return
+ */
+ public static boolean isCommentedExcelExists(HttpServletRequest request, Long sequenceNum) {
+ GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
+ if (UtilValidate.isEmpty(sequenceNum) || UtilValidate.isEmpty(userLogin)) {
+ Debug.logError("sequenceNum[" + sequenceNum + "] or userLogin is empty", module);
+ return false;
+ }
+ String userLoginId = userLogin.getString("userLoginId");
+ Delegator delegator = (Delegator) request.getAttribute("delegator");
+ GenericValue historyValue = null;
+ try {
+ historyValue = delegator.findOne("ExcelImportHistory", UtilMisc.toMap("userLoginId", userLoginId, "sequenceNum", Long.valueOf(sequenceNum)), false);
+ } catch (NumberFormatException e) {
+ Debug.logError(e.getMessage(), module);
+ return false;
+ } catch (GenericEntityException e) {
+ Debug.logError(e.getMessage(), module);
+ return false;
+ }
+ if (UtilValidate.isEmpty(historyValue)) {
+ Debug.logError("No ExcelImportHistory value found by sequenceNum[" + sequenceNum + "] and userLoginId[" + userLoginId + "].", module);
+ return false;
+ }
+ File file = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx");
+ if (file.exists()) {
+ return true;
+ }
+ return false;
+ }
+
+ protected void cleanupLogAndCommentedExcel() {
+ try {
+ report.print(UtilProperties.getMessage(resource, "CLEANUP_LOGANDEXCEL_BEGIN", locale), InterfaceReport.FORMAT_DEFAULT);
+ List historyValues = delegator.findByAnd("ExcelImportHistory", UtilMisc.toMap("userLoginId", userLoginId), UtilMisc.toList("sequenceNum DESC"), false);
+ if (UtilValidate.isEmpty(historyValues) || historyValues.size() <= HISTORY_MAX_FILENUMBER) {
+ report.print(UtilProperties.getMessage(resource, "HistoryLessThan", new Object[] {String.valueOf(HISTORY_MAX_FILENUMBER)}, locale), InterfaceReport.FORMAT_NOTE);
+ report.println(" ... " + UtilProperties.getMessage(resource, "skipped", locale), InterfaceReport.FORMAT_NOTE);
+ } else {
+ report.print(" ... " + UtilProperties.getMessage(resource, "HistoryEntryToRemove", new Object[] {historyValues.size() - HISTORY_MAX_FILENUMBER}, locale), InterfaceReport.FORMAT_NOTE);
+ List valuesToRemove = new ArrayList();
+ for (int i = HISTORY_MAX_FILENUMBER; i < historyValues.size(); i++) {
+ GenericValue historyValue = historyValues.get(i);
+ valuesToRemove.add(historyValue);
+ File excelFile = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + historyValue.getLong("sequenceNum") + ".xlsx");
+ if (excelFile.exists()) {
+ try {
+ excelFile.delete();
+ } catch (SecurityException e) {
+ Debug.logError(e.getMessage(), module);
+ report.print(e.getMessage(), InterfaceReport.FORMAT_ERROR);
+ }
+ }
+ File logFile = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + historyValue.getLong("sequenceNum") + ".log");
+ if (logFile.exists()) {
+ try {
+ logFile.delete();
+ } catch (SecurityException e) {
+ Debug.logError(e.getMessage(), module);
+ report.print(e.getMessage(), InterfaceReport.FORMAT_ERROR);
+ }
+ }
+ }
+ delegator.removeAll(valuesToRemove);
+ report.println(" ... " + UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ }
+ report.println();
+ } catch (GenericEntityException e) {
+ Debug.logError(e.getMessage(), module);
+ }
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java
new file mode 100644
index 0000000000..84ba499719
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java
@@ -0,0 +1,120 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat;
+
+import java.math.BigDecimal;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.entity.transaction.GenericTransactionException;
+
+/**
+ * Interface of pricat parser.
+ *
+ */
+public interface InterfacePricatParser {
+
+ public static final String PARSE_EXCEL = "parse_excel";
+
+ public static final String CONFIRM = "confirm_action";
+
+ public static final String[] messageLabels = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"};
+
+ public static final List messages = Collections.unmodifiableList(Arrays.asList(messageLabels));
+
+ public static final String tempFilesFolder = "runtime/pricat/";
+
+ public static final String FileDateTimePattern = "yyyyMMddHHmmss";
+
+ public static final String defaultColorName = "DefaultColor";
+
+ public static final String defaultDimensionName = "DefaultDimension";
+
+ public static final String defaultCategoryName = "DefaultCategory";
+
+ public static final String EXCEL_TEMPLATE_TYPE = "excelTemplateType";
+
+ public static final String FACILITY_ID = "facilityId";
+
+ public static final String resource = "PricatUiLabels";
+
+ public static final String PRICAT_FILE = "__PRICAT_FILE__";
+
+ public static final String DEFAULT_PRICAT_TYPE = "ApacheOFBiz";
+
+ public static final Map PricatTypeLabels = UtilMisc.toMap(DEFAULT_PRICAT_TYPE, "ApacheOFBizPricatTemplate", "SamplePricat", "SamplePricatTemplate");
+
+ public static final int HISTORY_MAX_FILENUMBER = UtilProperties.getPropertyAsInteger("pricat.properties", "pricat.history.max.filenumber", 20);
+
+ abstract void parsePricatExcel();
+
+ public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet);
+
+ public void initBasicConds(List orgPartyIds);
+
+ public boolean existsCurrencyId(XSSFSheet sheet);
+
+ abstract void parseRowByRow(XSSFSheet sheet);
+
+ abstract boolean parseCellContentsAndStore(XSSFRow row, List cellContents) throws GenericTransactionException;
+
+ public Map updateSkuPrice(String skuId, String ownerPartyId, BigDecimal memberPrice);
+
+ abstract String updateSku(XSSFRow row, String productId, String ownerPartyId, String facilityId, String barcode, BigDecimal inventory,
+ String colorId, String color, String dimensionId, String dimension, BigDecimal listPrice, BigDecimal averageCost);
+
+ public Map updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension);
+
+ public Map getDimensionIds(String productId, String ownerPartyId, String dimension);
+
+ public Map getColorIds(String productId, String ownerPartyId, String color);
+
+ abstract String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, BigDecimal listPrice);
+
+ public String getBrandId(String brandName, String ownerPartyId);
+
+ abstract Object getCellContent(List cellContents, String colName);
+
+ abstract String getProductCategoryId(List cellContents, String ownerPartyId);
+
+ abstract boolean isFacilityOk(XSSFRow row, String facilityName, String facilityId);
+
+ abstract List getCellContents(XSSFRow row, List colNames, int size);
+
+ abstract boolean isTableHeaderMatched(XSSFSheet sheet);
+
+ abstract boolean isVersionSupported(XSSFSheet sheet);
+
+ abstract boolean containsDataRows(XSSFSheet sheet);
+
+ public boolean isNumOfSheetsOK(XSSFWorkbook workbook);
+
+ abstract void setFacilityId(String selectedFacilityId);
+
+ public void endExcelImportHistory(String logFileName, String thruReasonId);
+
+ public boolean hasErrorMessages();
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java
new file mode 100644
index 0000000000..c4e14879af
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java
@@ -0,0 +1,193 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.jdom.JDOMException;
+import org.apache.ofbiz.base.location.ComponentLocationResolver;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.FileUtil;
+import org.apache.ofbiz.base.util.UtilHttp;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.pricat.AbstractPricatParser;
+import org.apache.ofbiz.pricat.InterfacePricatParser;
+import org.apache.ofbiz.pricat.PricatParseExcelHtmlThread;
+
+public class PricatEvents {
+
+ public static final String module = PricatEvents.class.getName();
+
+ public static final String PricatLatestVersion = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1");
+
+ public static final String PricatFileName = "PricatTemplate_" + PricatLatestVersion + ".xlsx";
+
+ public static final String PricatPath = "component://pricat/webapp/pricat/downloads/";
+
+ /**
+ * Download excel template.
+ *
+ * @param request
+ * @param response
+ * @return
+ * @throws IOException
+ * @throws JDOMException
+ */
+ public static String downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) {
+ String templateType = request.getParameter("templateType");
+ if (UtilValidate.isEmpty(templateType)) {
+ return "error";
+ }
+ try {
+ String path = ComponentLocationResolver.getBaseLocation(PricatPath).toString();
+ String fileName = null;
+ if ("pricatExcelTemplate".equals(templateType)) {
+ fileName = PricatFileName;
+ }
+ if (UtilValidate.isEmpty(fileName)) {
+ return "error";
+ }
+ Path file = Paths.get(path + fileName);
+ byte[] bytes = Files.readAllBytes(file);
+ UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", URLEncoder.encode(fileName, "UTF-8"));
+ } catch (MalformedURLException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ } catch (IOException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ }
+ return "success";
+ }
+
+ /**
+ * Upload a pricat.
+ */
+ public static String pricatUpload(HttpServletRequest request, HttpServletResponse response) {
+ boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
+ if (isMultiPart) {
+ return "parse_pricat";
+ } else {
+ String action = request.getParameter("action");
+ if (UtilValidate.isNotEmpty(action) && "downloadPricat".equals(action)) {
+ String sequenceNumString = (String) request.getParameter("sequenceNum");
+ long sequenceNum = -1;
+ if (UtilValidate.isNotEmpty(sequenceNumString)) {
+ try {
+ sequenceNum = Long.valueOf(sequenceNumString);
+ } catch (NumberFormatException e) {
+ // do nothing
+ }
+ }
+ String originalPricatFileName = (String) request.getSession().getAttribute(PricatParseExcelHtmlThread.PRICAT_FILE);
+ String pricatFileName = originalPricatFileName;
+ if (sequenceNum > 0 && AbstractPricatParser.isCommentedExcelExists(request, sequenceNum)) {
+ GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
+ String userLoginId = userLogin.getString("userLoginId");
+ pricatFileName = InterfacePricatParser.tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx";
+ }
+ if (UtilValidate.isNotEmpty(pricatFileName) && UtilValidate.isNotEmpty(originalPricatFileName)) {
+ try {
+ Path path = Paths.get(pricatFileName);
+ byte[] bytes = Files.readAllBytes(path);
+ path = Paths.get(originalPricatFileName);
+ UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", URLEncoder.encode(path.getName(path.getNameCount() - 1).toString(), "UTF-8"));
+ } catch (MalformedURLException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ } catch (IOException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ }
+ request.getSession().removeAttribute(PricatParseExcelHtmlThread.PRICAT_FILE);
+ return "download";
+ }
+ }
+ }
+ return "success";
+ }
+
+ /**
+ * Download commented excel file after it's parsed.
+ *
+ * @param request
+ * @param response
+ * @return
+ * @throws IOException
+ * @throws JDOMException
+ */
+ public static String downloadCommentedExcel(HttpServletRequest request, HttpServletResponse response) {
+ String sequenceNum = request.getParameter("sequenceNum");
+ GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
+ if (UtilValidate.isEmpty(sequenceNum) || UtilValidate.isEmpty(userLogin)) {
+ Debug.logError("sequenceNum[" + sequenceNum + "] or userLogin is empty", module);
+ return "error";
+ }
+ String userLoginId = userLogin.getString("userLoginId");
+ Delegator delegator = (Delegator) request.getAttribute("delegator");
+ GenericValue historyValue = null;
+ try {
+ historyValue = delegator.findOne("ExcelImportHistory", UtilMisc.toMap("userLoginId", userLoginId, "sequenceNum", Long.valueOf(sequenceNum)), false);
+ } catch (NumberFormatException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ } catch (GenericEntityException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ }
+ if (UtilValidate.isEmpty(historyValue)) {
+ Debug.logError("No ExcelImportHistory value found by sequenceNum[" + sequenceNum + "] and userLoginId[" + userLoginId + "].", module);
+ return "error";
+ }
+ String fileName = historyValue.getString("fileName");
+ if (UtilValidate.isEmpty(fileName)) {
+ fileName = sequenceNum + ".xlsx";
+ }
+ try {
+ File file = FileUtil.getFile(InterfacePricatParser.tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx");
+ if (file.exists()) {
+ Path path = Paths.get(file.getPath());
+ byte[] bytes = Files.readAllBytes(path);
+ UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", URLEncoder.encode(fileName, "UTF-8"));
+ }
+ } catch (MalformedURLException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ } catch (IOException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ }
+ return "success";
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlReport.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlReport.java
new file mode 100644
index 0000000000..59e5882e8c
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlReport.java
@@ -0,0 +1,140 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.ofbiz.htmlreport.AbstractHtmlReport;
+import org.apache.ofbiz.htmlreport.InterfaceReportThread;
+import org.apache.ofbiz.htmlreport.util.ReportStringUtil;
+
+/**
+ * Provides a html report for running parse a PriCat file.
+ *
+ */
+public class PricatParseExcelHtmlReport extends AbstractHtmlReport {
+
+ public static final String PRICAT_REPORT_CLASS = "PRICAT_HTML_REPORT";
+
+ /**
+ * Public constructor with report variables.
+ *
+ * @param req the HttpServletRequest request
+ * @param res the HttpServletResponse response
+ */
+ public PricatParseExcelHtmlReport(HttpServletRequest request, HttpServletResponse response) {
+
+ super(request, response, true, true);
+ }
+
+ public static PricatParseExcelHtmlReport getReport(HttpServletRequest request, HttpServletResponse response) {
+
+ PricatParseExcelHtmlReport wp = (PricatParseExcelHtmlReport) request.getAttribute(PRICAT_REPORT_CLASS);
+ if (wp == null) {
+ wp = new PricatParseExcelHtmlReport(request, response);
+ request.setAttribute(PRICAT_REPORT_CLASS, wp);
+ }
+ return wp;
+ }
+
+ public InterfaceReportThread initializeThread(HttpServletRequest request, HttpServletResponse response, String name) {
+
+ if (name == null) {
+ name = "";
+ }
+ ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
+ int i = threadGroup.activeCount();
+ Thread[] threads = new Thread[i];
+ threadGroup.enumerate(threads, true);
+ InterfaceReportThread thread = null;
+ for (int j=0; j
+ *
+ * @throws IOException
+ */
+ public void prepareDisplayReport(HttpServletRequest request, HttpServletResponse response, String name, String dialogUri) throws IOException {
+
+ if (ReportStringUtil.isNotEmpty(dialogUri)) {
+ setDialogRealUri(request, dialogUri);
+ }
+
+ String action = getParamAction(request);
+ if (action == null) action = "";
+ if (action.equals("reportend") || action.equals("cancel")) {
+ setParamAction("reportend");
+ setDialogRealUri(request, dialogUri);
+ } else if (action.equals("reportupdate")) {
+ setParamAction("reportupdate");
+ } else {
+ InterfaceReportThread thread = initializeThread(request, response, name);
+ thread.start();
+ setParamAction("reportbegin");
+ setParamThread(thread.getUUID().toString());
+ }
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java
new file mode 100644
index 0000000000..99147e199e
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java
@@ -0,0 +1,359 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.ofbiz.htmlreport.AbstractReportThread;
+import org.apache.ofbiz.htmlreport.InterfaceReport;
+import org.apache.ofbiz.pricat.sample.SamplePricatParser;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.FileUtil;
+import org.apache.ofbiz.base.util.UtilDateTime;
+import org.apache.ofbiz.base.util.UtilGenerics;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.condition.EntityCondition;
+import org.apache.ofbiz.entity.condition.EntityOperator;
+import org.apache.ofbiz.entity.util.EntityUtil;
+import org.apache.ofbiz.service.LocalDispatcher;
+
+/**
+ * Thread for running pricat import excel html report.
+ *
+ */
+public class PricatParseExcelHtmlThread extends AbstractReportThread {
+
+ public static final String module = PricatParseExcelHtmlThread.class.getName();
+
+ public static final String PARSE_EXCEL = "parse_excel";
+
+ public static final String CONFIRM = "confirm_action";
+
+ public static final String[] messageLabels = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"};
+
+ public static final List messages = Collections.unmodifiableList(Arrays.asList(messageLabels));
+
+ public static final String FileDateTimePattern = "yyyyMMddHHmmss";
+
+ public static final String defaultColorName = "DefaultColor";
+
+ public static final String defaultDimensionName = "DefaultDimension";
+
+ public static final String defaultCategoryName = "DefaultCategory";
+
+ public static final String EXCEL_TEMPLATE_TYPE = "excelTemplateType";
+
+ public static final String FACILITY_ID = "facilityId";
+
+ private LocalDispatcher dispatcher;
+
+ private Delegator delegator;
+
+ private List fileItems;
+
+ private File pricatFile;
+
+ private String userLoginId;
+
+ private GenericValue userLogin;
+
+ private Map facilities = new HashMap();
+
+ public static final String resource = "PricatUiLabels";
+
+ private HttpSession session;
+
+ public static final String PRICAT_FILE = "__PRICAT_FILE__";
+
+ public static final String DEFAULT_PRICAT_TYPE = "sample_pricat";
+
+ private String selectedPricatType = DEFAULT_PRICAT_TYPE;
+
+ private String selectedFacilityId;
+
+ public static final Map PricatTypeLabels = UtilMisc.toMap("sample_pricat", "SamplePricatTemplate",
+ "ofbiz_pricat", "OFBizPricatTemplate");
+
+ private InterfacePricatParser pricatParser;
+
+ private String thruReasonId = "EXCEL_IMPORT_SUCCESS";
+
+ /**
+ * Constructor, creates a new html thread.
+ *
+ * @param request
+ * @param response
+ * @param name
+ */
+ public PricatParseExcelHtmlThread(HttpServletRequest request, HttpServletResponse response, String name) {
+
+ super(request, response, name);
+ dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
+ setDelegator(dispatcher.getDelegator());
+ userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
+ if (UtilValidate.isEmpty(userLogin)) {
+ initHtmlReport(request, response, true, true);
+ getReport().println(UtilProperties.getMessage(resource, "PricatRequireUserLogin", getLocale()), InterfaceReport.FORMAT_ERROR);
+ return;
+ } else {
+ userLoginId = userLogin.getString("userLoginId");
+ session = request.getSession();
+ }
+
+ long sequenceNum = addExcelImportHistory();
+ File userFolder = FileUtil.getFile(InterfacePricatParser.tempFilesFolder + userLoginId + "/");
+ if (!userFolder.exists()) {
+ userFolder.mkdirs();
+ }
+ String logFileName = InterfacePricatParser.tempFilesFolder + userLoginId + "/" + sequenceNum + ".log";
+ initHtmlReport(request, response, true, true, logFileName);
+ if (sequenceNum > 0) {
+ getReport().setSequenceNum(sequenceNum);
+ getReport().addLogFile(logFileName);
+ }
+ try {
+ getReport().print(UtilProperties.getMessage(resource, "StartStoreExcel", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, userFolder));
+ fileItems = UtilGenerics.checkList(dfu.parseRequest(request));
+ } catch (FileUploadException e) {
+ getReport().addError(e);
+ }
+ if (UtilValidate.isEmpty(fileItems)) {
+ getReport().println(UtilProperties.getMessage(resource, "NoFileUploaded", getLocale()), InterfaceReport.FORMAT_ERROR);
+ } else {
+ getReport().println(UtilProperties.getMessage(resource, "ok", getLocale()), InterfaceReport.FORMAT_OK);
+ }
+ }
+
+ public String getReportUpdate() {
+
+ return getReport().getReportUpdate();
+ }
+
+ /**
+ * @see java.lang.Runnable#run()
+ */
+ public void run() {
+
+ try {
+ if (getName().startsWith(PARSE_EXCEL) && UtilValidate.isNotEmpty(fileItems)) {
+ getReport().println();
+ getReport().println(UtilProperties.getMessage(resource, "StartParsePricat", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ if (prepareParse()) {
+ if (selectedPricatType.equals(DEFAULT_PRICAT_TYPE)) {
+ pricatParser = new SamplePricatParser(dispatcher, delegator, getLocale(), getReport(), facilities, pricatFile, userLogin);
+ }
+ if (UtilValidate.isEmpty(pricatParser)) {
+ getReport().println(UtilProperties.getMessage(resource, "NoPricatParserFor", getLocale()), InterfaceReport.FORMAT_ERROR);
+ } else {
+ pricatParser.parsePricatExcel();
+ getReport().println(UtilProperties.getMessage(resource, "PricatParseCompleted", getLocale()), InterfaceReport.FORMAT_HEADLINE);
+ }
+ }
+ } else {
+ getReport().println(getName(), InterfaceReport.FORMAT_ERROR);
+ Debug.logError(getName(), module);
+ thruReasonId = "EXCEL_IMPORT_ERROR";
+ }
+ } catch (Exception e) {
+ getReport().println(e);
+ Debug.logError(e, module);
+ thruReasonId = "EXCEL_IMPORT_ERROR";
+ } finally {
+ // wait 5 seconds to wait page output
+ try {
+ sleep(5000);
+ } catch (InterruptedException e) {
+ }
+ // call report update to make sure all messages are output to file
+ getReport().getReportUpdate();
+ String logFileName = getReport().closeLogFile();
+ if (UtilValidate.isNotEmpty(pricatParser)) {
+ if (thruReasonId.equals("EXCEL_IMPORT_SUCCESS") && pricatParser.hasErrorMessages()) {
+ thruReasonId = "EXCEL_IMPORT_QUEST";
+ }
+ pricatParser.endExcelImportHistory(logFileName, thruReasonId);
+ }
+ }
+ }
+
+ private boolean prepareParse() throws IOException {
+ // 1 get facilities belong to current userLogin
+ facilities = getCurrentUserLoginFacilities();
+ if (UtilValidate.isEmpty(facilities)) {
+ getReport().println(UtilProperties.getMessage(resource, "CurrentUserLoginNoFacility", new Object[]{userLoginId}, getLocale()), InterfaceReport.FORMAT_ERROR);
+ return false;
+ } else {
+ getReport().println(" ... " + UtilProperties.getMessage(resource, "ok", getLocale()), InterfaceReport.FORMAT_OK);
+ getReport().println();
+ }
+
+ // 2. store the pricat excel file
+ if (!storePricatFile()) {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean storePricatFile() throws IOException {
+ FileItem fi = null;
+ FileItem pricatFi = null;
+ byte[] pricatBytes = {};
+ // check excelTemplateType
+ for (int i = 0; i < fileItems.size(); i++) {
+ fi = fileItems.get(i);
+ String fieldName = fi.getFieldName();
+ if (fi.isFormField() && UtilValidate.isNotEmpty(fieldName)) {
+ if (fieldName.equals(EXCEL_TEMPLATE_TYPE)) {
+ selectedPricatType = fi.getString();
+ }
+ }
+ }
+ getReport().print(UtilProperties.getMessage(resource, "ExcelTemplateTypeSelected", getLocale()), InterfaceReport.FORMAT_DEFAULT);
+ if (PricatTypeLabels.containsKey(selectedPricatType)) {
+ getReport().print(UtilProperties.getMessage(resource, PricatTypeLabels.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_DEFAULT);
+ getReport().println(" ... " + UtilProperties.getMessage(resource, "ok", getLocale()), InterfaceReport.FORMAT_OK);
+ } else {
+ getReport().println(UtilProperties.getMessage(resource, PricatTypeLabels.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_ERROR);
+ return false;
+ }
+
+ // store the file
+ for (int i = 0; i < fileItems.size(); i++) {
+ fi = fileItems.get(i);
+ String fieldName = fi.getFieldName();
+ if (fieldName.equals("filename")) {
+ pricatFi = fi;
+ pricatBytes = pricatFi.get();
+ Path path = Paths.get(fi.getName());
+ pricatFile = new File(InterfacePricatParser.tempFilesFolder + userLoginId + "/" + path.getFileName().toString());
+ FileOutputStream fos = new FileOutputStream(pricatFile);
+ fos.write(pricatBytes);
+ fos.flush();
+ fos.close();
+ session.setAttribute(PRICAT_FILE, pricatFile.getAbsolutePath());
+ }
+ }
+ return true;
+ }
+
+ private Map getCurrentUserLoginFacilities() {
+ getReport().println();
+ getReport().println(UtilProperties.getMessage(resource, "GetCurrentUserLoginFacility", getLocale()), InterfaceReport.FORMAT_DEFAULT);
+ Map context = new HashMap();
+ context.put("userLogin", userLogin);
+ context.put("locale", getLocale());
+ try {
+ List orgConditions = new LinkedList();
+ orgConditions.add(EntityCondition.makeCondition("onePartyIdFrom", EntityOperator.EQUALS, userLogin.getString("partyId")));
+ orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdFrom", EntityOperator.EQUALS, "INTERNAL_ORGANIZATIO"));
+ orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdTo", EntityOperator.EQUALS, "EMPLOYEE"));
+ orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdTo", EntityOperator.EQUALS, "EMPLOYEE"));
+ List organizations = delegator.findList("PartyRelationshipToFrom", EntityCondition.makeCondition(orgConditions), null, null, null, false);
+ Timestamp now = UtilDateTime.nowTimestamp();
+ organizations = EntityUtil.filterByDate(organizations, now, "twoFromDate", "twoThruDate", true);
+ organizations = EntityUtil.filterByDate(organizations, now, "oneFromDate", "oneThruDate", true);
+
+ List ownerPartyConditions = new LinkedList();
+ Set orgPartyIds = new HashSet();
+ for (GenericValue organization : organizations) {
+ String orgPartyId = organization.getString("onePartyIdTo");
+ if (!orgPartyIds.contains(orgPartyId)) {
+ ownerPartyConditions.add(EntityCondition.makeCondition("ownerPartyId", EntityOperator.EQUALS, orgPartyId));
+ orgPartyIds.add(orgPartyId);
+ }
+ }
+ if (UtilValidate.isEmpty(ownerPartyConditions)) {
+ return facilities;
+ }
+
+ List facilityValues = delegator.findList("Facility", EntityCondition.makeCondition(ownerPartyConditions, EntityOperator.OR), null, null, null, false);
+ if (UtilValidate.isNotEmpty(facilityValues)) {
+ int i = 1;
+ for (GenericValue facilityValue : facilityValues) {
+ if (UtilValidate.isNotEmpty(facilityValue)) {
+ String facilityId = facilityValue.getString("facilityId");
+ if (!facilities.containsKey(facilityId)) {
+ String facilityName = facilityValue.getString("facilityName");
+ facilities.put(facilityId, new String[] {facilityName, facilityValue.getString("ownerPartyId")});
+ getReport().println(UtilProperties.getMessage(resource, "FacilityFoundForCurrentUserLogin", new Object[]{String.valueOf(i), facilityName, facilityId}, getLocale()), InterfaceReport.FORMAT_NOTE);
+ i++;
+ }
+ }
+ }
+ }
+ }catch (GenericEntityException e) {
+ Debug.logError(e.getMessage(), module);
+ }
+ return facilities;
+ }
+
+ public Delegator getDelegator() {
+ return delegator;
+ }
+
+ public void setDelegator(Delegator delegator) {
+ this.delegator = delegator;
+ }
+
+ public synchronized long addExcelImportHistory() {
+ long latestId = 1;
+ try {
+ List historyValues = delegator.findByAnd("ExcelImportHistory", UtilMisc.toMap("userLoginId", userLoginId), UtilMisc.toList("sequenceNum DESC"), false);
+ GenericValue latestHistoryValue = EntityUtil.getFirst(historyValues);
+ if (UtilValidate.isNotEmpty(latestHistoryValue)) {
+ latestId = latestHistoryValue.getLong("sequenceNum") + 1;
+ }
+ GenericValue newHistoryValue = delegator.makeValue("ExcelImportHistory", UtilMisc.toMap("sequenceNum", latestId, "userLoginId", userLoginId,
+ "fileName", pricatFile == null ? "" : pricatFile.getName(), "statusId", isAlive() ? "EXCEL_IMPORTING" : "EXCEL_IMPORTED",
+ "fromDate", UtilDateTime.nowTimestamp(), "threadName", getName(), "logFileName", InterfacePricatParser.tempFilesFolder + userLoginId + "/" + latestId + ".log"));
+ newHistoryValue.create();
+ } catch (GenericEntityException e) {
+ Debug.logError(e, module);
+ return -1;
+ }
+ return latestId;
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java
new file mode 100644
index 0000000000..45a0b45e0e
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat.sample;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.jdom.JDOMException;
+import org.apache.ofbiz.base.location.ComponentLocationResolver;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilHttp;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.pricat.PricatEvents;
+
+public class SamplePricatEvents extends PricatEvents {
+
+ public static final String module = SamplePricatEvents.class.getName();
+
+ public static final String PricatLatestVersion = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1");
+
+ public static final String DemoPricatFileName = "SamplePricatTemplate_" + PricatLatestVersion + ".xlsx";
+
+ public static final String DemoPricatPath = "component://pricat/webapp/pricatdemo/downloads/";
+
+ /**
+ * Download excel template.
+ *
+ * @param request
+ * @param response
+ * @return
+ * @throws IOException
+ * @throws JDOMException
+ */
+ public static String downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) {
+ String templateType = request.getParameter("templateType");
+ if (UtilValidate.isEmpty(templateType)) {
+ return "error";
+ }
+ try {
+ String path = ComponentLocationResolver.getBaseLocation(DemoPricatPath).toString();
+ String fileName = null;
+ if ("pricatExcelTemplate".equals(templateType)) {
+ fileName = DemoPricatFileName;
+ }
+ if (UtilValidate.isEmpty(fileName)) {
+ return "error";
+ }
+ Path file = Paths.get(path + fileName);
+ byte[] bytes = Files.readAllBytes(file);
+ UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", URLEncoder.encode(fileName, "UTF-8"));
+ } catch (MalformedURLException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ } catch (IOException e) {
+ Debug.logError(e.getMessage(), module);
+ return "error";
+ }
+ return "success";
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java
new file mode 100644
index 0000000000..308b8f94c7
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java
@@ -0,0 +1,665 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.pricat.sample;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.poi.POIXMLException;
+import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
+import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.ofbiz.pricat.AbstractPricatParser;
+import org.apache.ofbiz.htmlreport.InterfaceReport;
+import org.apache.ofbiz.order.finaccount.FinAccountHelper;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.transaction.GenericTransactionException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ServiceUtil;
+
+/**
+ * Sample pricat excel parser.
+ *
+ */
+public class SamplePricatParser extends AbstractPricatParser {
+
+ public static final String module = SamplePricatParser.class.getName();
+
+ public static final Map> ColNamesList = UtilMisc.toMap("V1.1", genExcelHeaderNames("V1.1"));
+
+ public static final int headerRowNo = 4;
+
+ private List headerColNames = new ArrayList();
+
+ public SamplePricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, Map facilities, File pricatFile, GenericValue userLogin) {
+ super(dispatcher, delegator, locale, report, facilities, pricatFile, userLogin);
+ }
+
+ /**
+ * Parse pricat excel file in xlsx format.
+ *
+ */
+ public void parsePricatExcel(boolean writeFile) {
+ XSSFWorkbook workbook = null;
+ try {
+ // 1. read the pricat excel file
+ FileInputStream is = new FileInputStream(pricatFile);
+
+ // 2. use POI to load this bytes
+ report.print(UtilProperties.getMessage(resource, "ParsePricatFileStatement", new Object[] { pricatFile.getName() }, locale), InterfaceReport.FORMAT_DEFAULT);
+ try {
+ workbook = new XSSFWorkbook(is);
+ report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ } catch(IOException e) {
+ report.println(e);
+ report.println(UtilProperties.getMessage(resource, "PricatSuggestion", locale), InterfaceReport.FORMAT_ERROR);
+ return;
+ } catch(POIXMLException e) {
+ report.println(e);
+ report.println(UtilProperties.getMessage(resource, "PricatSuggestion", locale), InterfaceReport.FORMAT_ERROR);
+ return;
+ }
+
+ // 3. only first sheet will be parsed
+ // 3.1 verify the file has a sheet at least
+ formatter = new HSSFDataFormatter(locale);
+ isNumOfSheetsOK(workbook);
+
+ // 3.2 verify the version is supported
+ XSSFSheet sheet = workbook.getSheetAt(0);
+ if (!isVersionSupported(sheet)) {
+ return;
+ }
+
+ // 3.3 get currencyId
+ existsCurrencyId(sheet);
+
+ // 3.4 verify the table header row is just the same as column names, if not, print error and return
+ if (!isTableHeaderMatched(sheet)) {
+ return;
+ }
+
+ // 3.5 verify the first table has 6 rows at least
+ containsDataRows(sheet);
+
+ if (UtilValidate.isNotEmpty(errorMessages)) {
+ report.println(UtilProperties.getMessage(resource, "HeaderContainsError", locale), InterfaceReport.FORMAT_ERROR);
+ return;
+ }
+
+ // 4. parse data
+ // 4.1 parse row by row and store the contents into database
+ parseRowByRow(sheet);
+ if (UtilValidate.isNotEmpty(errorMessages)) {
+ report.println(UtilProperties.getMessage(resource, "DataContainsError", locale), InterfaceReport.FORMAT_ERROR);
+ if (writeFile) {
+ sequenceNum = report.getSequenceNum();
+ writeCommentsToFile(workbook, sheet);
+ }
+ }
+
+ // 5. clean up the log files and commented Excel files
+ cleanupLogAndCommentedExcel();
+ } catch (IOException e) {
+ report.println(e);
+ Debug.logError(e, module);
+ } finally {
+ if (UtilValidate.isNotEmpty(fileItems)) {
+ // remove tmp files
+ FileItem fi = null;
+ for (int i = 0; i < fileItems.size(); i++) {
+ fi = fileItems.get(i);
+ fi.delete();
+ }
+ }
+ if (workbook != null) {
+ try {
+ workbook.close();
+ } catch (IOException e) {
+ Debug.logError(e, module);
+ }
+ }
+ }
+ }
+
+ public boolean existsCurrencyId(XSSFSheet sheet) {
+ report.print(UtilProperties.getMessage(resource, "StartCheckCurrencyId", locale), InterfaceReport.FORMAT_NOTE);
+ XSSFCell currencyIdCell = sheet.getRow(2).getCell(1);
+ currencyId = currencyIdCell.getStringCellValue().trim().toUpperCase();
+ if (UtilValidate.isEmpty(currencyId)) {
+ String errorMessage = UtilProperties.getMessage(resource, "CurrencyIdRequired", locale);
+ report.println(errorMessage, InterfaceReport.FORMAT_ERROR);
+ errorMessages.put(new CellReference(currencyIdCell), errorMessage);
+ return false;
+ } else {
+ try {
+ GenericValue currencyUom = delegator.findOne("Uom", UtilMisc.toMap("uomId", currencyId), false);
+ if (!"CURRENCY_MEASURE".equals(currencyUom.getString("uomTypeId"))) {
+ String errorMessage = UtilProperties.getMessage(resource, "CurrencyIdNotCurrency", new Object[] {currencyId}, locale);
+ report.println(errorMessage, InterfaceReport.FORMAT_ERROR);
+ errorMessages.put(new CellReference(currencyIdCell), errorMessage);
+ return false;
+ }
+ } catch(GenericEntityException e) {
+ String errorMessage = UtilProperties.getMessage(resource, "CurrencyIdNotFound", new Object[] {currencyId}, locale);
+ report.println(errorMessage, InterfaceReport.FORMAT_ERROR);
+ errorMessages.put(new CellReference(currencyIdCell), errorMessage);
+ return false;
+ }
+ report.print(UtilProperties.getMessage(resource, "CurrencyIdIs", new Object[] {currencyId}, locale), InterfaceReport.FORMAT_NOTE);
+ report.println(" ... " + UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ }
+ return true;
+ }
+
+ public void parseRowByRow(XSSFSheet sheet) {
+ int rows = sheet.getPhysicalNumberOfRows();
+ List colNames = ColNamesList.get(pricatFileVersion);
+ int colNumber = colNames.size();
+
+ int emptyRowStart = -1;
+ int emptyRowEnd = -1;
+ for (int i = headerRowNo + 1; i < rows; i++) {
+ XSSFRow row = sheet.getRow(i);
+ if (UtilValidate.isEmpty(row) || isEmptyRow(row, colNumber, false)) {
+ if (emptyRowStart == -1) {
+ report.print("(" + (i + 1) + ") ", InterfaceReport.FORMAT_NOTE);
+ emptyRowStart = i;
+ } else {
+ emptyRowEnd = i;
+ }
+ continue;
+ } else {
+ if (emptyRowStart != -1) {
+ if (emptyRowEnd != -1) {
+ report.print(" - (" + (emptyRowEnd + 1) + ") ", InterfaceReport.FORMAT_NOTE);
+ }
+ report.print(UtilProperties.getMessage(resource, "ExcelEmptyRow", locale), InterfaceReport.FORMAT_NOTE);
+ report.println(" ... " + UtilProperties.getMessage(resource, "skipped", locale), InterfaceReport.FORMAT_NOTE);
+ emptyRowStart = -1;
+ emptyRowEnd = -1;
+ }
+ }
+ report.print("(" + (i + 1) + ") ", InterfaceReport.FORMAT_NOTE);
+ List cellContents = getCellContents(row, colNames, colNumber);
+ try {
+ if (parseCellContentsAndStore(row, cellContents)) {
+ report.println(" ... " + UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ } else {
+ report.println(" ... " + UtilProperties.getMessage(resource, "skipped", locale), InterfaceReport.FORMAT_NOTE);
+ }
+ } catch (GenericTransactionException e) {
+ report.println(e);
+ }
+ }
+ if (emptyRowEnd != -1) {
+ report.print(" - (" + (emptyRowEnd + 1) + ") ", InterfaceReport.FORMAT_NOTE);
+ report.print(UtilProperties.getMessage(resource, "ExcelEmptyRow", locale), InterfaceReport.FORMAT_NOTE);
+ report.println(" ... " + UtilProperties.getMessage(resource, "skipped", locale), InterfaceReport.FORMAT_NOTE);
+ }
+ }
+
+ /**
+ * Check data according to business logic. If data is ok, store it.
+ *
+ * @param row
+ * @param cellContents
+ * @param document
+ * @return
+ * @throws GenericTransactionException
+ */
+ public boolean parseCellContentsAndStore(XSSFRow row, List cellContents) throws GenericTransactionException {
+ if (UtilValidate.isEmpty(cellContents)) {
+ return false;
+ }
+ switch(pricatFileVersion) {
+ case "V1.1":
+ default:
+ return parseCellContentsAndStoreV1_X(row, cellContents);
+ }
+ }
+
+ private boolean parseCellContentsAndStoreV1_X(XSSFRow row, List cellContents) throws GenericTransactionException {
+ if (UtilValidate.isEmpty(cellContents)) {
+ return false;
+ }
+ // 1. check if facilityId is in the facilities belong to the user, or if the name is correct for the id
+ String facilityName = (String) getCellContent(cellContents, "Facility Name");
+ String facilityId = (String) getCellContent(cellContents, "FacilityId");
+ if (!isFacilityOk(row, facilityName, facilityId))
+ return false;
+
+ // 2. get productCategoryId
+ String ownerPartyId = facilities.get(facilityId)[1];
+ String productCategoryId = getProductCategoryId(cellContents, ownerPartyId);
+
+ // 3. get productFeatureId of brand
+ String brandName = (String) getCellContent(cellContents, "Brand");
+ String brandId = getBrandId(brandName, ownerPartyId);
+ if (UtilValidate.isEmpty(brandId)) {
+ return false;
+ }
+
+ // 4. get productId from brandId, model name
+ String modelName = (String) getCellContent(cellContents, "Style No");
+ String productName = (String) getCellContent(cellContents, "Product Name");
+ BigDecimal listPrice = (BigDecimal) getCellContent(cellContents, "List Price");
+ String productId = getProductId(row, brandId, modelName, productName, productCategoryId, ownerPartyId, listPrice);
+ if (UtilValidate.isEmpty(productId) || UtilValidate.isEmpty(listPrice)) {
+ return false;
+ }
+
+ // 5. update color and size if necessary
+ String color = (String) getCellContent(cellContents, "Color");
+ if (UtilValidate.isEmpty(color) || UtilValidate.isEmpty(color.trim())) {
+ color = defaultColorName;
+ }
+ String dimension = (String) getCellContent(cellContents, "Size");
+ if (UtilValidate.isEmpty(dimension) || UtilValidate.isEmpty(dimension.trim())) {
+ dimension = defaultDimensionName;
+ }
+ Map features = updateColorAndDimension(productId, ownerPartyId, color, dimension);
+ if (ServiceUtil.isError(features)) {
+ if (features.containsKey("index") && String.valueOf(features.get("index")).contains("0")) {
+ int cell = headerColNames.indexOf("Color");
+ XSSFCell colorCell = row.getCell(cell);
+ errorMessages.put(new CellReference(colorCell), UtilProperties.getMessage(resource, "PricatColorError", locale));
+ }
+ if (features.containsKey("index") && String.valueOf(features.get("index")).contains("1")) {
+ int cell = headerColNames.indexOf("Size");
+ XSSFCell colorCell = row.getCell(cell);
+ errorMessages.put(new CellReference(colorCell), UtilProperties.getMessage(resource, "PricatDimensionError", locale));
+ }
+ return false;
+ }
+ String colorId = (String) features.get("colorId");
+ String dimensionId = (String) features.get("dimensionId");
+
+ // 6. update skuIds by productId
+ String barcode = (String) getCellContent(cellContents, "Barcode");
+ BigDecimal inventory = (BigDecimal) getCellContent(cellContents, "Stock Qty");
+ BigDecimal averageCost = (BigDecimal) getCellContent(cellContents, "Average Cost");
+ String skuId = updateSku(row, productId, ownerPartyId, facilityId, barcode, inventory, colorId, color, dimensionId, dimension, listPrice, averageCost);
+ if (UtilValidate.isEmpty(skuId)) {
+ return false;
+ }
+
+ // 7. store prices
+ BigDecimal memberPrice = (BigDecimal) getCellContent(cellContents, "Member Price");
+ Map results = updateSkuPrice(skuId, ownerPartyId, memberPrice);
+ if (ServiceUtil.isError(results)) {
+ return false;
+ }
+
+ return true;
+ }
+
+
+ public String updateSku(XSSFRow row, String productId, String ownerPartyId, String facilityId, String barcode, BigDecimal inventory,
+ String colorId, String color, String dimensionId, String dimension, BigDecimal listPrice, BigDecimal averageCost) {
+ return "sampleSkuId";
+ }
+
+ public String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, BigDecimal listPrice) {
+ return "sampleProductId";
+ }
+
+ public Object getCellContent(List cellContents, String colName) {
+ if (UtilValidate.isNotEmpty(headerColNames) && headerColNames.contains(colName)) {
+ return cellContents.get(headerColNames.indexOf(colName));
+ }
+ return null;
+ }
+
+ public String getProductCategoryId(List cellContents, String ownerPartyId) {
+ return "sampleProductCategoryId";
+ }
+
+ public boolean isFacilityOk(XSSFRow row, String facilityName, String facilityId) {
+ if (!facilities.containsKey(facilityId)) {
+ if (UtilValidate.isEmpty(facilityId) && facilities.keySet().size() == 1) {
+ if (UtilValidate.isEmpty(facilityName)) {
+ return true;
+ } else {
+ String theFacilityId = (String) facilities.keySet().toArray()[0];
+ String name = facilities.get(theFacilityId)[0];
+ if (!name.equals(facilityName)) {
+ String errorMessage = UtilProperties.getMessage(resource, "FacilityNameNotMatchId", new Object[]{theFacilityId, name, facilityName}, locale);
+ report.println();
+ report.print(errorMessage, InterfaceReport.FORMAT_ERROR);
+ XSSFCell cell = row.getCell(0);
+ errorMessages.put(new CellReference(cell), errorMessage);
+ return false;
+ }
+ }
+ } else {
+ String errorMessage = UtilProperties.getMessage(resource, "FacilityNotBelongToYou", new Object[]{facilityName, facilityId}, locale);
+ report.println();
+ report.print(errorMessage, InterfaceReport.FORMAT_ERROR);
+ XSSFCell cell = row.getCell(1);
+ errorMessages.put(new CellReference(cell), errorMessage);
+ return false;
+ }
+ } else {
+ String name = facilities.get(facilityId)[0];
+ if (!name.equals(facilityName)) {
+ String errorMessage = UtilProperties.getMessage(resource, "FacilityNameNotMatchId", new Object[]{facilityId, name, facilityName}, locale);
+ report.println();
+ report.print(errorMessage, InterfaceReport.FORMAT_ERROR);
+ XSSFCell cell = row.getCell(0);
+ errorMessages.put(new CellReference(cell), errorMessage);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean isTableHeaderMatched(XSSFSheet sheet) {
+ List columnNames = ColNamesList.get(pricatFileVersion);
+ short cols = sheet.getRow(headerRowNo).getLastCellNum();
+ report.print(UtilProperties.getMessage(resource, "StartCheckHeaderColNum", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_NOTE);
+ if (cols != columnNames.size()) {
+ report.print(UtilProperties.getMessage(resource, "HeaderColNumNotMatch", new Object[] {String.valueOf(cols), String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_WARNING);
+ if (cols < columnNames.size()) {
+ report.println(UtilProperties.getMessage(resource, "HeaderColNumShortThanRequired", new Object[] {String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_ERROR);
+ return false;
+ } else {
+ report.println(UtilProperties.getMessage(resource, "UseHeaderColNum", new Object[] {String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_WARNING);
+ cols = (short) columnNames.size();
+ }
+ } else {
+ report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ }
+
+ report.print(UtilProperties.getMessage(resource, "StartCheckHeaderColLabel", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_NOTE);
+ boolean foundLabelNotMatch = false;
+ for (int i = 0; i < cols; i++) {
+ String coltext = sheet.getRow(headerRowNo).getCell(i).getStringCellValue().trim();
+ headerColNames.add(coltext);
+ Object[] versionColumn = columnNames.get(i);
+ if (!coltext.equals(versionColumn[0])) {
+ report.println(UtilProperties.getMessage(resource, "HeaderColLabelNotMatch", new Object[] {String.valueOf(headerRowNo + 1), String.valueOf(i + 1), coltext, versionColumn[0]}, locale), InterfaceReport.FORMAT_ERROR);
+ foundLabelNotMatch = true;
+ } else {
+ report.print(" " + coltext, InterfaceReport.FORMAT_NOTE);
+ if (i < cols - 1) {
+ report.print(",", InterfaceReport.FORMAT_NOTE);
+ }
+ }
+ }
+ if (foundLabelNotMatch) {
+ report.println();
+ return false;
+ }
+ report.println(" ... " + UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ return true;
+ }
+
+ public boolean isVersionSupported(XSSFSheet sheet) {
+ report.print(UtilProperties.getMessage(resource, "StartCheckPricatVersion", locale), InterfaceReport.FORMAT_NOTE);
+ pricatFileVersion = sheet.getRow(2).getCell(0).getStringCellValue().trim();
+ if (ColNamesList.containsKey(pricatFileVersion)) {
+ report.print(" " + pricatFileVersion + " ... ", InterfaceReport.FORMAT_NOTE);
+ report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
+ } else {
+ report.println(UtilProperties.getMessage(resource, "error", locale), InterfaceReport.FORMAT_ERROR);
+ report.println(UtilProperties.getMessage(resource, "PricatVersionNotSupport", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_ERROR);
+ return false;
+ }
+ return true;
+ }
+
+ public boolean containsDataRows(XSSFSheet sheet) {
+ int rows = sheet.getPhysicalNumberOfRows();
+ if (rows > headerRowNo + 1) {
+ report.println(UtilProperties.getMessage(resource, "PricatTableRows", new Object[] {String.valueOf(headerRowNo + 1), String.valueOf(rows - headerRowNo - 1), sheet.getSheetName()}, locale), InterfaceReport.FORMAT_NOTE);
+ } else {
+ report.println(UtilProperties.getMessage(resource, "PricatNoDataRows", new Object[] {sheet.getSheetName()}, locale), InterfaceReport.FORMAT_ERROR);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * The Object[] have 4 elements, they are:
+ * 1. Header Label Name.
+ * 2. Cell data type to return.
+ * 3. Boolean value to indicate whether the column is required.
+ * 4. Boolean value to indicate whether the column is a price when cell data type is BigDecimal, this element is optional.
+ *
+ * @param version
+ * @return List of Object[]
+ */
+ private static List genExcelHeaderNames(String version){
+ switch (version) {
+ case "V1.1":
+ default:
+ return genExcelHeaderNamesV1_1();
+ }
+ }
+
+ /**
+ * Get V1.1 pricat excel header names and attributes.
+ *
+ * @return list of Object[]
+ */
+ private static List genExcelHeaderNamesV1_1() {
+ List listHeaderName = new ArrayList();
+ listHeaderName.add(new Object[] {"Facility Name",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"FacilityId",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Category L1",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Category L2",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Category L3",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Category L4",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Brand",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Style No",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Product Name",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Color",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Size",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Barcode",
+ XSSFCell.CELL_TYPE_STRING,
+ Boolean.FALSE});
+ listHeaderName.add(new Object[] {"Stock Qty",
+ XSSFCell.CELL_TYPE_NUMERIC,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Average Cost",
+ XSSFCell.CELL_TYPE_NUMERIC,
+ Boolean.TRUE,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"List Price",
+ XSSFCell.CELL_TYPE_NUMERIC,
+ Boolean.TRUE,
+ Boolean.TRUE});
+ listHeaderName.add(new Object[] {"Member Price",
+ XSSFCell.CELL_TYPE_NUMERIC,
+ Boolean.FALSE,
+ Boolean.TRUE});
+ return listHeaderName;
+ }
+
+ @Override
+ public void parsePricatExcel() {
+ parsePricatExcel(true);
+ }
+
+ /**
+ * Get data by version definition.
+ *
+ * @param row
+ * @param colNames
+ * @param size
+ * @return
+ */
+ public List getCellContents(XSSFRow row, List colNames, int size) {
+ List results = new ArrayList();
+ boolean foundError = false;
+ if (isEmptyRow(row, size, true)) {
+ return null;
+ }
+
+ // check and get data
+ for (int i = 0; i < size; i++) {
+ XSSFCell cell = null;
+ if (row.getPhysicalNumberOfCells() > i) {
+ cell = row.getCell(i);
+ }
+ if (cell == null) {
+ if (((Boolean) colNames.get(i)[2]).booleanValue() && (facilities.keySet().size() > 1 || (facilities.keySet().size() == 1 && i >= 2))) {
+ report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING);
+ cell = row.createCell(i);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale));
+ foundError = true;
+ results.add(null);
+ continue;
+ } else {
+ cell = row.createCell(i);
+ }
+ }
+ int cellType = cell.getCellType();
+ String cellValue = formatter.formatCellValue(cell);
+ if (UtilValidate.isNotEmpty(cellValue) && UtilValidate.isNotEmpty(cellValue.trim())) {
+ if (cellType == XSSFCell.CELL_TYPE_FORMULA) {
+ try {
+ cellValue = BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding).toString();
+ } catch (IllegalStateException e) {
+ try {
+ cellValue = cell.getStringCellValue();
+ } catch (IllegalStateException e1) {
+ // do nothing
+ }
+ }
+ report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE);
+ } else {
+ report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE);
+ }
+ } else {
+ report.print(((i == 0)?"":","), InterfaceReport.FORMAT_NOTE);
+ }
+ if (((Boolean) colNames.get(i)[2]).booleanValue() && UtilValidate.isEmpty(cellValue) && (facilities.keySet().size() > 1 || (facilities.keySet().size() == 1 && i >= 2))) {
+ report.print(UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale));
+ foundError = true;
+ results.add(null);
+ continue;
+ }
+ if (((Boolean) colNames.get(i)[2]).booleanValue() && cellType != (int) colNames.get(i)[1]) {
+ // String warningMessage = "";
+ if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
+ if (UtilValidate.isNotEmpty(cellValue) && UtilValidate.isNotEmpty(cellValue.trim())) {
+ results.add(cellValue);
+ } else {
+ results.add(null);
+ }
+ } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
+ if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING) {
+ cell.setCellType(XSSFCell.CELL_TYPE_STRING);
+ }
+ try {
+ results.add(BigDecimal.valueOf(Double.parseDouble(cell.getStringCellValue())).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ }
+ } else {
+ if (UtilValidate.isEmpty(cellValue) || UtilValidate.isEmpty(cellValue.trim())) {
+ results.add(null);
+ continue;
+ }
+ if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_STRING) {
+ if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
+ cellValue = cell.getStringCellValue().trim();
+ results.add(cellValue);
+ } else {
+ results.add(cellValue.trim());
+ }
+ } else if ((int) colNames.get(i)[1] == XSSFCell.CELL_TYPE_NUMERIC) {
+ if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
+ try {
+ results.add(BigDecimal.valueOf(Double.valueOf(cell.getStringCellValue())));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
+ try {
+ results.add(BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ } else {
+ try {
+ results.add(BigDecimal.valueOf(Double.valueOf(cellValue)).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding));
+ } catch (NumberFormatException e) {
+ results.add(null);
+ errorMessages.put(new CellReference(cell), UtilProperties.getMessage(resource, "ErrorParseValueToNumeric", locale));
+ }
+ }
+ }
+ }
+ }
+ if (foundError) {
+ return null;
+ }
+ return results;
+ }
+
+ protected int getHeaderRowNo() {
+ return headerRowNo;
+ }
+}
diff --git a/specialpurpose/pricat/src/main/java/org/apache/poi/xssf/usermodel/OFBizPricatUtil.java b/specialpurpose/pricat/src/main/java/org/apache/poi/xssf/usermodel/OFBizPricatUtil.java
new file mode 100644
index 0000000000..5f1dc2cdbe
--- /dev/null
+++ b/specialpurpose/pricat/src/main/java/org/apache/poi/xssf/usermodel/OFBizPricatUtil.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.poi.xssf.usermodel;
+
+import org.apache.poi.ss.util.CellReference;
+import com.microsoft.schemas.vml.CTShape;
+
+public final class OFBizPricatUtil {
+ public static void formatCommentShape(XSSFSheet sheet, CellReference cell) {
+ XSSFVMLDrawing vml = sheet.getVMLDrawing(true);
+ CTShape ctshape = vml.findCommentShape(cell.getRow(), cell.getCol());
+ ctshape.setType("#_x0000_t202");
+ }
+
+ public static void formatCommentShape(XSSFSheet sheet, int rowNum, short colNum) {
+ XSSFVMLDrawing vml = sheet.getVMLDrawing(true);
+ CTShape ctshape = vml.findCommentShape(rowNum, colNum);
+ ctshape.setType("#_x0000_t202");
+ }
+}
diff --git a/specialpurpose/pricat/webapp/pricat/WEB-INF/controller.xml b/specialpurpose/pricat/webapp/pricat/WEB-INF/controller.xml
new file mode 100644
index 0000000000..1c837d3c1d
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/WEB-INF/controller.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
+
+
+ PriCat
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricat/WEB-INF/web.xml b/specialpurpose/pricat/webapp/pricat/WEB-INF/web.xml
new file mode 100644
index 0000000000..fce29c165e
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/WEB-INF/web.xml
@@ -0,0 +1,100 @@
+
+
+
+
+
+ Apache OFBiz - PriCat
+ PriCat Application of the Apache OFBiz Project
+
+
+ A unique name used to identify/recognize the local dispatcher for the Service Engine
+ localDispatcherName pricat
+
+
+ The Name of the Entity Delegator to use, defined in entityengine.xml
+ entityDelegatorName default
+
+
+ The location of the main-decorator screen to use for this webapp; referred to as a context variable in screen def XML files.
+ mainDecoratorLocation
+ component://pricat/widget/SampleScreens.xml
+
+
+ Remove unnecessary whitespace from HTML output.
+ compressHTML
+ false
+
+
+
+ ControlFilter
+ ControlFilter
+ org.apache.ofbiz.webapp.control.ControlFilter
+
+ allowedPaths
+ /error:/control:/select:/index.html:/index.jsp:/default.html:/default.jsp:/images:/js:/ws:/includes
+
+
+ redirectPath
+ /control/main
+
+
+
+ ContextFilter
+ ContextFilter
+ org.apache.ofbiz.webapp.control.ContextFilter
+
+
+ ControlFilter
+ /*
+
+
+ ContextFilter
+ /*
+
+
+ org.apache.ofbiz.webapp.control.ControlEventListener
+ org.apache.ofbiz.webapp.control.LoginEventListener
+
+
+
+
+ Main Control Servlet
+ ControlServlet
+ ControlServlet
+ org.apache.ofbiz.webapp.control.ControlServlet
+ 1
+
+ ControlServlet /control/*
+
+
+ 60
+
+ true
+ true
+
+ COOKIE
+
+
+
+ index.jsp
+ index.html
+ index.htm
+
+
diff --git a/specialpurpose/pricat/webapp/pricat/error/error.jsp b/specialpurpose/pricat/webapp/pricat/error/error.jsp
new file mode 100644
index 0000000000..7f4af8fe3b
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/error/error.jsp
@@ -0,0 +1,52 @@
+<%--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+--%>
+<%@ page import="org.apache.ofbiz.base.util.*" %>
+
+
+OFBiz Message
+
+
+
+<% String errorMsg = (String) request.getAttribute("_ERROR_MESSAGE_"); %>
+
+
+
+
+
+
+
+
+
+
+ :ERROR MESSAGE:
+
+
+
+
+ <%=UtilFormatOut.replaceString(errorMsg, "\n", " ")%>
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricat/ftl/ExcelImportHistoryReport.ftl b/specialpurpose/pricat/webapp/pricat/ftl/ExcelImportHistoryReport.ftl
new file mode 100644
index 0000000000..042bfec169
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/ftl/ExcelImportHistoryReport.ftl
@@ -0,0 +1,109 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+
+ ${uiLabelMap.ExcelImportHistoryList}
+ ${uiLabelMap.OnlyYourOwnImportHistoryDisplayed}
+
+
+
+
+
+
+
+
+ ${uiLabelMap.SerialNumber}
+ ${uiLabelMap.Filename}
+ ${uiLabelMap.FromDate}
+ ${uiLabelMap.ThruDate}
+ ${uiLabelMap.ImportStatus}
+ ${uiLabelMap.ThruReasonId}
+ ${uiLabelMap.Actions}
+
+
+ <#if (data?has_content)>
+ <#list data as historyEntry>
+
+
+ <#if historyEntry.statusId?exists && historyEntry.statusId == 'EXCEL_IMPORTING'>
+
+ <#elseif historyEntry.statusId?exists && historyEntry.statusId == 'EXCEL_IMPORTED' && historyEntry.thruReasonId?exists && historyEntry.thruReasonId?has_content>
+ <#if historyEntry.thruReasonId == 'EXCEL_IMPORT_SUCCESS'>
+ ${uiLabelMap.ReasonOK}
+ <#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_STOPPED'>
+ ${uiLabelMap.ReasonStopped}
+ <#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_ERROR'>
+ ${uiLabelMap.ReasonError}
+ <#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_QUEST'>
+ ${uiLabelMap.ReasonWarning}
+ #if>
+ #if>
+
+ ${historyEntry.sequenceNum!}
+ ${historyEntry.fileName!}
+ <#if historyEntry.fromDate?exists && historyEntry.fromDate?has_content>${historyEntry.fromDate?string("yyyy-MM-dd HH:mm:ss")}#if>
+ <#if historyEntry.thruDate?exists && historyEntry.thruDate?has_content>${historyEntry.thruDate?string("yyyy-MM-dd HH:mm:ss")}#if>
+ <#if historyEntry.statusId?exists && historyEntry.statusId?has_content>${uiLabelMap.get(historyEntry.statusId)}#if>
+ <#if historyEntry.statusId?exists && historyEntry.statusId == "EXCEL_IMPORTED" && historyEntry.thruReasonId?exists && historyEntry.thruReasonId?has_content>${uiLabelMap.get(historyEntry.thruReasonId)}#if>
+
+ <#assign buttons = 0 />
+ <#if historyEntry.logFileName?exists && historyEntry.logFileName?has_content>
+ <#if Static["org.apache.ofbiz.base.util.FileUtil"].getFile(historyEntry.logFileName).exists()>
+
+
+
+ <#assign buttons = buttons + 1 />
+ #if>
+ #if>
+ <#if buttons == 0>
+ <#--- -->
+ <#assign buttons = buttons + 1 />
+ #if>
+ <#if historyEntry.logFileName?exists && historyEntry.logFileName?has_content>
+ <#if Static["org.apache.ofbiz.pricat.AbstractPricatParser"].isCommentedExcelExists(request, historyEntry.sequenceNum)>
+
+ ${uiLabelMap.DownloadCommentedPricat}
+
+ <#assign buttons = buttons + 1 />
+ #if>
+ #if>
+ <#if buttons == 1>
+ <#--- -->
+ #if>
+
+
+ #list>
+ <#else>
+
+
+ ${uiLabelMap.ExcelImportTipNoData}
+
+
+ #if>
+
+
+
\ No newline at end of file
diff --git a/specialpurpose/pricat/webapp/pricat/ftl/pricatreport.ftl b/specialpurpose/pricat/webapp/pricat/ftl/pricatreport.ftl
new file mode 100644
index 0000000000..d539bcf258
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/ftl/pricatreport.ftl
@@ -0,0 +1,529 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<#assign report = Static["org.apache.ofbiz.htmlreport.HtmlReport"].getInstance(request, response)>
+<#assign resourceParam = "resource"
+ borderStyle = "2px inset ThreeDHighlight"
+ borderSimpleStyle = "2px solid ThreeDFace">
+<#if report.isMultiOperation(request)?string("true", "false") == "true">
+ <#assign resourceParam = null>
+#if>
+<#assign action = report.getParamAction(request)>
+<#-- start of switch statement -->
+<#switch action>
+ <#case "reportupdate">
+<#-- ACTION: get report update -->
+ <#assign htmlStart = report.htmlStart(false)>
+ ${StringUtil.wrapString(htmlStart)}
+
+
+
+ ${StringUtil.wrapString(report.bodyStart("empty", "style=\"background-color:ThreeDFace;\" onLoad=\"init();\""))}
+ ${StringUtil.wrapString(report.bodyEnd())}
+ ${StringUtil.wrapString(report.htmlEnd())}
+
+ <#break>
+ <#-- ACTION: report begin -->
+ <#case "reportbegin">
+ <#default>
+ ${report.setParamAction("reportend")}
+
+${StringUtil.wrapString(report.htmlStart())}
+
+
+
+ ${StringUtil.wrapString(report.bodyStart("", "onLoad=\"start();\""))}
+ ${StringUtil.wrapString(report.dialogStart())}
+
+
+
+ ${StringUtil.wrapString(report.dialogEnd())}
+ ${StringUtil.wrapString(report.bodyEnd())}
+ ${StringUtil.wrapString(report.htmlEnd())}
+
+#switch>
+<#-- //////////////////// end of switch statement -->
diff --git a/specialpurpose/pricat/webapp/pricat/ftl/report.ftl b/specialpurpose/pricat/webapp/pricat/ftl/report.ftl
new file mode 100644
index 0000000000..bb6c30c7f4
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/ftl/report.ftl
@@ -0,0 +1,510 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<#assign report = Static["org.apache.ofbiz.htmlreport.HtmlReport"].getInstance(request, response)>
+<#assign resourceParam = "resource"
+ borderStyle = "2px inset ThreeDHighlight"
+ borderSimpleStyle = "2px solid ThreeDFace">
+<#if report.isMultiOperation(request)?string("true", "false") == "true">
+ <#assign resourceParam = null>
+#if>
+<#assign action = report.getParamAction(request)>
+<#-- start of switch statement -->
+<#switch action>
+ <#case "reportupdate">
+<#-- ACTION: get report update -->
+ <#assign htmlStart = report.htmlStart(false)>
+ ${StringUtil.wrapString(htmlStart)}
+
+
+
+ ${StringUtil.wrapString(report.bodyStart("empty", "style=\"background-color:ThreeDFace;\" onLoad=\"init();\""))}
+ ${StringUtil.wrapString(report.bodyEnd())}
+ ${StringUtil.wrapString(report.htmlEnd())}
+
+ <#break>
+ <#-- ACTION: report begin -->
+ <#case "reportbegin">
+ <#default>
+ ${report.setParamAction("reportend")}
+
+${StringUtil.wrapString(report.htmlStart())}
+
+
+
+ ${StringUtil.wrapString(report.bodyStart("", "onLoad=\"start();\""))}
+ ${StringUtil.wrapString(report.dialogStart())}
+
+
+
+ ${StringUtil.wrapString(report.dialogEnd())}
+ ${StringUtil.wrapString(report.bodyEnd())}
+ ${StringUtil.wrapString(report.htmlEnd())}
+
+#switch>
+<#-- //////////////////// end of switch statement -->
diff --git a/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportHistory.ftl b/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportHistory.ftl
new file mode 100644
index 0000000000..70839a2185
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportHistory.ftl
@@ -0,0 +1,31 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+
+
+
+
+
+ <#include "component://pricat/webapp/pricat/ftl/ExcelImportHistoryReport.ftl"/>
+
+
+
+
+
+
\ No newline at end of file
diff --git a/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportLog.ftl b/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportLog.ftl
new file mode 100644
index 0000000000..256f6c919b
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/ftl/viewExcelImportLog.ftl
@@ -0,0 +1,39 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricat/includes/pricat.css b/specialpurpose/pricat/webapp/pricat/includes/pricat.css
new file mode 100644
index 0000000000..06feb2fdda
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/includes/pricat.css
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+.main input {
+ margin-right: 7px;
+}
+
+/* headline of dialog window */
+.dialoghead {
+ background-color: ActiveCaption;
+ margin-bottom: 8px;
+ padding: 2px;
+ color: CaptionText;
+ font-size: 12px;
+ font-weight: bold;
+ white-space: nowrap;
+}
+
+
+/* outer table of complete dialog window */
+table.dialog {
+ margin: 20px auto;
+ width: 85%;
+ border-left: 1px solid ThreeDLightShadow;
+ border-top: 1px solid ThreeDLightShadow;
+ border-right: 1px solid ThreedDarkShadow;
+ border-bottom: 1px solid ThreedDarkShadow;
+}
+
+/* inner table of complete dialog window */
+table.dialogbox {
+ width: 100%;
+ background-color: ThreeDFace;
+ background-color: ThreeDFace;
+ border-left: 1px solid ThreeDHighlight;
+ border-top: 1px solid ThreeDHighlight;
+ border-right: 1px solid ThreeDShadow;
+ border-bottom: 1px solid ThreeDShadow;
+ padding-top: 1px;
+
+}
+
+body.dialog {
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ font-size: 11px;
+ padding: 0;
+ margin: 0;
+
+}
+
+/* Button - Image button in image style */
+img.button {
+ height: 20px;
+ width: 20px;
+ border: 0px none;
+ vertical-align: middle;
+}
+
+/* Button - Link (href) style */
+a.button {
+ color: ButtonText;
+ text-decoration: none;
+ cursor: pointer;
+}
+
+/* Button - Normal style (inactive) */
+span.norm {
+ display: block;
+ border: 1px solid ThreeDFace;
+}
+
+/* Button - Hover style */
+span.over {
+ display: block;
+ border-top: 1px solid ThreeDHighlight;
+ border-left: 1px solid ThreeDHighlight;
+ border-bottom: 1px solid ThreeDShadow;
+ border-right: 1px solid ThreeDShadow;
+}
+
+/* Button - Push style */
+span.push {
+ display: block;
+ border-top: 1px solid ThreeDShadow;
+ border-left: 1px solid ThreeDShadow;
+ border-bottom: 1px solid ThreeDHighlight;
+ border-right: 1px solid ThreeDHighlight;
+}
+
+/* Button - Disabled style */
+span.disabled {
+ display: block;
+ border: 1px solid ThreeDFace;
+ color: GrayText;
+}
+
+/* Button - Separator */
+span.separator {
+ display: block;
+ height: 18px;
+ width: 0px;
+ border-top: 0px;
+ border-left: 1px solid ThreeDShadow;
+ border-bottom: 0px;
+ border-right: 1px solid ThreeDHighlight;
+}
+
+/* final button row of dialog window */
+.dialogbuttons {
+ padding: 3px 8px 5px;
+ text-align: center;
+
+}
+
+.dialogcontent {
+ border-left: 1px solid ThreeDHighlight;
+ border-top: 1px solid ThreeDHighlight;
+ border-right: 2px solid ThreeDShadow;
+ border-bottom: 2px solid ThreeDShadow;
+ margin: 8px;
+ padding: 15px;
+}
+
+/* Submit and other buttons */
+input.dialogbutton {
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ font-size: 11px;
+ background-color: ButtonFace;
+ width: 100px;
+ height: 20px;
+ padding: 0 5px;
+ margin-left: 12px;
+ overflow: visible;
+}
+
+/* empty dummy style */
+.empty {}
+
+/* element without margin and padding */
+.nomargin {
+ padding: 0;
+ margin: 0;
+}
+
+/* hide a block */
+.hide {
+ display: none;
+ visibility: hidden;
+}
+
+/* show a block */
+.show {
+ display: inline;
+ visibility: visible;
+}
+
+.help {
+ color: InfoText;
+ position: absolute;
+ top: 0px;
+ left: 0px;
+ padding: 5px;
+ width: 200px;
+ border: 1px solid WindowFrame;
+ background-color: InfoBackground;
+ visibility: hidden;
+ font-size: 8pt;
+}
+
+span.head { color: #000099; font-weight: bold; }
+span.note { color: #666666; }
+span.ok { color: #009900; }
+span.warn { color: #990000; padding-left: 40px; }
+span.err { color: #990000; font-weight: bold; padding-left: 40px; }
+span.throw { color: #990000; font-weight: bold; }
+
+.text-left {
+ text-align: left;
+}
+
+.p-md {
+ padding: 25px;
+}
+
+.table-striped > tbody > tr:nth-of-type(odd) {
+ background-color: #f9f9f9;
+}
+
+.table > thead > tr > th {
+ border-bottom: 1px solid #DDDDDD;
+ vertical-align: bottom;
+}
+.table > thead > tr > th,
+.table > tbody > tr > th,
+.table > tfoot > tr > th,
+.table > thead > tr > td,
+.table > tbody > tr > td,
+.table > tfoot > tr > td {
+ border-top: 1px solid #e7eaec;
+ line-height: 1.42857;
+ padding: 8px;
+ vertical-align: top;
+}
+
+.ms-table-primary thead{
+ background-color: #eeeeee;
+}
+.ms-table-primary tr.ms-table-header,
+tr.ms-table-header span{
+ font-weight: bold;
+}
+.ms-table-primary{
+ width: 100%;
+ border:0;
+ margin:0;
+ border-collapse:collapse;
+}
+.ms-table-primary td,th{
+ padding:0;
+ text-align: center;
+ vertical-align: middle !important;
+}
+.ms-table-primary .text-left{
+ padding:0;
+ text-align: left;
+ vertical-align: middle !important;
+}
+.ms-table-primary .text-right{
+ padding:0;
+ text-align: right;
+ vertical-align: middle !important;
+}
+
+.p-xs {
+ padding: 10px;
+}
+.p-sm {
+ padding: 15px;
+}
diff --git a/specialpurpose/pricat/webapp/pricat/index.jsp b/specialpurpose/pricat/webapp/pricat/index.jsp
new file mode 100644
index 0000000000..0ad9a3f911
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricat/index.jsp
@@ -0,0 +1,20 @@
+<%--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+--%>
+
+<%response.sendRedirect("control/main");%>
diff --git a/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/controller.xml b/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/controller.xml
new file mode 100644
index 0000000000..06d74fde0e
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/controller.xml
@@ -0,0 +1,88 @@
+
+
+
+
+
+
+
+
+ PriCat Demo
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/web.xml b/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/web.xml
new file mode 100644
index 0000000000..09955606a9
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/WEB-INF/web.xml
@@ -0,0 +1,100 @@
+
+
+
+
+
+ Apache OFBiz - PriCat Demo
+ PriCat Demo Application of the Apache OFBiz Project
+
+
+ A unique name used to identify/recognize the local dispatcher for the Service Engine
+ localDispatcherName pricat
+
+
+ The Name of the Entity Delegator to use, defined in entityengine.xml
+ entityDelegatorName default
+
+
+ The location of the main-decorator screen to use for this webapp; referred to as a context variable in screen def XML files.
+ mainDecoratorLocation
+ component://pricat/widget/SampleScreens.xml
+
+
+ Remove unnecessary whitespace from HTML output.
+ compressHTML
+ false
+
+
+
+ ControlFilter
+ ControlFilter
+ org.apache.ofbiz.webapp.control.ControlFilter
+
+ allowedPaths
+ /error:/control:/select:/index.html:/index.jsp:/default.html:/default.jsp:/images:/js:/ws
+
+
+ redirectPath
+ /control/main
+
+
+
+ ContextFilter
+ ContextFilter
+ org.apache.ofbiz.webapp.control.ContextFilter
+
+
+ ControlFilter
+ /*
+
+
+ ContextFilter
+ /*
+
+
+ org.apache.ofbiz.webapp.control.ControlEventListener
+ org.apache.ofbiz.webapp.control.LoginEventListener
+
+
+
+
+ Main Control Servlet
+ ControlServlet
+ ControlServlet
+ org.apache.ofbiz.webapp.control.ControlServlet
+ 1
+
+ ControlServlet /control/*
+
+
+ 60
+
+ true
+ true
+
+ COOKIE
+
+
+
+ index.jsp
+ index.html
+ index.htm
+
+
diff --git a/specialpurpose/pricat/webapp/pricatdemo/downloads/SamplePricatTemplate_V1.1.xlsx b/specialpurpose/pricat/webapp/pricatdemo/downloads/SamplePricatTemplate_V1.1.xlsx
new file mode 100644
index 0000000000..ed259a8d59
Binary files /dev/null and b/specialpurpose/pricat/webapp/pricatdemo/downloads/SamplePricatTemplate_V1.1.xlsx differ
diff --git a/specialpurpose/pricat/webapp/pricatdemo/error/error.jsp b/specialpurpose/pricat/webapp/pricatdemo/error/error.jsp
new file mode 100644
index 0000000000..7f4af8fe3b
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/error/error.jsp
@@ -0,0 +1,52 @@
+<%--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+--%>
+<%@ page import="org.apache.ofbiz.base.util.*" %>
+
+
+OFBiz Message
+
+
+
+<% String errorMsg = (String) request.getAttribute("_ERROR_MESSAGE_"); %>
+
+
+
+
+
+
+
+
+
+
+ :ERROR MESSAGE:
+
+
+
+
+ <%=UtilFormatOut.replaceString(errorMsg, "\n", " ")%>
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricatdemo/ftl/SamplePricat.ftl b/specialpurpose/pricat/webapp/pricatdemo/ftl/SamplePricat.ftl
new file mode 100644
index 0000000000..f04a33fadc
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/ftl/SamplePricat.ftl
@@ -0,0 +1,52 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+
+
+ ${uiLabelMap.ParseSamplePricat}
+
+
+
+
+
+
+
+
+ ${uiLabelMap.SamplePricatTemplate}
+
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricatdemo/ftl/countdownreport.ftl b/specialpurpose/pricat/webapp/pricatdemo/ftl/countdownreport.ftl
new file mode 100644
index 0000000000..56930e9dd3
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/ftl/countdownreport.ftl
@@ -0,0 +1,21 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+ <#assign report = Static["org.apache.ofbiz.htmlreport.sample.SampleHtmlReport"].getReport(request, response)>
+ ${report.prepareDisplayReport(request, response, "countdown", "/pricatdemo/control/countdownreport")}
+ <#include "component://pricat/webapp/pricat/ftl/report.ftl">
diff --git a/specialpurpose/pricat/webapp/pricatdemo/ftl/countupreport.ftl b/specialpurpose/pricat/webapp/pricatdemo/ftl/countupreport.ftl
new file mode 100644
index 0000000000..9f0a1a84f5
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/ftl/countupreport.ftl
@@ -0,0 +1,21 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+ <#assign report = Static["org.apache.ofbiz.htmlreport.sample.SampleHtmlReport"].getReport(request, response)>
+ ${report.prepareDisplayReport(request, response, "countup", "/pricatdemo/control/countupreport")}
+ <#include "component://pricat/webapp/pricat/ftl/report.ftl">
diff --git a/specialpurpose/pricat/webapp/pricatdemo/ftl/main.ftl b/specialpurpose/pricat/webapp/pricatdemo/ftl/main.ftl
new file mode 100644
index 0000000000..d7638bb7b7
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/ftl/main.ftl
@@ -0,0 +1,33 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+
+
+
+ ${uiLabelMap.PriCatDemoMainPage}
+
+
+
+
+
+
${uiLabelMap.PricatDemoMessage}
+
+
+
+
diff --git a/specialpurpose/pricat/webapp/pricatdemo/ftl/parsePricatExcel.ftl b/specialpurpose/pricat/webapp/pricatdemo/ftl/parsePricatExcel.ftl
new file mode 100644
index 0000000000..73acdfffd4
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/ftl/parsePricatExcel.ftl
@@ -0,0 +1,21 @@
+<#--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+ <#assign report = Static["org.apache.ofbiz.pricat.PricatParseExcelHtmlReport"].getReport(request, response)>
+ ${report.prepareDisplayReport(request, response, "parse_excel", "/pricatdemo/control/parseSamplePricat")}
+ <#include "component://pricat/webapp/pricat/ftl/pricatreport.ftl">
diff --git a/specialpurpose/pricat/webapp/pricatdemo/index.jsp b/specialpurpose/pricat/webapp/pricatdemo/index.jsp
new file mode 100644
index 0000000000..0ad9a3f911
--- /dev/null
+++ b/specialpurpose/pricat/webapp/pricatdemo/index.jsp
@@ -0,0 +1,20 @@
+<%--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+--%>
+
+<%response.sendRedirect("control/main");%>
diff --git a/specialpurpose/pricat/widget/CommonScreens.xml b/specialpurpose/pricat/widget/CommonScreens.xml
new file mode 100644
index 0000000000..c6184848c8
--- /dev/null
+++ b/specialpurpose/pricat/widget/CommonScreens.xml
@@ -0,0 +1,80 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/specialpurpose/pricat/widget/PriCatDemoMenus.xml b/specialpurpose/pricat/widget/PriCatDemoMenus.xml
new file mode 100644
index 0000000000..3f147cc66f
--- /dev/null
+++ b/specialpurpose/pricat/widget/PriCatDemoMenus.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/specialpurpose/pricat/widget/PriCatMenus.xml b/specialpurpose/pricat/widget/PriCatMenus.xml
new file mode 100644
index 0000000000..953cc6b380
--- /dev/null
+++ b/specialpurpose/pricat/widget/PriCatMenus.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/specialpurpose/pricat/widget/SampleScreens.xml b/specialpurpose/pricat/widget/SampleScreens.xml
new file mode 100644
index 0000000000..00606eb0bf
--- /dev/null
+++ b/specialpurpose/pricat/widget/SampleScreens.xml
@@ -0,0 +1,141 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+