OFBIZ-9123 Add a PriCat component under specialpurpose

git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1770621 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Shi Jinghai
2016-11-21 08:07:57 +00:00
parent e84c8c99b4
commit 4d4e5f85fc
50 changed files with 9035 additions and 0 deletions
+25
View File
@@ -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'
}
@@ -0,0 +1,532 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<property key="PriCatCompanyName">
<value xml:lang="en">OFBiz: PriCat Demo</value>
<value xml:lang="zh">OFBiz:价目表</value>
</property>
<property key="PriCatApplication">
<value xml:lang="en">PriCat</value>
<value xml:lang="zh">价目表</value>
</property>
<property key="PriCatDemoCompanyName">
<value xml:lang="en">OFBiz: PriCat Demo</value>
<value xml:lang="zh">OFBiz:价目表演示</value>
</property>
<property key="PriCatDemoApplication">
<value xml:lang="en">PriCat Demo</value>
<value xml:lang="zh">价目表演示</value>
</property>
<property key="PriCatDemoCountDown">
<value xml:lang="en">HTML Report Demo - Count Down</value>
<value xml:lang="zh">页面输出演示 - 倒计数</value>
</property>
<property key="PriCatDemoCountUp">
<value xml:lang="en">HTML Report Demo - Count Up</value>
<value xml:lang="zh">页面输出演示 - 正计数</value>
</property>
<property key="PriCatDemoParseSamplePricat">
<value xml:lang="en">PriCat Demo - Parse PriCat</value>
<value xml:lang="zh">价目表演示 - 解析价目表</value>
</property>
<property key="PriCatDemoMainPage">
<value xml:lang="en">PriCat Demo Main Page</value>
<value xml:lang="zh">价目表演示首页</value>
</property>
<property key="PricatDemoMessage">
<value xml:lang="en">PriCat Demo includes 2 HTML Report Demo and 1 Parse PriCat File Demo.</value>
<value xml:lang="zh">价目表演示包含了2个页面输出演示和1个解析价目表文件的演示。</value>
</property>
<property key="ParseSamplePricatDemo">
<value xml:lang="en">Parse Sample PriCat Demo</value>
<value xml:lang="zh">演示解析样例价目表文件</value>
</property>
<property key="SamplePricatTemplate">
<value xml:lang="en">Sample PriCat Template</value>
<value xml:lang="zh">价目表样例模板</value>
</property>
<property key="DownloadPricatTemplate">
<value xml:lang="en">Download PriCat Template</value>
<value xml:lang="zh">下载价目表模板</value>
</property>
<property key="UploadPricat">
<value xml:lang="en">Upload PriCat</value>
<value xml:lang="zh">上传价目表</value>
</property>
<property key="ParseSamplePricat">
<value xml:lang="en">Parse Sample PriCat</value>
<value xml:lang="zh">解析样例价目表</value>
</property>
<property key="ExcelTemplateType">
<value xml:lang="en">Template Type</value>
<value xml:lang="zh">模板类型</value>
</property>
<property key="SamplePricatType">
<value xml:lang="en">Sample PriCat</value>
<value xml:lang="zh">样例价目表</value>
</property>
<property key="OFBizPricatType">
<value xml:lang="en">OFBiz Type</value>
<value xml:lang="zh">OFBiz类型</value>
</property>
<property key="StartStoreExcel">
<value xml:lang="en">Storing your upload file to server ... </value>
<value xml:lang="zh">正在把上传文件存到服务器中 ... </value>
</property>
<property key="NoFileUploaded">
<value xml:lang="en">no file uploaded!</value>
<value xml:lang="zh">没有上传文件!</value>
</property>
<property key="StartParsePricat">
<value xml:lang="en">Start parsing the uploaded file ...</value>
<value xml:lang="zh">开始解析上传的文件 ...</value>
</property>
<property key="PricatParseCompleted">
<value xml:lang="en">... parsing completed</value>
<value xml:lang="zh">... 完成解析</value>
</property>
<property key="CurrentUserLoginNoFacility">
<value xml:lang="en">Cannot find any facility for current user(userLoginId: [{0}]).</value>
<value xml:lang="zh">没有找到当前用户(userLoginId: [{0}])的任何一个仓库。</value>
</property>
<property key="GetCurrentUserLoginFacility">
<value xml:lang="en">Getting facilities of current user ... </value>
<value xml:lang="zh">正在获得当前用户的仓库 ... </value>
</property>
<property key="FacilityFoundForCurrentUserLogin">
<value xml:lang="en">({0}) Facility found for current user: {1}[{2}].</value>
<value xml:lang="zh">({0}) 找到当前用户的仓库:{1}[{2}]。</value>
</property>
<property key="FacilityNotBelongToYou">
<value xml:lang="en">Facility {0}[{1}] does not belong to you. Please use a facility of yours.</value>
<value xml:lang="zh">仓库{0}[{1}]不属于你,请改为你自己的仓库。</value>
</property>
<property key="ExcelTemplateTypeSelected">
<value xml:lang="en">The selected Excel template type: </value>
<value xml:lang="zh">选择的Excel模板类型:</value>
</property>
<property key="FacilityIdSelected">
<value xml:lang="en">The selected facility Id: </value>
<value xml:lang="zh">选择的仓库编号:</value>
</property>
<property key="ParsePricatFileStatement">
<value xml:lang="en">Loading file {0} ... </value>
<value xml:lang="zh">正在读入文件{0} ... </value>
</property>
<property key="PricatSuggestion">
<value xml:lang="en">Please make sure your Excel file is in format of Microsoft Excel 2007 and later. And then try again.</value>
<value xml:lang="zh">请确认你的Excel文件格式是微软Office 2007或更新版本的,然后重试一下。</value>
</property>
<property key="CheckPricatHasSheet">
<value xml:lang="en">Checking whether your file contains at least a sheet ... </value>
<value xml:lang="zh">正在检查你的文件是否包含至少一个表单 ... </value>
</property>
<property key="PricatVersionNotSupport">
<value xml:lang="en">Pricat Version {0} is not supported.</value>
<value xml:lang="zh">还不能支持这个价格分类的版本{0}。</value>
</property>
<property key="PricatTableOnlyParse1stSheet">
<value xml:lang="en">Only the 1st sheet will be parsed.</value>
<value xml:lang="zh">只解析第一张表。</value>
</property>
<property key="PricatTableNoSheet">
<value xml:lang="en">There's no sheet in the PriCat file.</value>
<value xml:lang="zh">价格分类文件中没有表。</value>
</property>
<property key="PricatTableRows">
<value xml:lang="en">Sheet [{2}] has {0} rows of header and {1} rows of data.</value>
<value xml:lang="zh">表单[{2}]有{0}行表头和{1}行数据。</value>
</property>
<property key="PricatTableRow">
<value xml:lang="en">Sheet [{0}] has only 1 row of data.</value>
<value xml:lang="zh">表单[{0}]只有一行数据。</value>
</property>
<property key="ExcelTableNoRow">
<value xml:lang="en">There's no row in sheet [{0}].</value>
<value xml:lang="zh">表单[{0}]中没有数据。</value>
</property>
<property key="ExcelTableColumnNumberNotMatch">
<value xml:lang="en">The sheet has {0} columns, it's not the same as sample sheet's {1}.</value>
<value xml:lang="zh">表单有{0}列,与样例表单的{1}列不同。</value>
</property>
<property key="ExcelTableColumnNotMatch">
<value xml:lang="en">The column {0} has a name {1}, it's not identical to {2}.</value>
<value xml:lang="zh">列{0}的名字是{1},应是{2}。</value>
</property>
<property key="ExcelParsingRow">
<value xml:lang="en">({0}) parsing {1} ...</value>
<value xml:lang="zh">({0}) 正在解析 {1} ...</value>
</property>
<property key="StartCheckPricatVersion">
<value xml:lang="en">Check PriCat file's version ... </value>
<value xml:lang="zh">检查价格分类文件的版本 ... </value>
</property>
<property key="StartCheckCurrencyId">
<value xml:lang="en">Checking currencyId ... </value>
<value xml:lang="zh">正在检查币种 ... </value>
</property>
<property key="CurrencyIdRequired">
<value xml:lang="en">CurrencyId is required. Please set it at row 3 column 2.</value>
<value xml:lang="zh">必须设置货币。请设置在第三行、第二列。</value>
</property>
<property key="CurrencyIdIs">
<value xml:lang="en">CurrencyId is {0}</value>
<value xml:lang="zh">货币是{0}</value>
</property>
<property key="CurrencyIdNotFound">
<value xml:lang="en">CurrencyId {0} cannot be found in this system.</value>
<value xml:lang="zh">本系统中找不到货币{0}。</value>
</property>
<property key="CurrencyIdNotCurrency">
<value xml:lang="en">{0} is not a currency in this system.</value>
<value xml:lang="zh">{0}在这个系统里不是货币。</value>
</property>
<property key="HeaderContainsError">
<value xml:lang="en">There are errors in PriCat header. Please correct it and upload it again.</value>
<value xml:lang="zh">表头中有错误,请修改后重新上传。</value>
</property>
<property key="PricatNoDataRows">
<value xml:lang="en">There are no data in your PriCat file, no further operation is required.</value>
<value xml:lang="zh">你的价格分类文件中没有数据,不再做数据解析了。</value>
</property>
<property key="DataContainsError">
<value xml:lang="en">There are errors in data of your PriCat file. Please correct it and upload it again.</value>
<value xml:lang="zh">价格分类文件的数据中有错误,请修改后重新上传。</value>
</property>
<property key="CellTypeNotString">
<value xml:lang="en">The type of cell[{0}, {1}] is not String. The cell value will be changed to String type.</value>
<value xml:lang="zh">单元格[{0}, {1}]不是字符类型。将把这个单元格的值转为字符类型。</value>
</property>
<property key="CellTypeNotNumeric">
<value xml:lang="en">The type of cell[{0}, {1}] is not numeric. The cell value will be changed to numeric type.</value>
<value xml:lang="zh">单元格[{0}, {1}]不是数字类型。将把这个单元格的值转为数字类型。</value>
</property>
<property key="ErrorParseValueToNumeric">
<value xml:lang="en">Unable to parse the value to a numeric.</value>
<value xml:lang="zh">无法把这个单元格的值转为数字。</value>
</property>
<property key="StartCheckHeaderColNum">
<value xml:lang="en">Checking whether the number of header columns matches the template's of version {0} ... </value>
<value xml:lang="zh">正在检查表头的列数是否与版本{0}的模板一致 ... </value>
</property>
<property key="HeaderColNumNotMatch">
<value xml:lang="en">The number of columns of {0} template header columns, column number {1} and imported template columns are not consistent ... </value>
<value xml:lang="zh">模板表头的列数{0}列,与导入的模板的列数{1}列不一致 ... </value>
</property>
<property key="StartCheckHeaderColLabel">
<value xml:lang="en">Checking whether the header labels match the template's of version {0} ... </value>
<value xml:lang="zh">正在检查表头的文字是否与版本{0}的模板一致 ... </value>
</property>
<property key="HeaderColLabelNotMatch">
<value xml:lang="en">The lable of row {0} colum {1} is [{2}], it does not match [{3}] as expected.</value>
<value xml:lang="zh">行{0}列{1}的文字是[{2}],与期望的[{3}]不一致。</value>
</property>
<property key="HeaderColNumShortThanRequired">
<value xml:lang="en">Table header column number less than the required {0}</value>
<value xml:lang="zh">表头列数小于要求的{0}列</value>
</property>
<property key="UseHeaderColNum">
<value xml:lang="en">the first {0} column labels will be checked</value>
<value xml:lang="zh">将检查表头的前{0}列的标签</value>
</property>
<property key="WriteCommentsBackToExcel">
<value xml:lang="en">Writing errors as commonts to your Excel file ... </value>
<value xml:lang="zh">正在把错误信息作为批注写到你的Excel文件里 ... </value>
</property>
<property key="CLEANUP_LOGANDEXCEL_BEGIN">
<value xml:lang="en">Start to clean log and commented excel files</value>
<value xml:lang="zh">开始清理日志和批注过的Excel文件</value>
</property>
<property key="HistoryLessThan">
<value xml:lang="en">history entries less than {0}</value>
<value xml:lang="zh">历史记录少于{0}条</value>
</property>
<property key="HistoryEntryToRemove">
<value xml:lang="en">{0} entries to remove</value>
<value xml:lang="zh">要删除{0}条记录</value>
</property>
<property key="FacilityNameNotMatchId">
<value xml:lang="en">In the system, the name of facilityId[{0}] is [{1}], NOT [{2}]. Please correct it and import again.</value>
<value xml:lang="zh">系统中,仓库标识[{0}]的名称是[{1}],不是[{2}]。请修改后重新导入。</value>
</property>
<property key="ExcelEmptyRow">
<value xml:lang="en">empty row</value>
<value xml:lang="zh">空行</value>
</property>
<property key="REPORT_EXCEPTION">
<value xml:lang="en">Exception: </value>
<value xml:lang="zh">意外错误:</value>
</property>
<property key="DIALOG_BUTTON_OK">
<value xml:lang="en">OK</value>
<value xml:lang="zh">确定</value>
</property>
<property key="DIALOG_BUTTON_CANCEL">
<value xml:lang="en">Cancel</value>
<value xml:lang="zh">取消</value>
</property>
<property key="DIALOG_BUTTON_EDIT">
<value xml:lang="en">Edit</value>
<value xml:lang="zh">编辑</value>
</property>
<property key="DIALOG_BUTTON_DISCARD">
<value xml:lang="en">Discard</value>
<value xml:lang="zh">放弃</value>
</property>
<property key="DIALOG_BUTTON_CLOSE">
<value xml:lang="en">Close</value>
<value xml:lang="zh">关闭</value>
</property>
<property key="DIALOG_BUTTON_ADVANCE">
<value xml:lang="en">Advance</value>
<value xml:lang="zh">高级</value>
</property>
<property key="DIALOG_BUTTON_SET">
<value xml:lang="en">Set</value>
<value xml:lang="zh">设置</value>
</property>
<property key="DIALOG_BUTTON_BACK">
<value xml:lang="en">Back</value>
<value xml:lang="zh">返回</value>
</property>
<property key="DIALOG_BUTTON_CONTINUE">
<value xml:lang="en">Continue</value>
<value xml:lang="zh">继续</value>
</property>
<property key="DIALOG_BUTTON_DETAIL">
<value xml:lang="en">Detail</value>
<value xml:lang="zh">详细</value>
</property>
<property key="DIALOG_BUTTON_DOWNLOAD">
<value xml:lang="en">Download</value>
<value xml:lang="zh">下载</value>
</property>
<property key="FORMAT_DEFAULT">
<value xml:lang="en">({0}) This is default format.</value>
<value xml:lang="zh">({0}) 这是缺省格式。</value>
</property>
<property key="FORMAT_WARNING">
<value xml:lang="en">({0}) This is warning format.</value>
<value xml:lang="zh">({0}) 这是警告格式。</value>
</property>
<property key="FORMAT_HEADLINE">
<value xml:lang="en">({0}) This is headline format.</value>
<value xml:lang="zh">({0}) 这是标题格式。</value>
</property>
<property key="FORMAT_NOTE">
<value xml:lang="en">({0}) This is note format.</value>
<value xml:lang="zh">({0}) 这是记录格式。</value>
</property>
<property key="FORMAT_OK">
<value xml:lang="en">({0}) This is OK format.</value>
<value xml:lang="zh">({0}) 这是正确时的格式。</value>
</property>
<property key="FORMAT_ERROR">
<value xml:lang="en">({0}) This is error format.</value>
<value xml:lang="zh">({0}) 这是错误时的格式。</value>
</property>
<property key="FORMAT_THROWABLE">
<value xml:lang="en">({0}) This is throwable format.</value>
<value xml:lang="zh">({0}) 这是抛出错误的格式。</value>
</property>
<property key="START_COUNT_DOWN">
<value xml:lang="en">Start counting down ...</value>
<value xml:lang="zh">开始倒数 ...</value>
</property>
<property key="COUNT_COMPLETED">
<value xml:lang="en">... counting completed.</value>
<value xml:lang="zh">... 完成计数。</value>
</property>
<property key="START_COUNT_UP">
<value xml:lang="en">String counting up ...</value>
<value xml:lang="zh">开始正计数 ...</value>
</property>
<property key="RPT_ERROR">
<value xml:lang="en">Error: </value>
<value xml:lang="zh">错误:</value>
</property>
<property key="RPT_ERROR_DETAILS">
<value xml:lang="en">Details: </value>
<value xml:lang="zh">详细:</value>
</property>
<property key="ParseExcelDemo">
<value xml:lang="en">Click here to see Import Excel demo</value>
<value xml:lang="zh">点击这里看导入Excel演示</value>
</property>
<property key="StartParseExcel">
<value xml:lang="en">Start parsing a sample excel file ...</value>
<value xml:lang="zh">开始解析一个Excel样例文件 ...</value>
</property>
<property key="ExcelParseCompleted">
<value xml:lang="en">... parsing completed</value>
<value xml:lang="zh">... 完成解析</value>
</property>
<property key="ExcelTableOnlyParse1stSheet">
<value xml:lang="en">Only the 1st sheet will be parsed.</value>
<value xml:lang="zh">只解析第一张表。</value>
</property>
<property key="ExcelTableNoSheet">
<value xml:lang="en">There's no sheet in the excel.</value>
<value xml:lang="zh">Excel中没有表。</value>
</property>
<property key="ExcelTableRows">
<value xml:lang="en">Sheet {1} has {0} rows.</value>
<value xml:lang="zh">表单{1}有{0}行数据。</value>
</property>
<property key="ExcelTableRow">
<value xml:lang="en">Sheet {0} has only 1 row.</value>
<value xml:lang="zh">表单{0}只有一行数据。</value>
</property>
<property key="ExcelTableNoRow">
<value xml:lang="en">There's no row in sheet {0}.</value>
<value xml:lang="zh">表单{0}中没有数据。</value>
</property>
<property key="ExcelTableColumnNumberNotMatch">
<value xml:lang="en">The sheet has {0} columns, it's not the same as sample sheet's {1}.</value>
<value xml:lang="zh">表单有{0}列,与样例表单的{1}列不同。</value>
</property>
<property key="ExcelTableColumnNotMatch">
<value xml:lang="en">The column {0} has a name {1}, it's not identical to {2}.</value>
<value xml:lang="zh">列{0}的名字是{1},应是{2}。</value>
</property>
<property key="ExcelParsingRow">
<value xml:lang="en">({0}) parsing {1} ...</value>
<value xml:lang="zh">({0}) 正在解析 {1} ...</value>
</property>
<property key="ParseExcelEncoding">
<value xml:lang="en"> Using {0} to parsing the excel file.</value>
<value xml:lang="zh"> 正在使用{0}解析Excel文件。</value>
</property>
<property key="ParseExcelToolStatement">
<value xml:lang="en"> Using {0} to parsing the {1} format excel file...</value>
<value xml:lang="zh"> 正在使用{0}解析{1}格式的Excel文件...</value>
</property>
<property key="ok">
<value xml:lang="en">ok</value>
<value xml:lang="zh">完成</value>
</property>
<property key="error">
<value xml:lang="en">error</value>
<value xml:lang="zh">出错了</value>
</property>
<property key="skipped">
<value xml:lang="en">skipped</value>
<value xml:lang="zh">跳过</value>
</property>
<property key="ExcelImportHistoryList">
<value xml:lang="en">Excel Import History</value>
<value xml:lang="zh">Excel导入操作历史记录</value>
</property>
<property key="OnlyYourOwnImportHistoryDisplayed">
<value xml:lang="en">(Only current login user's history can be displayed)</value>
<value xml:lang="zh">(仅能显示当前用户的导入操作历史记录)</value>
</property>
<property key="SerialNumber">
<value xml:lang="en">No.</value>
<value xml:lang="zh">序号</value>
</property>
<property key="Filename">
<value xml:lang="en">Filename</value>
<value xml:lang="zh">文件名</value>
</property>
<property key="FromDate">
<value xml:lang="en">Start Time</value>
<value xml:lang="zh">开始时间</value>
</property>
<property key="ThruDate">
<value xml:lang="en">End Time</value>
<value xml:lang="zh">结束时间</value>
</property>
<property key="ThruReasonId">
<value xml:lang="en">End Reason</value>
<value xml:lang="zh">结束原因</value>
</property>
<property key="ImportStatus">
<value xml:lang="en">Import Status</value>
<value xml:lang="zh">导入状态</value>
</property>
<property key="Actions">
<value xml:lang="en">Actions</value>
<value xml:lang="zh">操作</value>
</property>
<property key="ExcelImportTipNoData">
<value xml:lang="en">No excel import history data.</value>
<value xml:lang="zh">没有Excel导入历史记录</value>
</property>
<property key="EXCEL_IMPORTING">
<value xml:lang="en">Importing</value>
<value xml:lang="zh">正在导入</value>
</property>
<property key="EXCEL_IMPORTED">
<value xml:lang="en">Imported</value>
<value xml:lang="zh">已导入</value>
</property>
<property key="EXCEL_IMPORT_SUCCESS">
<value xml:lang="en">Success</value>
<value xml:lang="zh">成功</value>
</property>
<property key="EXCEL_IMPORT_STOPPED">
<value xml:lang="en">Stopped by user</value>
<value xml:lang="zh">用户终止了导入</value>
</property>
<property key="EXCEL_IMPORT_ERROR">
<value xml:lang="en">Stopped by error</value>
<value xml:lang="zh">因出错而停止了导入</value>
</property>
<property key="EXCEL_IMPORT_QUEST">
<value xml:lang="en">Data error found</value>
<value xml:lang="zh">数据中有错误</value>
</property>
<property key="ViewExcelImportLogContent">
<value xml:lang="en">View log content</value>
<value xml:lang="zh">浏览日志内容</value>
</property>
<property key="DownloadCommentedExcel">
<value xml:lang="en">Download excel</value>
<value xml:lang="zh">下载Excel</value>
</property>
<property key="ViewExcelImportHistory">
<value xml:lang="en">View Import History</value>
<value xml:lang="zh">导入操作历史记录</value>
</property>
<property key="ViewPricatLog">
<value xml:lang="en">View</value>
<value xml:lang="zh">浏览</value>
</property>
<property key="DownloadCommentedPricat">
<value xml:lang="en">Download</value>
<value xml:lang="zh">下载</value>
</property>
<property key="ReasonOK">
<value xml:lang="en">OK</value>
</property>
<property key="ReasonStopped">
<value xml:lang="en">[S]</value>
</property>
<property key="ReasonError">
<value xml:lang="en">[E]</value>
</property>
<property key="ReasonWarning">
<value xml:lang="en">[W]</value>
</property>
</resource>
@@ -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
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<entity-engine-xml>
<!-- Enumeration for thruReasonId of ExcelImportHistory entity -->
<EnumerationType description="Excel import thru reasons" enumTypeId="EXCEL_IMPORT_THRU" hasTable="N" parentTypeId=""/>
<Enumeration enumId="EXCEL_IMPORT_SUCCESS" enumCode="EXCEL_IMPORT_SUCCESS" description="Excel Imported Successfully" sequenceId="01" enumTypeId="EXCEL_IMPORT_THRU"/>
<Enumeration enumId="EXCEL_IMPORT_STOPPED" enumCode="EXCEL_IMPORT_STOPPED" description="Excel Imported Stopped by user" sequenceId="02" enumTypeId="EXCEL_IMPORT_THRU"/>
<Enumeration enumId="EXCEL_IMPORT_ERROR" enumCode="EXCEL_IMPORT_ERROR" description="Excel Imported Exits Errorly" sequenceId="03" enumTypeId="EXCEL_IMPORT_THRU"/>
<Enumeration enumId="EXCEL_IMPORT_QUEST" enumCode="EXCEL_IMPORT_QUEST" description="Excel Imported Has Error Messages" sequenceId="04" enumTypeId="EXCEL_IMPORT_THRU"/>
<!-- Enumeration for statusId of ExcelImportHistory entity -->
<EnumerationType description="Excel import status" enumTypeId="EXCEL_IMPORT_STATUS" hasTable="N" parentTypeId=""/>
<Enumeration enumId="EXCEL_IMPORTING" enumCode="EXCEL_IMPORTING" description="Excel is being imported in progress" sequenceId="01" enumTypeId="EXCEL_IMPORT_STATUS"/>
<Enumeration enumId="EXCEL_IMPORTED" enumCode="EXCEL_IMPORTED" description="Excel has been imported" sequenceId="02" enumTypeId="EXCEL_IMPORT_STATUS"/>
</entity-engine-xml>
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<entitymodel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/entitymodel.xsd">
<entity entity-name="ExcelImportHistory"
package-name="org.ofbiz.product.catalog"
title="Excel Import History Entity">
<field name="userLoginId" type="id-vlong-ne"></field>
<field name="sequenceNum" type="numeric"></field>
<field name="fileName" type="value"></field>
<field name="fromDate" type="date-time"></field>
<field name="thruDate" type="date-time"></field>
<field name="thruReasonId" type="id-ne"></field>
<field name="statusId" type="id-ne"></field>
<field name="threadName" type="name"></field>
<field name="logFileName" type="value"></field>
<prim-key field="userLoginId"/>
<prim-key field="sequenceNum"/>
<relation rel-entity-name="UserLogin" type="one" fk-name="EXCELIMPORT_USERLOGIN">
<key-map field-name="userLoginId"/>
</relation>
<relation rel-entity-name="Enumeration" type="one" fk-name="EXCELIMPORT_STATUS">
<key-map field-name="statusId" rel-field-name="enumId"/>
</relation>
<relation rel-entity-name="Enumeration" type="one" fk-name="EXCELIMPORT_REASON">
<key-map field-name="thruReasonId" rel-field-name="enumId"/>
</relation>
</entity>
</entitymodel>
@@ -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;
@@ -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;
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<ofbiz-component name="pricat" enabled="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ofbiz-component.xsd">
<resource-loader name="main" type="component"/>
<classpath type="dir" location="config"/>
<!-- entity resources: model(s), eca(s), group, and data definitions -->
<entity-resource type="model" reader-name="main" loader="main" location="entitydef/entitymodel.xml"/>
<entity-resource type="data" reader-name="seed" loader="main" location="data/PricatData.xml"/>
<webapp name="pricat"
title="PriCat"
server="default-server"
location="webapp/pricat"
app-bar-display="false"
base-permission="OFBTOOLS,CATALOG"
mount-point="/pricat" />
<webapp name="pricatdemo"
title="PriCat Demo"
server="default-server"
location="webapp/pricatdemo"
app-bar-display="false"
base-permission="OFBTOOLS,EXAMPLE"
mount-point="/pricatdemo" />
</ofbiz-component>
@@ -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 <code>true</code>, this report should generate HTML instead of JavaScript output
* @param isTransient If set to <code>true</code> 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.<p>
*
* @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.<p>
*
* @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";
}
}
@@ -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<Object> 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<Object> warnings = new ArrayList<Object>();
/** 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<Object> getErrors() {
return errors;
}
public Locale getLocale() {
return locale;
}
public long getRuntime() {
return System.currentTimeMillis() - startTime;
}
public List<Object> 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.<p>
*
* @param locale the locale for this report
*/
protected void init(Locale locale) {
startTime = System.currentTimeMillis();
this.locale = locale;
errors = new ArrayList<Object>();
}
/**
* Prints a String to the report.<p>
*
* @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.<p>
*
* Use the contants starting with <code>FORMAT</code> from this interface
* to indicate which formatting to use.<p>
*
* @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.<p>
*
* @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.<p>
*
* Use the contants starting with <code>FORMAT</code> from this interface
* to indicate which formatting to use.<p>
*
* @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();
}
}
@@ -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.<p>
*
* @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.<p>
*
* @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.<p>
*
* @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.<p>
*
* @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.<p>
*
* @return the part of the report that is ready for output
*/
public abstract String getReportUpdate();
/**
* Returns the time this report has been running.<p>
*
* @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.<p>
*
* @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.<p>
*
* A OFBiz deamon Thread (the "Grim Reaper") will collect all
* doomed Threads, i.e. threads that are not longer active for some
* time.<p>
*
* @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.<p>
*
* @return the report where the output of this Thread is written to
*/
protected InterfaceReport getReport() {
return report;
}
/**
* Initialize a HTML report for this Thread.<p>
*
* @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.<p>
*
* @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;
}
}
File diff suppressed because it is too large Load Diff
@@ -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.<p>
*
*/
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.<p>
*
* @param obj the error object
*/
void addError(Object obj);
/**
* Adds a warning object to the list of warnings that occured during the report.<p>
*
* @param obj the error object
*/
void addWarning(Object obj);
/**
* Formats the runtime formatted as "hh:mm:ss".<p>
*
* @return the runtime formatted as "hh:mm:ss"
*/
String formatRuntime();
/**
* Returns a list of all errors that occured during the report.<p>
*
* @return an error list that occured during the report
*/
List<Object> getErrors();
/**
* Returns the locale this report was initialized with.<p>
*
* @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.<p>
*
* 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.<p>
*
* @return new elements that have been added to the report and not yet processed.
*/
String getReportUpdate();
/**
* Returns the time this report has been running.<p>
*
* @return the time this report has been running
*/
long getRuntime();
/**
* Returns a list of all warnings that occured during the report.<p>
*
* @return a warning list that occured during the report
*/
List<Object> getWarnings();
/**
* Returns if the report generated an error output.<p>
*
* @return true if the report generated an error, otherwise false
*/
boolean hasError();
/**
* Returns if the report generated a warning output.<p>
*
* @return true if the report generated a warning, otherwise false
*/
boolean hasWarning();
/**
* Prints a localized message to the report.<p>
*
* @param uiLabel the String to add
*/
void print(String uiLabel);
/**
* Prints a localized message to the report, using the indicated formatting.<p>
*
* Use the contants starting with <code>FORMAT</code> from this interface
* to indicate which formatting to use.<p>
*
* @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.<p>
*/
void println();
/**
* Prints a localized message to the report.<p>
*
* @param uiLabel the message to add
*/
void println(String uiLabel);
/**
* Prints a localized message to the report, using the indicated formatting.<p>
*
* Use the contants starting with <code>FORMAT</code> from this interface
* to indicate which formatting to use.<p>
*
* @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.<p>
*
* The exception will be stored and the output will later be processed
* in a special way.<p>
*
* @param t the exception to add
*
*/
void println(Throwable t);
/**
* Prints a localized message followed by a parameter and dots to the report.<p>
*
* @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.<p>
*
* 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.<p>
*/
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();
}
@@ -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.<p>
*/
void start();
/**
* Returns the UUID of this report thread.<p>
*
* @return the UUID of this report thread
*/
UUID getUUID();
}
@@ -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.<p>
*
* @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<threads.length; j++) {
Thread threadInstance = threads[j];
if (threadInstance instanceof SampleHtmlThread) {
thread = (InterfaceReportThread) threadInstance;
break;
}
}
if (thread == null) {
thread = new SampleHtmlThread(request, response, name.toLowerCase());
}
return thread;
}
}
@@ -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.
*******************************************************************************/
package org.apache.ofbiz.htmlreport.sample;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.htmlreport.AbstractReportThread;
import org.apache.ofbiz.htmlreport.InterfaceReport;
/**
* Thread for running sample html report.
*
*/
public class SampleHtmlThread extends AbstractReportThread {
public static final String COUNT_DOWN = "countdown";
public static final String COUNT_UP = "countup";
public static final String CONFIRM = "confirm_action";
public static final String[] messageLables = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"};
public static final List<String> 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);
}
}
}
}
@@ -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.<p>
*
* The methods in this class are substitutes for <code>java.net.URLEncoder.encode()</code> and
* <code>java.net.URLDecoder.decode()</code>.<p>
*
* The de- and encoding uses the same coding mechanism as JavaScript, special characters are
* replaced with <code>%hex</code> where hex is a two digit hex number.<p>
*
* <b>Note:</b> On the client side (browser) instead of using corresponding <code>escape</code>
* and <code>unescape</code> JavaScript functions, better use <code>encodeURIComponent</code> and
* <code>decodeURIComponent</code> functions which are work properly with unicode characters.
* These functions are supported in IE 5.5+ and NS 6+ only.<p>
*
*/
public final class ReportEncoder {
/** Constant for the standard <code>ISO-8859-1</code> encoding. */
public static final String ENCODING_ISO_8859_1 = "ISO-8859-1";
/** Constant for the standard <code>US-ASCII</code> encoding. */
public static final String ENCODING_US_ASCII = "US-ASCII";
/**
* Constant for the standard <code>UTF-8</code> encoding.<p>
*
* Default encoding for JavaScript decodeUriComponent methods is <code>UTF-8</code> 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<String, String> encodingCache = new HashMap<String, String>(16);
/** The plus entity. */
private static final String PLUS_ENTITY = ENTITY_PREFIX + "043;";
/**
* Constructor.<p>
*/
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.<p>
*
* Just calls {@link #decodeHtmlEntities(String, String)} first and feeds the result
* to {@link #encodeHtmlEntities(String, String)}. <p>
*
* @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.<p>
*
* @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.<p>
*
* Use this method as a replacement for <code>new String(byte[], encoding)</code>
* to avoid possible encoding problems.<p>
*
* @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.<p>
*
* @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 <code>URLDecoder.decode()</code>.<p>
*
* In case you don't know what encoding to use, set the value of
* the <code>encoding</code> parameter to <code>null</code>.
* This method will then default to UTF-8 encoding, which is probably the right one.<p>
*
* @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 <code>&amp;#8364;</code> that are contained in the
* String to a regular character, but only if that character is contained in the given
* encodings charset.<p>
*
* @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.<p>
*
* @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.<p>
*
* @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 <code>URLEncoder.encode()</code>.<p>
*
* In case you don't know what encoding to use, set the value of
* the <code>encoding</code> parameter to <code>null</code>.
* This method will then default to UTF-8 encoding, which is probably the right one.<p>
*
* @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 <code>&amp;#8364;</code>.<p>
*
* 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.<p>
*
* @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 <code>\u20ac</code>.<p>
*
* This can be used to escape values used in Java property files.<p>
*
* @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.<p>
*
* 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.<p>
*
* @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 &amp; becomes &amp;#38;.<p>
*
* A character <code>num</code> is replaced if<br>
* <code>((ch != 32) && ((ch > 122) || (ch < 48) || (ch == 60) || (ch == 62)))</code><p>
*
* @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 &amp; becomes &amp;#38;.<p>
*
* A character <code>num</code> is replaced if<br>
* <code>(ch > 255)</code><p>
*
* @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 <code>%20</code>.<p>
*
* @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.<p>
*
* This method replaces the following characters in a String:
* <ul>
* <li><b>&lt;</b> with &amp;lt;
* <li><b>&gt;</b> with &amp;gt;
* <li><b>&amp;</b> with &amp;amp;
* <li><b>&quot;</b> with &amp;quot;
* </ul><p>
*
* @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.<p>
*
* This method replaces the following characters in a String:
* <ul>
* <li><b>&lt;</b> with &amp;lt;
* <li><b>&gt;</b> with &amp;gt;
* <li><b>&amp;</b> with &amp;amp;
* <li><b>&quot;</b> with &amp;quot;
* </ul><p>
*
* @param source the string to escape
* @param doubleEscape if <code>false</code>, 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("&lt;");
break;
case '>':
result.append("&gt;");
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("&amp;");
break;
case '"':
result.append("&quot;");
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.<p>
*
* 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.<p>
*
* Please see <a href="http://www.iana.org/assignments/character-sets">http://www.iana.org/assignments/character-sets</a>
* for a list of valid charset alias names.<p>
*
* @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.<p>
*
* @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);
}
}
@@ -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.<p>
*
*/
public final class ReportStringUtil {
/** Constant for <code>"false"</code>. */
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 <code>"true"</code>. */
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.<p>
*/
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.<p>
*
* @param collection the collection to print
* @param separator the item separator
*
* @return the string representation for the given collection
*/
public static String collectionAsString(Collection<String> collection, String separator) {
StringBuffer string = new StringBuffer(128);
Iterator<String> 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.<p>
*
* This method currently replaces line breaks to <code>&lt;br/&gt;</code> and special HTML chars
* like <code>&lt; &gt; &amp; &quot;</code> with their HTML entity representation.<p>
*
* @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", "<br/>\n");
return source;
}
/**
* Escapes a String so it may be used in JavaScript String definitions.<p>
*
* This method replaces line breaks, quotation marks and \ characters.<p>
*
* @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.<p>
*
* This method replaces the following characters in a String:<br>
* <code>{}[]()\$^.*+/</code><p>
*
* @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.<p>
*
* If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.<p>
*
* @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 <code>true</code> if the provided String is either <code>null</code>
* or the empty String <code>""</code>.<p>
*
* @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 <code>true</code> if the provided String is either <code>null</code>
* or contains only white spaces.<p>
*
* @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 <code>true</code> if the provided Objects are either both <code>null</code>
* or equal according to {@link Object#equals(Object)}.<p>
*
* @param value1 the first object to compare
* @param value2 the second object to compare
*
* @return <code>true</code> if the provided Objects are either both <code>null</code>
* 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 <code>true</code> if the provided String is neither <code>null</code>
* nor the empty String <code>""</code>.<p>
*
* @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 <code>true</code> if the provided String is neither <code>null</code>
* nor contains only white spaces.<p>
*
* @param value the value to check
*
* @return <code>true</code>, if the provided value is <code>null</code>
* or contains only white spaces, <code>false</code> 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.<p>
*
* If no char is found, -1 is returned.<p>
*
* @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.<p>
*
* If no whitespace char is found, -1 is returned.<p>
*
* @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 <code>searchString</code> in the given source String with <code>replaceString</code>.<p>
*
* This is a high-performance implementation which should be used as a replacement for
* <code>{@link String#replaceAll(java.lang.String, java.lang.String)}</code> in case no
* regular expression evaluation is required.<p>
*
* @param source the content which is scanned
* @param searchString the String which is searched in content
* @param replaceString the String which replaces <code>searchString</code>
*
* @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. <p>
*
* This is the form of the String that had to be written into source code
* using the unicode escape sequence for special characters. <p>
*
* Example: "�" would be transformed to "\\u00C4".<p>
*
* @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.<p>
*
* This is the same as calling {@link #trimToSize(String, int, String)} with the
* parameters <code>(source, length, " ...")</code>.<p>
*
* @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.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* This is almost the same as calling {@link #trimToSize(String, int, int, String)} with the
* parameters <code>(source, length, length*, suffix)</code>. If <code>length</code>
* if larger then 100, then <code>length* = length / 2</code>,
* otherwise <code>length* = length</code>.<p>
*
* @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 <code>area</code> chars in the source at a sentence ending char or whitespace.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* @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;
}
}
@@ -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<FileItem> fileItems;
protected File pricatFile;
protected String userLoginId;
protected GenericValue userLogin;
protected String pricatFileVersion;
protected String currencyId;
protected Map<CellReference, String> errorMessages = new HashMap<CellReference, String>();
protected HSSFDataFormatter formatter = new HSSFDataFormatter();
protected Map<String, String[]> facilities = new HashMap<String, String[]>();
protected HttpSession session;
protected List<EntityCondition> basicCategoryConds;
protected List<EntityCondition> 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<String, String[]> 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<XSSFPictureData> pics = workbook.getAllPictures();
List<XSSFShape> 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<Integer, Integer> rowMapping = new HashMap<Integer, Integer>();
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<String> orgPartyIds) {
basicCategoryConds = new ArrayList<EntityCondition>();
basicCategoryConds.add(EntityCondition.makeCondition("isPublic", "N"));
//basicCategoryConds.add(EntityCondition.makeCondition("isDefault", "Y"));
basicBrandConds = new ArrayList<EntityCondition>();
basicBrandConds.add(EntityCondition.makeCondition("isPublic", "N"));
basicBrandConds.add(EntityCondition.makeCondition("productFeatureTypeId", "BRAND"));
List<EntityCondition> partyIdConds = new ArrayList<EntityCondition>();
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<String, Object> updateSkuPrice(String skuId, String ownerPartyId, BigDecimal memberPrice) {
return ServiceUtil.returnSuccess();
}
public Map<String, Object> updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension) {
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("colorId", "sampleColorId");
results.put("dimensionId", "sampleDimensionId");
return results;
}
public Map<String, Object> getDimensionIds(String productId, String ownerPartyId, String dimension) {
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("dimensionId", "sampleDimensionId");
return results;
}
public Map<String, Object> getColorIds(String productId, String ownerPartyId, String color) {
Map<String, Object> 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<Object> getCellContents(XSSFRow row, List<Object[]> colNames, int size) {
List<Object> results = new ArrayList<Object>();
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<GenericValue> 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<GenericValue> valuesToRemove = new ArrayList<GenericValue>();
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);
}
}
}
@@ -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<String> 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<String, String> 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<String> orgPartyIds);
public boolean existsCurrencyId(XSSFSheet sheet);
abstract void parseRowByRow(XSSFSheet sheet);
abstract boolean parseCellContentsAndStore(XSSFRow row, List<Object> cellContents) throws GenericTransactionException;
public Map<String, Object> 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<String, Object> updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension);
public Map<String, Object> getDimensionIds(String productId, String ownerPartyId, String dimension);
public Map<String, Object> 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<Object> cellContents, String colName);
abstract String getProductCategoryId(List<Object> cellContents, String ownerPartyId);
abstract boolean isFacilityOk(XSSFRow row, String facilityName, String facilityId);
abstract List<Object> getCellContents(XSSFRow row, List<Object[]> 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();
}
@@ -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";
}
}
@@ -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.<p>
*
*/
public class PricatParseExcelHtmlReport extends AbstractHtmlReport {
public static final String PRICAT_REPORT_CLASS = "PRICAT_HTML_REPORT";
/**
* Public constructor with report variables.<p>
*
* @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<threads.length; j++) {
Thread threadInstance = threads[j];
if (threadInstance instanceof PricatParseExcelHtmlThread) {
thread = (PricatParseExcelHtmlThread) threadInstance;
break;
}
}
if (thread == null) {
thread = new PricatParseExcelHtmlThread(request, response, name);
}
return thread;
}
public static String checkButton(HttpServletRequest request, HttpServletResponse response) {
String action = request.getParameter("action");
if (ReportStringUtil.isNotEmpty(action)) {
if (action.equalsIgnoreCase("ok")) {
request.removeAttribute(PRICAT_REPORT_CLASS);
request.removeAttribute(DIALOG_URI);
return "ok";
} else if (action.equalsIgnoreCase("cancel")) {
request.removeAttribute(PRICAT_REPORT_CLASS);
request.removeAttribute(DIALOG_URI);
return "cancel";
}
}
action = request.getParameter("ok");
if (ReportStringUtil.isNotEmpty(action)) {
if (action.equalsIgnoreCase("ok")) {
request.removeAttribute(PRICAT_REPORT_CLASS);
request.removeAttribute(DIALOG_URI);
return "ok";
}
}
action = request.getParameter("cancel");
if (ReportStringUtil.isNotEmpty(action)) {
if (action.equalsIgnoreCase("cancel")) {
request.removeAttribute(PRICAT_REPORT_CLASS);
request.removeAttribute(DIALOG_URI);
return "cancel";
}
}
return "success";
}
/**
* Performs the dialog actions depending on the initialized action.<p>
*
* @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());
}
}
}
@@ -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<String> 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<FileItem> fileItems;
private File pricatFile;
private String userLoginId;
private GenericValue userLogin;
private Map<String, String[]> facilities = new HashMap<String, String[]>();
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<String, String> 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<String, String[]> getCurrentUserLoginFacilities() {
getReport().println();
getReport().println(UtilProperties.getMessage(resource, "GetCurrentUserLoginFacility", getLocale()), InterfaceReport.FORMAT_DEFAULT);
Map<String, Object> context = new HashMap<String, Object>();
context.put("userLogin", userLogin);
context.put("locale", getLocale());
try {
List<EntityCondition> orgConditions = new LinkedList<EntityCondition>();
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<GenericValue> 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<EntityCondition> ownerPartyConditions = new LinkedList<EntityCondition>();
Set<String> orgPartyIds = new HashSet<String>();
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<GenericValue> 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<GenericValue> 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;
}
}
@@ -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";
}
}
@@ -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<String, List<Object[]>> ColNamesList = UtilMisc.toMap("V1.1", genExcelHeaderNames("V1.1"));
public static final int headerRowNo = 4;
private List<String> headerColNames = new ArrayList<String>();
public SamplePricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, Map<String, String[]> 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<Object[]> 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<Object> 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<Object> 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<Object> 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<String, Object> 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<String, Object> 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<Object> cellContents, String colName) {
if (UtilValidate.isNotEmpty(headerColNames) && headerColNames.contains(colName)) {
return cellContents.get(headerColNames.indexOf(colName));
}
return null;
}
public String getProductCategoryId(List<Object> 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<Object[]> 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<Object[]> 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<Object[]> genExcelHeaderNamesV1_1() {
List<Object[]> listHeaderName = new ArrayList<Object[]>();
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<Object> getCellContents(XSSFRow row, List<Object[]> colNames, int size) {
List<Object> results = new ArrayList<Object>();
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;
}
}
@@ -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");
}
}
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<site-conf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Site-Conf" xsi:schemaLocation="http://ofbiz.apache.org/Site-Conf http://ofbiz.apache.org/dtds/site-conf.xsd">
<include location="component://common/webcommon/WEB-INF/common-controller.xml"/>
<include location="component://common/webcommon/WEB-INF/portal-controller.xml"/>
<description>PriCat</description>
<!-- define -->
<request-map uri="main">
<security https="true" auth="true"/>
<response name="success" type="view" value="main"/>
</request-map>
<request-map uri="downloadCommentedExcel">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.pricat.PricatEvents" invoke="downloadCommentedExcel"/>
<response name="success" type="none" />
<response name="error" type="none" />
</request-map>
<request-map uri="viewExcelImportLog">
<security https="true" auth="true"/>
<response name="success" type="view" value="viewExcelImportLog"/>
</request-map>
<view-map name="main" type="screen" page="component://pricat/widget/CommonScreens.xml#viewExcelImportHistory"/>
<view-map name="viewExcelImportLog" type="screen" page="component://pricat/widget/CommonScreens.xml#viewExcelImportLog"/>
</site-conf>
@@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<web-app version="3.0">
<display-name>Apache OFBiz - PriCat</display-name>
<description>PriCat Application of the Apache OFBiz Project</description>
<context-param>
<description>A unique name used to identify/recognize the local dispatcher for the Service Engine</description>
<param-name>localDispatcherName</param-name><param-value>pricat</param-value>
</context-param>
<context-param>
<description>The Name of the Entity Delegator to use, defined in entityengine.xml</description>
<param-name>entityDelegatorName</param-name><param-value>default</param-value>
</context-param>
<context-param>
<description>The location of the main-decorator screen to use for this webapp; referred to as a context variable in screen def XML files.</description>
<param-name>mainDecoratorLocation</param-name>
<param-value>component://pricat/widget/SampleScreens.xml</param-value>
</context-param>
<context-param>
<description>Remove unnecessary whitespace from HTML output.</description>
<param-name>compressHTML</param-name>
<param-value>false</param-value>
</context-param>
<filter>
<display-name>ControlFilter</display-name>
<filter-name>ControlFilter</filter-name>
<filter-class>org.apache.ofbiz.webapp.control.ControlFilter</filter-class>
<init-param>
<param-name>allowedPaths</param-name>
<param-value>/error:/control:/select:/index.html:/index.jsp:/default.html:/default.jsp:/images:/js:/ws:/includes</param-value>
</init-param>
<init-param>
<param-name>redirectPath</param-name>
<param-value>/control/main</param-value>
</init-param>
</filter>
<filter>
<display-name>ContextFilter</display-name>
<filter-name>ContextFilter</filter-name>
<filter-class>org.apache.ofbiz.webapp.control.ContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ControlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener><listener-class>org.apache.ofbiz.webapp.control.ControlEventListener</listener-class></listener>
<listener><listener-class>org.apache.ofbiz.webapp.control.LoginEventListener</listener-class></listener>
<!-- NOTE: not all app servers support mounting implementations of the HttpSessionActivationListener interface -->
<!-- <listener><listener-class>org.apache.ofbiz.webapp.control.ControlActivationEventListener</listener-class></listener> -->
<servlet>
<description>Main Control Servlet</description>
<display-name>ControlServlet</display-name>
<servlet-name>ControlServlet</servlet-name>
<servlet-class>org.apache.ofbiz.webapp.control.ControlServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping><servlet-name>ControlServlet</servlet-name><url-pattern>/control/*</url-pattern></servlet-mapping>
<session-config>
<session-timeout>60</session-timeout><!-- in minutes -->
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>
@@ -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.*" %>
<html>
<head>
<title>OFBiz Message</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<% String errorMsg = (String) request.getAttribute("_ERROR_MESSAGE_"); %>
<body bgcolor="#FFFFFF">
<div align="center">
<br/>
<table width="100%" border="1" height="200">
<tr>
<td>
<table width="100%" border="0" height="200">
<tr bgcolor="#CC6666">
<td height="45">
<div align="center"><font face="Verdana, Arial, Helvetica, sans-serif" size="4" color="#FFFFFF"><b>:ERROR MESSAGE:</b></font></div>
</td>
</tr>
<tr>
<td>
<div align="left"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><%=UtilFormatOut.replaceString(errorMsg, "\n", "<br/>")%></font></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div align="center"></div>
</body>
</html>
@@ -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.
-->
<div class="row">
<div class="col-sm-12 m-b-xs text-left p-xs">
<label >${uiLabelMap.ExcelImportHistoryList}</label>
<span class="tooltip pad-left30 top">${uiLabelMap.OnlyYourOwnImportHistoryDisplayed}</span>
</div>
</div>
<div id="loadBody" style="display:none">
</div>
<table id="productlist" name="productlist" class="table table-striped ms-table-primary">
<thead>
<th></th>
<th>${uiLabelMap.SerialNumber}</th>
<th>${uiLabelMap.Filename}</th>
<th>${uiLabelMap.FromDate}</th>
<th>${uiLabelMap.ThruDate}</th>
<th>${uiLabelMap.ImportStatus}</th>
<th>${uiLabelMap.ThruReasonId}</th>
<th>${uiLabelMap.Actions}</th>
</thead>
<tbody>
<#if (data?has_content)>
<#list data as historyEntry>
<tr name="${historyEntry.sequenceNum!}">
<td>
<#if historyEntry.statusId?exists && historyEntry.statusId == 'EXCEL_IMPORTING'>
<img src="/erptheme/images/blue_anime.gif" alt="${uiLabelMap.EXCE_IMPORTING}" tooltip="${uiLabelMap.EXCE_IMPORTING}">
<#elseif historyEntry.statusId?exists && historyEntry.statusId == 'EXCEL_IMPORTED' && historyEntry.thruReasonId?exists && historyEntry.thruReasonId?has_content>
<#if historyEntry.thruReasonId == 'EXCEL_IMPORT_SUCCESS'>
<button id="excel-import-status" data-tooltip="${uiLabelMap.get(historyEntry.thruReasonId)}"><i class="icon-ok-sign success-color">${uiLabelMap.ReasonOK}</i></button>
<#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_STOPPED'>
<button id="excel-import-status" data-tooltip="${uiLabelMap.get(historyEntry.thruReasonId)}"><i class="icon-remove-sign stopped-color">${uiLabelMap.ReasonStopped}</i></button>
<#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_ERROR'>
<button id="excel-import-status" data-tooltip="${uiLabelMap.get(historyEntry.thruReasonId)}"><i class="icon-exclamation-sign error-color"></i>${uiLabelMap.ReasonError}</button>
<#elseif historyEntry.thruReasonId == 'EXCEL_IMPORT_QUEST'>
<button id="excel-import-status" data-tooltip="${uiLabelMap.get(historyEntry.thruReasonId)}"><i class="icon-question-sign question-color"></i>${uiLabelMap.ReasonWarning}</button>
</#if>
</#if>
</td>
<td>${historyEntry.sequenceNum!}</td>
<td style="text-align:right;">${historyEntry.fileName!}</td>
<td><#if historyEntry.fromDate?exists && historyEntry.fromDate?has_content>${historyEntry.fromDate?string("yyyy-MM-dd HH:mm:ss")}</#if></td>
<td><#if historyEntry.thruDate?exists && historyEntry.thruDate?has_content>${historyEntry.thruDate?string("yyyy-MM-dd HH:mm:ss")}</#if></td>
<td><#if historyEntry.statusId?exists && historyEntry.statusId?has_content>${uiLabelMap.get(historyEntry.statusId)}</#if></td>
<td><#if historyEntry.statusId?exists && historyEntry.statusId == "EXCEL_IMPORTED" && historyEntry.thruReasonId?exists && historyEntry.thruReasonId?has_content>${uiLabelMap.get(historyEntry.thruReasonId)}</#if></td>
<td>
<#assign buttons = 0 />
<#if historyEntry.logFileName?exists && historyEntry.logFileName?has_content>
<#if Static["org.apache.ofbiz.base.util.FileUtil"].getFile(historyEntry.logFileName).exists()>
<button id="excel-import-log" type="button" onclick="viewExcelImportLog(${historyEntry.sequenceNum});" data-tooltip="${uiLabelMap.ViewExcelImportLogContent}">
<i class="icon-comments icon-blue">${uiLabelMap.ViewPricatLog}</i>
</button>
<#assign buttons = buttons + 1 />
</#if>
</#if>
<#if buttons == 0>
<#--- <button id="excel-import-empty" type="button"></button> -->
<#assign buttons = buttons + 1 />
</#if>
<#if historyEntry.logFileName?exists && historyEntry.logFileName?has_content>
<#if Static["org.apache.ofbiz.pricat.AbstractPricatParser"].isCommentedExcelExists(request, historyEntry.sequenceNum)>
<button id="excel-import-download" type="button" onclick="downloadCommentedExcel(${historyEntry.sequenceNum});" data-tooltip="${uiLabelMap.DownloadCommentedExcel}">
<i class="icon-download icon-blue">${uiLabelMap.DownloadCommentedPricat}</i>
</button>
<#assign buttons = buttons + 1 />
</#if>
</#if>
<#if buttons == 1>
<#--- <button id="excel-import-empty" type="button"></button> -->
</#if>
</td>
</tr>
</#list>
<#else>
<tr>
<td colspan="10" style="text-align:center;vertical-align:middle;height:60px;">
${uiLabelMap.ExcelImportTipNoData}
</td>
</tr>
</#if>
</tbody>
</table>
<script type="text/javascript" language="JavaScript">
function viewExcelImportLog(sequenceNum) {
document.location = "<@ofbizUrl>viewExcelImportLog</@ofbizUrl>?sequenceNum=" + sequenceNum;
}
function downloadCommentedExcel(sequenceNum) {
document.location = "<@ofbizUrl>downloadCommentedExcel</@ofbizUrl>?sequenceNum=" + sequenceNum;
}
</script>
@@ -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)}
<script language='JavaScript'>
<!--
function a(message) {
parent.append(message);
}
function aH(message) {
parent.appendHead(message);
}
function aW(message) {
parent.appendWarning(message);
}
function aE(message) {
parent.appendError(message);
}
function aN(message) {
parent.appendNote(message);
}
function aO(message) {
parent.appendOk(message);
}
function aT(message) {
parent.appendThrowable(message);
}
function aB() {
parent.appendBr();
}
var active = null;
function init() {
if (active != null) {
clearTimeout(active);
}
<#assign alive = report.isAlive(request)?string("true", "false")>
var alive=${alive};
parent.flushArray();
${StringUtil.wrapString(report.getReportUpdate())}
parent.update();
if (alive) {
active = setTimeout("reload('reportupdate');", 2000);
} else {
var hasNext = "${report.getParamThreadHasNext(request)}";
if (hasNext == "true") {
if (!${report.hasError()?string("true", "false")} || parent.isContinueChecked()) {
// all actions ok or continue checked, continue automatically
continueReport();
} else {
// wait for user interaction
setTimeout('parent.stop();', 10);
}// end hasError
} else {
setTimeout('parent.stop();', 10);
}// end hasNext
}// end alive
}
function reload(actionParam) {
<#assign resName = report.getResourceList(request).get(0)>
var resName = "${resName}";
if (resName != "") {
resName = "&resource=" + encodeURIComponent(resName);
}
<#assign dialogUri = report.getDialogRealUri(request)
thread = report.getParamThread(request)
threadhasnext = report.getParamThreadHasNext(request)>
location.href="${StringUtil.wrapString(dialogUri)}?action=" + actionParam + "&thread=${thread}&threadhasnext=${threadhasnext}" + resName;
}
function continueReport() {
if (!parent.buttonsInitialized) {
parent.initButtons();
}
parent.disableButtons("buttonrowok");
parent.displayButtonRowOk();
parent.hasError = false;
parent.lastError = "";
setTimeout("reload('reportend');", 2000);
if (parent.document.main.threadhasnext) {
parent.document.main.threadhasnext.value = "false";
}
}
// -->
</script>
${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())}
<script type="text/javascript" language="JavaScript">
<!--
// saves the HTML of the extended report format,
// built from the server-side generated JavaScripts
var htmlText = "";
// boolean flag whether this report is still running
var isRunning = false;
// boolean flag whether this report received the output of a warning/error message
var hasError = false;
// saves the last received headline in the report output
var lastHeadline = "";
// saves the last received warning/error message in the report output
var lastError = "";
// array to save the formats of the last received messages
var reportOutputFormats = new Array();
// array to save the last received messages
var reportOutputMessages = new Array();
// format flags for the HTML formatting of the messages
var FORMAT_DEFAULT = 0;
var FORMAT_WARNING = 1;
var FORMAT_HEADLINE = 2;
var FORMAT_NOTE = 3;
var FORMAT_OK = 4;
var FORMAT_NEWLINE = 5;
var FORMAT_THROWABLE = 6;
var FORMAT_ERROR = 7;
// flag indicating that the button rows are initialized
var buttonsInitialized = false;
function append(message) {
reportOutputFormats.push(FORMAT_DEFAULT);
reportOutputMessages.push(message);
}
function appendHead(message) {
reportOutputFormats.push(FORMAT_HEADLINE);
reportOutputMessages.push(message);
lastHeadline = "" + message;
}
function appendWarning(message) {
reportOutputFormats.push(FORMAT_WARNING);
reportOutputMessages.push(message);
}
function appendError(message) {
reportOutputFormats.push(FORMAT_ERROR);
reportOutputMessages.push(message);
hasError = true;
lastError = message;
}
function appendNote(message) {
reportOutputFormats.push(FORMAT_NOTE);
reportOutputMessages.push(message);
}
function appendOk(message) {
reportOutputFormats.push(FORMAT_OK);
reportOutputMessages.push(message);
}
function appendThrowable(message) {
reportOutputFormats.push(FORMAT_THROWABLE);
reportOutputMessages.push(message);
}
function appendBr() {
reportOutputFormats.push(FORMAT_NEWLINE);
reportOutputMessages.push("");
}
var cssStyle =
"<style type='text/css'>\n" +
"body { box-sizing: border-box; -moz-box-sizing: border-box; padding: 2px; margin: 0; color: #000000; background-color:#ffffff; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; }\n" +
"div.main { box-sizing: border-box; -moz-box-sizing: border-box; color: #000000; white-space: nowrap; }\n" +
"span.head { color: #000099; font-weight: bold; }\n" +
"span.note { color: #666666; }\n" +
"span.ok { color: #009900; }\n" +
"span.warn { color: #990000; padding-left: 40px; }\n" +
"span.err { color: #990000; font-weight: bold; padding-left: 40px; }\n" +
"span.throw { color: #990000; font-weight: bold; }\n" +
"span.link1 { color: #666666; }\n" +
"span.link2 { color: #666666; padding-left: 40px; }\n" +
"span.link2 { color: #990000; }\n" +
"</style>\n";
var pageStartSimple =
"<html>\n<head>\n" +
"<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'>\n" +
"<link rel='stylesheet' type='text/css' href='/pricat/includes/pricat.css'>\n" +
cssStyle +
"</head>\n" +
"<body style='background-color:Menu;'>\n" +
"<div style='vertical-align:middle; height: 100%;'>\n"+
"<table border='0' style='vertical-align:middle; height: 100%;'>\n" +
"<tr><td width='40' align='center' valign='middle'><img name='report_img' src='/pricat/images/wait.gif' width='32' height='32' alt=''></td>\n" +
"<td valign='middle'>";
var pageEndSimple =
"</td></tr>\n" +
"</table></div>\n" +
"</body>\n</html>";
var pageStartExtended =
"<html>\n<head>\n" +
"<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'>\n"+
cssStyle +
"</head>\n" +
"<body style='overflow: auto;'>\n" +
"<div class='main'>\n";
var pageEndExtended =
"</div>\n" +
"</body>\n" +
"</html>\n";
function start() {
isRunning = true;
initButtons();
}
function stop() {
isRunning = false;
if (document.main.threadhasnext) {
document.main.threadhasnext.value = "false";
}
enableButtons("buttonrowcontinue");
enableButtons("buttonrowok");
updateReport();
}
// flush the arrays with the report formats and messages
function flushArray() {
reportOutputFormats = new Array();
reportOutputMessages = new Array();
}
// updates the report, builds the HTML string from the JavaScript input
function update() {
var size = 512000;
// resize the HTML string
if (htmlText.length > size) {
htmlText = htmlText.substring(htmlText.length - size, htmlText.length);
var pos = htmlText.indexOf("\n");
if (pos > 0) {
// cut output at the first linebreak to have a "nice" start
htmlText = htmlText.substring(pos, htmlText.length);
}
}
// append the HTML of the extended report format to the HTML string
htmlText += getContentExtended();
// write the HTML output to the iframe
updateReport();
}
// writes the HTML output to the iframe
// this function gets also invoked when the report output format is toggled
function updateReport() {
pageBody = pageStartExtended + htmlText + pageEndExtended;
document.getElementById("report").style.border = "${borderStyle}";
report.document.open();
report.document.write(pageBody);
report.document.close();
setTimeout('doScroll();', 1);
}
// builds the HTML string from the JavaScript input
function getContentExtended() {
var htmlStr = "";
var i = 0;
for (i=0;i<reportOutputFormats.length && i<reportOutputMessages.length;i++) {
switch (reportOutputFormats[i]) {
case FORMAT_WARNING :
htmlStr += "<span class='warn'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_ERROR :
htmlStr += "<span class='err'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_HEADLINE :
htmlStr += "<span class='head'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_NOTE :
htmlStr += "<span class='note'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_OK :
htmlStr += "<span class='ok'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_NEWLINE :
htmlStr += "\n";
break;
case FORMAT_THROWABLE :
htmlStr += "<span class='throw'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_DEFAULT :
default :
htmlStr += "<span>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
}
}
return htmlStr;
}
function doScroll() {
var pos = 1000000;
report.window.scrollTo(0, pos);
}
function isContinueChecked() {
if (document.main.continuereport && document.main.continuereport.checked == true) {
return true;
} else {
return false;
}
}
function displayButtonRowContinue() {
displayButtonRow("buttonrowcontinue", true);
displayButtonRow("checkcontinue", true);
displayButtonRow("buttonrowok", false);
}
function displayButtonRowOk() {
displayButtonRow("buttonrowcontinue", false);
toggleButton("continuereport", true);
displayButtonRow("buttonrowok", true);
}
function displayButtonRow(rowId, show) {
if (show) {
document.getElementById(rowId).className = "show";
} else {
document.getElementById(rowId).className = "hide";
}
}
function enableButtons(rowId) {
if (rowId == "buttonrowcontinue") {
toggleButton("contok", false);
toggleButton("contcancel", false);
} else {
toggleButton("okclose", false);
}
}
function disableButtons(rowId) {
if (rowId == "buttonrowcontinue") {
toggleButton("contok", true);
toggleButton("contcancel", true);
} else {
toggleButton("okclose", true);
toggleButton("okcancel", true);
}
}
function toggleButton(buttonId, disableButton) {
if (document.getElementById(buttonId)) {
document.getElementById(buttonId).disabled = disableButton;
}
}
function initButtons() {
if (document.main.threadhasnext && document.main.threadhasnext.value == "true"
&& document.main.reportcontinuekey && document.main.reportcontinuekey.value != "") {
displayButtonRowContinue();
} else {
displayButtonRowOk();
}
disableButtons("buttonrowcontinue");
disableButtons("buttonrowok");
buttonsInitialized = true;
}
function submitActionRefresh(para1, para2, para3) {
<#if report.getParamRefreshWorkplace()?has_content && report.getParamRefreshWorkplace() == "true">
<#-- workplace must be refresehd (reloaded) -->
top.location.href = "${StringUtil.wrapString(report.getDialogRealUri(request))}";
<#else>
<#-- no workplace refresh required -->
return submitAction(para1, para2, para3);
</#if>
}
function downloadPricat() {
toggleButton("download", true);
var theform = document.forms["main"];
theform.action = "/pricatdemo/control/pricatUpload";
theform.action.value = "downloadPricat";
theform.submit();
return false;
}
function downloadPricat(sequenceNum) {
toggleButton("download", true);
var theform = document.forms["main"];
theform.action = "/pricatdemo/control/pricatUpload";
theform.action.value = "downloadPricat";
theform.sequenceNum.value = sequenceNum;
theform.submit();
return false;
}
//-->
</script>
${StringUtil.wrapString(report.bodyStart("", "onLoad=\"start();\""))}
${StringUtil.wrapString(report.dialogStart())}
<form name="main" action="${StringUtil.wrapString(report.getDialogRealUri(request))}" method="post" class="nomargin" onsubmit="return submitActionRefresh('ok', null, 'main');">
${StringUtil.wrapString(report.dialogContentStart(report.getParamTitle(request)))}
${StringUtil.wrapString(report.paramsAsHidden(request))}
<input type="hidden" name="action" value>
<input type="hidden" name="sequenceNum" value="">
${StringUtil.wrapString(report.reportIntroductionText())}
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="400">
<tr>
<td><iframe name="report" id="report" src="about:blank" frameborder="0" style="width:99.8%; height:400px; padding: 0; margin: 0; border: ${borderStyle};"></iframe></td>
</tr>
</table>
${StringUtil.wrapString(report.reportConclusionText())}
${StringUtil.wrapString(report.dialogContentEnd())}
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="100%" id="buttonrowcontinue" class="hide">
${StringUtil.wrapString(report.dialogButtonsContinue("id=\"contok\" onclick=\"updateWin.continueReport();\"", "id=\"contcancel\""))}
</td></tr>
<tr><td width="100%" id="buttonrowok" class="hide">
${StringUtil.wrapString(report.dialogButtonsOkCancelDownload(request, "id=\"okclose\"", "id=\"okcancel\"", "id=\"download\""))}
</td></tr>
<tr><td>
<#assign resources = "">
<#if report.getResourceListAsParam(request)?has_content>
<#assign resources = report.getResourceListAsParam(request)>
</#if>
<iframe src="${StringUtil.wrapString(report.getDialogRealUri(request))}?action=reportupdate&thread=${report.getParamThread(request)}&threadhasnext=${report.getParamThreadHasNext(request)}<#if resourceParam?has_content>${"&" + resourceParam + "=" + resources}<#else>${""}</#if>" name="updateWin" style="width:20px; height:20px; margin: 0px;" marginwidth="0"
marginheight="0" frameborder="0" framespacing="0" scrolling="no" class='hide'></iframe>
</td></tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" align="center"><tr>
<td class="hide" style="width: 100%; text-align: center;" id="checkcontinue"><input type="checkbox" name="continuereport" id="continuereport" value="true">&nbsp;${StringUtil.wrapString(report.getParamReportContinueKey())}</td>
</tr></table>
</form>
${StringUtil.wrapString(report.dialogEnd())}
${StringUtil.wrapString(report.bodyEnd())}
${StringUtil.wrapString(report.htmlEnd())}
</#switch>
<#-- //////////////////// end of switch statement -->
@@ -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)}
<script language='JavaScript'>
<!--
function a(message) {
parent.append(message);
}
function aH(message) {
parent.appendHead(message);
}
function aW(message) {
parent.appendWarning(message);
}
function aE(message) {
parent.appendError(message);
}
function aN(message) {
parent.appendNote(message);
}
function aO(message) {
parent.appendOk(message);
}
function aT(message) {
parent.appendThrowable(message);
}
function aB() {
parent.appendBr();
}
var active = null;
function init() {
if (active != null) {
clearTimeout(active);
}
<#assign alive = report.isAlive(request)?string("true", "false")>
var alive=${alive};
parent.flushArray();
${StringUtil.wrapString(report.getReportUpdate())}
parent.update();
if (alive) {
active = setTimeout("reload('reportupdate');", 2000);
} else {
var hasNext = "${report.getParamThreadHasNext(request)}";
if (hasNext == "true") {
if (!${report.hasError()?string("true", "false")} || parent.isContinueChecked()) {
// all actions ok or continue checked, continue automatically
continueReport();
} else {
// wait for user interaction
setTimeout('parent.stop();', 10);
}// end hasError
} else {
setTimeout('parent.stop();', 10);
}// end hasNext
}// end alive
}
function reload(actionParam) {
<#assign resName = report.getResourceList(request).get(0)>
var resName = "${resName}";
if (resName != "") {
resName = "&resource=" + encodeURIComponent(resName);
}
<#assign dialogUri = report.getDialogRealUri(request)
thread = report.getParamThread(request)
threadhasnext = report.getParamThreadHasNext(request)>
location.href="${StringUtil.wrapString(dialogUri)}?&action=" + actionParam + "&thread=${thread}&threadhasnext=${threadhasnext}" + resName;
}
function continueReport() {
if (!parent.buttonsInitialized) {
parent.initButtons();
}
parent.disableButtons("buttonrowok");
parent.displayButtonRowOk();
parent.hasError = false;
parent.lastError = "";
setTimeout("reload('reportend');", 2000);
if (parent.document.main.threadhasnext) {
parent.document.main.threadhasnext.value = "false";
}
}
// -->
</script>
${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())}
<script type="text/javascript" language="JavaScript">
<!--
// saves the HTML of the extended report format,
// built from the server-side generated JavaScripts
var htmlText = "";
// boolean flag whether this report is still running
var isRunning = false;
// boolean flag whether this report received the output of a warning/error message
var hasError = false;
// saves the last received headline in the report output
var lastHeadline = "";
// saves the last received warning/error message in the report output
var lastError = "";
// array to save the formats of the last received messages
var reportOutputFormats = new Array();
// array to save the last received messages
var reportOutputMessages = new Array();
// format flags for the HTML formatting of the messages
var FORMAT_DEFAULT = 0;
var FORMAT_WARNING = 1;
var FORMAT_HEADLINE = 2;
var FORMAT_NOTE = 3;
var FORMAT_OK = 4;
var FORMAT_NEWLINE = 5;
var FORMAT_THROWABLE = 6;
var FORMAT_ERROR = 7;
// flag indicating that the button rows are initialized
var buttonsInitialized = false;
function append(message) {
reportOutputFormats.push(FORMAT_DEFAULT);
reportOutputMessages.push(message);
}
function appendHead(message) {
reportOutputFormats.push(FORMAT_HEADLINE);
reportOutputMessages.push(message);
lastHeadline = "" + message;
}
function appendWarning(message) {
reportOutputFormats.push(FORMAT_WARNING);
reportOutputMessages.push(message);
}
function appendError(message) {
reportOutputFormats.push(FORMAT_ERROR);
reportOutputMessages.push(message);
hasError = true;
lastError = message;
}
function appendNote(message) {
reportOutputFormats.push(FORMAT_NOTE);
reportOutputMessages.push(message);
}
function appendOk(message) {
reportOutputFormats.push(FORMAT_OK);
reportOutputMessages.push(message);
}
function appendThrowable(message) {
reportOutputFormats.push(FORMAT_THROWABLE);
reportOutputMessages.push(message);
}
function appendBr() {
reportOutputFormats.push(FORMAT_NEWLINE);
reportOutputMessages.push("");
}
var cssStyle =
"<style type='text/css'>\n" +
"body { box-sizing: border-box; -moz-box-sizing: border-box; padding: 2px; margin: 0; color: #000000; background-color:#ffffff; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; }\n" +
"div.main { box-sizing: border-box; -moz-box-sizing: border-box; color: #000000; white-space: nowrap; }\n" +
"span.head { color: #000099; font-weight: bold; }\n" +
"span.note { color: #666666; }\n" +
"span.ok { color: #009900; }\n" +
"span.warn { color: #990000; padding-left: 40px; }\n" +
"span.err { color: #990000; font-weight: bold; padding-left: 40px; }\n" +
"span.throw { color: #990000; font-weight: bold; }\n" +
"span.link1 { color: #666666; }\n" +
"span.link2 { color: #666666; padding-left: 40px; }\n" +
"span.link2 { color: #990000; }\n" +
"</style>\n";
var pageStartSimple =
"<html>\n<head>\n" +
"<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'>\n" +
"<link rel='stylesheet' type='text/css' href='/pricat/includes/pricat.css'>\n" +
cssStyle +
"</head>\n" +
"<body style='background-color:Menu;'>\n" +
"<div style='vertical-align:middle; height: 100%;'>\n"+
"<table border='0' style='vertical-align:middle; height: 100%;'>\n" +
"<tr><td width='40' align='center' valign='middle'><img name='report_img' src='/pricat/images/wait.gif' width='32' height='32' alt=''></td>\n" +
"<td valign='middle'>";
var pageEndSimple =
"</td></tr>\n" +
"</table></div>\n" +
"</body>\n</html>";
var pageStartExtended =
"<html>\n<head>\n" +
"<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'>\n"+
cssStyle +
"</head>\n" +
"<body style='overflow: auto;'>\n" +
"<div class='main'>\n";
var pageEndExtended =
"</div>\n" +
"</body>\n" +
"</html>\n";
function start() {
isRunning = true;
initButtons();
}
function stop() {
isRunning = false;
if (document.main.threadhasnext) {
document.main.threadhasnext.value = "false";
}
enableButtons("buttonrowcontinue");
enableButtons("buttonrowok");
updateReport();
}
// flush the arrays with the report formats and messages
function flushArray() {
reportOutputFormats = new Array();
reportOutputMessages = new Array();
}
// updates the report, builds the HTML string from the JavaScript input
function update() {
var size = 512000;
// resize the HTML string
if (htmlText.length > size) {
htmlText = htmlText.substring(htmlText.length - size, htmlText.length);
var pos = htmlText.indexOf("\n");
if (pos > 0) {
// cut output at the first linebreak to have a "nice" start
htmlText = htmlText.substring(pos, htmlText.length);
}
}
// append the HTML of the extended report format to the HTML string
htmlText += getContentExtended();
// write the HTML output to the iframe
updateReport();
}
// writes the HTML output to the iframe
// this function gets also invoked when the report output format is toggled
function updateReport() {
pageBody = pageStartExtended + htmlText + pageEndExtended;
document.getElementById("report").style.border = "${borderStyle}";
report.document.open();
report.document.write(pageBody);
report.document.close();
setTimeout('doScroll();', 1);
}
// builds the HTML string from the JavaScript input
function getContentExtended() {
var htmlStr = "";
var i = 0;
for (i=0;i<reportOutputFormats.length && i<reportOutputMessages.length;i++) {
switch (reportOutputFormats[i]) {
case FORMAT_WARNING :
htmlStr += "<span class='warn'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_ERROR :
htmlStr += "<span class='err'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_HEADLINE :
htmlStr += "<span class='head'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_NOTE :
htmlStr += "<span class='note'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_OK :
htmlStr += "<span class='ok'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_NEWLINE :
htmlStr += "\n";
break;
case FORMAT_THROWABLE :
htmlStr += "<span class='throw'>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
break;
case FORMAT_DEFAULT :
default :
htmlStr += "<span>";
htmlStr += reportOutputMessages[i];
htmlStr += "</span>";
}
}
return htmlStr;
}
function doScroll() {
var pos = 1000000;
report.window.scrollTo(0, pos);
}
function isContinueChecked() {
if (document.main.continuereport && document.main.continuereport.checked == true) {
return true;
} else {
return false;
}
}
function displayButtonRowContinue() {
displayButtonRow("buttonrowcontinue", true);
displayButtonRow("checkcontinue", true);
displayButtonRow("buttonrowok", false);
}
function displayButtonRowOk() {
displayButtonRow("buttonrowcontinue", false);
toggleButton("continuereport", true);
displayButtonRow("buttonrowok", true);
}
function displayButtonRow(rowId, show) {
if (show) {
document.getElementById(rowId).className = "show";
} else {
document.getElementById(rowId).className = "hide";
}
}
function enableButtons(rowId) {
if (rowId == "buttonrowcontinue") {
toggleButton("contok", false);
toggleButton("contcancel", false);
} else {
toggleButton("okclose", false);
}
}
function disableButtons(rowId) {
if (rowId == "buttonrowcontinue") {
toggleButton("contok", true);
toggleButton("contcancel", true);
} else {
toggleButton("okclose", true);
toggleButton("okcancel", true);
}
}
function toggleButton(buttonId, disableButton) {
if (document.getElementById(buttonId)) {
document.getElementById(buttonId).disabled = disableButton;
}
}
function initButtons() {
if (document.main.threadhasnext && document.main.threadhasnext.value == "true"
&& document.main.reportcontinuekey && document.main.reportcontinuekey.value != "") {
displayButtonRowContinue();
} else {
displayButtonRowOk();
}
disableButtons("buttonrowcontinue");
disableButtons("buttonrowok");
buttonsInitialized = true;
}
function submitActionRefresh(para1, para2, para3) {
<#if report.getParamRefreshWorkplace()?has_content && report.getParamRefreshWorkplace() == "true">
<#-- workplace must be refresehd (reloaded) -->
top.location.href = "${StringUtil.wrapString(report.getDialogRealUri(request))}";
<#else>
<#-- no workplace refresh required -->
return submitAction(para1, para2, para3);
</#if>
}
//-->
</script>
${StringUtil.wrapString(report.bodyStart("", "onLoad=\"start();\""))}
${StringUtil.wrapString(report.dialogStart())}
<form name="main" action="${StringUtil.wrapString(report.getDialogRealUri(request))}" method="post" class="nomargin" onsubmit="return submitActionRefresh('ok', null, 'main');">
${StringUtil.wrapString(report.dialogContentStart(report.getParamTitle(request)))}
${StringUtil.wrapString(report.paramsAsHidden(request))}
<input type="hidden" name="action" value>
${StringUtil.wrapString(report.reportIntroductionText())}
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="400">
<tr>
<td><iframe name="report" id="report" src="about:blank" frameborder="0" style="width:99.8%; height:400px; padding: 0; margin: 0; border: ${borderStyle};"></iframe></td>
</tr>
</table>
${StringUtil.wrapString(report.reportConclusionText())}
${StringUtil.wrapString(report.dialogContentEnd())}
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="100%" id="buttonrowcontinue" class="hide">
${StringUtil.wrapString(report.dialogButtonsContinue("id=\"contok\" onclick=\"updateWin.continueReport();\"", "id=\"contcancel\""))}
</td></tr>
<tr><td width="100%" id="buttonrowok" class="hide">
${StringUtil.wrapString(report.dialogButtonsOkCancel(request, "id=\"okclose\"", "id=\"okcancel\""))}
</td></tr>
<tr><td>
<#assign resources = "">
<#if report.getResourceListAsParam(request)?has_content>
<#assign resources = report.getResourceListAsParam(request)>
</#if>
<iframe src="${StringUtil.wrapString(report.getDialogRealUri(request))}?action=reportupdate&thread=${report.getParamThread(request)}&threadhasnext=${report.getParamThreadHasNext(request)}<#if resourceParam?has_content>${"&" + resourceParam + "=" + resources}<#else>${""}</#if>" name="updateWin" style="width:20px; height:20px; margin: 0px;" marginwidth="0"
marginheight="0" frameborder="0" framespacing="0" scrolling="no" class='hide'></iframe>
</td></tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" align="center"><tr>
<td class="hide" style="width: 100%; text-align: center;" id="checkcontinue"><input type="checkbox" name="continuereport" id="continuereport" value="true">&nbsp;${StringUtil.wrapString(report.getParamReportContinueKey())}</td>
</tr></table>
</form>
${StringUtil.wrapString(report.dialogEnd())}
${StringUtil.wrapString(report.bodyEnd())}
${StringUtil.wrapString(report.htmlEnd())}
</#switch>
<#-- //////////////////// end of switch statement -->
@@ -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.
-->
<div id="wrapper">
<div id="page-wrapper" class="gray-bg">
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-content text-left p-md">
<#include "component://pricat/webapp/pricat/ftl/ExcelImportHistoryReport.ftl"/>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -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.
-->
<div id="wrapper">
<div id="page-wrapper" class="gray-bg">
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div id="htmlreport" class="ibox-content text-left p-md">
</div>
</div>
</div>
</div>
</div>
</div>
<script language='JavaScript'>
<!--
jQuery(document).ready( function() {
jQuery("#htmlreport").html("${StringUtil.wrapString(logFileContent!)}");
});
//-->
</script>
@@ -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;
}
@@ -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");%>
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<site-conf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Site-Conf" xsi:schemaLocation="http://ofbiz.apache.org/Site-Conf http://ofbiz.apache.org/dtds/site-conf.xsd">
<!-- The controller elements that are common to all OFBiz components
can be found in the following xml file. A component can override the
elements found in the common-controller.xml file. -->
<include location="component://common/webcommon/WEB-INF/common-controller.xml"/>
<include location="component://common/webcommon/WEB-INF/portal-controller.xml"/>
<description>PriCat Demo</description>
<!-- define -->
<request-map uri="main">
<security https="true" auth="true"/>
<response name="success" type="view" value="main"/>
<response name="error" type="view" value="login" />
</request-map>
<request-map uri="countdownreport">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.htmlreport.sample.SampleHtmlReport" invoke="checkButton" />
<response name="success" type="view" value="countdownreport"/>
<response name="ok" type="view" value="main"/>
<response name="cancel" type="view" value="main"/>
</request-map>
<request-map uri="countupreport">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.htmlreport.sample.SampleHtmlReport" invoke="checkButton" />
<response name="success" type="view" value="countupreport"/>
<response name="ok" type="view" value="main"/>
<response name="cancel" type="view" value="main"/>
</request-map>
<request-map uri="SamplePricat">
<security https="true" auth="true"/>
<response name="success" type="view" value="SamplePricat"/>
</request-map>
<request-map uri="downloadExcelTemplate">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.pricat.sample.SamplePricatEvents" invoke="downloadExcelTemplate"/>
<response name="success" type="none" />
<response name="error" type="none" />
</request-map>
<request-map uri="pricatUpload">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.pricat.PricatEvents" invoke="pricatUpload"/>
<response name="success" type="view" value="main"/>
<response name="error" type="view" value="main"/>
<response name="parse_pricat" type="request" value="parseSamplePricat"/>
<response name="download" type="none"/>
</request-map>
<request-map uri="parseSamplePricat">
<security https="true" auth="true"/>
<event type="java" path="org.apache.ofbiz.pricat.PricatParseExcelHtmlReport" invoke="checkButton" />
<response name="success" type="view" value="parseSamplePricat"/>
<response name="ok" type="request" value="SamplePricat"/>
<response name="cancel" type="request" value="main"/>
</request-map>
<view-map name="main" type="screen" page="component://pricat/widget/SampleScreens.xml#main"/>
<view-map name="countdownreport" type="screen" page="component://pricat/widget/SampleScreens.xml#countdownreport"/>
<view-map name="countupreport" type="screen" page="component://pricat/widget/SampleScreens.xml#countupreport"/>
<view-map name="SamplePricat" page="component://pricat/widget/SampleScreens.xml#SamplePricat" type="screen"/>
<view-map name="parseSamplePricat" page="component://pricat/widget/SampleScreens.xml#parseSamplePricat" type="screen"/>
</site-conf>
@@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<web-app version="3.0">
<display-name>Apache OFBiz - PriCat Demo</display-name>
<description>PriCat Demo Application of the Apache OFBiz Project</description>
<context-param>
<description>A unique name used to identify/recognize the local dispatcher for the Service Engine</description>
<param-name>localDispatcherName</param-name><param-value>pricat</param-value>
</context-param>
<context-param>
<description>The Name of the Entity Delegator to use, defined in entityengine.xml</description>
<param-name>entityDelegatorName</param-name><param-value>default</param-value>
</context-param>
<context-param>
<description>The location of the main-decorator screen to use for this webapp; referred to as a context variable in screen def XML files.</description>
<param-name>mainDecoratorLocation</param-name>
<param-value>component://pricat/widget/SampleScreens.xml</param-value>
</context-param>
<context-param>
<description>Remove unnecessary whitespace from HTML output.</description>
<param-name>compressHTML</param-name>
<param-value>false</param-value>
</context-param>
<filter>
<display-name>ControlFilter</display-name>
<filter-name>ControlFilter</filter-name>
<filter-class>org.apache.ofbiz.webapp.control.ControlFilter</filter-class>
<init-param>
<param-name>allowedPaths</param-name>
<param-value>/error:/control:/select:/index.html:/index.jsp:/default.html:/default.jsp:/images:/js:/ws</param-value>
</init-param>
<init-param>
<param-name>redirectPath</param-name>
<param-value>/control/main</param-value>
</init-param>
</filter>
<filter>
<display-name>ContextFilter</display-name>
<filter-name>ContextFilter</filter-name>
<filter-class>org.apache.ofbiz.webapp.control.ContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ControlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener><listener-class>org.apache.ofbiz.webapp.control.ControlEventListener</listener-class></listener>
<listener><listener-class>org.apache.ofbiz.webapp.control.LoginEventListener</listener-class></listener>
<!-- NOTE: not all app servers support mounting implementations of the HttpSessionActivationListener interface -->
<!-- <listener><listener-class>org.apache.ofbiz.webapp.control.ControlActivationEventListener</listener-class></listener> -->
<servlet>
<description>Main Control Servlet</description>
<display-name>ControlServlet</display-name>
<servlet-name>ControlServlet</servlet-name>
<servlet-class>org.apache.ofbiz.webapp.control.ControlServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping><servlet-name>ControlServlet</servlet-name><url-pattern>/control/*</url-pattern></servlet-mapping>
<session-config>
<session-timeout>60</session-timeout><!-- in minutes -->
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>
@@ -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.*" %>
<html>
<head>
<title>OFBiz Message</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<% String errorMsg = (String) request.getAttribute("_ERROR_MESSAGE_"); %>
<body bgcolor="#FFFFFF">
<div align="center">
<br/>
<table width="100%" border="1" height="200">
<tr>
<td>
<table width="100%" border="0" height="200">
<tr bgcolor="#CC6666">
<td height="45">
<div align="center"><font face="Verdana, Arial, Helvetica, sans-serif" size="4" color="#FFFFFF"><b>:ERROR MESSAGE:</b></font></div>
</td>
</tr>
<tr>
<td>
<div align="left"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><%=UtilFormatOut.replaceString(errorMsg, "\n", "<br/>")%></font></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div align="center"></div>
</body>
</html>
@@ -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.
-->
<div class="screenlet">
<div class="screenlet-title-bar">
<ul>
<li class="h3">${uiLabelMap.ParseSamplePricat}</li>
</ul>
<br class="clear"/>
</div>
<div class="screenlet-body">
<form method="post" enctype="multipart/form-data" action="<@ofbizUrl>pricatUpload</@ofbizUrl>">
<input type="hidden" name="action" value="store_excel" />
<input type="file" size="60" name="filename"/><br />
${uiLabelMap.ExcelTemplateType}:
<select name="excelTemplateType" id="excelTemplateType">
<option value="sample_pricat" checked>${uiLabelMap.SamplePricatType}</option>
<option value="ofbiz_pricat">${uiLabelMap.OFBizPricatType}</option>
</select>
<div class="button-bar"><input type="submit" value="${uiLabelMap.UploadPricat}"/></div>
</form>
</div>
</div>
<div class="screenlet">
<div class="screenlet-title-bar">
<ul>
<li class="h3">${uiLabelMap.SamplePricatTemplate}</li>
</ul>
<br class="clear"/>
</div>
<div class="screenlet-body">
<label id="downloadTemplate">
<a href="<@ofbizUrl>downloadExcelTemplate?templateType=pricatExcelTemplate</@ofbizUrl>" target="_BLANK" class="buttontext">${uiLabelMap.DownloadPricatTemplate}</a>
</label>
<br class="clear"/>
</div>
</div>
@@ -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">
@@ -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">
@@ -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.
-->
<div class="screenlet">
<div class="screenlet-title-bar">
<ul>
<li class="h3">${uiLabelMap.PriCatDemoMainPage}</li>
</ul>
<br class="clear"/>
</div>
<div class="screenlet-body">
<br />
<div>${uiLabelMap.PricatDemoMessage}</div>
<br />
<br />
</div>
</div>
@@ -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">
@@ -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");%>
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Widget-Screen" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd">
<screen name="main-decorator">
<section>
<actions>
<set field="activeApp" value="pricat" global="true"/>
<property-map resource="PricatUiLabels" map-name="uiLabelMap" global="true"/>
<property-map resource="CommonUiLabels" map-name="uiLabelMap" global="true"/>
<set field="layoutSettings.companyName" from-field="uiLabelMap.PriCatCompanyName" global="true"/>
<set field="applicationMenuName" value="PriCatAppBar" global="true"/>
<set field="applicationMenuLocation" value="component://pricat/widget/PriCatMenus.xml" global="true"/>
<set field="applicationTitle" value="${uiLabelMap.PriCatApplication}" global="true"/>
<set field="layoutSettings.styleSheets[]" value="/pricat/includes/pricat.css" global="true"/>
</actions>
<widgets>
<include-screen name="GlobalDecorator" location="component://common/widget/CommonScreens.xml"/>
</widgets>
</section>
</screen>
<screen name="viewExcelImportHistory">
<section>
<actions>
<property-map resource="PricatUiLabels" map-name="uiLabelMap" global="true"/>
<property-map resource="CommonUiLabels" map-name="uiLabelMap" global="true"/>
<set field="titleProperty" value="ViewExcelImportHistory"/>
<script location="component://pricat/groovyScripts/pricat/FindMyExcelImport.groovy"/>
</actions>
<widgets>
<decorator-screen name="main-decorator">
<decorator-section name="body">
<platform-specific><html><html-template location="component://pricat/webapp/pricat/ftl/viewExcelImportHistory.ftl"/></html></platform-specific>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
<screen name="viewExcelImportLog">
<section>
<actions>
<property-map resource="PricatUiLabels" map-name="uiLabelMap" global="true"/>
<property-map resource="CommonUiLabels" map-name="uiLabelMap" global="true"/>
<set field="titleProperty" value="ViewExcelImportLogContent"/>
<script location="component://pricat/groovyScripts/pricat/FindMyExcelImportLog.groovy"/>
</actions>
<widgets>
<decorator-screen name="main-decorator">
<decorator-section name="body">
<platform-specific><html><html-template location="component://pricat/webapp/pricat/ftl/viewExcelImportLog.ftl"/></html></platform-specific>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
</screens>
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<menus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Widget-Menu" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Menu http://ofbiz.apache.org/dtds/widget-menu.xsd">
<menu name="PriCatDemoAppBar" title="${uiLabelMap.PriCatDemoApplication}" extends="CommonAppBarMenu" extends-resource="component://common/widget/CommonMenus.xml">
<menu-item name="countdownreport" title="${uiLabelMap.PriCatDemoCountDown}">
<link target="countdownreport"/>
</menu-item>
<menu-item name="countupreport" title="${uiLabelMap.PriCatDemoCountUp}">
<link target="countupreport"/>
</menu-item>
<menu-item name="SamplePricat" title="${uiLabelMap.PriCatDemoParseSamplePricat}">
<link target="SamplePricat"/>
</menu-item>
<menu-item name="main" title="${uiLabelMap.CommonMain}">
<link target="main"/>
</menu-item>
</menu>
</menus>
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<menus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Widget-Menu" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Menu http://ofbiz.apache.org/dtds/widget-menu.xsd">
<menu name="PriCatAppBar" title="${uiLabelMap.PriCatApplication}" extends="CommonAppBarMenu" extends-resource="component://common/widget/CommonMenus.xml">
<menu-item name="main" title="${uiLabelMap.ViewExcelImportHistory}">
<link target="main"/>
</menu-item>
</menu>
</menus>
@@ -0,0 +1,141 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://ofbiz.apache.org/Widget-Screen" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd">
<screen name="main-decorator">
<section>
<actions>
<set field="activeApp" value="pricatdemo" global="true"/>
<property-map resource="PricatUiLabels" map-name="uiLabelMap" global="true"/>
<property-map resource="CommonUiLabels" map-name="uiLabelMap" global="true"/>
<set field="layoutSettings.companyName" from-field="uiLabelMap.PriCatDemoCompanyName" global="true"/>
<set field="applicationMenuName" value="PriCatDemoAppBar" global="true"/>
<set field="applicationMenuLocation" value="component://pricat/widget/PriCatDemoMenus.xml" global="true"/>
<set field="applicationTitle" value="${uiLabelMap.PriCatDemoApplication}" global="true"/>
</actions>
<widgets>
<include-screen name="GlobalDecorator" location="component://common/widget/CommonScreens.xml"/>
</widgets>
</section>
</screen>
<screen name="main">
<section>
<actions>
<set field="tabButtonItem" value="main"></set>
</actions>
<widgets>
<decorator-screen name="main-decorator">
<decorator-section name="body">
<section>
<widgets>
<platform-specific>
<html>
<html-template location="component://pricat/webapp/pricatdemo/ftl/main.ftl"/>
</html>
</platform-specific>
</widgets>
</section>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
<screen name="countdownreport">
<section>
<actions>
<set field="tabButtonItem" value="countdownreport"></set>
</actions>
<widgets>
<decorator-screen name="main-decorator">
<decorator-section name="body">
<section>
<widgets>
<platform-specific>
<html>
<html-template location="component://pricat/webapp/pricatdemo/ftl/countdownreport.ftl"/>
</html>
</platform-specific>
</widgets>
</section>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
<screen name="countupreport">
<section>
<actions>
<set field="tabButtonItem" value="countupreport"></set>
</actions>
<widgets>
<decorator-screen name="main-decorator">
<decorator-section name="body">
<section>
<widgets>
<platform-specific>
<html>
<html-template location="component://pricat/webapp/pricatdemo/ftl/countupreport.ftl"/>
</html>
</platform-specific>
</widgets>
</section>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
<screen name="SamplePricat">
<section>
<actions>
<set field="tabButtonItem" value="SamplePricat"></set>
</actions>
<widgets>
<decorator-screen name="main-decorator" location="${parameters.mainDecoratorLocation}">
<decorator-section name="body">
<platform-specific><html><html-template location="component://pricat/webapp/pricatdemo/ftl/SamplePricat.ftl"/></html></platform-specific>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
<screen name="parseSamplePricat">
<section>
<actions>
<property-map resource="PricatUiLabels" map-name="uiLabelMap" global="true"/>
</actions>
<widgets>
<decorator-screen name="main-decorator" location="${parameters.mainDecoratorLocation}">
<decorator-section name="body">
<platform-specific><html><html-template location="component://pricat/webapp/pricatdemo/ftl/parsePricatExcel.ftl"/></html></platform-specific>
</decorator-section>
</decorator-screen>
</widgets>
</section>
</screen>
</screens>