private void initAnchorsMap(final Workbook wb,
			final ChartsData chartsData) {
		try {
			if (wb instanceof XSSFWorkbook) {
				ChartUtility.initXSSFAnchorsMap((XSSFWorkbook) wb,
						chartsData);
			}
		} catch (Exception e) {
			LOG.log(Level.SEVERE,
					"Web Form getAnchorsMap Error Exception = "
							+ e.getLocalizedMessage(),
					e);
		}
	}

initial anchors map for specified workbook. Excel put the chart position
information in draw.xml instead of chart.xml. anchors map contains the
information getting from draw.xml.

@param wb
specified workbook.
@param chartsData
the charts data

initial anchors map for specified workbook . Excel put the chart position information in draw . xml instead of chart . xml . anchors map contains the information getting from draw . xml .


private void generateSingleXSSFChart(final XSSFChart chart,
			final String chartId, final XSSFSheet sheet,
			final Map<String, ClientAnchor> anchorMap,
			final Map<String, BufferedImage> chartMap,
			final Map<String, ChartData> chartDataMap) {
		ClientAnchor anchor;
		try {
			anchor = anchorMap.get(chartId);
			if (anchor != null) {
				ChartData chartData = ChartUtility
						.initChartDataFromXSSFChart(chartId, chart,
								(XSSFWorkbook) parent.getWb());
				chartDataMap.put(chartId, chartData);
				JFreeChart jchart = createChart(chartData);
				if (jchart != null) {
					AnchorSize anchorSize = PicturesUtility
							.getAnchorSize(sheet, null, null, anchor);
					BufferedImage img = jchart.createBufferedImage(
							anchorSize.getWidth(), anchorSize.getHeight());
					chartMap.put(chartId, img);
				}
			}
		} catch (Exception ex) {
			LOG.log(Level.SEVERE, "generate chart for " + chartId
					+ " error = " + ex.getLocalizedMessage(), ex);
		}
	}

private
void
generateSingleXSSFChart
(
final
XSSFChart
chart
,
final
String
chartId
,
final
XSSFSheet
sheet
,
final
Map
<
String
,
ClientAnchor
>
anchorMap
,
final
Map
<
String
,
BufferedImage
>
chartMap
,
final
Map
<
String
,
ChartData
>
chartDataMap
)
{
ClientAnchor
anchor
;
try
{
anchor
=
anchorMap
.
get
(
chartId
)
;
if
(
anchor
!=
)
{
ChartData
chartData
=
ChartUtility
.
initChartDataFromXSSFChart
(
chartId
,
chart
,
(
XSSFWorkbook
)
parent
.
getWb
(
)
)
;
chartDataMap
.
put
(
chartId
,
chartData
)
;
JFreeChart
jchart
=
createChart
(
chartData
)
;
if
(
jchart
!=
)
{
AnchorSize
anchorSize
=
PicturesUtility
.
getAnchorSize
(
sheet
,
,
,
anchor
)
;
BufferedImage
img
=
jchart
.
createBufferedImage
(
anchorSize
.
getWidth
(
)
,
anchorSize
.
getHeight
(
)
)
;
chartMap
.
put
(
chartId
,
img
)
;
}
}
}
catch
(
Exception
ex
)
{
LOG
.
log
(
Level
.
SEVERE
,
"generate chart for "
+
chartId
+
" error = "
+
ex
.
getLocalizedMessage
(
)
,
ex
)
;
}
}

Generate single XSSF chart.

@param chart
the chart
@param chartId
the chart id
@param sheet
the sheet
@param anchorMap
the anchor map
@param chartMap
the chart map
@param chartDataMap
the chart data map


@SuppressWarnings("rawtypes")
	public static Collection transformToCollectionObject(
			final ExpressionEngine engine, final String collectionName,
			final Map<String, Object> context) {
		Object collectionObject = engine.evaluate(collectionName, context);
		if (!(collectionObject instanceof Collection)) {
			throw new EvaluationException(
					collectionName + " expression is not a collection");
		}
		return (Collection) collectionObject;
	}

@
SuppressWarnings
(
"rawtypes"
)
public
static
Collection
transformToCollectionObject
(
final
ExpressionEngine
engine
,
final
String
collectionName
,
final
Map
<
String
,
Object
>
context
)
{
Object
collectionObject
=
engine
.
evaluate
(
collectionName
,
context
)
;
if
(
!
(
collectionObject
instanceof
Collection
)
)
{
throw
new
EvaluationException
(
collectionName
+
" expression is not a collection"
)
;
}
return
(
Collection
)
collectionObject
;
}

Transform to collection object.

@param engine
the engine
@param collectionName
the collection name
@param context
the context
@return the collection


public static String getFullNameFromRow(final Row row) {
		if (row != null) {
			Cell cell = row.getCell(TieConstants.HIDDEN_FULL_NAME_COLUMN);
			if (cell != null) {
				return cell.getStringCellValue();
			}
		}
		return null;
	}

public static String getFullNameFromRow ( final Row row ) { if ( row != null ) { Cell cell = row . getCell ( TieConstants . HIDDEN_FULL_NAME_COLUMN ) ; if ( cell != null ) { return cell . getStringCellValue ( ) ; } } return null ; }

Gets the full name from row.

@param row
the row
@return the full name from row


public static void reBuildUpperLevelFormula(
			final ConfigBuildRef configBuildRef,
			final String actionFullName) {
		Map<Cell, String> cachedMap = configBuildRef.getCachedCells();
		Map<String, List<RowsMapping>> rowsMap = new HashMap<>();
		for (Map.Entry<Cell, String> entry : cachedMap.entrySet()) {
			Cell cell = entry.getKey();
			String originFormula = entry.getValue();
			if (originFormula != null) {
				setupUpperLevelFormula(cell, originFormula, actionFullName,
						rowsMap, configBuildRef);
			}
		}

	}

public static void reBuildUpperLevelFormula ( final ConfigBuildRef configBuildRef , final String actionFullName ) { Map < Cell , String > cachedMap = configBuildRef . getCachedCells ( ) ; Map < String , List < RowsMapping > > rowsMap = new HashMap <> ( ) ; for ( Map . Entry < Cell , String > entry : cachedMap . entrySet ( ) ) { Cell cell = entry . getKey ( ) ; String originFormula = entry . getValue ( ) ; if ( originFormula != null ) { setupUpperLevelFormula ( cell , originFormula , actionFullName , rowsMap , configBuildRef ) ; } } }

Re build upper level formula.

@param configBuildRef
the config build ref
@param actionFullName
the action full name


private static void setupUpperLevelFormula(final Cell cell,
			final String originFormula, final String actionFullName,
			final Map<String, List<RowsMapping>> rowsMap,
			final ConfigBuildRef configBuildRef) {
		String fullName = getFullNameFromRow(cell.getRow());
		// check wither it's upper level
		if (actionFullName.startsWith(fullName + ":")) {
			// get rows mapping for upper level row
			List<RowsMapping> currentRowsMappingList = rowsMap
					.get(fullName);
			if (currentRowsMappingList == null) {
				currentRowsMappingList = gatherRowsMappingByFullName(
						configBuildRef, fullName);
				rowsMap.put(fullName, currentRowsMappingList);
			}
			ShiftFormulaRef shiftFormulaRef = new ShiftFormulaRef(
					configBuildRef.getWatchList(), currentRowsMappingList);
			shiftFormulaRef.setFormulaChanged(0);
			buildCellFormulaForShiftedRows(configBuildRef.getSheet(),
					configBuildRef.getWbWrapper(), shiftFormulaRef, cell,
					originFormula);
			if (shiftFormulaRef.getFormulaChanged() > 0) {
				configBuildRef.getCachedCells().put(cell, originFormula);
			}

		}
	}

Setup upper level formula.

@param cell
cell.
@param originFormula
originFormula.
@param actionFullName
add full name.
@param rowsMap
rowsmap.
@param configBuildRef
config build ref.


public static void buildCellFormulaForShiftedRows(final Sheet sheet,
			final XSSFEvaluationWorkbook wbWrapper,
			final ShiftFormulaRef shiftFormulaRef, final Cell cell,
			final String originFormula) {
		// only shift when there's watchlist exist.
		if ((shiftFormulaRef.getWatchList() != null)
				&& (!shiftFormulaRef.getWatchList().isEmpty())) {
			Ptg[] ptgs = FormulaParser.parse(originFormula, wbWrapper,
					FormulaType.CELL,
					sheet.getWorkbook().getSheetIndex(sheet));
			Ptg[] convertedFormulaPtg = ShiftFormulaUtility
					.convertSharedFormulas(ptgs, shiftFormulaRef);
			if (shiftFormulaRef.getFormulaChanged() > 0) {
				// only change formula when indicator is true
				cell.setCellFormula(FormulaRenderer
						.toFormulaString(wbWrapper, convertedFormulaPtg));

			}
		}
	}

Builds the cell formula for shifted rows.

@param sheet
the sheet
@param wbWrapper
the wb wrapper
@param shiftFormulaRef
the shift formula ref
@param cell
the cell
@param originFormula
the origin formula

Builds the cell formula for shifted rows .


public static List<RowsMapping> gatherRowsMappingByFullName(
			final ConfigBuildRef configBuildRef, final String fullName) {
		List<RowsMapping> list = new ArrayList<>();
		Map<String, ConfigRangeAttrs> shiftMap = configBuildRef
				.getShiftMap();
		for (Map.Entry<String, ConfigRangeAttrs> entry : shiftMap
				.entrySet()) {
			String fname = entry.getKey();
			if (fname.startsWith(fullName + ":")
					|| fname.equals(fullName)) {
				ConfigRangeAttrs attrs = entry.getValue();
				list.add(attrs.getUnitRowsMapping());
			}
		}
		return list;
	}

public static List < RowsMapping > gatherRowsMappingByFullName ( final ConfigBuildRef configBuildRef , final String fullName ) { List < RowsMapping > list = new ArrayList <> ( ) ; Map < String , ConfigRangeAttrs > shiftMap = configBuildRef . getShiftMap ( ) ; for ( Map . Entry < String , ConfigRangeAttrs > entry : shiftMap . entrySet ( ) ) { String fname = entry . getKey ( ) ; if ( fname . startsWith ( fullName + ":" ) || fname . equals ( fullName ) ) { ConfigRangeAttrs attrs = entry . getValue ( ) ; list . add ( attrs . getUnitRowsMapping ( ) ) ; } } return list ; }

Gather rows mapping by full name.

@param configBuildRef
the config build ref
@param fullName
the full name
@return the list


public static void changeIndexNumberInShiftMap(
			final Map<String, ConfigRangeAttrs> shiftMap,
			final Map<String, String> changeMap) {
		for (Map.Entry<String, String> entry : changeMap.entrySet()) {
			String key = entry.getKey();
			String newKey = entry.getValue();
			ConfigRangeAttrs attrs = shiftMap.get(key);
			if (attrs != null) {
				shiftMap.remove(key);
				shiftMap.put(newKey, attrs);
			}
		}
	}

public static void changeIndexNumberInShiftMap ( final Map < String , ConfigRangeAttrs > shiftMap , final Map < String , String > changeMap ) { for ( Map . Entry < String , String > entry : changeMap . entrySet ( ) ) { String key = entry . getKey ( ) ; String newKey = entry . getValue ( ) ; ConfigRangeAttrs attrs = shiftMap . get ( key ) ; if ( attrs != null ) { shiftMap . remove ( key ) ; shiftMap . put ( newKey , attrs ) ; } } }

Increase index number in shift map.

@param shiftMap
the shift map
@param changeMap
the change map


public static void changeUpperLevelFinalLength(
			final Map<String, ConfigRangeAttrs> shiftMap,
			final String addedFullName, final int increasedLength) {
		String[] parts = addedFullName.split(":");
		StringBuilder fname = new StringBuilder();
		for (int i = 0; i < (parts.length - 1); i++) {
			if (i == 0) {
				fname.append(parts[i]);
			} else {
				fname.append(":").append(parts[i]);
			}
			String sname = fname.toString();
			shiftMap.get(sname).setFinalLength(
					shiftMap.get(sname).getFinalLength() + increasedLength);
		}
	}

public static void changeUpperLevelFinalLength ( final Map < String , ConfigRangeAttrs > shiftMap , final String addedFullName , final int increasedLength ) { String [ ] parts = addedFullName . split ( ":" ) ; StringBuilder fname = new StringBuilder ( ) ; for ( int i = 0 ; i < ( parts . length - 1 ) ; i ++ ) { if ( i == 0 ) { fname . append ( parts [ i ] ) ; } else { fname . append ( ":" ) . append ( parts [ i ] ) ; } String sname = fname . toString ( ) ; shiftMap . get ( sname ) . setFinalLength ( shiftMap . get ( sname ) . getFinalLength ( ) + increasedLength ) ; } }

Increase upper level final length.

@param shiftMap
the shift map
@param addedFullName
the added full name
@param increasedLength
the increased length


public static void changeIndexNumberInHiddenColumn(
			final ConfigBuildRef configBuildRef, final int startRowIndex,
			final String fullName, final Map<String, String> changeMap,
			final int steps) {
		String searchName = fullName.substring(0,
				fullName.lastIndexOf('.') + 1);
		Sheet sheet = configBuildRef.getSheet();
		for (int i = startRowIndex; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			String fname = getFullNameFromRow(row);
			if ((fname != null) && (fname.indexOf(searchName) >= 0)) {
				int sindex = fname.indexOf(searchName);
				String snum = fname.substring(sindex + searchName.length());
				int sufindex = snum.indexOf(':');
				String suffix = "";
				if (sufindex > 0) {
					snum = snum.substring(0, sufindex);
					suffix = ":";
				}
				int increaseNum = Integer.parseInt(snum) + steps;
				String realFullName = fname.substring(sindex);
				String changeName = fname.replace(
						searchName + snum + suffix,
						searchName + increaseNum + suffix);
				if (changeMap.get(realFullName) == null) {
					changeMap.put(realFullName,
							changeName.substring(sindex));
				}
				setFullNameInHiddenColumn(row, changeName);
			} else {
				return;
			}
		}
	}

public static void changeIndexNumberInHiddenColumn ( final ConfigBuildRef configBuildRef , final int startRowIndex , final String fullName , final Map < String , String > changeMap , final int steps ) { String searchName = fullName . substring ( 0 , fullName . lastIndexOf ( ' ' ) + 1 ) ; Sheet sheet = configBuildRef . getSheet ( ) ; for ( int i = startRowIndex ; i <= sheet . getLastRowNum ( ) ; i ++ ) { Row row = sheet . getRow ( i ) ; String fname = getFullNameFromRow ( row ) ; if ( ( fname != null ) && ( fname . indexOf ( searchName ) >= 0 ) ) { int sindex = fname . indexOf ( searchName ) ; String snum = fname . substring ( sindex + searchName . length ( ) ) ; int sufindex = snum . indexOf ( ' ' ) ; String suffix = "" ; if ( sufindex > 0 ) { snum = snum . substring ( 0 , sufindex ) ; suffix = ":" ; } int increaseNum = Integer . parseInt ( snum ) + steps ; String realFullName = fname . substring ( sindex ) ; String changeName = fname . replace ( searchName + snum + suffix , searchName + increaseNum + suffix ) ; if ( changeMap . get ( realFullName ) == null ) { changeMap . put ( realFullName , changeName . substring ( sindex ) ) ; } setFullNameInHiddenColumn ( row , changeName ) ; } else { return ; } } }

Change index number in hidden column.

@param configBuildRef
the config build ref
@param startRowIndex
the start row index
@param fullName
the full name
@param changeMap
the change map
@param steps
the steps ( 1 add -1 delete ).


public static void setFullNameInHiddenColumn(final Row row,
			final String fullName) {
		Cell cell = row.getCell(TieConstants.HIDDEN_FULL_NAME_COLUMN,
				MissingCellPolicy.CREATE_NULL_AS_BLANK);

		cell.setCellValue(fullName);
	}

public static void setFullNameInHiddenColumn ( final Row row , final String fullName ) { Cell cell = row . getCell ( TieConstants . HIDDEN_FULL_NAME_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; cell . setCellValue ( fullName ) ; }

Sets the full name in hidden column.

@param row
the row
@param fullName
the full name


public static int getOriginalRowNumInHiddenColumn(final Row row) {
		if (row != null) {
			Cell cell = row.getCell(
					TieConstants.HIDDEN_ORIGIN_ROW_NUMBER_COLUMN,
					MissingCellPolicy.CREATE_NULL_AS_BLANK);
			String rowNum = cell.getStringCellValue();
			try {
				if ((rowNum != null) && (!rowNum.isEmpty())
						&& (WebSheetUtility.isNumeric(rowNum))) {
					return Integer.parseInt(rowNum);
				}

			} catch (Exception ex) {
				LOG.log(Level.SEVERE,
						"getOriginalRowNumInHiddenColumn rowNum = " + rowNum
								+ " error = " + ex.getLocalizedMessage(),
						ex);

			}
		}
		return -1;
	}

Gets the original row num in hidden column.

@param row
the row
@return the original row num in hidden column

Gets the original row num in hidden column .


public static void setOriginalRowNumInHiddenColumn(final Row row,
			final int rowNum) {
		Cell cell = row.getCell(
				TieConstants.HIDDEN_ORIGIN_ROW_NUMBER_COLUMN,
				MissingCellPolicy.CREATE_NULL_AS_BLANK);
		cell.setCellValue(Integer.toString(rowNum));
		cell.setCellType(CellType.STRING);
	}

public static void setOriginalRowNumInHiddenColumn ( final Row row , final int rowNum ) { Cell cell = row . getCell ( TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; cell . setCellValue ( Integer . toString ( rowNum ) ) ; cell . setCellType ( CellType . STRING ) ; }

Sets the original row num in hidden column.

@param row
the row.
@param rowNum
row number.

Sets the original row num in hidden column .


public static List<RowsMapping> findParentRowsMappingFromShiftMap(
			final String[] parts,
			final Map<String, ConfigRangeAttrs> shiftMap) {

		StringBuilder fullName = new StringBuilder();
		List<RowsMapping> rowsMappingList = new ArrayList<>();
		/**
		 * skip first one and last one. first one is line no. last one is it's
		 * self.
		 */
		for (int i = 1; i < parts.length - 1; i++) {
			String part = parts[i];
			if (fullName.length() == 0) {
				fullName.append(part);
			} else {
				fullName.append(":" + part);
			}
			if (fullName.length() > 0) {
				ConfigRangeAttrs rangeAttrs = shiftMap
						.get(fullName.toString());
				if (rangeAttrs != null) {
					rowsMappingList.add(rangeAttrs.getUnitRowsMapping());
				}
			}
		}
		return rowsMappingList;
	}

Find parent rows mapping from shift map.

@param parts
the parts
@param shiftMap
the shift map
@return the list

Find parent rows mapping from shift map .


public static List<RowsMapping> findChildRowsMappingFromShiftMap(
			final String fullName,
			final NavigableMap<String, ConfigRangeAttrs> shiftMap) {

		List<RowsMapping> rowsMappingList = new ArrayList<>();
		NavigableMap<String, ConfigRangeAttrs> tailmap = shiftMap
				.tailMap(fullName, false);
		for (Map.Entry<String, ConfigRangeAttrs> entry : tailmap
				.entrySet()) {
			String key = entry.getKey();
			// check it's children
			if (key.startsWith(fullName)) {
				rowsMappingList.add(entry.getValue().getUnitRowsMapping());
			} else {
				break;
			}
		}
		return rowsMappingList;
	}

public
static
List
<
RowsMapping
>
findChildRowsMappingFromShiftMap
(
final
String
fullName
,
final
NavigableMap
<
String
,
ConfigRangeAttrs
>
shiftMap
)
{
List
<
RowsMapping
>
rowsMappingList
=
new
ArrayList
<>
(
)
;
NavigableMap
<
String
,
ConfigRangeAttrs
>
tailmap
=
shiftMap
.
tailMap
(
fullName
,
false
)
;
for
(
Map
.
Entry
<
String
,
ConfigRangeAttrs
>
entry
:
tailmap
.
entrySet
(
)
)
{
String
key
=
entry
.
getKey
(
)
;
// check it's children
if
(
key
.
startsWith
(
fullName
)
)
{
rowsMappingList
.
add
(
entry
.
getValue
(
)
.
getUnitRowsMapping
(
)
)
;
}
else
{
break
;
}
}
return
rowsMappingList
;
}

Find child rows mapping from shift map.

@param fullName
the full name
@param shiftMap
the shift map
@return the list

Find child rows mapping from shift map .


@SuppressWarnings("rawtypes")
	public static Object findItemInCollection(final Collection collection,
			final int index) {
		if (index >= 0) {
			if (collection instanceof List) {
				List list = (List) collection;
				return list.get(index);
			}
			int i = 0;
			for (Object object : collection) {
				if (i == index) {
					return object;
				}
				i++;
			}

		}
		return null;
	}

@ SuppressWarnings ( "rawtypes" ) public static Object findItemInCollection ( final Collection collection , final int index ) { if ( index >= 0 ) { if ( collection instanceof List ) { List list = ( List ) collection ; return list . get ( index ) ; } int i = 0 ; for ( Object object : collection ) { if ( i == index ) { return object ; } i ++ ; } } return null ; }

Find item in collection.

@param collection
the collection
@param index
the index
@return the object


public static ConfigRange buildCurrentRange(
			final ConfigRange sourceConfigRange, final Sheet sheet,
			final int insertPosition) {
		ConfigRange current = new ConfigRange(sourceConfigRange);
		int shiftNum = insertPosition
				- sourceConfigRange.getFirstRowAddr().getRow();
		current.shiftRowRef(sheet, shiftNum);
		return current;
	}

public static ConfigRange buildCurrentRange ( final ConfigRange sourceConfigRange , final Sheet sheet , final int insertPosition ) { ConfigRange current = new ConfigRange ( sourceConfigRange ) ; int shiftNum = insertPosition - sourceConfigRange . getFirstRowAddr ( ) . getRow ( ) ; current . shiftRowRef ( sheet , shiftNum ) ; return current ; }

Builds the current range.

@param sourceConfigRange
the source config range
@param sheet
the sheet
@param insertPosition
the insert position
@return the config range


public static boolean isStaticRow(final ConfigRange sourceConfigRange,
			final int rowIndex) {
		if (sourceConfigRange.getCommandList() != null) {
			for (int i = 0; i < sourceConfigRange.getCommandList()
					.size(); i++) {
				Command command = sourceConfigRange.getCommandList().get(i);
				if ((rowIndex >= command.getConfigRange().getFirstRowAddr()
						.getRow())
						&& (rowIndex < (command.getConfigRange()
								.getLastRowPlusAddr().getRow()))) {
					return false;
				}
			}
		}
		return true;
	}

public static boolean isStaticRow ( final ConfigRange sourceConfigRange , final int rowIndex ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; if ( ( rowIndex >= command . getConfigRange ( ) . getFirstRowAddr ( ) . getRow ( ) ) && ( rowIndex < ( command . getConfigRange ( ) . getLastRowPlusAddr ( ) . getRow ( ) ) ) ) { return false ; } } } return true ; }

Whether the row is static. This only check rowIndex against original
template.

@param sourceConfigRange
the source config range
@param rowIndex
the row index
@return true is static false is not.

Whether the row is static . This only check rowIndex against original template .


public static boolean isStaticRowRef(
			final ConfigRange sourceConfigRange, final Row row) {
		if (sourceConfigRange.getCommandList() != null) {
			for (int i = 0; i < sourceConfigRange.getCommandList()
					.size(); i++) {
				Command command = sourceConfigRange.getCommandList().get(i);
				int rowIndex = row.getRowNum();
				if ((rowIndex >= command.getTopRow())
						&& (rowIndex < (command.getTopRow()
								+ command.getFinalLength()))) {
					return false;
				}
			}
		}
		return true;
	}

public static boolean isStaticRowRef ( final ConfigRange sourceConfigRange , final Row row ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; int rowIndex = row . getRowNum ( ) ; if ( ( rowIndex >= command . getTopRow ( ) ) && ( rowIndex < ( command . getTopRow ( ) + command . getFinalLength ( ) ) ) ) { return false ; } } } return true ; }

Whether the row is static.This check row after shifted.

@param sourceConfigRange
the source config range
@param row
the row for check.
@return true is static false is not.

Whether the row is static . This check row after shifted .


public static String replaceExpressionWithCellValue(
			final String attrValue, final int rowIndex, final Sheet sheet) {

		int ibegin = 0;
		int ifind;
		int inameEnd;
		String tempStr;
		String findStr;
		String replaceStr;
		String returnStr = attrValue;
		while ((ifind = attrValue.indexOf(TieConstants.CELL_ADDR_PRE_FIX,
				ibegin)) > 0) {
			inameEnd = ParserUtility.findFirstNonCellNamePosition(attrValue, ifind);
			if (inameEnd > 0) {
				findStr = attrValue.substring(ifind, inameEnd);
			} else {
				findStr = attrValue.substring(ifind);
			}
			if (findStr.indexOf(TieConstants.CELL_ADDR_PRE_FIX, 1) < 0) {
				// only $A
				tempStr = findStr + TieConstants.CELL_ADDR_PRE_FIX
						+ (rowIndex + 1);
			} else {
				tempStr = findStr;
			}
			replaceStr = CellUtility.getCellValueWithoutFormat(
					WebSheetUtility.getCellByReference(tempStr, sheet));
			if (replaceStr == null) {
				replaceStr = "";
			}
			returnStr = attrValue.replace(findStr, replaceStr);

			ibegin = ifind + 1;

		}
		return returnStr;
	}

public
static
String
replaceExpressionWithCellValue
(
final
String
attrValue
,
final
int
rowIndex
,
final
Sheet
sheet
)
{
int
ibegin
=
0
;
int
ifind
;
int
inameEnd
;
String
tempStr
;
String
findStr
;
String
replaceStr
;
String
returnStr
=
attrValue
;
while
(
(
ifind
=
attrValue
.
indexOf
(
TieConstants
.
CELL_ADDR_PRE_FIX
,
ibegin
)
)
>
0
)
{
inameEnd
=
ParserUtility
.
findFirstNonCellNamePosition
(
attrValue
,
ifind
)
;
if
(
inameEnd
>
0
)
{
findStr
=
attrValue
.
substring
(
ifind
,
inameEnd
)
;
}
else
{
findStr
=
attrValue
.
substring
(
ifind
)
;
}
if
(
findStr
.
indexOf
(
TieConstants
.
CELL_ADDR_PRE_FIX
,
1
)
<
0
)
{
// only $A
tempStr
=
findStr
+
TieConstants
.
CELL_ADDR_PRE_FIX
+
(
rowIndex
+
1
)
;
}
else
{
tempStr
=
findStr
;
}
replaceStr
=
CellUtility
.
getCellValueWithoutFormat
(
WebSheetUtility
.
getCellByReference
(
tempStr
,
sheet
)
)
;
if
(
replaceStr
==
)
{
replaceStr
=
""
;
}
returnStr
=
attrValue
.
replace
(
findStr
,
replaceStr
)
;
ibegin
=
ifind
+
1
;
}
return
returnStr
;
}


public static Map<String, CellRangeAddress> indexMergedRegion(
			final Sheet sheet1) {

		int numRegions = sheet1.getNumMergedRegions();
		Map<String, CellRangeAddress> cellRangeMap = new HashMap<>();
		for (int i = 0; i < numRegions; i++) {

			CellRangeAddress caddress = sheet1.getMergedRegion(i);
			if (caddress != null) {
				cellRangeMap.put(CellUtility.getCellIndexNumberKey(
						caddress.getFirstColumn(), caddress.getFirstRow()),
						caddress);
			}
		}
		return cellRangeMap;
	}

public static Map < String , CellRangeAddress > indexMergedRegion ( final Sheet sheet1 ) { int numRegions = sheet1 . getNumMergedRegions ( ) ; Map < String , CellRangeAddress > cellRangeMap = new HashMap <> ( ) ; for ( int i = 0 ; i < numRegions ; i ++ ) { CellRangeAddress caddress = sheet1 . getMergedRegion ( i ) ; if ( caddress != null ) { cellRangeMap . put ( CellUtility . getCellIndexNumberKey ( caddress . getFirstColumn ( ) , caddress . getFirstRow ( ) ) , caddress ) ; } } return cellRangeMap ; }

Index merged region.

@param sheet1
the sheet 1
@return the map


public static List<String> skippedRegionCells(final Sheet sheet1) {
		int numRegions = sheet1.getNumMergedRegions();
		List<String> skipCellList = new ArrayList<>();
		for (int i = 0; i < numRegions; i++) {

			CellRangeAddress caddress = sheet1.getMergedRegion(i);
			if (caddress != null) {
				addSkipCellToListInTheRegion(skipCellList, caddress);
			}
		}
		return skipCellList;
	}

public static List < String > skippedRegionCells ( final Sheet sheet1 ) { int numRegions = sheet1 . getNumMergedRegions ( ) ; List < String > skipCellList = new ArrayList <> ( ) ; for ( int i = 0 ; i < numRegions ; i ++ ) { CellRangeAddress caddress = sheet1 . getMergedRegion ( i ) ; if ( caddress != null ) { addSkipCellToListInTheRegion ( skipCellList , caddress ) ; } } return skipCellList ; }

Skipped region cells.

@param sheet1
the sheet 1
@return the list


private static void addSkipCellToListInTheRegion(
			final List<String> skipCellList,
			final CellRangeAddress caddress) {
		for (int col = caddress.getFirstColumn(); col <= caddress
				.getLastColumn(); col++) {
			for (int row = caddress.getFirstRow(); row <= caddress
					.getLastRow(); row++) {
				if ((col == caddress.getFirstColumn())
						&& (row == caddress.getFirstRow())) {
					continue;
				}
				skipCellList
						.add(CellUtility.getCellIndexNumberKey(col, row));
			}
		}
	}

private static void addSkipCellToListInTheRegion ( final List < String > skipCellList , final CellRangeAddress caddress ) { for ( int col = caddress . getFirstColumn ( ) ; col <= caddress . getLastColumn ( ) ; col ++ ) { for ( int row = caddress . getFirstRow ( ) ; row <= caddress . getLastRow ( ) ; row ++ ) { if ( ( col == caddress . getFirstColumn ( ) ) && ( row == caddress . getFirstRow ( ) ) ) { continue ; } skipCellList . add ( CellUtility . getCellIndexNumberKey ( col , row ) ) ; } } }

Add skipped cell into the list of a region.

@param skipCellList
list.
@param caddress
region.

Add skipped cell into the list of a region .


public static void buildSheetCommentFromAlias(Sheet sheet, List<TieCommandAlias> tieCommandAliasList) {

		if ((tieCommandAliasList == null)||(tieCommandAliasList.isEmpty())) {
			return;
		}
        for (Row row : sheet) {
            for (Cell cell : row) {
                buildCellCommentFromalias(tieCommandAliasList, cell);
            }
        }

	}

public static void buildSheetCommentFromAlias ( Sheet sheet , List < TieCommandAlias > tieCommandAliasList ) { if ( ( tieCommandAliasList == null ) || ( tieCommandAliasList . isEmpty ( ) ) ) { return ; } for ( Row row : sheet ) { for ( Cell cell : row ) { buildCellCommentFromalias ( tieCommandAliasList , cell ) ; } } }

Build Sheet Comment From command alias.

@param sheet sheet.
@param tieCommandAliasList 			list of ommand alias

Build Sheet Comment From command alias .


private static void buildCellCommentFromalias(List<TieCommandAlias> tieCommandAliasList, Cell cell) {
		String value = CellUtility.getCellValueWithoutFormat(cell);
		if ((value!=null)&&(!value.isEmpty())) {
			for (TieCommandAlias alias : tieCommandAliasList) {
				Matcher matcher = alias.getPattern().matcher(value);
				if (matcher.find()) {
					CellUtility.createOrInsertComment(cell, alias.getCommand());
					if (alias.isRemove()) {
						CellUtility.setCellValue(cell, ParserUtility.removeCharsFromString(value, matcher.start(), matcher.end()));
					}
				}
			}
		}
	}

private static void buildCellCommentFromalias ( List < TieCommandAlias > tieCommandAliasList , Cell cell ) { String value = CellUtility . getCellValueWithoutFormat ( cell ) ; if ( ( value != null ) && ( ! value . isEmpty ( ) ) ) { for ( TieCommandAlias alias : tieCommandAliasList ) { Matcher matcher = alias . getPattern ( ) . matcher ( value ) ; if ( matcher . find ( ) ) { CellUtility . createOrInsertComment ( cell , alias . getCommand ( ) ) ; if ( alias . isRemove ( ) ) { CellUtility . setCellValue ( cell , ParserUtility . removeCharsFromString ( value , matcher . start ( ) , matcher . end ( ) ) ) ; } } } } }

Builds the cell comment fromalias.

@param tieCommandAliasList the tie command alias list
@param cell the cell


public final Map<String, SheetConfiguration> buildConfiguration() {

		Map<String, SheetConfiguration> sheetConfigMap = new LinkedHashMap<>();
		// in buildsheet, it's possible to add sheets in workbook.
		// so cache the sheetname first here.
		List<String> sheetNames = new ArrayList<>();
		String sname;
		for (int i = 0; i < parent.getWb().getNumberOfSheets(); i++) {
			sname = parent.getWb().getSheetName(i);
			if (!sname.startsWith(org.tiefaces.common.TieConstants.COPY_SHEET_PREFIX)) {
				sheetNames.add(sname);
			}
		}

		for (String sheetName : sheetNames) {
			Sheet sheet = parent.getWb().getSheet(sheetName);
			ConfigurationUtility.buildSheetCommentFromAlias(sheet, parent.getTieCommandAliasList());
			buildSheet(sheet, sheetConfigMap, parent.getCellAttributesMap());
		}
		return sheetConfigMap;

	}

Builds the configuration.

@return the map


private SheetConfiguration getSheetConfiguration(final Sheet sheet, final String formName,
			final int sheetRightCol) {

		SheetConfiguration sheetConfig = new SheetConfiguration();
		sheetConfig.setFormName(formName);
		sheetConfig.setSheetName(sheet.getSheetName());
		int leftCol = sheet.getLeftCol();
		int lastRow = sheet.getLastRowNum();
		int firstRow = sheet.getFirstRowNum();
		int rightCol = 0;
		int maxRow = 0;
		for (Row row : sheet) {
			if (row.getRowNum() > TieConstants.TIE_WEB_SHEET_MAX_ROWS) {
				break;
			}
			maxRow = row.getRowNum();
			int firstCellNum = row.getFirstCellNum();
			if (firstCellNum >= 0 && firstCellNum < leftCol) {
				leftCol = firstCellNum;
			}
			if ((row.getLastCellNum() - 1) > rightCol) {
				int verifiedcol = verifyLastCell(row, rightCol, sheetRightCol);
				if (verifiedcol > rightCol) {
					rightCol = verifiedcol;
				}
			}
		}
		if (maxRow < lastRow) {
			lastRow = maxRow;
		}
		// header range row set to 0 while column set to first column to
		// max
		// column (FF) e.g. $A$0 : $FF$0
		String tempStr = TieConstants.CELL_ADDR_PRE_FIX + WebSheetUtility.getExcelColumnName(leftCol)
				+ TieConstants.CELL_ADDR_PRE_FIX + "0 : " + TieConstants.CELL_ADDR_PRE_FIX
				+ WebSheetUtility.getExcelColumnName(rightCol) + TieConstants.CELL_ADDR_PRE_FIX + "0";
		sheetConfig.setFormHeaderRange(tempStr);
		sheetConfig.setHeaderCellRange(new CellRange(tempStr));
		// body range row set to first row to last row while column set
		// to
		// first column to max column (FF) e.g. $A$1 : $FF$1000
		tempStr = TieConstants.CELL_ADDR_PRE_FIX + WebSheetUtility.getExcelColumnName(leftCol)
				+ TieConstants.CELL_ADDR_PRE_FIX + (firstRow + 1) + " : " + TieConstants.CELL_ADDR_PRE_FIX
				+ WebSheetUtility.getExcelColumnName(rightCol) + TieConstants.CELL_ADDR_PRE_FIX + (lastRow + 1);
		sheetConfig.setFormBodyRange(tempStr);
		sheetConfig.setBodyCellRange(new CellRange(tempStr));
		sheetConfig.setFormBodyType(org.tiefaces.common.TieConstants.FORM_TYPE_FREE);
		sheetConfig.setCellFormAttributes(new HashMap<String, List<CellFormAttributes>>());

		// check it's a hidden sheet
		int sheetIndex = parent.getWb().getSheetIndex(sheet);
		if (parent.getWb().isSheetHidden(sheetIndex) || parent.getWb().isSheetVeryHidden(sheetIndex)) {
			sheetConfig.setHidden(true);
		}

		return sheetConfig;

	}

Gets the sheet configuration.

@param sheet
the sheet
@param formName
the form name
@param sheetRightCol
the sheet right col
@return the sheet configuration


private FormCommand buildFormCommandFromSheetConfig(final SheetConfiguration sheetConfig, final Sheet sheet) {

		int firstRow = sheetConfig.getBodyCellRange().getTopRow();
		int leftCol = sheetConfig.getBodyCellRange().getLeftCol();
		int rightCol = sheetConfig.getBodyCellRange().getRightCol();
		int lastRow = sheetConfig.getBodyCellRange().getBottomRow();

		Cell firstCell = sheet.getRow(firstRow).getCell(leftCol, MissingCellPolicy.CREATE_NULL_AS_BLANK);

		FormCommand fcommand = new FormCommand();
		fcommand.setCommandTypeName(TieConstants.COMMAND_FORM);
		if (sheetConfig.isHidden()) {
			fcommand.setHidden(TieConstants.TRUE_STRING);
		} else {
			fcommand.setHidden(TieConstants.FALSE_STRING);
		}
		fcommand.setName(sheetConfig.getFormName());
		fcommand.getConfigRange().setFirstRowRef(firstCell, true);
		fcommand.getConfigRange().setLastRowPlusRef(sheet, rightCol, lastRow, true);
		fcommand.setHeaderLength("0");
		fcommand.setFooterLength("0");
		fcommand.setLength(Integer.toString(lastRow - firstRow + 1));
		return fcommand;
	}

private FormCommand buildFormCommandFromSheetConfig ( final SheetConfiguration sheetConfig , final Sheet sheet ) { int firstRow = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int leftCol = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int rightCol = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; int lastRow = sheetConfig . getBodyCellRange ( ) . getBottomRow ( ) ; Cell firstCell = sheet . getRow ( firstRow ) . getCell ( leftCol , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; FormCommand fcommand = new FormCommand ( ) ; fcommand . setCommandTypeName ( TieConstants . COMMAND_FORM ) ; if ( sheetConfig . isHidden ( ) ) { fcommand . setHidden ( TieConstants . TRUE_STRING ) ; } else { fcommand . setHidden ( TieConstants . FALSE_STRING ) ; } fcommand . setName ( sheetConfig . getFormName ( ) ) ; fcommand . getConfigRange ( ) . setFirstRowRef ( firstCell , true ) ; fcommand . getConfigRange ( ) . setLastRowPlusRef ( sheet , rightCol , lastRow , true ) ; fcommand . setHeaderLength ( "0" ) ; fcommand . setFooterLength ( "0" ) ; fcommand . setLength ( Integer . toString ( lastRow - firstRow + 1 ) ) ; return fcommand ; }

Builds the form command from sheet config.

@param sheetConfig
the sheet config
@param sheet
the sheet
@return the form command

Builds the form command from sheet config .


private int verifyLastCell(final Row row, final int stoppoint, final int sheetRightCol) {

		int lastCol = sheetRightCol;
		int col;
		for (col = lastCol; col >= stoppoint; col--) {

			Cell cell = row.getCell(col);
			if ((cell != null) && (cell.getCellTypeEnum() != CellType.BLANK)) {
				break;
			}
		}
		return col;
	}

private int verifyLastCell ( final Row row , final int stoppoint , final int sheetRightCol ) { int lastCol = sheetRightCol ; int col ; for ( col = lastCol ; col >= stoppoint ; col -- ) { Cell cell = row . getCell ( col ) ; if ( ( cell != null ) && ( cell . getCellTypeEnum ( ) != CellType . BLANK ) ) { break ; } } return col ; }

check last column. if it's blank then treat it as null cell.

@param row
row object.
@param stoppoint
the left cell we want to stop check.
@param sheetRightCol
the sheet right col
@return integer. the last column without blank cell.

check last column . if it s blank then treat it as null cell .


public final void buildSheet(final Sheet sheet, final Map<String, SheetConfiguration> sheetConfigMap,
			final CellAttributesMap cellAttributesMap) {

		if ((sheet.getLastRowNum() <= 0) && (sheet.getRow(0) == null)) {
			// this is a empty sheet. skip it.
			return;
		}
		checkAndRepairLastRow(sheet);

		int sheetRightCol = WebSheetUtility.getSheetRightCol(sheet);

		List<ConfigCommand> commandList = buildCommandListFromSheetComment((XSSFSheet) sheet, sheetRightCol,
				cellAttributesMap);

		boolean hasEachCommand = hasEachCommandInTheList(commandList);

		List<String> formList = new ArrayList<>();

		buildSheetConfigMapFromFormCommand(sheet, sheetConfigMap, commandList, formList, sheetRightCol);
		// match parent command
		matchParentCommand(commandList);
		// setup save attrs in hidden column in the sheet.
		// loop command list again to assemble other command list into sheet
		// configuration
		matchSheetConfigForm(sheetConfigMap, commandList, formList);
		initTemplateForCommand(sheet, sheetConfigMap, formList, hasEachCommand);
	}

build a sheet for configuration map.

@param sheet
sheet.
@param sheetConfigMap
sheetConfiguration map.
@param cellAttributesMap
the cell attributes map


private final void checkAndRepairLastRow(final Sheet sheet) {
		// repair last row if it's inserted in the configuration generation
		Row lastrow = sheet.getRow(sheet.getLastRowNum());
		// if it's lastrow and all the cells are blank. then remove the lastrow.
		if (lastrow != null) {
			for (Cell cell : lastrow) {
				if ((cell.getCellTypeEnum() != CellType._NONE) && (cell.getCellTypeEnum() != CellType.BLANK)) {
					return;
				}
			}
			sheet.removeRow(lastrow);
		}

	}

check and repair the sheet's lastrow. If the row is blank then remove it.

@param sheet
the sheet

check and repair the sheet s lastrow . If the row is blank then remove it .


private List<ConfigCommand> buildCommandListFromSheetComment(final XSSFSheet sheet, final int sheetRightCol,
			final CellAttributesMap cellAttributesMap) {
		List<ConfigCommand> commandList = new ArrayList<>();
		// if skip then return empty list.
		if (parent.isSkipConfiguration()) {
			return commandList;
		}

		Map<CellAddress, ? extends Comment> comments = null;

		try {
			// due to a poi bug. null exception throwed if no comments in the
			// sheet.
			comments = sheet.getCellComments();
		} catch (Exception ex) {
			LOG.log(Level.FINE, "Null exception throwed when no comment exists: " + ex.getLocalizedMessage(), ex);
		}
		if (comments == null) {
			return commandList;
		}

		// not sure the map is sorted. So use tree map to sort it.
		SortedSet<CellAddress> keys = new TreeSet<>(comments.keySet());
		// go through each comments
		// if found tie command then transfer it to list also remove from
		// comments.
		for (CellAddress key : keys) {
			Cell cell = sheet.getRow(key.getRow()).getCell(key.getColumn(), MissingCellPolicy.CREATE_NULL_AS_BLANK);
			buildCommandList(sheet, sheetRightCol, cell, commandList, cellAttributesMap);
		}
		return commandList;

	}

build command list from comments. after transfer the comment to command,
remove it from comments.

@param sheet
sheet.
@param sheetRightCol
the sheet right col
@param cellAttributesMap
the cell attributes map
@return command list.

build command list from comments . after transfer the comment to command remove it from comments .


private void setParentForChildCommand(final List<ConfigCommand> commandList, final int i,
			final ConfigCommand child) {
		int matchIndex = -1;
		ConfigRange matchRange = null;
		for (int j = 0; j < commandList.size(); j++) {
			if (j != i) {
				Command commandParent = commandList.get(j);
				if (!commandParent.getCommandTypeName().equalsIgnoreCase(TieConstants.COMMAND_FORM)
						&& WebSheetUtility.insideRange(child.getConfigRange(), commandParent.getConfigRange())
						&& ((matchRange == null)
								|| (WebSheetUtility.insideRange(commandParent.getConfigRange(), matchRange)))) {
					matchRange = commandParent.getConfigRange();
					matchIndex = j;
				}
			}

		}
		if (matchIndex >= 0) {
			commandList.get(matchIndex).getConfigRange().addCommand(child);
			child.setParentFound(true);
		}
	}

private void setParentForChildCommand ( final List < ConfigCommand > commandList , final int i , final ConfigCommand child ) { int matchIndex = - 1 ; ConfigRange matchRange = null ; for ( int j = 0 ; j < commandList . size ( ) ; j ++ ) { if ( j != i ) { Command commandParent = commandList . get ( j ) ; if ( ! commandParent . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_FORM ) && WebSheetUtility . insideRange ( child . getConfigRange ( ) , commandParent . getConfigRange ( ) ) && ( ( matchRange == null ) || ( WebSheetUtility . insideRange ( commandParent . getConfigRange ( ) , matchRange ) ) ) ) { matchRange = commandParent . getConfigRange ( ) ; matchIndex = j ; } } } if ( matchIndex >= 0 ) { commandList . get ( matchIndex ) . getConfigRange ( ) . addCommand ( child ) ; child . setParentFound ( true ) ; } }

Sets the parent for child command.

@param commandList
the command list
@param i
the i
@param child
the child


private boolean hasEachCommandInTheList(final List<ConfigCommand> commandList) {

		if (commandList != null) {
			for (ConfigCommand command : commandList) {
				if (command.getCommandTypeName().equalsIgnoreCase(TieConstants.COMMAND_EACH)) {
					return true;
				}
			}
		}
		return false;
	}

private boolean hasEachCommandInTheList ( final List < ConfigCommand > commandList ) { if ( commandList != null ) { for ( ConfigCommand command : commandList ) { if ( command . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_EACH ) ) { return true ; } } } return false ; }

check whether contain each command in the list.

@param commandList
command list.
@return true if contain each command.

check whether contain each command in the list .


private void matchCommandToSheetConfigForm(final Map<String, SheetConfiguration> sheetConfigMap,
			final List<String> formList, final ConfigCommand command) {
		for (String formname : formList) {
			SheetConfiguration sheetConfig = sheetConfigMap.get(formname);
			if (WebSheetUtility.insideRange(command.getConfigRange(), sheetConfig.getFormCommand().getConfigRange())) {
				sheetConfig.getFormCommand().getConfigRange().addCommand(command);
				break;
			}
		}
	}

private void matchCommandToSheetConfigForm ( final Map < String , SheetConfiguration > sheetConfigMap , final List < String > formList , final ConfigCommand command ) { for ( String formname : formList ) { SheetConfiguration sheetConfig = sheetConfigMap . get ( formname ) ; if ( WebSheetUtility . insideRange ( command . getConfigRange ( ) , sheetConfig . getFormCommand ( ) . getConfigRange ( ) ) ) { sheetConfig . getFormCommand ( ) . getConfigRange ( ) . addCommand ( command ) ; break ; } } }

Match command to sheet config form.

@param sheetConfigMap
the sheet config map
@param formList
the form list
@param command
the command


private void copyTemplateForTieCommands(final Sheet sheet) {
		// if skip configuration. then return.
		if (parent.isSkipConfiguration()) {
			return;
		}
		Workbook wb = sheet.getWorkbook();
		String copyName = TieConstants.COPY_SHEET_PREFIX + sheet.getSheetName();
		if (wb.getSheet(copyName) == null) {
			Sheet newSheet = wb.cloneSheet(wb.getSheetIndex(sheet));
			int sheetIndex = wb.getSheetIndex(newSheet);
			wb.setSheetName(sheetIndex, copyName);
			wb.setSheetHidden(sheetIndex, Workbook.SHEET_STATE_VERY_HIDDEN);
		}
	}

private
void
copyTemplateForTieCommands
(
final
Sheet
sheet
)
{
// if skip configuration. then return.
if
(
parent
.
isSkipConfiguration
(
)
)
{
return
;
}
Workbook
wb
=
sheet
.
getWorkbook
(
)
;
String
copyName
=
TieConstants
.
COPY_SHEET_PREFIX
+
sheet
.
getSheetName
(
)
;
if
(
wb
.
getSheet
(
copyName
)
==
)
{
Sheet
newSheet
=
wb
.
cloneSheet
(
wb
.
getSheetIndex
(
sheet
)
)
;
int
sheetIndex
=
wb
.
getSheetIndex
(
newSheet
)
;
wb
.
setSheetName
(
sheetIndex
,
copyName
)
;
wb
.
setSheetHidden
(
sheetIndex
,
Workbook
.
SHEET_STATE_VERY_HIDDEN
)
;
}
}

Copy the each command area to seperated sheet. As it will be used for
iteration.

@param sheet
sheet.

Copy the each command area to seperated sheet . As it will be used for iteration .


private List<ConfigCommand> buildCommandList(final Sheet sheet, final int sheetRightCol, final Cell cell,
			final List<ConfigCommand> cList, final CellAttributesMap cellAttributesMap) {

		Comment comment = cell.getCellComment();
		String text = comment.getString().getString();
		String[] commentLines = text.split("\\n");
		StringBuilder newComment = new StringBuilder();
		boolean changed = false;
		for (String commentLine : commentLines) {
			String line = commentLine.trim();
			if (ParserUtility.isCommandString(line)) {
				processCommandLine(sheet, cell, line, cList, sheetRightCol);
				changed = true;
			} else if (ParserUtility.isEmptyMethodString(line) || ParserUtility.isMethodString(line)) {
				processMethodLine(cell, line, cellAttributesMap);
				changed = true;
			} else {
				if (newComment.length() > 0) {
					newComment.append("\\n" + commentLine);
				} else {
					newComment.append(commentLine);
				}
			}
		}
		if (!changed) {
			moveCommentToMap(cell, text, cellAttributesMap.getTemplateCommentMap(), true);
		} else {
			// reset comment string if changed
			if (newComment.length() > 0) {
				moveCommentToMap(cell, newComment.toString(), cellAttributesMap.getTemplateCommentMap(), true);
				CreationHelper factory = sheet.getWorkbook().getCreationHelper();
				RichTextString str = factory.createRichTextString(newComment.toString());
				comment.setString(str);
			} else {
				// remove cell comment if new comment become empty.
				cell.removeCellComment();
			}
		}

		return cList;
	}

build command list from comment.

@param sheet
sheet.
@param sheetRightCol
sheet right column.
@param cell
the cell
@param cList
command list.
@param cellAttributesMap
the cell attributes map
@return command list.


private void processMethodLine(final Cell cell, final String line, final CellAttributesMap cellAttributesMap) {
		if (ParserUtility.isWidgetMethodString(line)) {
			ParserUtility.parseWidgetAttributes(cell, line, cellAttributesMap);
		} else if (ParserUtility.isValidateMethodString(line)) {
			ParserUtility.parseValidateAttributes(cell, line, cellAttributesMap);
		} else {
			moveCommentToMap(cell, line, cellAttributesMap.getTemplateCommentMap(), false);
		}
	}

private void processMethodLine ( final Cell cell , final String line , final CellAttributesMap cellAttributesMap ) { if ( ParserUtility . isWidgetMethodString ( line ) ) { ParserUtility . parseWidgetAttributes ( cell , line , cellAttributesMap ) ; } else if ( ParserUtility . isValidateMethodString ( line ) ) { ParserUtility . parseValidateAttributes ( cell , line , cellAttributesMap ) ; } else { moveCommentToMap ( cell , line , cellAttributesMap . getTemplateCommentMap ( ) , false ) ; } }

Process method line.

@param cell
the cell
@param line
the line
@param cellAttributesMap
the cell attributes map


private void processCommandLine(final Sheet sheet, final Cell cell, final String line,
			final List<ConfigCommand> cList, final int sheetRightCol) {
		int nameEndIndex = line.indexOf(TieConstants.ATTR_PREFIX, TieConstants.COMMAND_PREFIX.length());
		if (nameEndIndex < 0) {
			String errMsg = "Failed to parse command line [" + line + "]. Expected '" + TieConstants.ATTR_PREFIX
					+ "' symbol.";
			LOG.severe(errMsg);
			throw new IllegalStateException(errMsg);
		}
		String commandName = line.substring(TieConstants.COMMAND_PREFIX.length(), nameEndIndex).trim();
		Map<String, String> attrMap = buildAttrMap(line, nameEndIndex);
		ConfigCommand configCommand = createConfigCommand(sheet, cell, sheetRightCol, commandName, attrMap);
		if (configCommand != null) {
			cList.add(configCommand);
		}
	}

private
void
processCommandLine
(
final
Sheet
sheet
,
final
Cell
cell
,
final
String
line
,
final
List
<
ConfigCommand
>
cList
,
final
int
sheetRightCol
)
{
int
nameEndIndex
=
line
.
indexOf
(
TieConstants
.
ATTR_PREFIX
,
TieConstants
.
COMMAND_PREFIX
.
length
(
)
)
;
if
(
nameEndIndex
<
0
)
{
String
errMsg
=
"Failed to parse command line ["
+
line
+
"]. Expected '"
+
TieConstants
.
ATTR_PREFIX
+
"' symbol."
;
LOG
.
severe
(
errMsg
)
;
throw
new
IllegalStateException
(
errMsg
)
;
}
String
commandName
=
line
.
substring
(
TieConstants
.
COMMAND_PREFIX
.
length
(
)
,
nameEndIndex
)
.
trim
(
)
;
Map
<
String
,
String
>
attrMap
=
buildAttrMap
(
line
,
nameEndIndex
)
;
ConfigCommand
configCommand
=
createConfigCommand
(
sheet
,
cell
,
sheetRightCol
,
commandName
,
attrMap
)
;
if
(
configCommand
!=
)
{
cList
.
add
(
configCommand
)
;
}
}

Process command line.

@param sheet
the sheet
@param cell
the cell
@param line
the line
@param cList
the c list
@param sheetRightCol
the sheet right col


private void moveCommentToMap(final Cell cell, final String newComment,
			final Map<String, Map<String, String>> sheetCommentMap, final boolean normalComment) {

		String cellKey = cell.getSheet().getSheetName() + "!$" + cell.getColumnIndex() + "$" + cell.getRowIndex();

		ParserUtility.parseCommentToMap(cellKey, newComment, sheetCommentMap, normalComment);

	}

private void moveCommentToMap ( final Cell cell , final String newComment , final Map < String , Map < String , String > > sheetCommentMap , final boolean normalComment ) { String cellKey = cell . getSheet ( ) . getSheetName ( ) + "!$" + cell . getColumnIndex ( ) + "$" + cell . getRowIndex ( ) ; ParserUtility . parseCommentToMap ( cellKey , newComment , sheetCommentMap , normalComment ) ; }

change the comment.

@param cell
the cell
@param newComment
updated comment.
@param sheetCommentMap
the sheet comment map
@param normalComment
the normal comment


private ConfigCommand createConfigCommand(final Sheet sheet, final Cell firstCell, final int sheetRightCol,
			final String commandName, final Map<String, String> attrMap) {
		@SuppressWarnings("rawtypes")
		Class clas = commandMap.get(commandName);
		if (clas == null) {
			LOG.log(Level.WARNING, "Cannot find command class for {} ", commandName);
			return null;
		}
		try {
			ConfigCommand command = (ConfigCommand) clas.newInstance();
			command.setCommandTypeName(commandName);
			for (Map.Entry<String, String> attr : attrMap.entrySet()) {
				WebSheetUtility.setObjectProperty(command, attr.getKey(), attr.getValue(), true);
			}
			command.getConfigRange().setFirstRowRef(firstCell, true);
			command.getConfigRange().setLastRowPlusRef(sheet, sheetRightCol, command.getLastRow(), true);
			return command;
		} catch (Exception e) {
			LOG.log(Level.WARNING,
					"Failed to initialize command class " + clas.getName() + " for command" + commandName, e);
			return null;
		}
	}

private
ConfigCommand
createConfigCommand
(
final
Sheet
sheet
,
final
Cell
firstCell
,
final
int
sheetRightCol
,
final
String
commandName
,
final
Map
<
String
,
String
>
attrMap
)
{
@
SuppressWarnings
(
"rawtypes"
)
Class
clas
=
commandMap
.
get
(
commandName
)
;
if
(
clas
==
)
{
LOG
.
log
(
Level
.
WARNING
,
"Cannot find command class for {} "
,
commandName
)
;
return
;
}
try
{
ConfigCommand
command
=
(
ConfigCommand
)
clas
.
newInstance
(
)
;
command
.
setCommandTypeName
(
commandName
)
;
for
(
Map
.
Entry
<
String
,
String
>
attr
:
attrMap
.
entrySet
(
)
)
{
WebSheetUtility
.
setObjectProperty
(
command
,
attr
.
getKey
(
)
,
attr
.
getValue
(
)
,
true
)
;
}
command
.
getConfigRange
(
)
.
setFirstRowRef
(
firstCell
,
true
)
;
command
.
getConfigRange
(
)
.
setLastRowPlusRef
(
sheet
,
sheetRightCol
,
command
.
getLastRow
(
)
,
true
)
;
return
command
;
}
catch
(
Exception
e
)
{
LOG
.
log
(
Level
.
WARNING
,
"Failed to initialize command class "
+
clas
.
getName
(
)
+
" for command"
+
commandName
,
e
)
;
return
;
}
}

create configuration command.

@param sheet
sheet.
@param firstCell
first cell.
@param sheetRightCol
sheet right col.
@param commandName
command name.
@param attrMap
attibutes map.
@return configuration command.


private Map<String, String> buildAttrMap(final String commandLine, final int nameEndIndex) {
		int paramsEndIndex = commandLine.lastIndexOf(TieConstants.ATTR_SUFFIX);
		if (paramsEndIndex < 0) {
			String errMsg = "Failed to parse command line [" + commandLine + "]. Expected '" + TieConstants.ATTR_SUFFIX
					+ "' symbol.";
			throw new IllegalArgumentException(errMsg);
		}
		String attrString = commandLine.substring(nameEndIndex + 1, paramsEndIndex).trim();
		return ParserUtility.parseCommandAttributes(attrString);
	}

private
Map
<
String
,
String
>
buildAttrMap
(
final
String
commandLine
,
final
int
nameEndIndex
)
{
int
paramsEndIndex
=
commandLine
.
lastIndexOf
(
TieConstants
.
ATTR_SUFFIX
)
;
if
(
paramsEndIndex
<
0
)
{
String
errMsg
=
"Failed to parse command line ["
+
commandLine
+
"]. Expected '"
+
TieConstants
.
ATTR_SUFFIX
+
"' symbol."
;
throw
new
IllegalArgumentException
(
errMsg
)
;
}
String
attrString
=
commandLine
.
substring
(
nameEndIndex
+
1
,
paramsEndIndex
)
.
trim
(
)
;
return
ParserUtility
.
parseCommandAttributes
(
attrString
)
;
}

Build the attributes map.

@param commandLine
command line from comment.
@param nameEndIndex
index of command name's end.
@return attributes map.


private SheetConfiguration getSheetConfigurationFromConfigCommand(final Sheet sheet, final FormCommand fcommand,
			final int sheetRightCol) {

		SheetConfiguration sheetConfig = new SheetConfiguration();
		sheetConfig.setFormName(fcommand.getName());
		sheetConfig.setSheetName(sheet.getSheetName());
		int leftCol = fcommand.getLeftCol();
		int lastRow = fcommand.getLastRow();
		int rightCol = 0;
		int maxRow = 0;
		for (Row row : sheet) {
			if (row.getRowNum() > TieConstants.TIE_WEB_SHEET_MAX_ROWS) {
				break;
			}
			maxRow = row.getRowNum();
			if ((row.getLastCellNum() - 1) > rightCol) {
				int verifiedcol = verifyLastCell(row, rightCol, sheetRightCol);
				if (verifiedcol > rightCol) {
					rightCol = verifiedcol;
				}
			}
		}
		if (maxRow < lastRow) {
			lastRow = maxRow;
		}
		// header range row set to 0 while column set to first column to
		// max
		// column (FF) e.g. $A$0 : $FF$0
		setHeaderOfSheetConfiguration(fcommand, sheetConfig, leftCol, rightCol);
		// body range row set to first row to last row while column set
		// to
		// first column to max column (FF) e.g. $A$1 : $FF$1000
		setBodyOfSheetConfiguration(fcommand, sheetConfig, leftCol, lastRow, rightCol);

		// footer range row set to 0 while column set to first column to
		// max
		// column (FF) e.g. $A$0 : $FF$0
		setFooterOfSheetConfiguration(fcommand, sheetConfig, leftCol, rightCol);

		String hidden = fcommand.getHidden();
		if ((hidden != null) && (Boolean.parseBoolean(hidden))) {
			sheetConfig.setHidden(true);
		}
		String fixedWidthStyle = fcommand.getFixedWidthStyle();
		if ((fixedWidthStyle != null) && (Boolean.parseBoolean(fixedWidthStyle))) {
			sheetConfig.setFixedWidthStyle(true);
		}
		sheetConfig.setFormCommand(fcommand);
		return sheetConfig;

	}

Create sheet configuration from form command.

@param sheet
sheet.
@param fcommand
form command.
@param sheetRightCol
the sheet right col
@return sheet configuration.

Create sheet configuration from form command .


private void setFooterOfSheetConfiguration(final FormCommand fcommand, final SheetConfiguration sheetConfig,
			final int leftCol, final int rightCol) {
		String tempStr;
		if (fcommand.calcFooterLength() == 0) {
			tempStr = CellUtility.getCellIndexLetterKey(leftCol, 0) + " : "
					+ CellUtility.getCellIndexLetterKey(rightCol, 0);
		} else {
			tempStr = CellUtility.getCellIndexLetterKey(leftCol,
					fcommand.getTopRow() + fcommand.calcHeaderLength() + fcommand.calcBodyLength()) + " : "
					+ CellUtility.getCellIndexLetterKey(rightCol, fcommand.getTopRow() + fcommand.calcHeaderLength());
		}
		sheetConfig.setFormFooterRange(tempStr);
		sheetConfig.setFooterCellRange(new CellRange(tempStr));
	}

private
void
setFooterOfSheetConfiguration
(
final
FormCommand
fcommand
,
final
SheetConfiguration
sheetConfig
,
final
int
leftCol
,
final
int
rightCol
)
{
String
tempStr
;
if
(
fcommand
.
calcFooterLength
(
)
==
0
)
{
tempStr
=
CellUtility
.
getCellIndexLetterKey
(
leftCol
,
0
)
+
" : "
+
CellUtility
.
getCellIndexLetterKey
(
rightCol
,
0
)
;
}
else
{
tempStr
=
CellUtility
.
getCellIndexLetterKey
(
leftCol
,
fcommand
.
getTopRow
(
)
+
fcommand
.
calcHeaderLength
(
)
+
fcommand
.
calcBodyLength
(
)
)
+
" : "
+
CellUtility
.
getCellIndexLetterKey
(
rightCol
,
fcommand
.
getTopRow
(
)
+
fcommand
.
calcHeaderLength
(
)
)
;
}
sheetConfig
.
setFormFooterRange
(
tempStr
)
;
sheetConfig
.
setFooterCellRange
(
new
CellRange
(
tempStr
)
)
;
}

Sets the footer of sheet configuration.

@param fcommand
the fcommand
@param sheetConfig
the sheet config
@param leftCol
the left col
@param rightCol
the right col

Sets the footer of sheet configuration .


private void setBodyOfSheetConfiguration(final FormCommand fcommand, final SheetConfiguration sheetConfig,
			final int leftCol, final int lastRow, final int rightCol) {
		String tempStr;
		tempStr = CellUtility.getCellIndexLetterKey(leftCol, fcommand.getTopRow() + fcommand.calcHeaderLength() + 1)
				+ " : " + CellUtility.getCellIndexLetterKey(rightCol, lastRow + 1);

		sheetConfig.setFormBodyRange(tempStr);
		sheetConfig.setBodyCellRange(new CellRange(tempStr));
		sheetConfig.setFormBodyType(TieConstants.FORM_TYPE_FREE);
		sheetConfig.setCellFormAttributes(new HashMap<String, List<CellFormAttributes>>());
	}

private
void
setBodyOfSheetConfiguration
(
final
FormCommand
fcommand
,
final
SheetConfiguration
sheetConfig
,
final
int
leftCol
,
final
int
lastRow
,
final
int
rightCol
)
{
String
tempStr
;
tempStr
=
CellUtility
.
getCellIndexLetterKey
(
leftCol
,
fcommand
.
getTopRow
(
)
+
fcommand
.
calcHeaderLength
(
)
+
1
)
+
" : "
+
CellUtility
.
getCellIndexLetterKey
(
rightCol
,
lastRow
+
1
)
;
sheetConfig
.
setFormBodyRange
(
tempStr
)
;
sheetConfig
.
setBodyCellRange
(
new
CellRange
(
tempStr
)
)
;
sheetConfig
.
setFormBodyType
(
TieConstants
.
FORM_TYPE_FREE
)
;
sheetConfig
.
setCellFormAttributes
(
new
HashMap
<
String
,
List
<
CellFormAttributes
>
>
(
)
)
;
}

Sets the body of sheet configuration.

@param fcommand
the fcommand
@param sheetConfig
the sheet config
@param leftCol
the left col
@param lastRow
the last row
@param rightCol
the right col


private void setHeaderOfSheetConfiguration(final FormCommand fcommand, final SheetConfiguration sheetConfig,
			final int leftCol, final int rightCol) {
		String tempStr;
		if (fcommand.calcHeaderLength() == 0) {
			tempStr = CellUtility.getCellIndexLetterKey(leftCol, 0) + " : "
					+ CellUtility.getCellIndexLetterKey(rightCol, 0);
		} else {
			tempStr = CellUtility.getCellIndexLetterKey(leftCol, fcommand.getTopRow() + 1) + " : "
					+ CellUtility.getCellIndexLetterKey(rightCol, fcommand.getTopRow() + fcommand.calcHeaderLength());
		}
		sheetConfig.setFormHeaderRange(tempStr);
		sheetConfig.setHeaderCellRange(new CellRange(tempStr));
	}

private
void
setHeaderOfSheetConfiguration
(
final
FormCommand
fcommand
,
final
SheetConfiguration
sheetConfig
,
final
int
leftCol
,
final
int
rightCol
)
{
String
tempStr
;
if
(
fcommand
.
calcHeaderLength
(
)
==
0
)
{
tempStr
=
CellUtility
.
getCellIndexLetterKey
(
leftCol
,
0
)
+
" : "
+
CellUtility
.
getCellIndexLetterKey
(
rightCol
,
0
)
;
}
else
{
tempStr
=
CellUtility
.
getCellIndexLetterKey
(
leftCol
,
fcommand
.
getTopRow
(
)
+
1
)
+
" : "
+
CellUtility
.
getCellIndexLetterKey
(
rightCol
,
fcommand
.
getTopRow
(
)
+
fcommand
.
calcHeaderLength
(
)
)
;
}
sheetConfig
.
setFormHeaderRange
(
tempStr
)
;
sheetConfig
.
setHeaderCellRange
(
new
CellRange
(
tempStr
)
)
;
}

Sets the header of sheet configuration.

@param fcommand
the fcommand
@param sheetConfig
the sheet config
@param leftCol
the left col
@param rightCol
the right col

Sets the header of sheet configuration .


@SuppressWarnings({ "rawtypes" })
	public static int deleteRow(final ConfigBuildRef configBuildRef,
			final int rowIndex, final Map<String, Object> dataContext,
			final SheetConfiguration sheetConfig,
			final List<FacesRow> bodyRows) {

		String fullName = ConfigurationUtility.getFullNameFromRow(
				configBuildRef.getSheet().getRow(rowIndex));

		configBuildRef.getCellHelper().restoreDataContext(fullName);
		CollectionObject collect = configBuildRef.getCellHelper()
				.getLastCollect(fullName);

		Collection lastCollection = collect.getLastCollection();
		int lastCollectionIndex = collect.getLastCollectionIndex();
		EachCommand eachCommand = collect.getEachCommand();
		if (lastCollectionIndex < 0) {
			// no each command in the loop.
			throw new DeleteRowException("No each command found.");
		}
		if (lastCollection.size() <= 1) {
			// this is the last record and no parent left.
			throw new DeleteRowException(
					"Cannot delete the last record in the group.");
		}

		CommandUtility.deleteObjectInContext(lastCollection, eachCommand,
				lastCollectionIndex, dataContext);

		// find range from shiftmap.
		ConfigRangeAttrs currentRangeAttrs = configBuildRef.getShiftMap()
				.get(fullName);
		if (currentRangeAttrs == null) {
			throw new DeleteRowException("Cannot find delete range.");

		}

		// The lastRowRef is wrong in rangeAttrs. So use length to recalc it.
		int startRow = currentRangeAttrs.getFirstRowIndex();
		int length = currentRangeAttrs.getFinalLength();
		int endRow = startRow + length - 1;

		List<String> removeFullNameList = findRemoveFullNameList(
				configBuildRef.getSheet(), startRow, endRow);
		// remove range from shiftmap.
		removeRangesFromShiftMap(configBuildRef.getShiftMap(),
				removeFullNameList);
		// 1. remove ranged rows from sheet
		String var = eachCommand.getVar();
		CommandUtility.removeRowsInSheet(configBuildRef.getSheet(),
				startRow, endRow, configBuildRef.getCachedCells());
		// 2. reset FacesRow row index.
		CommandUtility.removeRowsInBody(sheetConfig, bodyRows, startRow,
				endRow);
		// 3. decrease index number in hidden column
		Map<String, String> changeMap = new TreeMap<>();
		ConfigurationUtility.changeIndexNumberInHiddenColumn(configBuildRef,
				startRow, fullName, changeMap, -1);
		// 4. decrease index number in shift map
		ConfigurationUtility.changeIndexNumberInShiftMap(
				configBuildRef.getShiftMap(), changeMap);
		// 5. rebuild upper level formula
		ConfigurationUtility.reBuildUpperLevelFormula(configBuildRef,
				fullName);
		// 6. decrease upper level final length
		ConfigurationUtility.changeUpperLevelFinalLength(
				configBuildRef.getShiftMap(), fullName, -length);

		dataContext.remove(var);

		return length;

	}

Delete row.

@param configBuildRef
the config build ref
@param rowIndex
the row index
@param dataContext
the data context
@param sheetConfig
the sheet config
@param bodyRows
the body rows
@return the int
@throws DeleteRowException
the delete row exception


private static void removeRangesFromShiftMap(
			final NavigableMap<String, ConfigRangeAttrs> shiftMap,
			final List<String> removeFullNameList) {
		for (String fname : removeFullNameList) {
			shiftMap.remove(fname);
		}

	}

private static void removeRangesFromShiftMap ( final NavigableMap < String , ConfigRangeAttrs > shiftMap , final List < String > removeFullNameList ) { for ( String fname : removeFullNameList ) { shiftMap . remove ( fname ) ; } }

Removes the ranges from shift map.

@param shiftMap
the shift map
@param removeFullNameList
the remove full name list


private static List<String> findRemoveFullNameList(final Sheet sheet,
			final int startRow, final int endRow) {

		List<String> list = new ArrayList<>();

		for (int rowIndex = startRow; rowIndex <= endRow; rowIndex++) {
			String fullName = ConfigurationUtility
					.getFullNameFromRow(sheet.getRow(rowIndex));
			if (!list.contains(fullName)) {
				list.add(fullName);
			}
		}

		return list;
	}

private static List < String > findRemoveFullNameList ( final Sheet sheet , final int startRow , final int endRow ) { List < String > list = new ArrayList <> ( ) ; for ( int rowIndex = startRow ; rowIndex <= endRow ; rowIndex ++ ) { String fullName = ConfigurationUtility . getFullNameFromRow ( sheet . getRow ( rowIndex ) ) ; if ( ! list . contains ( fullName ) ) { list . add ( fullName ) ; } } return list ; }

Find remove full name list.

@param sheet
the sheet
@param startRow
the start row
@param endRow
the end row
@return the list


public static EachCommand getEachCommandFromPartsName(
			final Map<String, Command> commandIndexMap,
			final String[] varparts) {
		if (varparts.length == TieConstants.DEFAULT_COMMAND_PART_LENGTH) {
			return (EachCommand) commandIndexMap
					.get(TieConstants.EACH_COMMAND_FULL_NAME_PREFIX
							+ varparts[1]);
		}
		return null;

	}

public static EachCommand getEachCommandFromPartsName ( final Map < String , Command > commandIndexMap , final String [ ] varparts ) { if ( varparts . length == TieConstants . DEFAULT_COMMAND_PART_LENGTH ) { return ( EachCommand ) commandIndexMap . get ( TieConstants . EACH_COMMAND_FULL_NAME_PREFIX + varparts [ 1 ] ) ; } return null ; }

Gets the each command from parts name.

@param commandIndexMap
the command index map
@param varparts
the varparts
@return the each command from parts name


@SuppressWarnings({ "rawtypes", "unchecked" })
	private static String insertEmptyObjectInContext(final String fullName,
			final Collection lastCollection, final EachCommand eachCommand,
			final int lastCollectionIndex,
			final Map<String, Object> dataContext) {
		if (!(lastCollection instanceof List)) {
			throw new EvaluationException(
					"Collection must be list in order to insert/delete.");
		}
		List collectionList = (List) lastCollection;
		// the object must support empty constructor.
		Object currentObj = collectionList.get(lastCollectionIndex);
		Object insertObj;
		try {
			insertObj = currentObj.getClass().newInstance();
			collectionList.add(lastCollectionIndex + 1, insertObj);
			dataContext.put(eachCommand.getVar(), insertObj);
			return fullName.substring(0, fullName.lastIndexOf('.') + 1)
					+ (lastCollectionIndex + 1);
		} catch (InstantiationException | IllegalAccessException e) {
			throw new EvaluationException(e);

		}

	}

Insert empty object in context.

@param fullName
the full name
@param lastCollection
the last collection
@param eachCommand
the each command
@param lastCollectionIndex
the last collection index
@param dataContext
the data context
@return the string
@throws EvaluationException
the evaluation exception


@SuppressWarnings({ "rawtypes" })
	private static void deleteObjectInContext(
			final Collection lastCollection, final EachCommand eachCommand,
			final int lastCollectionIndex,
			final Map<String, Object> dataContext) {
		if (!(lastCollection instanceof List)) {
			throw new EvaluationException(eachCommand.getVar()
					+ TieConstants.EACH_COMMAND_INVALID_MSG);
		}
		List collectionList = (List) lastCollection;
		// the object must support empty constructor.

		collectionList.remove(lastCollectionIndex);
		dataContext.remove(eachCommand.getVar());

	}

Delete object in context.

@param lastCollection
the last collection
@param eachCommand
the each command
@param lastCollectionIndex
the last collection index
@param dataContext
the data context


@SuppressWarnings("rawtypes")
	public static int prepareCollectionDataInContext(
			final String[] varparts, final Collection collection,
			final Map<String, Object> dataContext) {
		if (varparts.length == TieConstants.DEFAULT_COMMAND_PART_LENGTH) {
			int collectionIndex = Integer.parseInt(varparts[2]);
			Object obj = ConfigurationUtility
					.findItemInCollection(collection, collectionIndex);
			if (obj != null) {
				dataContext.put(varparts[1], obj);
				return collectionIndex;
			}
		}
		return -1;
	}

@ SuppressWarnings ( "rawtypes" ) public static int prepareCollectionDataInContext ( final String [ ] varparts , final Collection collection , final Map < String , Object > dataContext ) { if ( varparts . length == TieConstants . DEFAULT_COMMAND_PART_LENGTH ) { int collectionIndex = Integer . parseInt ( varparts [ 2 ] ) ; Object obj = ConfigurationUtility . findItemInCollection ( collection , collectionIndex ) ; if ( obj != null ) { dataContext . put ( varparts [ 1 ] , obj ) ; return collectionIndex ; } } return - 1 ; }

Prepare collection data in context.

@param varparts
the varparts
@param collection
the collection
@param dataContext
the data context
@return the int


public static void indexCommandRange(
			final ConfigRange sourceConfigRange,
			final Map<String, Command> indexMap) {
		if (sourceConfigRange.getCommandList() != null) {
			for (int i = 0; i < sourceConfigRange.getCommandList()
					.size(); i++) {
				Command command = sourceConfigRange.getCommandList().get(i);
				indexMap.put(command.getCommandName(), command);
				command.getConfigRange().indexCommandRange(indexMap);
			}
		}

	}

public static void indexCommandRange ( final ConfigRange sourceConfigRange , final Map < String , Command > indexMap ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; indexMap . put ( command . getCommandName ( ) , command ) ; command . getConfigRange ( ) . indexCommandRange ( indexMap ) ; } } }

Index command range.

@param sourceConfigRange
the source config range
@param indexMap
the index map


public static boolean isRowAllowAdd(final Row row,
			final SheetConfiguration sheetConfig) {
		String fullName = ConfigurationUtility.getFullNameFromRow(row);
		if (fullName != null) {
			ConfigRangeAttrs attrs = sheetConfig.getShiftMap()
					.get(fullName);
			if ((attrs != null) && (attrs.isAllowAdd()) && (row
					.getRowNum() == attrs.getFirstRowRef().getRowIndex())) {
				return true;
			}
		}
		return false;
	}

public static boolean isRowAllowAdd ( final Row row , final SheetConfiguration sheetConfig ) { String fullName = ConfigurationUtility . getFullNameFromRow ( row ) ; if ( fullName != null ) { ConfigRangeAttrs attrs = sheetConfig . getShiftMap ( ) . get ( fullName ) ; if ( ( attrs != null ) && ( attrs . isAllowAdd ( ) ) && ( row . getRowNum ( ) == attrs . getFirstRowRef ( ) . getRowIndex ( ) ) ) { return true ; } } return false ; }

Checks if is row allow add.

@param row
the row
@param sheetConfig
the sheet config
@return true, if is row allow add


public static void insertEachTemplate(
			final ConfigRange sourceConfigRange,
			final ConfigBuildRef configBuildRef, final int index,
			final int insertPosition, final RowsMapping unitRowsMapping) {
		int srcStartRow = sourceConfigRange.getFirstRowAddr().getRow();
		int srcEndRow = sourceConfigRange.getLastRowPlusAddr().getRow() - 1;

		Sheet sheet = configBuildRef.getSheet();
		Workbook wb = sheet.getWorkbook();
		// excel sheet name has limit 31 chars
		String copyName = TieConstants.COPY_SHEET_PREFIX
				+ sheet.getSheetName();
		if (copyName.length() > TieConstants.EXCEL_SHEET_NAME_LIMIT) {
			copyName = copyName.substring(0,
					TieConstants.EXCEL_SHEET_NAME_LIMIT);
		}
		Sheet srcSheet = wb.getSheet(copyName);
		if (index > 0) {
			CellUtility.copyRows(srcSheet, sheet, srcStartRow, srcEndRow,
					insertPosition, false, true);
		}

		for (int rowIndex = srcStartRow; rowIndex <= srcEndRow; rowIndex++) {
			if (configBuildRef.getWatchList().contains(rowIndex)
					&& (ConfigurationUtility.isStaticRow(sourceConfigRange,
							rowIndex))) {
				unitRowsMapping.addRow(rowIndex, sheet
						.getRow(insertPosition + rowIndex - srcStartRow));
			}
		}
	}

public
static
void
insertEachTemplate
(
final
ConfigRange
sourceConfigRange
,
final
ConfigBuildRef
configBuildRef
,
final
int
index
,
final
int
insertPosition
,
final
RowsMapping
unitRowsMapping
)
{
int
srcStartRow
=
sourceConfigRange
.
getFirstRowAddr
(
)
.
getRow
(
)
;
int
srcEndRow
=
sourceConfigRange
.
getLastRowPlusAddr
(
)
.
getRow
(
)
1
;
Sheet
sheet
=
configBuildRef
.
getSheet
(
)
;
Workbook
wb
=
sheet
.
getWorkbook
(
)
;
// excel sheet name has limit 31 chars
String
copyName
=
TieConstants
.
COPY_SHEET_PREFIX
+
sheet
.
getSheetName
(
)
;
if
(
copyName
.
length
(
)
>
TieConstants
.
EXCEL_SHEET_NAME_LIMIT
)
{
copyName
=
copyName
.
substring
(
0
,
TieConstants
.
EXCEL_SHEET_NAME_LIMIT
)
;
}
Sheet
srcSheet
=
wb
.
getSheet
(
copyName
)
;
if
(
index
>
0
)
{
CellUtility
.
copyRows
(
srcSheet
,
sheet
,
srcStartRow
,
srcEndRow
,
insertPosition
,
false
,
true
)
;
}
for
(
int
rowIndex
=
srcStartRow
;
rowIndex
<=
srcEndRow
;
rowIndex
++
)
{
if
(
configBuildRef
.
getWatchList
(
)
.
contains
(
rowIndex
)
&&
(
ConfigurationUtility
.
isStaticRow
(
sourceConfigRange
,
rowIndex
)
)
)
{
unitRowsMapping
.
addRow
(
rowIndex
,
sheet
.
getRow
(
insertPosition
+
rowIndex
srcStartRow
)
)
;
}
}
}

Insert each template.

@param sourceConfigRange
the source config range
@param configBuildRef
the config build ref
@param index
the index
@param insertPosition
the insert position
@param unitRowsMapping
the unit rows mapping


public static void evaluateNormalCells(final Cell cell,
			final String strValue, final Map<String, Object> context,
			final ExpressionEngine engine) {
		if (strValue.contains(TieConstants.METHOD_PREFIX)) {

			Object evaluationResult = evaluate(strValue, context, engine);
			if (evaluationResult == null) {
				evaluationResult = "";
			}
			CellUtility.setCellValue(cell, evaluationResult.toString());

			createTieCell(cell, context, engine);

		}
	}

public static void evaluateNormalCells ( final Cell cell , final String strValue , final Map < String , Object > context , final ExpressionEngine engine ) { if ( strValue . contains ( TieConstants . METHOD_PREFIX ) ) { Object evaluationResult = evaluate ( strValue , context , engine ) ; if ( evaluationResult == null ) { evaluationResult = "" ; } CellUtility . setCellValue ( cell , evaluationResult . toString ( ) ) ; createTieCell ( cell , context , engine ) ; } }

Evaluate normal cells.

@param cell
cell.
@param strValue
string value.
@param context
context.
@param engine
engine.


private static void evaluateUserFormula(final Cell cell,
			final String strValue) {
		String formulaStr = strValue.substring(2, strValue.length() - 1);
		if ((formulaStr != null) && (!formulaStr.isEmpty())) {
			cell.setCellFormula(formulaStr);
		}
	}

private static void evaluateUserFormula ( final Cell cell , final String strValue ) { String formulaStr = strValue . substring ( 2 , strValue . length ( ) - 1 ) ; if ( ( formulaStr != null ) && ( ! formulaStr . isEmpty ( ) ) ) { cell . setCellFormula ( formulaStr ) ; } }

Evaluate user formula.

@param cell
the cell
@param strValue
the str value


private static boolean isUserFormula(final String str) {
		return str.startsWith(TieConstants.USER_FORMULA_PREFIX)
				&& str.endsWith(TieConstants.USER_FORMULA_SUFFIX);
	}

private static boolean isUserFormula ( final String str ) { return str . startsWith ( TieConstants . USER_FORMULA_PREFIX ) && str . endsWith ( TieConstants . USER_FORMULA_SUFFIX ) ; }

Checks if is user formula.

@param str
the str
@return true, if is user formula


public static void createCellComment(final Cell cell,
			final String newComment,
			final Map<Cell, String> finalCommentMap) {
		// due to poi's bug. the comment must be set in sorted order ( row first
		// then column),
		// otherwise poi will mess up.
		// workaround solution is to save all comments into a map,
		// and output them together when download workbook.

		if (newComment != null) {
			finalCommentMap.put(cell, newComment);

		}
	}

Creates the cell comment.

@param cell
the cell
@param newComment
the new comment
@param finalCommentMap
the final comment map


public static boolean evalBoolExpression(
			final ExpressionEngine expEngine, final String pscript) {
		Object result = null;
		String script = "( " + pscript + " )";
		script = script.toUpperCase().replace("AND", "&&");
		script = script.toUpperCase().replace("OR", "||");
		try {
			result = expEngine.evaluate(script);
		} catch (Exception e) {
			LOG.log(Level.SEVERE,
					"WebForm WebFormHelper evalBoolExpression script = "
							+ script + "; error = "
							+ e.getLocalizedMessage(),
					e);
		}
		if (result != null) {
			return ((Boolean) result).booleanValue();
		} else {
			return false;
		}
	}

evaluate boolean express.

@param expEngine
expression engine.
@param pscript
script.
@return true (express is true) false ( express is false or invalid).


public static void removeRowsInSheet(final Sheet sheet,
			final int rowIndexStart, final int rowIndexEnd,
			final Map<Cell, String> cachedMap) {

		for (int irow = rowIndexStart; irow <= rowIndexEnd; irow++) {
			removeCachedCellForRow(sheet, irow, cachedMap);
		}
		int irows = rowIndexEnd - rowIndexStart + 1;
		if ((irows < 1) || (rowIndexStart < 0)) {
			return;
		}
		int lastRowNum = sheet.getLastRowNum();
		if (rowIndexEnd < lastRowNum) {
			sheet.shiftRows(rowIndexEnd + 1, lastRowNum, -irows);
		}
		if (rowIndexEnd == lastRowNum) {
			// reverse order to delete rows.
			for (int i = rowIndexEnd; i >= rowIndexStart; i--) {
				removeSingleRowInSheet(sheet, rowIndexStart);
			}
		}
	}

public
static
void
removeRowsInSheet
(
final
Sheet
sheet
,
final
int
rowIndexStart
,
final
int
rowIndexEnd
,
final
Map
<
Cell
,
String
>
cachedMap
)
{
for
(
int
irow
=
rowIndexStart
;
irow
<=
rowIndexEnd
;
irow
++
)
{
removeCachedCellForRow
(
sheet
,
irow
,
cachedMap
)
;
}
int
irows
=
rowIndexEnd
rowIndexStart
+
1
;
if
(
(
irows
<
1
)
||
(
rowIndexStart
<
0
)
)
{
return
;
}
int
lastRowNum
=
sheet
.
getLastRowNum
(
)
;
if
(
rowIndexEnd
<
lastRowNum
)
{
sheet
.
shiftRows
(
rowIndexEnd
+
1
,
lastRowNum
,
irows
)
;
}
if
(
rowIndexEnd
==
lastRowNum
)
{
// reverse order to delete rows.
for
(
int
i
=
rowIndexEnd
;
i
>=
rowIndexStart
;
i
)
{
removeSingleRowInSheet
(
sheet
,
rowIndexStart
)
;
}
}
}

Remove the rows.

@param sheet
the sheet
@param rowIndexStart
start row index.
@param rowIndexEnd
end row index.
@param cachedMap
the cached map


private static void removeSingleRowInSheet(final Sheet sheet,
			final int rowIndexStart) {
		Row removingRow = sheet.getRow(rowIndexStart);
		if (removingRow != null) {
			sheet.removeRow(removingRow);
		}
	}

private static void removeSingleRowInSheet ( final Sheet sheet , final int rowIndexStart ) { Row removingRow = sheet . getRow ( rowIndexStart ) ; if ( removingRow != null ) { sheet . removeRow ( removingRow ) ; } }

Removes the single row in sheet.

@param sheet
the sheet
@param rowIndexStart
the row index start


private static void removeCachedCellForRow(final Sheet sheet,
			final int rowIndexStart, final Map<Cell, String> cachedMap) {
		Row removingRow = sheet.getRow(rowIndexStart);
		if (removingRow != null) {
			// remove cached cell.
			for (Cell cell : removingRow) {
				cachedMap.remove(cell);
			}
		}
	}

private
static
void
removeCachedCellForRow
(
final
Sheet
sheet
,
final
int
rowIndexStart
,
final
Map
<
Cell
,
String
>
cachedMap
)
{
Row
removingRow
=
sheet
.
getRow
(
rowIndexStart
)
;
if
(
removingRow
!=
)
{
// remove cached cell.
for
(
Cell
cell
:
removingRow
)
{
cachedMap
.
remove
(
cell
)
;
}
}
}

Removes the cached cell for row.

@param sheet
the sheet
@param rowIndexStart
the row index start
@param cachedMap
the cached map


public static void removeRowsInBody(
			final SheetConfiguration sheetConfig,
			final List<FacesRow> bodyRows, final int rowIndexStart,
			final int rowIndexEnd) {
		int top = sheetConfig.getBodyCellRange().getTopRow();
		if ((rowIndexEnd < rowIndexStart) || (rowIndexStart < top)) {
			return;
		}

		int irows = rowIndexEnd - rowIndexStart + 1;
		for (int rowIndex = rowIndexEnd; rowIndex >= rowIndexStart; rowIndex--) {
			bodyRows.remove(rowIndex - top);
		}
		for (int irow = rowIndexStart - top; irow < bodyRows
				.size(); irow++) {
			FacesRow facesrow = bodyRows.get(irow);
			facesrow.setRowIndex(facesrow.getRowIndex() - irows);
		}
	}

public static void removeRowsInBody ( final SheetConfiguration sheetConfig , final List < FacesRow > bodyRows , final int rowIndexStart , final int rowIndexEnd ) { int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; if ( ( rowIndexEnd < rowIndexStart ) || ( rowIndexStart < top ) ) { return ; } int irows = rowIndexEnd - rowIndexStart + 1 ; for ( int rowIndex = rowIndexEnd ; rowIndex >= rowIndexStart ; rowIndex -- ) { bodyRows . remove ( rowIndex - top ) ; } for ( int irow = rowIndexStart - top ; irow < bodyRows . size ( ) ; irow ++ ) { FacesRow facesrow = bodyRows . get ( irow ) ; facesrow . setRowIndex ( facesrow . getRowIndex ( ) - irows ) ; } }

Removes the rows in body.

@param sheetConfig
the sheet config
@param bodyRows
the body rows
@param rowIndexStart
the row index start
@param rowIndexEnd
the row index end


private String loadPicture(final int rowIndex, final int colIndex) {

		FacesCell facesCell = parent.getCellHelper()
				.getFacesCellWithRowColFromCurrentPage(rowIndex, colIndex);
		if (facesCell != null && facesCell.isContainPic()) {
			FacesContext context = FacesContext.getCurrentInstance();
			String pictureId = facesCell.getPictureId();
			String pictureViewId = Integer.toHexString(
					System.identityHashCode(parent.getWb())) + pictureId;
			Map<String, Object> sessionMap = context.getExternalContext()
					.getSessionMap();
			if (sessionMap.get(pictureViewId) == null) {
				sessionMap.put(pictureViewId, parent.getPicturesMap()
						.get(pictureId).getPictureData());
			}
			return pictureViewId;
		} else {
			return null;
		}
	}

private String loadPicture ( final int rowIndex , final int colIndex ) { FacesCell facesCell = parent . getCellHelper ( ) . getFacesCellWithRowColFromCurrentPage ( rowIndex , colIndex ) ; if ( facesCell != null && facesCell . isContainPic ( ) ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; String pictureId = facesCell . getPictureId ( ) ; String pictureViewId = Integer . toHexString ( System . identityHashCode ( parent . getWb ( ) ) ) + pictureId ; Map < String , Object > sessionMap = context . getExternalContext ( ) . getSessionMap ( ) ; if ( sessionMap . get ( pictureViewId ) == null ) { sessionMap . put ( pictureViewId , parent . getPicturesMap ( ) . get ( pictureId ) . getPictureData ( ) ) ; } return pictureViewId ; } else { return null ; } }

Put picture image to session map and return the key to web.

@param rowIndex
the row index of the cell which contains picture.
@param colIndex
the column index of the cell which contains picture.
@return the key of the picture image in the session map.

Put picture image to session map and return the key to web .


private String loadChart(final int rowIndex, final int colIndex) {

		FacesCell facesCell = parent.getCellHelper()
				.getFacesCellWithRowColFromCurrentPage(rowIndex, colIndex);
		if (facesCell != null && facesCell.isContainChart()) {
			FacesContext context = FacesContext.getCurrentInstance();
			String chartId = facesCell.getChartId();
			String chartViewId = Integer.toHexString(
					System.identityHashCode(parent.getWb())) + chartId;
			if (context != null) {
				Map<String, Object> sessionMap = context
						.getExternalContext().getSessionMap();
				if (sessionMap.get(chartViewId) == null) {
					sessionMap.put(chartViewId, parent.getCharsData()
							.getChartsMap().get(chartId));
				}
			}
			return chartViewId;
		} else {
			return null;
		}
	}

private String loadChart ( final int rowIndex , final int colIndex ) { FacesCell facesCell = parent . getCellHelper ( ) . getFacesCellWithRowColFromCurrentPage ( rowIndex , colIndex ) ; if ( facesCell != null && facesCell . isContainChart ( ) ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; String chartId = facesCell . getChartId ( ) ; String chartViewId = Integer . toHexString ( System . identityHashCode ( parent . getWb ( ) ) ) + chartId ; if ( context != null ) { Map < String , Object > sessionMap = context . getExternalContext ( ) . getSessionMap ( ) ; if ( sessionMap . get ( chartViewId ) == null ) { sessionMap . put ( chartViewId , parent . getCharsData ( ) . getChartsMap ( ) . get ( chartId ) ) ; } } return chartViewId ; } else { return null ; } }

Put chart image to session map and return the key to web.

@param rowIndex
the row index of the cell which contains picture.
@param colIndex
the column index of the cell which contains picture.
@return the key of the picture image in the session map.

Put chart image to session map and return the key to web .


private String assembleNewValue(final Object value,
			final FacesCell facesCell) {
		String newValue;
		if (value instanceof java.util.Date) {
			String datePattern = facesCell.getDatePattern();
			if (datePattern == null || datePattern.isEmpty()) {
			    datePattern = parent.getDefaultDatePattern();
			}
			Format formatter = new SimpleDateFormat(datePattern);
			newValue = formatter.format(value);
		} else {
			newValue = (String) value;
		}
		if ("textarea".equalsIgnoreCase(facesCell.getInputType())
				&& (newValue != null)) {
			// remove "\r" because excel issue
			newValue = newValue.replace("\r\n", "\n");
		}
		return newValue;
	}

private
String
assembleNewValue
(
final
Object
value
,
final
FacesCell
facesCell
)
{
String
newValue
;
if
(
value
instanceof
java
.
util
.
Date
)
{
String
datePattern
=
facesCell
.
getDatePattern
(
)
;
if
(
datePattern
==
||
datePattern
.
isEmpty
(
)
)
{
datePattern
=
parent
.
getDefaultDatePattern
(
)
;
}
Format
formatter
=
new
SimpleDateFormat
(
datePattern
)
;
newValue
=
formatter
.
format
(
value
)
;
}
else
{
newValue
=
(
String
)
value
;
}
if
(
"textarea"
.
equalsIgnoreCase
(
facesCell
.
getInputType
(
)
)
&&
(
newValue
!=
)
)
{
// remove "\r" because excel issue
newValue
=
newValue
.
replace
(
"\r\n"
,
"\n"
)
;
}
return
newValue
;
}

Assemble new value.

@param value
the value
@param facesCell
the faces cell
@return the string


@SuppressWarnings("deprecation")
	public static String getCellValueWithFormat(final Cell poiCell, final FormulaEvaluator formulaEvaluator,
			final DataFormatter dataFormatter) {

		if (poiCell == null) {
			return null;
		}

		String result;
		try {
			CellType cellType = poiCell.getCellTypeEnum();
			if (cellType == CellType.FORMULA) {
				cellType = formulaEvaluator.evaluate(poiCell).getCellTypeEnum();
			}
			if (cellType == CellType.ERROR) {
				result = "";
			} else {
				result = dataFormatter.formatCellValue(poiCell, formulaEvaluator);
			}
		} catch (Exception e) {
			LOG.log(Level.SEVERE,
					"Web Form WebFormHelper getCellValue Error row = " + poiCell.getRowIndex() + " column = "
							+ poiCell.getColumnIndex() + " error = " + e.getLocalizedMessage()
							+ "; Change return result to blank",
					e);
			result = "";
		}

		return result;
	}

return cell value with format.

@param poiCell
cell.
@param formulaEvaluator
formula evaluator.
@param dataFormatter
data formatter.
@return cell string value with format.


@SuppressWarnings("deprecation")
	public static String getCellValueWithoutFormat(final Cell poiCell) {

		if (poiCell == null) {
			return null;
		}

		if (poiCell.getCellTypeEnum() == CellType.FORMULA) {
			return getCellStringValueWithType(poiCell, poiCell.getCachedFormulaResultTypeEnum());
		} else {
			return getCellStringValueWithType(poiCell, poiCell.getCellTypeEnum());
		}
	}

@ SuppressWarnings ( "deprecation" ) public static String getCellValueWithoutFormat ( final Cell poiCell ) { if ( poiCell == null ) { return null ; } if ( poiCell . getCellTypeEnum ( ) == CellType . FORMULA ) { return getCellStringValueWithType ( poiCell , poiCell . getCachedFormulaResultTypeEnum ( ) ) ; } else { return getCellStringValueWithType ( poiCell , poiCell . getCellTypeEnum ( ) ) ; } }

get input cell value. none input return blank

@param poiCell
cell.
@return String cell value.

get input cell value . none input return blank


private static String getCellStringValueWithType(final Cell poiCell, final CellType cellType) {

		switch (cellType) {
		case BOOLEAN:
			return getCellStringValueWithBooleanType(poiCell);
		case NUMERIC:
			return getCellStringValueWithNumberType(poiCell);
		case STRING:
			return poiCell.getStringCellValue();
		default:
			return "";
		} // switch

	}

private
static
String
getCellStringValueWithType
(
final
Cell
poiCell
,
final
CellType
cellType
)
{
switch
(
cellType
)
{
case
BOOLEAN
:
return
getCellStringValueWithBooleanType
(
poiCell
)
;
case
NUMERIC
:
return
getCellStringValueWithNumberType
(
poiCell
)
;
case
STRING
:
return
poiCell
.
getStringCellValue
(
)
;
default
:
return
""
;
}
// switch
}

Get cell value as string but with giving type.

@param poiCell
cell.
@param cellType
cell type.
@return Sting cell value.

Get cell value as string but with giving type .


private static String getCellStringValueWithNumberType(final Cell poiCell) {
		String result;
		if (DateUtil.isCellDateFormatted(poiCell)) {
			result = poiCell.getDateCellValue().toString();
		} else {
			result = BigDecimal.valueOf(poiCell.getNumericCellValue()).toPlainString();
			// remove .0 from end for int
			if (result.endsWith(".0")) {
				result = result.substring(0, result.length() - 2);
			}
		}
		return result;
	}

private
static
String
getCellStringValueWithNumberType
(
final
Cell
poiCell
)
{
String
result
;
if
(
DateUtil
.
isCellDateFormatted
(
poiCell
)
)
{
result
=
poiCell
.
getDateCellValue
(
)
.
toString
(
)
;
}
else
{
result
=
BigDecimal
.
valueOf
(
poiCell
.
getNumericCellValue
(
)
)
.
toPlainString
(
)
;
// remove .0 from end for int
if
(
result
.
endsWith
(
".0"
)
)
{
result
=
result
.
substring
(
0
,
result
.
length
(
)
2
)
;
}
}
return
result
;
}

Gets the cell string value with number type.

@param poiCell
the poi cell
@return the cell string value with number type

Gets the cell string value with number type .


@SuppressWarnings("deprecation")
	public static Cell setCellValue(final Cell c, final String value) {

		try {
			if (value.length() == 0) {
				c.setCellType(CellType.BLANK);
			} else if (WebSheetUtility.isNumeric(value)) {
				setCellValueNumber(c, value);
			} else if (WebSheetUtility.isDate(value)) {
				setCellValueDate(c, value);
			} else if (c.getCellTypeEnum() == CellType.BOOLEAN) {
				setCellValueBoolean(c, value);
			} else {
				setCellValueString(c, value);
			}
		} catch (Exception e) {
			LOG.log(Level.SEVERE, " error in setCellValue of CellUtility = " + e.getLocalizedMessage(), e);
			setCellValueString(c, value);
		}
		return c;
	}

Set cell value with giving String value.

@param c
cell.
@param value
giving value.
@return cell.

Set cell value with giving String value .


private static void setCellValueString(final Cell c, final String value) {
		c.setCellType(CellType.STRING);
		c.setCellValue(value);
	}

private static void setCellValueString ( final Cell c , final String value ) { c . setCellType ( CellType . STRING ) ; c . setCellValue ( value ) ; }

Sets the cell value string.

@param c
the c
@param value
the value


private static void setCellValueBoolean(final Cell c, final String value) {
		if ("Y".equalsIgnoreCase(value) || "Yes".equalsIgnoreCase(value) || "True".equalsIgnoreCase(value)) {
			c.setCellValue(true);
		} else {
			c.setCellValue(false);
		}
	}

private static void setCellValueBoolean ( final Cell c , final String value ) { if ( "Y" . equalsIgnoreCase ( value ) || "Yes" . equalsIgnoreCase ( value ) || "True" . equalsIgnoreCase ( value ) ) { c . setCellValue ( true ) ; } else { c . setCellValue ( false ) ; } }

Sets the cell value boolean.

@param c
the c
@param value
the value


private static void setCellValueDate(final Cell c, final String value) {
		String date = WebSheetUtility.parseDate(value);
		setCellValueString(c, date);
	}

private static void setCellValueDate ( final Cell c , final String value ) { String date = WebSheetUtility . parseDate ( value ) ; setCellValueString ( c , date ) ; }

Sets the cell value date.

@param c
the c
@param value
the value


private static void setCellValueNumber(final Cell c, final String value) {
		double val = Double.parseDouble(value.replace(Character.toString(','), ""));
		c.setCellType(CellType.NUMERIC);
		c.setCellValue(val);
	}

private static void setCellValueNumber ( final Cell c , final String value ) { double val = Double . parseDouble ( value . replace ( Character . toString ( ' ' ) , "" ) ) ; c . setCellType ( CellType . NUMERIC ) ; c . setCellValue ( val ) ; }

Sets the cell value number.

@param c
the c
@param value
the value


public static void copyRows(final Sheet srcSheet, final Sheet destSheet, final int srcRowStart, final int srcRowEnd,
			final int destRow, final boolean checkLock, final boolean setHiddenColumn) {

		int length = srcRowEnd - srcRowStart + 1;
		if (length <= 0) {
			return;
		}
		destSheet.shiftRows(destRow, destSheet.getLastRowNum(), length, true, false);
		for (int i = 0; i < length; i++) {
			copySingleRow(srcSheet, destSheet, srcRowStart + i, destRow + i, checkLock, setHiddenColumn);
		}
		// If there are are any merged regions in the source row, copy to new
		// row
		for (int i = 0; i < srcSheet.getNumMergedRegions(); i++) {
			CellRangeAddress cellRangeAddress = srcSheet.getMergedRegion(i);
			if ((cellRangeAddress.getFirstRow() >= srcRowStart) && (cellRangeAddress.getLastRow() <= srcRowEnd)) {
				int targetRowFrom = cellRangeAddress.getFirstRow() - srcRowStart + destRow;
				int targetRowTo = cellRangeAddress.getLastRow() - srcRowStart + destRow;

				CellRangeAddress newCellRangeAddress = new CellRangeAddress(targetRowFrom, targetRowTo,
						cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
				destSheet.addMergedRegion(newCellRangeAddress);
			}
		}
	}

Copy rows.

@param srcSheet
the src sheet
@param destSheet
the dest sheet
@param srcRowStart
the src row start
@param srcRowEnd
the src row end
@param destRow
the dest row
@param checkLock
the check lock
@param setHiddenColumn
the set hidden column


private static void copySingleRow(final Sheet srcSheet, final Sheet destSheet, final int sourceRowNum,
			final int destinationRowNum, final boolean checkLock, final boolean setHiddenColumn) {
		// Get the source / new row
		Row newRow = destSheet.getRow(destinationRowNum);
		Row sourceRow = srcSheet.getRow(sourceRowNum);

		if (newRow == null) {
			newRow = destSheet.createRow(destinationRowNum);
		}
		newRow.setHeight(sourceRow.getHeight());
		// Loop through source columns to add to new row
		for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
			// Grab a copy of the old/new cell
			copyCell(destSheet, sourceRow, newRow, i, checkLock);
		}
		if (setHiddenColumn) {
			ConfigurationUtility.setOriginalRowNumInHiddenColumn(newRow, sourceRow.getRowNum());
		}
		return;

	}

Copy single row.

@param srcSheet
the src sheet
@param destSheet
the dest sheet
@param sourceRowNum
the source row num
@param destinationRowNum
the destination row num
@param checkLock
the check lock
@param setHiddenColumn
the set hidden column


public static Cell copyCell(final Sheet destSheet, final Row sourceRow, final Row newRow, final int cellIndex,
			final boolean checkLock) {
		// If the old cell is null jump to next cell
		Cell sourceCell = sourceRow.getCell(cellIndex);
		if (sourceCell == null) {
			return null;
		}
		// If source cell is dest cell refresh it
		boolean refreshCell = false;
		if (sourceRow.equals(newRow)&&(sourceCell.getColumnIndex()==cellIndex)) {
			sourceRow.removeCell(sourceCell);
			refreshCell = true;
		}
		Cell newCell = newRow.createCell(cellIndex);
		try {
			if (!refreshCell && (sourceCell.getCellComment() != null)) {
				// If there is a cell comment, copy
				cloneComment(sourceCell, newCell);
			}
			copyCellSetStyle(destSheet, sourceCell, newCell);
			copyCellSetValue(sourceCell, newCell, checkLock);
		} catch (Exception ex) {
			LOG.log(Level.SEVERE, "copy cell set error = " + ex.getLocalizedMessage(), ex);
		}

		return newCell;
	}

Copy cell.

@param destSheet
the dest sheet
@param sourceRow
the source row
@param newRow
the new row
@param cellIndex
the cell index
@param checkLock
the check lock
@return the int


@SuppressWarnings("deprecation")
	private static void copyCellSetValue(final Cell sourceCell, final Cell newCell, final boolean checkLock) {

		CellStyle newCellStyle = newCell.getCellStyle();
		String name = sourceCell.getCellTypeEnum().toString();
		CellValueType e = Enum.valueOf(CellValueType.class, name);
		e.setCellValue(newCell, sourceCell, checkLock, newCellStyle);
	}

@ SuppressWarnings ( "deprecation" ) private static void copyCellSetValue ( final Cell sourceCell , final Cell newCell , final boolean checkLock ) { CellStyle newCellStyle = newCell . getCellStyle ( ) ; String name = sourceCell . getCellTypeEnum ( ) . toString ( ) ; CellValueType e = Enum . valueOf ( CellValueType . class , name ) ; e . setCellValue ( newCell , sourceCell , checkLock , newCellStyle ) ; }

set cell value.

@param sourceCell
source cell.
@param newCell
new cell.
@param checkLock
check lock flag.


@SuppressWarnings("deprecation")
	private static void copyCellSetStyle(final Sheet destSheet, final Cell sourceCell, final Cell newCell) {
		CellStyle newCellStyle = getCellStyleFromSourceCell(destSheet, sourceCell);
		newCell.setCellStyle(newCellStyle);

		// If there is a cell hyperlink, copy
		if (sourceCell.getHyperlink() != null) {
			newCell.setHyperlink(sourceCell.getHyperlink());
		}

		// Set the cell data type
		newCell.setCellType(sourceCell.getCellTypeEnum());
	}

@
SuppressWarnings
(
"deprecation"
)
private
static
void
copyCellSetStyle
(
final
Sheet
destSheet
,
final
Cell
sourceCell
,
final
Cell
newCell
)
{
CellStyle
newCellStyle
=
getCellStyleFromSourceCell
(
destSheet
,
sourceCell
)
;
newCell
.
setCellStyle
(
newCellStyle
)
;
// If there is a cell hyperlink, copy
if
(
sourceCell
.
getHyperlink
(
)
!=
)
{
newCell
.
setHyperlink
(
sourceCell
.
getHyperlink
(
)
)
;
}
// Set the cell data type
newCell
.
setCellType
(
sourceCell
.
getCellTypeEnum
(
)
)
;
}

set up cell style.

@param destSheet
dest sheet.
@param sourceCell
source cell.
@param newCell
new cell.